diff options
author | George Hazan <ghazan@miranda.im> | 2022-11-30 17:48:47 +0300 |
---|---|---|
committer | George Hazan <ghazan@miranda.im> | 2022-11-30 17:48:47 +0300 |
commit | 0ece30dc7c0e34b4c5911969b8fa99c33c6d023c (patch) | |
tree | 671325d3fec09b999411e4e3ab84ef8259261818 /protocols/Telegram/tdlib/td/sqlite | |
parent | 46c53ffc6809c67e4607e99951a2846c382b63b2 (diff) |
Telegram: update for TDLIB
Diffstat (limited to 'protocols/Telegram/tdlib/td/sqlite')
-rw-r--r-- | protocols/Telegram/tdlib/td/sqlite/CMakeLists.txt | 44 | ||||
-rw-r--r-- | protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.c | 109762 | ||||
-rw-r--r-- | protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.h | 6597 | ||||
-rw-r--r-- | protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3ext.h | 930 | ||||
-rw-r--r-- | protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3session.h | 757 |
5 files changed, 74882 insertions, 43208 deletions
diff --git a/protocols/Telegram/tdlib/td/sqlite/CMakeLists.txt b/protocols/Telegram/tdlib/td/sqlite/CMakeLists.txt index c94efe4f57..518e3f0aa1 100644 --- a/protocols/Telegram/tdlib/td/sqlite/CMakeLists.txt +++ b/protocols/Telegram/tdlib/td/sqlite/CMakeLists.txt @@ -1,4 +1,10 @@ -cmake_minimum_required(VERSION 3.0.2 FATAL_ERROR) +if ((CMAKE_MAJOR_VERSION LESS 3) OR (CMAKE_VERSION VERSION_LESS "3.0.2")) + message(FATAL_ERROR "CMake >= 3.0.2 is required") +endif() + +if (NOT DEFINED CMAKE_INSTALL_LIBDIR) + set(CMAKE_INSTALL_LIBDIR "lib") +endif() if (NOT OPENSSL_FOUND) find_package(OpenSSL REQUIRED) @@ -13,40 +19,58 @@ set(SQLITE_SOURCE sqlite/sqlite3session.h ) +# all SQLite functions are moved to namespace tdsqlite3 by `sed -Ebi 's/sqlite3([^.]|$)/td&/g' *` + add_library(tdsqlite STATIC ${SQLITE_SOURCE}) target_include_directories(tdsqlite PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>) target_include_directories(tdsqlite SYSTEM PRIVATE ${OPENSSL_INCLUDE_DIR}) target_link_libraries(tdsqlite PRIVATE ${OPENSSL_CRYPTO_LIBRARY} ${CMAKE_DL_LIBS} ${ZLIB_LIBRARIES}) +if (WIN32) + if (MINGW) + target_link_libraries(tdsqlite PRIVATE ws2_32 mswsock crypt32) + else() + target_link_libraries(tdsqlite PRIVATE ws2_32 Mswsock Crypt32) + endif() +endif() + target_compile_definitions(tdsqlite PRIVATE + -DOMIT_MEMLOCK -DSQLITE_DEFAULT_MEMSTATUS=0 - -DSQLITE_OMIT_LOAD_EXTENSION + -DSQLITE_DEFAULT_RECURSIVE_TRIGGERS=1 + -DSQLITE_DEFAULT_SYNCHRONOUS=1 + -DSQLITE_DISABLE_LFS + -DSQLITE_ENABLE_FTS5 + -DSQLITE_HAS_CODEC -DSQLITE_OMIT_DECLTYPE + -DSQLITE_OMIT_DEPRECATED + -DSQLITE_OMIT_DESERIALIZE + -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_OMIT_PROGRESS_CALLBACK - #-DSQLITE_OMIT_DEPRECATED # SQLCipher uses deprecated sqlite3_profile #-DSQLITE_OMIT_SHARED_CACHE + -DSQLITE_TEMP_STORE=2 ) -target_compile_definitions(tdsqlite PRIVATE -DSQLITE_HAS_CODEC -DSQLITE_TEMP_STORE=2 -DSQLITE_ENABLE_FTS5 -DSQLITE_DISABLE_LFS) if (NOT WIN32) target_compile_definitions(tdsqlite PRIVATE -DHAVE_USLEEP -DNDEBUG=1) endif() -if ("${CMAKE_SYSTEM_NAME}" STREQUAL "WindowsStore") +if (CMAKE_SYSTEM_NAME STREQUAL "WindowsStore") target_compile_definitions(tdsqlite PRIVATE -DSQLITE_OS_WINRT=1) endif() if (GCC OR CLANG) target_compile_options(tdsqlite PRIVATE -Wno-deprecated-declarations -Wno-unused-variable -Wno-unused-const-variable -Wno-unused-function) if (CLANG) - target_compile_options(tdsqlite PRIVATE -Wno-parentheses-equality -Wno-unused-value) + target_compile_options(tdsqlite PRIVATE -Wno-parentheses-equality -Wno-unused-value -Wno-unused-command-line-argument -Qunused-arguments) + endif() + if (GCC AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10.0)) + target_compile_options(tdsqlite PRIVATE -Wno-return-local-addr -Wno-stringop-overflow) endif() elseif (MSVC) target_compile_options(tdsqlite PRIVATE /wd4996) endif() install(TARGETS tdsqlite EXPORT TdTargets - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib - RUNTIME DESTINATION bin - INCLUDES DESTINATION include + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" ) diff --git a/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.c b/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.c index a7bb6243ca..4fb5bc5e5d 100644 --- a/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.c +++ b/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.c @@ -1,6 +1,6 @@ /****************************************************************************** ** This file is an amalgamation of many separate C source files from SQLite -** version 3.15.2. By combining all the individual C code files into this +** version 3.31.0. By combining all the individual C code files into this ** single large file, the entire code can be compiled as a single translation ** unit. This allows many compilers to do optimizations that would not be ** possible if the files were compiled separately. Performance improvements @@ -14,7 +14,7 @@ ** the text of this file. Search for "Begin file sqlite3.h" to find the start ** of the embedded sqlite3.h header file.) Additional code files may be needed ** if you want a wrapper to interface SQLite with your choice of programming -** language. The code for the "sqlite3" command-line shell is also in a +** language. The code for the "tdsqlite3" command-line shell is also in a ** separate file. This file contains only code for the core SQLite library. */ #define SQLITE_CORE 1 @@ -22,6 +22,774 @@ #ifndef SQLITE_PRIVATE # define SQLITE_PRIVATE static #endif +/************** Begin file ctime.c *******************************************/ +/* +** 2010 February 23 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements routines used to report what compile-time options +** SQLite was built with. +*/ + +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */ + +/* +** Include the configuration header output by 'configure' if we're using the +** autoconf-based build +*/ +#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H) +#include "config.h" +#define SQLITECONFIG_H 1 +#endif + +/* These macros are provided to "stringify" the value of the define +** for those options in which the value is meaningful. */ +#define CTIMEOPT_VAL_(opt) #opt +#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) + +/* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This +** option requires a separate macro because legal values contain a single +** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */ +#define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2 +#define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt) + +/* +** An array of names of all compile-time options. This array should +** be sorted A-Z. +** +** This array looks large, but in a typical installation actually uses +** only a handful of compile-time options, so most times this array is usually +** rather short and uses little memory space. +*/ +static const char * const tdsqlite3azCompileOpt[] = { + +/* +** BEGIN CODE GENERATED BY tool/mkctime.tcl +*/ +#if SQLITE_32BIT_ROWID + "32BIT_ROWID", +#endif +#if SQLITE_4_BYTE_ALIGNED_MALLOC + "4_BYTE_ALIGNED_MALLOC", +#endif +#if SQLITE_64BIT_STATS + "64BIT_STATS", +#endif +#if SQLITE_ALLOW_COVERING_INDEX_SCAN + "ALLOW_COVERING_INDEX_SCAN", +#endif +#if SQLITE_ALLOW_URI_AUTHORITY + "ALLOW_URI_AUTHORITY", +#endif +#ifdef SQLITE_BITMASK_TYPE + "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE), +#endif +#if SQLITE_BUG_COMPATIBLE_20160819 + "BUG_COMPATIBLE_20160819", +#endif +#if SQLITE_CASE_SENSITIVE_LIKE + "CASE_SENSITIVE_LIKE", +#endif +#if SQLITE_CHECK_PAGES + "CHECK_PAGES", +#endif +#if defined(__clang__) && defined(__clang_major__) + "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "." + CTIMEOPT_VAL(__clang_minor__) "." + CTIMEOPT_VAL(__clang_patchlevel__), +#elif defined(_MSC_VER) + "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER), +#elif defined(__GNUC__) && defined(__VERSION__) + "COMPILER=gcc-" __VERSION__, +#endif +#if SQLITE_COVERAGE_TEST + "COVERAGE_TEST", +#endif +#if SQLITE_DEBUG + "DEBUG", +#endif +#if SQLITE_DEFAULT_AUTOMATIC_INDEX + "DEFAULT_AUTOMATIC_INDEX", +#endif +#if SQLITE_DEFAULT_AUTOVACUUM + "DEFAULT_AUTOVACUUM", +#endif +#ifdef SQLITE_DEFAULT_CACHE_SIZE + "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE), +#endif +#if SQLITE_DEFAULT_CKPTFULLFSYNC + "DEFAULT_CKPTFULLFSYNC", +#endif +#ifdef SQLITE_DEFAULT_FILE_FORMAT + "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT), +#endif +#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS + "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS), +#endif +#if SQLITE_DEFAULT_FOREIGN_KEYS + "DEFAULT_FOREIGN_KEYS", +#endif +#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT + "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT), +#endif +#ifdef SQLITE_DEFAULT_LOCKING_MODE + "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), +#endif +#ifdef SQLITE_DEFAULT_LOOKASIDE + "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE), +#endif +#if SQLITE_DEFAULT_MEMSTATUS + "DEFAULT_MEMSTATUS", +#endif +#ifdef SQLITE_DEFAULT_MMAP_SIZE + "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE), +#endif +#ifdef SQLITE_DEFAULT_PAGE_SIZE + "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE), +#endif +#ifdef SQLITE_DEFAULT_PCACHE_INITSZ + "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ), +#endif +#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS + "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS), +#endif +#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS + "DEFAULT_RECURSIVE_TRIGGERS", +#endif +#ifdef SQLITE_DEFAULT_ROWEST + "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST), +#endif +#ifdef SQLITE_DEFAULT_SECTOR_SIZE + "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE), +#endif +#ifdef SQLITE_DEFAULT_SYNCHRONOUS + "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS), +#endif +#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT + "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT), +#endif +#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS + "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS), +#endif +#ifdef SQLITE_DEFAULT_WORKER_THREADS + "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS), +#endif +#if SQLITE_DIRECT_OVERFLOW_READ + "DIRECT_OVERFLOW_READ", +#endif +#if SQLITE_DISABLE_DIRSYNC + "DISABLE_DIRSYNC", +#endif +#if SQLITE_DISABLE_FTS3_UNICODE + "DISABLE_FTS3_UNICODE", +#endif +#if SQLITE_DISABLE_FTS4_DEFERRED + "DISABLE_FTS4_DEFERRED", +#endif +#if SQLITE_DISABLE_INTRINSIC + "DISABLE_INTRINSIC", +#endif +#if SQLITE_DISABLE_LFS + "DISABLE_LFS", +#endif +#if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS + "DISABLE_PAGECACHE_OVERFLOW_STATS", +#endif +#if SQLITE_DISABLE_SKIPAHEAD_DISTINCT + "DISABLE_SKIPAHEAD_DISTINCT", +#endif +#ifdef SQLITE_ENABLE_8_3_NAMES + "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES), +#endif +#if SQLITE_ENABLE_API_ARMOR + "ENABLE_API_ARMOR", +#endif +#if SQLITE_ENABLE_ATOMIC_WRITE + "ENABLE_ATOMIC_WRITE", +#endif +#if SQLITE_ENABLE_BATCH_ATOMIC_WRITE + "ENABLE_BATCH_ATOMIC_WRITE", +#endif +#if SQLITE_ENABLE_CEROD + "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD), +#endif +#if SQLITE_ENABLE_COLUMN_METADATA + "ENABLE_COLUMN_METADATA", +#endif +#if SQLITE_ENABLE_COLUMN_USED_MASK + "ENABLE_COLUMN_USED_MASK", +#endif +#if SQLITE_ENABLE_COSTMULT + "ENABLE_COSTMULT", +#endif +#if SQLITE_ENABLE_CURSOR_HINTS + "ENABLE_CURSOR_HINTS", +#endif +#if SQLITE_ENABLE_DBSTAT_VTAB + "ENABLE_DBSTAT_VTAB", +#endif +#if SQLITE_ENABLE_EXPENSIVE_ASSERT + "ENABLE_EXPENSIVE_ASSERT", +#endif +#if SQLITE_ENABLE_FTS1 + "ENABLE_FTS1", +#endif +#if SQLITE_ENABLE_FTS2 + "ENABLE_FTS2", +#endif +#if SQLITE_ENABLE_FTS3 + "ENABLE_FTS3", +#endif +#if SQLITE_ENABLE_FTS3_PARENTHESIS + "ENABLE_FTS3_PARENTHESIS", +#endif +#if SQLITE_ENABLE_FTS3_TOKENIZER + "ENABLE_FTS3_TOKENIZER", +#endif +#if SQLITE_ENABLE_FTS4 + "ENABLE_FTS4", +#endif +#if SQLITE_ENABLE_FTS5 + "ENABLE_FTS5", +#endif +#if SQLITE_ENABLE_GEOPOLY + "ENABLE_GEOPOLY", +#endif +#if SQLITE_ENABLE_HIDDEN_COLUMNS + "ENABLE_HIDDEN_COLUMNS", +#endif +#if SQLITE_ENABLE_ICU + "ENABLE_ICU", +#endif +#if SQLITE_ENABLE_IOTRACE + "ENABLE_IOTRACE", +#endif +#if SQLITE_ENABLE_JSON1 + "ENABLE_JSON1", +#endif +#if SQLITE_ENABLE_LOAD_EXTENSION + "ENABLE_LOAD_EXTENSION", +#endif +#ifdef SQLITE_ENABLE_LOCKING_STYLE + "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), +#endif +#if SQLITE_ENABLE_MEMORY_MANAGEMENT + "ENABLE_MEMORY_MANAGEMENT", +#endif +#if SQLITE_ENABLE_MEMSYS3 + "ENABLE_MEMSYS3", +#endif +#if SQLITE_ENABLE_MEMSYS5 + "ENABLE_MEMSYS5", +#endif +#if SQLITE_ENABLE_MULTIPLEX + "ENABLE_MULTIPLEX", +#endif +#if SQLITE_ENABLE_NORMALIZE + "ENABLE_NORMALIZE", +#endif +#if SQLITE_ENABLE_NULL_TRIM + "ENABLE_NULL_TRIM", +#endif +#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK + "ENABLE_OVERSIZE_CELL_CHECK", +#endif +#if SQLITE_ENABLE_PREUPDATE_HOOK + "ENABLE_PREUPDATE_HOOK", +#endif +#if SQLITE_ENABLE_QPSG + "ENABLE_QPSG", +#endif +#if SQLITE_ENABLE_RBU + "ENABLE_RBU", +#endif +#if SQLITE_ENABLE_RTREE + "ENABLE_RTREE", +#endif +#if SQLITE_ENABLE_SELECTTRACE + "ENABLE_SELECTTRACE", +#endif +#if SQLITE_ENABLE_SESSION + "ENABLE_SESSION", +#endif +#if SQLITE_ENABLE_SNAPSHOT + "ENABLE_SNAPSHOT", +#endif +#if SQLITE_ENABLE_SORTER_REFERENCES + "ENABLE_SORTER_REFERENCES", +#endif +#if SQLITE_ENABLE_SQLLOG + "ENABLE_SQLLOG", +#endif +#if defined(SQLITE_ENABLE_STAT4) + "ENABLE_STAT4", +#endif +#if SQLITE_ENABLE_STMTVTAB + "ENABLE_STMTVTAB", +#endif +#if SQLITE_ENABLE_STMT_SCANSTATUS + "ENABLE_STMT_SCANSTATUS", +#endif +#if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION + "ENABLE_UNKNOWN_SQL_FUNCTION", +#endif +#if SQLITE_ENABLE_UNLOCK_NOTIFY + "ENABLE_UNLOCK_NOTIFY", +#endif +#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT + "ENABLE_UPDATE_DELETE_LIMIT", +#endif +#if SQLITE_ENABLE_URI_00_ERROR + "ENABLE_URI_00_ERROR", +#endif +#if SQLITE_ENABLE_VFSTRACE + "ENABLE_VFSTRACE", +#endif +#if SQLITE_ENABLE_WHERETRACE + "ENABLE_WHERETRACE", +#endif +#if SQLITE_ENABLE_ZIPVFS + "ENABLE_ZIPVFS", +#endif +#if SQLITE_EXPLAIN_ESTIMATED_ROWS + "EXPLAIN_ESTIMATED_ROWS", +#endif +#if SQLITE_EXTRA_IFNULLROW + "EXTRA_IFNULLROW", +#endif +#ifdef SQLITE_EXTRA_INIT + "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT), +#endif +#ifdef SQLITE_EXTRA_SHUTDOWN + "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN), +#endif +#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH + "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH), +#endif +#if SQLITE_FTS5_ENABLE_TEST_MI + "FTS5_ENABLE_TEST_MI", +#endif +#if SQLITE_FTS5_NO_WITHOUT_ROWID + "FTS5_NO_WITHOUT_ROWID", +#endif +#if SQLITE_HAS_CODEC + "HAS_CODEC", +#endif +#if HAVE_ISNAN || SQLITE_HAVE_ISNAN + "HAVE_ISNAN", +#endif +#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX + "HOMEGROWN_RECURSIVE_MUTEX", +#endif +#if SQLITE_IGNORE_AFP_LOCK_ERRORS + "IGNORE_AFP_LOCK_ERRORS", +#endif +#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS + "IGNORE_FLOCK_LOCK_ERRORS", +#endif +#if SQLITE_INLINE_MEMCPY + "INLINE_MEMCPY", +#endif +#if SQLITE_INT64_TYPE + "INT64_TYPE", +#endif +#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX + "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX), +#endif +#if SQLITE_LIKE_DOESNT_MATCH_BLOBS + "LIKE_DOESNT_MATCH_BLOBS", +#endif +#if SQLITE_LOCK_TRACE + "LOCK_TRACE", +#endif +#if SQLITE_LOG_CACHE_SPILL + "LOG_CACHE_SPILL", +#endif +#ifdef SQLITE_MALLOC_SOFT_LIMIT + "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT), +#endif +#ifdef SQLITE_MAX_ATTACHED + "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED), +#endif +#ifdef SQLITE_MAX_COLUMN + "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN), +#endif +#ifdef SQLITE_MAX_COMPOUND_SELECT + "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT), +#endif +#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE + "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE), +#endif +#ifdef SQLITE_MAX_EXPR_DEPTH + "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH), +#endif +#ifdef SQLITE_MAX_FUNCTION_ARG + "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG), +#endif +#ifdef SQLITE_MAX_LENGTH + "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH), +#endif +#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH + "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH), +#endif +#ifdef SQLITE_MAX_MEMORY + "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY), +#endif +#ifdef SQLITE_MAX_MMAP_SIZE + "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE), +#endif +#ifdef SQLITE_MAX_MMAP_SIZE_ + "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_), +#endif +#ifdef SQLITE_MAX_PAGE_COUNT + "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT), +#endif +#ifdef SQLITE_MAX_PAGE_SIZE + "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE), +#endif +#ifdef SQLITE_MAX_SCHEMA_RETRY + "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY), +#endif +#ifdef SQLITE_MAX_SQL_LENGTH + "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH), +#endif +#ifdef SQLITE_MAX_TRIGGER_DEPTH + "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH), +#endif +#ifdef SQLITE_MAX_VARIABLE_NUMBER + "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER), +#endif +#ifdef SQLITE_MAX_VDBE_OP + "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP), +#endif +#ifdef SQLITE_MAX_WORKER_THREADS + "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS), +#endif +#if SQLITE_MEMDEBUG + "MEMDEBUG", +#endif +#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT + "MIXED_ENDIAN_64BIT_FLOAT", +#endif +#if SQLITE_MMAP_READWRITE + "MMAP_READWRITE", +#endif +#if SQLITE_MUTEX_NOOP + "MUTEX_NOOP", +#endif +#if SQLITE_MUTEX_NREF + "MUTEX_NREF", +#endif +#if SQLITE_MUTEX_OMIT + "MUTEX_OMIT", +#endif +#if SQLITE_MUTEX_PTHREADS + "MUTEX_PTHREADS", +#endif +#if SQLITE_MUTEX_W32 + "MUTEX_W32", +#endif +#if SQLITE_NEED_ERR_NAME + "NEED_ERR_NAME", +#endif +#if SQLITE_NOINLINE + "NOINLINE", +#endif +#if SQLITE_NO_SYNC + "NO_SYNC", +#endif +#if SQLITE_OMIT_ALTERTABLE + "OMIT_ALTERTABLE", +#endif +#if SQLITE_OMIT_ANALYZE + "OMIT_ANALYZE", +#endif +#if SQLITE_OMIT_ATTACH + "OMIT_ATTACH", +#endif +#if SQLITE_OMIT_AUTHORIZATION + "OMIT_AUTHORIZATION", +#endif +#if SQLITE_OMIT_AUTOINCREMENT + "OMIT_AUTOINCREMENT", +#endif +#if SQLITE_OMIT_AUTOINIT + "OMIT_AUTOINIT", +#endif +#if SQLITE_OMIT_AUTOMATIC_INDEX + "OMIT_AUTOMATIC_INDEX", +#endif +#if SQLITE_OMIT_AUTORESET + "OMIT_AUTORESET", +#endif +#if SQLITE_OMIT_AUTOVACUUM + "OMIT_AUTOVACUUM", +#endif +#if SQLITE_OMIT_BETWEEN_OPTIMIZATION + "OMIT_BETWEEN_OPTIMIZATION", +#endif +#if SQLITE_OMIT_BLOB_LITERAL + "OMIT_BLOB_LITERAL", +#endif +#if SQLITE_OMIT_BTREECOUNT + "OMIT_BTREECOUNT", +#endif +#if SQLITE_OMIT_CAST + "OMIT_CAST", +#endif +#if SQLITE_OMIT_CHECK + "OMIT_CHECK", +#endif +#if SQLITE_OMIT_COMPLETE + "OMIT_COMPLETE", +#endif +#if SQLITE_OMIT_COMPOUND_SELECT + "OMIT_COMPOUND_SELECT", +#endif +#if SQLITE_OMIT_CONFLICT_CLAUSE + "OMIT_CONFLICT_CLAUSE", +#endif +#if SQLITE_OMIT_CTE + "OMIT_CTE", +#endif +#if SQLITE_OMIT_DATETIME_FUNCS + "OMIT_DATETIME_FUNCS", +#endif +#if SQLITE_OMIT_DECLTYPE + "OMIT_DECLTYPE", +#endif +#if SQLITE_OMIT_DEPRECATED + "OMIT_DEPRECATED", +#endif +#if SQLITE_OMIT_DISKIO + "OMIT_DISKIO", +#endif +#if SQLITE_OMIT_EXPLAIN + "OMIT_EXPLAIN", +#endif +#if SQLITE_OMIT_FLAG_PRAGMAS + "OMIT_FLAG_PRAGMAS", +#endif +#if SQLITE_OMIT_FLOATING_POINT + "OMIT_FLOATING_POINT", +#endif +#if SQLITE_OMIT_FOREIGN_KEY + "OMIT_FOREIGN_KEY", +#endif +#if SQLITE_OMIT_GET_TABLE + "OMIT_GET_TABLE", +#endif +#if SQLITE_OMIT_HEX_INTEGER + "OMIT_HEX_INTEGER", +#endif +#if SQLITE_OMIT_INCRBLOB + "OMIT_INCRBLOB", +#endif +#if SQLITE_OMIT_INTEGRITY_CHECK + "OMIT_INTEGRITY_CHECK", +#endif +#if SQLITE_OMIT_LIKE_OPTIMIZATION + "OMIT_LIKE_OPTIMIZATION", +#endif +#if SQLITE_OMIT_LOAD_EXTENSION + "OMIT_LOAD_EXTENSION", +#endif +#if SQLITE_OMIT_LOCALTIME + "OMIT_LOCALTIME", +#endif +#if SQLITE_OMIT_LOOKASIDE + "OMIT_LOOKASIDE", +#endif +#if SQLITE_OMIT_MEMORYDB + "OMIT_MEMORYDB", +#endif +#if SQLITE_OMIT_OR_OPTIMIZATION + "OMIT_OR_OPTIMIZATION", +#endif +#if SQLITE_OMIT_PAGER_PRAGMAS + "OMIT_PAGER_PRAGMAS", +#endif +#if SQLITE_OMIT_PARSER_TRACE + "OMIT_PARSER_TRACE", +#endif +#if SQLITE_OMIT_POPEN + "OMIT_POPEN", +#endif +#if SQLITE_OMIT_PRAGMA + "OMIT_PRAGMA", +#endif +#if SQLITE_OMIT_PROGRESS_CALLBACK + "OMIT_PROGRESS_CALLBACK", +#endif +#if SQLITE_OMIT_QUICKBALANCE + "OMIT_QUICKBALANCE", +#endif +#if SQLITE_OMIT_REINDEX + "OMIT_REINDEX", +#endif +#if SQLITE_OMIT_SCHEMA_PRAGMAS + "OMIT_SCHEMA_PRAGMAS", +#endif +#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS + "OMIT_SCHEMA_VERSION_PRAGMAS", +#endif +#if SQLITE_OMIT_SHARED_CACHE + "OMIT_SHARED_CACHE", +#endif +#if SQLITE_OMIT_SHUTDOWN_DIRECTORIES + "OMIT_SHUTDOWN_DIRECTORIES", +#endif +#if SQLITE_OMIT_SUBQUERY + "OMIT_SUBQUERY", +#endif +#if SQLITE_OMIT_TCL_VARIABLE + "OMIT_TCL_VARIABLE", +#endif +#if SQLITE_OMIT_TEMPDB + "OMIT_TEMPDB", +#endif +#if SQLITE_OMIT_TEST_CONTROL + "OMIT_TEST_CONTROL", +#endif +#if SQLITE_OMIT_TRACE + "OMIT_TRACE", +#endif +#if SQLITE_OMIT_TRIGGER + "OMIT_TRIGGER", +#endif +#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION + "OMIT_TRUNCATE_OPTIMIZATION", +#endif +#if SQLITE_OMIT_UTF16 + "OMIT_UTF16", +#endif +#if SQLITE_OMIT_VACUUM + "OMIT_VACUUM", +#endif +#if SQLITE_OMIT_VIEW + "OMIT_VIEW", +#endif +#if SQLITE_OMIT_VIRTUALTABLE + "OMIT_VIRTUALTABLE", +#endif +#if SQLITE_OMIT_WAL + "OMIT_WAL", +#endif +#if SQLITE_OMIT_WSD + "OMIT_WSD", +#endif +#if SQLITE_OMIT_XFER_OPT + "OMIT_XFER_OPT", +#endif +#if SQLITE_PCACHE_SEPARATE_HEADER + "PCACHE_SEPARATE_HEADER", +#endif +#if SQLITE_PERFORMANCE_TRACE + "PERFORMANCE_TRACE", +#endif +#if SQLITE_POWERSAFE_OVERWRITE + "POWERSAFE_OVERWRITE", +#endif +#if SQLITE_PREFER_PROXY_LOCKING + "PREFER_PROXY_LOCKING", +#endif +#if SQLITE_PROXY_DEBUG + "PROXY_DEBUG", +#endif +#if SQLITE_REVERSE_UNORDERED_SELECTS + "REVERSE_UNORDERED_SELECTS", +#endif +#if SQLITE_RTREE_INT_ONLY + "RTREE_INT_ONLY", +#endif +#if SQLITE_SECURE_DELETE + "SECURE_DELETE", +#endif +#if SQLITE_SMALL_STACK + "SMALL_STACK", +#endif +#ifdef SQLITE_SORTER_PMASZ + "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ), +#endif +#if SQLITE_SOUNDEX + "SOUNDEX", +#endif +#ifdef SQLITE_STAT4_SAMPLES + "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES), +#endif +#ifdef SQLITE_STMTJRNL_SPILL + "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL), +#endif +#if SQLITE_SUBSTR_COMPATIBILITY + "SUBSTR_COMPATIBILITY", +#endif +#if SQLITE_SYSTEM_MALLOC + "SYSTEM_MALLOC", +#endif +#if SQLITE_TCL + "TCL", +#endif +#ifdef SQLITE_TEMP_STORE + "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE), +#endif +#if SQLITE_TEST + "TEST", +#endif +#if defined(SQLITE_THREADSAFE) + "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE), +#elif defined(THREADSAFE) + "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE), +#else + "THREADSAFE=1", +#endif +#if SQLITE_UNLINK_AFTER_CLOSE + "UNLINK_AFTER_CLOSE", +#endif +#if SQLITE_UNTESTABLE + "UNTESTABLE", +#endif +#if SQLITE_USER_AUTHENTICATION + "USER_AUTHENTICATION", +#endif +#if SQLITE_USE_ALLOCA + "USE_ALLOCA", +#endif +#if SQLITE_USE_FCNTL_TRACE + "USE_FCNTL_TRACE", +#endif +#if SQLITE_USE_URI + "USE_URI", +#endif +#if SQLITE_VDBE_COVERAGE + "VDBE_COVERAGE", +#endif +#if SQLITE_WIN32_MALLOC + "WIN32_MALLOC", +#endif +#if SQLITE_ZERO_MALLOC + "ZERO_MALLOC", +#endif +/* +** END CODE GENERATED BY tool/mkctime.tcl +*/ +}; + +SQLITE_PRIVATE const char **tdsqlite3CompileOptions(int *pnOpt){ + *pnOpt = sizeof(tdsqlite3azCompileOpt) / sizeof(tdsqlite3azCompileOpt[0]); + return (const char**)tdsqlite3azCompileOpt; +} + +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + +/************** End of ctime.c ***********************************************/ /************** Begin file sqliteInt.h ***************************************/ /* ** 2001 September 15 @@ -76,14 +844,6 @@ #endif /* -** Make sure that rand_s() is available on Windows systems with MSVC 2005 -** or higher. -*/ -#if defined(_MSC_VER) && _MSC_VER>=1400 -# define _CRT_RAND_S -#endif - -/* ** Include the header file used to customize the compiler options for MSVC. ** This should be done first so that it can successfully prevent spurious ** compiler warnings due to subsequent content in this file and other files @@ -126,6 +886,11 @@ #pragma warning(disable : 4706) #endif /* defined(_MSC_VER) */ +#if defined(_MSC_VER) && !defined(_WIN64) +#undef SQLITE_4_BYTE_ALIGNED_MALLOC +#define SQLITE_4_BYTE_ALIGNED_MALLOC +#endif /* defined(_MSC_VER) && !defined(_WIN64) */ + #endif /* SQLITE_MSVC_H */ /************** End of msvc.h ************************************************/ @@ -204,12 +969,29 @@ # define _LARGEFILE_SOURCE 1 #endif -/* What version of GCC is being used. 0 means GCC is not being used */ -#ifdef __GNUC__ +/* The GCC_VERSION and MSVC_VERSION macros are used to +** conditionally include optimizations for each of these compilers. A +** value of 0 means that compiler is not being used. The +** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific +** optimizations, and hence set all compiler macros to 0 +** +** There was once also a CLANG_VERSION macro. However, we learn that the +** version numbers in clang are for "marketing" only and are inconsistent +** and unreliable. Fortunately, all versions of clang also recognize the +** gcc version numbers and have reasonable settings for gcc version numbers, +** so the GCC_VERSION macro will be set to a correct non-zero value even +** when compiling with clang. +*/ +#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) #else # define GCC_VERSION 0 #endif +#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) +# define MSVC_VERSION _MSC_VER +#else +# define MSVC_VERSION 0 +#endif /* Needed for various definitions... */ #if defined(__GNUC__) && !defined(_GNU_SOURCE) @@ -259,7 +1041,7 @@ /************** Include sqlite3.h in the middle of sqliteInt.h ***************/ /************** Begin file sqlite3.h *****************************************/ /* -** 2001 September 15 +** 2001-09-15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: @@ -374,20 +1156,22 @@ extern "C" { ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to ** a string which identifies a particular check-in of SQLite ** within its configuration management system. ^The SQLITE_SOURCE_ID -** string contains the date and time of the check-in (UTC) and an SHA1 -** hash of the entire source tree. +** string contains the date and time of the check-in (UTC) and a SHA1 +** or SHA3-256 hash of the entire source tree. If the source code has +** been edited in any way since it was last checked in, then the last +** four hexadecimal digits of the hash may be modified. ** -** See also: [sqlite3_libversion()], -** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** See also: [tdsqlite3_libversion()], +** [tdsqlite3_libversion_number()], [tdsqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ -#define SQLITE_VERSION "3.15.2" -#define SQLITE_VERSION_NUMBER 3015002 -#define SQLITE_SOURCE_ID "2016-11-28 19:13:37 bbd85d235f7037c6a033a9690534391ffeacecc8" +#define SQLITE_VERSION "3.31.0" +#define SQLITE_VERSION_NUMBER 3031000 +#define SQLITE_SOURCE_ID "2020-01-22 18:38:59 f6affdd41608946fcfcea914ece149038a8b25a62bbe719ed2561c649b86alt1" /* ** CAPI3REF: Run-Time Library Version Numbers -** KEYWORDS: sqlite3_version, sqlite3_sourceid +** KEYWORDS: tdsqlite3_version tdsqlite3_sourceid ** ** These interfaces provide the same information as the [SQLITE_VERSION], ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros @@ -398,59 +1182,64 @@ extern "C" { ** compiled with matching library and header files. ** ** <blockquote><pre> -** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER ); -** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 ); -** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 ); +** assert( tdsqlite3_libversion_number()==SQLITE_VERSION_NUMBER ); +** assert( strncmp(tdsqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 ); +** assert( strcmp(tdsqlite3_libversion(),SQLITE_VERSION)==0 ); ** </pre></blockquote>)^ ** -** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] -** macro. ^The sqlite3_libversion() function returns a pointer to the -** to the sqlite3_version[] string constant. The sqlite3_libversion() +** ^The tdsqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The tdsqlite3_libversion() function returns a pointer to the +** to the tdsqlite3_version[] string constant. The tdsqlite3_libversion() ** function is provided for use in DLLs since DLL users usually do not have ** direct access to string constants within the DLL. ^The -** sqlite3_libversion_number() function returns an integer equal to -** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns +** tdsqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^(The tdsqlite3_sourceid() function returns ** a pointer to a string constant whose value is the same as the -** [SQLITE_SOURCE_ID] C preprocessor macro. +** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built +** using an edited copy of [the amalgamation], then the last four characters +** of the hash might be different from [SQLITE_SOURCE_ID].)^ ** ** See also: [sqlite_version()] and [sqlite_source_id()]. */ -SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; -SQLITE_API const char *sqlite3_libversion(void); -SQLITE_API const char *sqlite3_sourceid(void); -SQLITE_API int sqlite3_libversion_number(void); +SQLITE_API const char tdsqlite3_version[] = SQLITE_VERSION; +SQLITE_API const char *tdsqlite3_libversion(void); +SQLITE_API const char *tdsqlite3_sourceid(void); +SQLITE_API int tdsqlite3_libversion_number(void); /* ** CAPI3REF: Run-Time Library Compilation Options Diagnostics ** -** ^The sqlite3_compileoption_used() function returns 0 or 1 +** ^The tdsqlite3_compileoption_used() function returns 0 or 1 ** indicating whether the specified option was defined at ** compile time. ^The SQLITE_ prefix may be omitted from the -** option name passed to sqlite3_compileoption_used(). +** option name passed to tdsqlite3_compileoption_used(). ** -** ^The sqlite3_compileoption_get() function allows iterating +** ^The tdsqlite3_compileoption_get() function allows iterating ** over the list of options that were defined at compile time by ** returning the N-th compile time option string. ^If N is out of range, -** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** tdsqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ ** prefix is omitted from any strings returned by -** sqlite3_compileoption_get(). +** tdsqlite3_compileoption_get(). ** -** ^Support for the diagnostic functions sqlite3_compileoption_used() -** and sqlite3_compileoption_get() may be omitted by specifying the +** ^Support for the diagnostic functions tdsqlite3_compileoption_used() +** and tdsqlite3_compileoption_get() may be omitted by specifying the ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. ** ** See also: SQL functions [sqlite_compileoption_used()] and ** [sqlite_compileoption_get()] and the [compile_options pragma]. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -SQLITE_API int sqlite3_compileoption_used(const char *zOptName); -SQLITE_API const char *sqlite3_compileoption_get(int N); +SQLITE_API int tdsqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *tdsqlite3_compileoption_get(int N); +#else +# define tdsqlite3_compileoption_used(X) 0 +# define tdsqlite3_compileoption_get(X) ((void*)0) #endif /* ** CAPI3REF: Test To See If The Library Is Threadsafe ** -** ^The sqlite3_threadsafe() function returns zero if and only if +** ^The tdsqlite3_threadsafe() function returns zero if and only if ** SQLite was compiled with mutexing code omitted due to the ** [SQLITE_THREADSAFE] compile-time option being set to 0. ** @@ -473,33 +1262,33 @@ SQLITE_API const char *sqlite3_compileoption_get(int N); ** This interface only reports on the compile-time mutex setting ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but -** can be fully or partially disabled using a call to [sqlite3_config()] +** can be fully or partially disabled using a call to [tdsqlite3_config()] ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the -** sqlite3_threadsafe() function shows only the compile-time setting of +** tdsqlite3_threadsafe() function shows only the compile-time setting of ** thread safety, not any run-time changes to that setting made by -** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() -** is unchanged by calls to sqlite3_config().)^ +** tdsqlite3_config(). In other words, the return value from tdsqlite3_threadsafe() +** is unchanged by calls to tdsqlite3_config().)^ ** ** See the [threading mode] documentation for additional information. */ -SQLITE_API int sqlite3_threadsafe(void); +SQLITE_API int tdsqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle ** KEYWORDS: {database connection} {database connections} ** ** Each open SQLite database is represented by a pointer to an instance of -** the opaque structure named "sqlite3". It is useful to think of an sqlite3 -** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] -** and [sqlite3_close_v2()] are its destructors. There are many other +** the opaque structure named "tdsqlite3". It is useful to think of an tdsqlite3 +** pointer as an object. The [tdsqlite3_open()], [tdsqlite3_open16()], and +** [tdsqlite3_open_v2()] interfaces are its constructors, and [tdsqlite3_close()] +** and [tdsqlite3_close_v2()] are its destructors. There are many other ** interfaces (such as -** [sqlite3_prepare_v2()], [sqlite3_create_function()], and -** [sqlite3_busy_timeout()] to name but three) that are methods on an -** sqlite3 object. +** [tdsqlite3_prepare_v2()], [tdsqlite3_create_function()], and +** [tdsqlite3_busy_timeout()] to name but three) that are methods on an +** tdsqlite3 object. */ -typedef struct sqlite3 sqlite3; +typedef struct tdsqlite3 tdsqlite3; /* ** CAPI3REF: 64-Bit Integer Types @@ -508,18 +1297,22 @@ typedef struct sqlite3 sqlite3; ** Because there is no cross-platform way to specify 64-bit integer types ** SQLite includes typedefs for 64-bit signed and unsigned integers. ** -** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The tdsqlite3_int64 and tdsqlite3_uint64 are the preferred type definitions. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards ** compatibility only. ** -** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** ^The tdsqlite3_int64 and sqlite_int64 types can store integer values ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The -** sqlite3_uint64 and sqlite_uint64 types can store integer values +** tdsqlite3_uint64 and sqlite_uint64 types can store integer values ** between 0 and +18446744073709551615 inclusive. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; - typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +# ifdef SQLITE_UINT64_TYPE + typedef SQLITE_UINT64_TYPE sqlite_uint64; +# else + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +# endif #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef __int64 sqlite_int64; typedef unsigned __int64 sqlite_uint64; @@ -527,116 +1320,116 @@ typedef struct sqlite3 sqlite3; typedef long long int sqlite_int64; typedef unsigned long long int sqlite_uint64; #endif -typedef sqlite_int64 sqlite3_int64; -typedef sqlite_uint64 sqlite3_uint64; +typedef sqlite_int64 tdsqlite3_int64; +typedef sqlite_uint64 tdsqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point. */ #ifdef SQLITE_OMIT_FLOATING_POINT -# define double sqlite3_int64 +# define double tdsqlite3_int64 #endif /* ** CAPI3REF: Closing A Database Connection -** DESTRUCTOR: sqlite3 +** DESTRUCTOR: tdsqlite3 ** -** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors -** for the [sqlite3] object. -** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if -** the [sqlite3] object is successfully destroyed and all associated +** ^The tdsqlite3_close() and tdsqlite3_close_v2() routines are destructors +** for the [tdsqlite3] object. +** ^Calls to tdsqlite3_close() and tdsqlite3_close_v2() return [SQLITE_OK] if +** the [tdsqlite3] object is successfully destroyed and all associated ** resources are deallocated. ** ** ^If the database connection is associated with unfinalized prepared -** statements or unfinished sqlite3_backup objects then sqlite3_close() +** statements or unfinished tdsqlite3_backup objects then tdsqlite3_close() ** will leave the database connection open and return [SQLITE_BUSY]. -** ^If sqlite3_close_v2() is called with unfinalized prepared statements -** and/or unfinished sqlite3_backups, then the database connection becomes +** ^If tdsqlite3_close_v2() is called with unfinalized prepared statements +** and/or unfinished tdsqlite3_backups, then the database connection becomes ** an unusable "zombie" which will automatically be deallocated when the -** last prepared statement is finalized or the last sqlite3_backup is -** finished. The sqlite3_close_v2() interface is intended for use with +** last prepared statement is finalized or the last tdsqlite3_backup is +** finished. The tdsqlite3_close_v2() interface is intended for use with ** host languages that are garbage collected, and where the order in which ** destructors are called is arbitrary. ** -** Applications should [sqlite3_finalize | finalize] all [prepared statements], -** [sqlite3_blob_close | close] all [BLOB handles], and -** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated -** with the [sqlite3] object prior to attempting to close the object. ^If -** sqlite3_close_v2() is called on a [database connection] that still has +** Applications should [tdsqlite3_finalize | finalize] all [prepared statements], +** [tdsqlite3_blob_close | close] all [BLOB handles], and +** [tdsqlite3_backup_finish | finish] all [tdsqlite3_backup] objects associated +** with the [tdsqlite3] object prior to attempting to close the object. ^If +** tdsqlite3_close_v2() is called on a [database connection] that still has ** outstanding [prepared statements], [BLOB handles], and/or -** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation +** [tdsqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation ** of resources is deferred until all [prepared statements], [BLOB handles], -** and [sqlite3_backup] objects are also destroyed. +** and [tdsqlite3_backup] objects are also destroyed. ** -** ^If an [sqlite3] object is destroyed while a transaction is open, +** ^If an [tdsqlite3] object is destroyed while a transaction is open, ** the transaction is automatically rolled back. ** -** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] +** The C parameter to [tdsqlite3_close(C)] and [tdsqlite3_close_v2(C)] ** must be either a NULL -** pointer or an [sqlite3] object pointer obtained -** from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()], and not previously closed. -** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer +** pointer or an [tdsqlite3] object pointer obtained +** from [tdsqlite3_open()], [tdsqlite3_open16()], or +** [tdsqlite3_open_v2()], and not previously closed. +** ^Calling tdsqlite3_close() or tdsqlite3_close_v2() with a NULL pointer ** argument is a harmless no-op. */ -SQLITE_API int sqlite3_close(sqlite3*); -SQLITE_API int sqlite3_close_v2(sqlite3*); +SQLITE_API int tdsqlite3_close(tdsqlite3*); +SQLITE_API int tdsqlite3_close_v2(tdsqlite3*); /* ** The type for a callback function. ** This is legacy and deprecated. It is included for historical ** compatibility and is not documented. */ -typedef int (*sqlite3_callback)(void*,int,char**, char**); +typedef int (*tdsqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** The sqlite3_exec() interface is a convenience wrapper around -** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** The tdsqlite3_exec() interface is a convenience wrapper around +** [tdsqlite3_prepare_v2()], [tdsqlite3_step()], and [tdsqlite3_finalize()], ** that allows an application to run multiple statements of SQL ** without having to use a lot of C code. ** -** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** ^The tdsqlite3_exec() interface runs zero or more UTF-8 encoded, ** semicolon-separate SQL statements passed into its 2nd argument, ** in the context of the [database connection] passed in as its 1st ** argument. ^If the callback function of the 3rd argument to -** sqlite3_exec() is not NULL, then it is invoked for each result row +** tdsqlite3_exec() is not NULL, then it is invoked for each result row ** coming out of the evaluated SQL statements. ^The 4th argument to -** sqlite3_exec() is relayed through to the 1st argument of each -** callback invocation. ^If the callback pointer to sqlite3_exec() +** tdsqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to tdsqlite3_exec() ** is NULL, then no callback is ever invoked and result rows are ** ignored. ** ** ^If an error occurs while evaluating the SQL statements passed into -** sqlite3_exec(), then execution of the current statement stops and -** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** tdsqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to tdsqlite3_exec() ** is not NULL then any error message is written into memory obtained -** from [sqlite3_malloc()] and passed back through the 5th parameter. -** To avoid memory leaks, the application should invoke [sqlite3_free()] +** from [tdsqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [tdsqlite3_free()] ** on error message strings returned through the 5th parameter of -** sqlite3_exec() after the error message string is no longer needed. -** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors -** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** tdsqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to tdsqlite3_exec() is not NULL and no errors +** occur, then tdsqlite3_exec() sets the pointer in its 5th parameter to ** NULL before returning. ** -** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** ^If an tdsqlite3_exec() callback returns non-zero, the tdsqlite3_exec() ** routine returns SQLITE_ABORT without invoking the callback again and ** without running any subsequent SQL statements. ** -** ^The 2nd argument to the sqlite3_exec() callback function is the -** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** ^The 2nd argument to the tdsqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the tdsqlite3_exec() ** callback is an array of pointers to strings obtained as if from -** [sqlite3_column_text()], one for each column. ^If an element of a +** [tdsqlite3_column_text()], one for each column. ^If an element of a ** result row is NULL then the corresponding string pointer for the -** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the -** sqlite3_exec() callback is an array of pointers to strings where each +** tdsqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** tdsqlite3_exec() callback is an array of pointers to strings where each ** entry represents the name of corresponding result column as obtained -** from [sqlite3_column_name()]. +** from [tdsqlite3_column_name()]. ** -** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** ^If the 2nd parameter to tdsqlite3_exec() is a NULL pointer, a pointer ** to an empty string, or a pointer that contains only whitespace and/or ** SQL comments, then no SQL statements are evaluated and the database ** is not changed. @@ -644,16 +1437,16 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); ** Restrictions: ** ** <ul> -** <li> The application must ensure that the 1st parameter to sqlite3_exec() +** <li> The application must ensure that the 1st parameter to tdsqlite3_exec() ** is a valid and open [database connection]. ** <li> The application must not close the [database connection] specified by -** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +** the 1st parameter to tdsqlite3_exec() while tdsqlite3_exec() is running. ** <li> The application must not modify the SQL statement text passed into -** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +** the 2nd parameter of tdsqlite3_exec() while tdsqlite3_exec() is running. ** </ul> */ -SQLITE_API int sqlite3_exec( - sqlite3*, /* An open database */ +SQLITE_API int tdsqlite3_exec( + tdsqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ @@ -673,7 +1466,7 @@ SQLITE_API int sqlite3_exec( */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ -#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_ERROR 1 /* Generic error */ #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ #define SQLITE_PERM 3 /* Access permission denied */ #define SQLITE_ABORT 4 /* Callback routine requested an abort */ @@ -681,14 +1474,14 @@ SQLITE_API int sqlite3_exec( #define SQLITE_LOCKED 6 /* A table in the database is locked */ #define SQLITE_NOMEM 7 /* A malloc() failed */ #define SQLITE_READONLY 8 /* Attempt to write a readonly database */ -#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_INTERRUPT 9 /* Operation terminated by tdsqlite3_interrupt()*/ #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ #define SQLITE_CORRUPT 11 /* The database disk image is malformed */ -#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in tdsqlite3_file_control() */ #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ -#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_EMPTY 16 /* Internal use only */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ @@ -696,13 +1489,13 @@ SQLITE_API int sqlite3_exec( #define SQLITE_MISUSE 21 /* Library used incorrectly */ #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ #define SQLITE_AUTH 23 /* Authorization denied */ -#define SQLITE_FORMAT 24 /* Auxiliary database format error */ -#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_FORMAT 24 /* Not used */ +#define SQLITE_RANGE 25 /* 2nd parameter to tdsqlite3_bind out of range */ #define SQLITE_NOTADB 26 /* File opened that is not a database file */ -#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ -#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ -#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ -#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +#define SQLITE_NOTICE 27 /* Notifications from tdsqlite3_log() */ +#define SQLITE_WARNING 28 /* Warnings from tdsqlite3_log() */ +#define SQLITE_ROW 100 /* tdsqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* tdsqlite3_step() has finished executing */ /* end-of-error-codes */ /* @@ -718,10 +1511,13 @@ SQLITE_API int sqlite3_exec( ** support for additional result codes that provide more detailed information ** about errors. These [extended result codes] are enabled or disabled ** on a per database connection basis using the -** [sqlite3_extended_result_codes()] API. Or, the extended code for +** [tdsqlite3_extended_result_codes()] API. Or, the extended code for ** the most recent error can be obtained using -** [sqlite3_extended_errcode()]. +** [tdsqlite3_extended_errcode()]. */ +#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8)) +#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8)) +#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8)) #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) @@ -750,18 +1546,27 @@ SQLITE_API int sqlite3_exec( #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) +#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8)) +#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8)) +#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) +#define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */ +#define SQLITE_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8)) #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) +#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8)) #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8)) +#define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8)) +#define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8)) #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) @@ -773,27 +1578,29 @@ SQLITE_API int sqlite3_exec( #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) +#define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8)) #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) +#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* ** CAPI3REF: Flags For File Open Operations ** ** These bit values are intended for use in the -** 3rd parameter to the [sqlite3_open_v2()] interface and -** in the 4th parameter to the [sqlite3_vfs.xOpen] method. +** 3rd parameter to the [tdsqlite3_open_v2()] interface and +** in the 4th parameter to the [tdsqlite3_vfs.xOpen] method. */ -#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for tdsqlite3_open_v2() */ #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ -#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_URI 0x00000040 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for tdsqlite3_open_v2() */ #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ @@ -801,21 +1608,22 @@ SQLITE_API int sqlite3_exec( #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ -#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for tdsqlite3_open_v2() */ #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ +#define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for tdsqlite3_open_v2() */ /* Reserved: 0x00F00000 */ /* ** CAPI3REF: Device Characteristics ** -** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** The xDeviceCharacteristics method of the [tdsqlite3_io_methods] ** object returns an integer which is a vector of these ** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] +** device that holds the file that the [tdsqlite3_io_methods] ** refers to. ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of @@ -832,10 +1640,15 @@ SQLITE_API int sqlite3_exec( ** file that were written at the application level might have changed ** and that adjacent bytes, even bytes within the same sector are ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN -** flag indicate that a file cannot be deleted when open. The +** flag indicates that a file cannot be deleted when open. The ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on ** read-only media and cannot be changed even by processes with ** elevated privileges. +** +** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying +** filesystem supports doing multiple write operations atomically when those +** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and +** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. */ #define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC512 0x00000002 @@ -851,13 +1664,14 @@ SQLITE_API int sqlite3_exec( #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000 +#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000 /* ** CAPI3REF: File Locking Levels ** ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods -** of an [sqlite3_io_methods] object. +** of an [tdsqlite3_io_methods] object. */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 @@ -869,7 +1683,7 @@ SQLITE_API int sqlite3_exec( ** CAPI3REF: Synchronization Type Flags ** ** When SQLite invokes the xSync() method of an -** [sqlite3_io_methods] object it uses a combination of +** [tdsqlite3_io_methods] object it uses a combination of ** these integer values as the second argument. ** ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the @@ -898,33 +1712,33 @@ SQLITE_API int sqlite3_exec( /* ** CAPI3REF: OS Interface Open File Handle ** -** An [sqlite3_file] object represents an open file in the -** [sqlite3_vfs | OS interface layer]. Individual OS interface +** An [tdsqlite3_file] object represents an open file in the +** [tdsqlite3_vfs | OS interface layer]. Individual OS interface ** implementations will ** want to subclass this object by appending additional fields ** for their own use. The pMethods entry is a pointer to an -** [sqlite3_io_methods] object that defines methods for performing +** [tdsqlite3_io_methods] object that defines methods for performing ** I/O operations on the open file. */ -typedef struct sqlite3_file sqlite3_file; -struct sqlite3_file { - const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +typedef struct tdsqlite3_file tdsqlite3_file; +struct tdsqlite3_file { + const struct tdsqlite3_io_methods *pMethods; /* Methods for an open file */ }; /* ** CAPI3REF: OS Interface File Virtual Methods Object ** -** Every file opened by the [sqlite3_vfs.xOpen] method populates an -** [sqlite3_file] object (or, more commonly, a subclass of the -** [sqlite3_file] object) with a pointer to an instance of this object. +** Every file opened by the [tdsqlite3_vfs.xOpen] method populates an +** [tdsqlite3_file] object (or, more commonly, a subclass of the +** [tdsqlite3_file] object) with a pointer to an instance of this object. ** This object defines the methods used to perform various operations -** against the open file represented by the [sqlite3_file] object. +** against the open file represented by the [tdsqlite3_file] object. ** -** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element -** to a non-NULL pointer, then the sqlite3_io_methods.xClose method -** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The -** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] -** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element +** If the [tdsqlite3_vfs.xOpen] method sets the tdsqlite3_file.pMethods element +** to a non-NULL pointer, then the tdsqlite3_io_methods.xClose method +** may be invoked even if the [tdsqlite3_vfs.xOpen] reported that it failed. The +** only way to prevent a call to xClose following a failed [tdsqlite3_vfs.xOpen] +** is for the [tdsqlite3_vfs.xOpen] to set the tdsqlite3_file.pMethods element ** to NULL. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or @@ -949,7 +1763,7 @@ struct sqlite3_file { ** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the -** [sqlite3_file_control()] interface. The second "op" argument is an +** [tdsqlite3_file_control()] interface. The second "op" argument is an ** integer opcode. The third argument is a generic pointer intended to ** point to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be @@ -982,6 +1796,10 @@ struct sqlite3_file { ** <li> [SQLITE_IOCAP_ATOMIC64K] ** <li> [SQLITE_IOCAP_SAFE_APPEND] ** <li> [SQLITE_IOCAP_SEQUENTIAL] +** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN] +** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE] +** <li> [SQLITE_IOCAP_IMMUTABLE] +** <li> [SQLITE_IOCAP_BATCH_ATOMIC] ** </ul> ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of @@ -1001,29 +1819,29 @@ struct sqlite3_file { ** failure to zero-fill short reads will eventually lead to ** database corruption. */ -typedef struct sqlite3_io_methods sqlite3_io_methods; -struct sqlite3_io_methods { +typedef struct tdsqlite3_io_methods tdsqlite3_io_methods; +struct tdsqlite3_io_methods { int iVersion; - int (*xClose)(sqlite3_file*); - int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); - int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); - int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); - int (*xSync)(sqlite3_file*, int flags); - int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); - int (*xLock)(sqlite3_file*, int); - int (*xUnlock)(sqlite3_file*, int); - int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); - int (*xFileControl)(sqlite3_file*, int op, void *pArg); - int (*xSectorSize)(sqlite3_file*); - int (*xDeviceCharacteristics)(sqlite3_file*); + int (*xClose)(tdsqlite3_file*); + int (*xRead)(tdsqlite3_file*, void*, int iAmt, tdsqlite3_int64 iOfst); + int (*xWrite)(tdsqlite3_file*, const void*, int iAmt, tdsqlite3_int64 iOfst); + int (*xTruncate)(tdsqlite3_file*, tdsqlite3_int64 size); + int (*xSync)(tdsqlite3_file*, int flags); + int (*xFileSize)(tdsqlite3_file*, tdsqlite3_int64 *pSize); + int (*xLock)(tdsqlite3_file*, int); + int (*xUnlock)(tdsqlite3_file*, int); + int (*xCheckReservedLock)(tdsqlite3_file*, int *pResOut); + int (*xFileControl)(tdsqlite3_file*, int op, void *pArg); + int (*xSectorSize)(tdsqlite3_file*); + int (*xDeviceCharacteristics)(tdsqlite3_file*); /* Methods above are valid for version 1 */ - int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); - int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); - void (*xShmBarrier)(sqlite3_file*); - int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + int (*xShmMap)(tdsqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(tdsqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(tdsqlite3_file*); + int (*xShmUnmap)(tdsqlite3_file*, int deleteFlag); /* Methods above are valid for version 2 */ - int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); - int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); + int (*xFetch)(tdsqlite3_file*, tdsqlite3_int64 iOfst, int iAmt, void **pp); + int (*xUnfetch)(tdsqlite3_file*, tdsqlite3_int64 iOfst, void *p); /* Methods above are valid for version 3 */ /* Additional methods may be added in future releases */ }; @@ -1033,7 +1851,7 @@ struct sqlite3_io_methods { ** KEYWORDS: {file control opcodes} {file control opcode} ** ** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** of the [tdsqlite3_io_methods] object and for the [tdsqlite3_file_control()] ** interface. ** ** <ul> @@ -1054,10 +1872,19 @@ struct sqlite3_io_methods { ** file space based on this hint in order to help writes to the database ** file run faster. ** +** <li>[[SQLITE_FCNTL_SIZE_LIMIT]] +** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that +** implements [tdsqlite3_deserialize()] to set an upper bound on the size +** of the in-memory database. The argument is a pointer to a [tdsqlite3_int64]. +** If the integer pointed to is negative, then it is filled in with the +** current limit. Otherwise the limit is set to the larger of the value +** of the integer pointed to and the current database size. The integer +** pointed to is set to the new limit. +** ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]] ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS ** extends and truncates the database file in chunks of a size specified -** by the user. The fourth argument to [sqlite3_file_control()] should +** by the user. The fourth argument to [tdsqlite3_file_control()] should ** point to an integer (type int) containing the new chunk-size to use ** for the nominated database. Allocating database file space in large ** chunks (say 1MB at a time), may reduce file-system fragmentation and @@ -1065,12 +1892,12 @@ struct sqlite3_io_methods { ** ** <li>[[SQLITE_FCNTL_FILE_POINTER]] ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer -** to the [sqlite3_file] object associated with a particular database +** to the [tdsqlite3_file] object associated with a particular database ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. ** ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]] ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer -** to the [sqlite3_file] object associated with the journal file (either +** to the [tdsqlite3_file] object associated with the journal file (either ** the [rollback journal] or the [write-ahead log]) for a particular database ** connection. See also [SQLITE_FCNTL_FILE_POINTER]. ** @@ -1088,7 +1915,7 @@ struct sqlite3_io_methods { ** as part of a multi-database commit, the argument points to a nul-terminated ** string containing the transactions master-journal file name. VFSes that ** do not need this signal should silently ignore this opcode. Applications -** should not call [sqlite3_file_control()] with this opcode as doing so may +** should not call [tdsqlite3_file_control()] with this opcode as doing so may ** disrupt the operation of the specialized VFSes that do require it. ** ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]] @@ -1096,7 +1923,7 @@ struct sqlite3_io_methods { ** and sent to the VFS after a transaction has been committed immediately ** but before the database is unlocked. VFSes that do not need this signal ** should silently ignore this opcode. Applications should not call -** [sqlite3_file_control()] with this opcode as doing so may disrupt the +** [tdsqlite3_file_control()] with this opcode as doing so may disrupt the ** operation of the specialized VFSes that do require it. ** ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]] @@ -1110,7 +1937,7 @@ struct sqlite3_io_methods { ** opcode allows these two values (10 retries and 25 milliseconds of delay) ** to be adjusted. The values are changed for all database connections ** within the same process. The argument is a pointer to an array of two -** integers where the first integer i the new retry count and the second +** integers where the first integer is the new retry count and the second ** integer is the delay. If either integer is negative, then the setting ** is not changed but instead the prior value of that setting is written ** into the array entry, allowing the current retry settings to be @@ -1119,14 +1946,15 @@ struct sqlite3_io_methods { ** <li>[[SQLITE_FCNTL_PERSIST_WAL]] ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary -** write ahead log and shared memory files used for transaction control +** write ahead log ([WAL file]) and shared memory +** files used for transaction control ** are automatically deleted when the latest connection to the database ** closes. Setting persistent WAL mode causes those files to persist after ** close. Persisting the files is useful when other processes that do not ** have write permission on the directory containing the database file want ** to read the database file, as the WAL and shared memory files must exist ** in order for the database to be readable. The fourth parameter to -** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** [tdsqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent ** WAL mode. If the integer is -1, then it is overwritten with the current ** WAL persistence setting. @@ -1136,7 +1964,7 @@ struct sqlite3_io_methods { ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the ** xDeviceCharacteristics methods. The fourth parameter to -** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** [tdsqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage ** mode. If the integer is -1, then it is overwritten with the current ** zero-damage mode setting. @@ -1151,8 +1979,8 @@ struct sqlite3_io_methods { ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of ** all [VFSes] in the VFS stack. The names are of all VFS shims and the ** final bottom-level VFS are written into memory obtained from -** [sqlite3_malloc()] and the result is stored in the char* variable -** that the fourth parameter of [sqlite3_file_control()] points to. +** [tdsqlite3_malloc()] and the result is stored in the char* variable +** that the fourth parameter of [tdsqlite3_file_control()] points to. ** The caller is responsible for freeing the memory when done. As with ** all file-control actions, there is no guarantee that this will actually ** do anything. Callers should initialize the char* variable to a NULL @@ -1162,22 +1990,22 @@ struct sqlite3_io_methods { ** <li>[[SQLITE_FCNTL_VFS_POINTER]] ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level ** [VFSes] currently in use. ^(The argument X in -** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be -** of type "[sqlite3_vfs] **". This opcodes will set *X +** tdsqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be +** of type "[tdsqlite3_vfs] **". This opcodes will set *X ** to a pointer to the top-level VFS.)^ ** ^When there are multiple VFS shims in the stack, this opcode finds the ** upper-most shim only. ** ** <li>[[SQLITE_FCNTL_PRAGMA]] ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] -** file control is sent to the open [sqlite3_file] object corresponding +** file control is sent to the open [tdsqlite3_file] object corresponding ** to the database file to which the pragma statement refers. ^The argument ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of ** pointers to strings (char**) in which the second element of the array ** is the name of the pragma and the third element is the argument to the ** pragma or NULL if the pragma has no argument. ^The handler for an ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element -** of the char** argument point to a string obtained from [sqlite3_mprintf()] +** of the char** argument point to a string obtained from [tdsqlite3_mprintf()] ** or the equivalent and that string will become the result of the pragma or ** the error message if the pragma fails. ^If the ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal @@ -1197,27 +2025,27 @@ struct sqlite3_io_methods { ** ^The [SQLITE_FCNTL_BUSYHANDLER] ** file-control may be invoked by SQLite on the database file handle ** shortly after it is opened in order to provide a custom VFS with access -** to the connections busy-handler callback. The argument is of type (void **) +** to the connection's busy-handler callback. The argument is of type (void**) ** - an array of two (void *) values. The first (void *) actually points -** to a function of type (int (*)(void *)). In order to invoke the connections +** to a function of type (int (*)(void *)). In order to invoke the connection's ** busy-handler, this function should be invoked with the second (void *) in ** the array as the only argument. If it returns non-zero, then the operation ** should be retried. If it returns zero, the custom VFS should abandon the ** current operation. ** ** <li>[[SQLITE_FCNTL_TEMPFILENAME]] -** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control +** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control ** to have SQLite generate a ** temporary filename using the same algorithm that is followed to generate ** temporary filenames for TEMP tables and other internal uses. The ** argument should be a char** which will be filled with the filename -** written into memory obtained from [sqlite3_malloc()]. The caller should -** invoke [sqlite3_free()] on the result to avoid a memory leak. +** written into memory obtained from [tdsqlite3_malloc()]. The caller should +** invoke [tdsqlite3_free()] on the result to avoid a memory leak. ** ** <li>[[SQLITE_FCNTL_MMAP_SIZE]] ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the ** maximum number of bytes that will be used for memory-mapped I/O. -** The argument is a pointer to a value of type sqlite3_int64 that +** The argument is a pointer to a value of type tdsqlite3_int64 that ** is an advisory maximum number of bytes in the file to memory map. The ** pointer is overwritten with the old value. The limit is not changed if ** the value originally pointed to is negative, and so the current limit @@ -1265,6 +2093,72 @@ struct sqlite3_io_methods { ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for ** this opcode. +** +** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]] +** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then +** the file descriptor is placed in "batch write mode", which +** means all subsequent write operations will be deferred and done +** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems +** that do not support batch atomic writes will return SQLITE_NOTFOUND. +** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to +** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or +** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make +** no VFS interface calls on the same [tdsqlite3_file] file descriptor +** except for calls to the xWrite method and the xFileControl method +** with [SQLITE_FCNTL_SIZE_HINT]. +** +** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]] +** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write +** operations since the previous successful call to +** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically. +** This file control returns [SQLITE_OK] if and only if the writes were +** all performed successfully and have been committed to persistent storage. +** ^Regardless of whether or not it is successful, this file control takes +** the file descriptor out of batch write mode so that all subsequent +** write operations are independent. +** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without +** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. +** +** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]] +** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write +** operations since the previous successful call to +** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back. +** ^This file control takes the file descriptor out of batch write mode +** so that all subsequent write operations are independent. +** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without +** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. +** +** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]] +** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain +** a file lock using the xLock or xShmLock methods of the VFS to wait +** for up to M milliseconds before failing, where M is the single +** unsigned integer parameter. +** +** <li>[[SQLITE_FCNTL_DATA_VERSION]] +** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to +** a database file. The argument is a pointer to a 32-bit unsigned integer. +** The "data version" for the pager is written into the pointer. The +** "data version" changes whenever any change occurs to the corresponding +** database file, either through SQL statements on the same database +** connection or through transactions committed by separate database +** connections possibly in other processes. The [tdsqlite3_total_changes()] +** interface can be used to find if any database on the connection has changed, +** but that interface responds to changes on TEMP as well as MAIN and does +** not provide a mechanism to detect changes to MAIN only. Also, the +** [tdsqlite3_total_changes()] interface responds to internal changes only and +** omits changes made by other database connections. The +** [PRAGMA data_version] command provides a mechanism to detect changes to +** a single attached database that occur due to other database connections, +** but omits changes implemented by the database connection on which it is +** called. This file control is the only mechanism to detect changes that +** happen either internally or externally and that are associated with +** a particular attached database. +** +** <li>[[SQLITE_FCNTL_CKPT_DONE]] +** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint +** in wal mode after the client has finished copying pages from the wal +** file to the database file, but before the *-shm file is updated to +** record the fact that the pages have been checkpointed. ** </ul> */ #define SQLITE_FCNTL_LOCKSTATE 1 @@ -1295,6 +2189,14 @@ struct sqlite3_io_methods { #define SQLITE_FCNTL_VFS_POINTER 27 #define SQLITE_FCNTL_JOURNAL_POINTER 28 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29 +#define SQLITE_FCNTL_PDB 30 +#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31 +#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32 +#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33 +#define SQLITE_FCNTL_LOCK_TIMEOUT 34 +#define SQLITE_FCNTL_DATA_VERSION 35 +#define SQLITE_FCNTL_SIZE_LIMIT 36 +#define SQLITE_FCNTL_CKPT_DONE 37 /* deprecated names */ #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE @@ -1305,61 +2207,67 @@ struct sqlite3_io_methods { /* ** CAPI3REF: Mutex Handle ** -** The mutex module within SQLite defines [sqlite3_mutex] to be an +** The mutex module within SQLite defines [tdsqlite3_mutex] to be an ** abstract type for a mutex object. The SQLite core never looks -** at the internal representation of an [sqlite3_mutex]. It only -** deals with pointers to the [sqlite3_mutex] object. +** at the internal representation of an [tdsqlite3_mutex]. It only +** deals with pointers to the [tdsqlite3_mutex] object. ** -** Mutexes are created using [sqlite3_mutex_alloc()]. +** Mutexes are created using [tdsqlite3_mutex_alloc()]. */ -typedef struct sqlite3_mutex sqlite3_mutex; +typedef struct tdsqlite3_mutex tdsqlite3_mutex; /* ** CAPI3REF: Loadable Extension Thunk ** -** A pointer to the opaque sqlite3_api_routines structure is passed as +** A pointer to the opaque tdsqlite3_api_routines structure is passed as ** the third parameter to entry points of [loadable extensions]. This ** structure must be typedefed in order to work around compiler warnings ** on some platforms. */ -typedef struct sqlite3_api_routines sqlite3_api_routines; +typedef struct tdsqlite3_api_routines tdsqlite3_api_routines; /* ** CAPI3REF: OS Interface Object ** -** An instance of the sqlite3_vfs object defines the interface between +** An instance of the tdsqlite3_vfs object defines the interface between ** the SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". See ** the [VFS | VFS documentation] for further information. ** -** The value of the iVersion field is initially 1 but may be larger in -** future versions of SQLite. Additional fields may be appended to this -** object when the iVersion value is increased. Note that the structure -** of the sqlite3_vfs object changes in the transaction between -** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not -** modified. -** -** The szOsFile field is the size of the subclassed [sqlite3_file] +** The VFS interface is sometimes extended by adding new methods onto +** the end. Each time such an extension occurs, the iVersion field +** is incremented. The iVersion value started out as 1 in +** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2 +** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased +** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields +** may be appended to the tdsqlite3_vfs object and the iVersion value +** may increase again in future versions of SQLite. +** Note that due to an oversight, the structure +** of the tdsqlite3_vfs object changed in the transition from +** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0] +** and yet the iVersion field was not increased. +** +** The szOsFile field is the size of the subclassed [tdsqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** -** Registered sqlite3_vfs objects are kept on a linked list formed by -** the pNext pointer. The [sqlite3_vfs_register()] -** and [sqlite3_vfs_unregister()] interfaces manage this list -** in a thread-safe way. The [sqlite3_vfs_find()] interface +** Registered tdsqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [tdsqlite3_vfs_register()] +** and [tdsqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [tdsqlite3_vfs_find()] interface ** searches the list. Neither the application code nor the VFS ** implementation should use the pNext pointer. ** -** The pNext field is the only field in the sqlite3_vfs +** The pNext field is the only field in the tdsqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. -** The application should never modify anything within the sqlite3_vfs +** The application should never modify anything within the tdsqlite3_vfs ** object once the object has been registered. ** ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** -** [[sqlite3_vfs.xOpen]] +** [[tdsqlite3_vfs.xOpen]] ** ^SQLite guarantees that the zFilename parameter to xOpen ** is either a NULL pointer or string obtained ** from xFullPathname() with an optional suffix added. @@ -1369,7 +2277,7 @@ typedef struct sqlite3_api_routines sqlite3_api_routines; ** ^SQLite further guarantees that ** the string will be valid and unchanged until xClose() is ** called. Because of the previous sentence, -** the [sqlite3_file] can safely store a pointer to the +** the [tdsqlite3_file] can safely store a pointer to the ** filename if it needs to remember the filename for some reason. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen ** must invent its own temporary name for the file. ^Whenever the @@ -1377,8 +2285,8 @@ typedef struct sqlite3_api_routines sqlite3_api_routines; ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** The flags argument to xOpen() includes all bits set in -** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] -** or [sqlite3_open16()] is used, then flags includes at least +** the flags argument to [tdsqlite3_open_v2()]. Or if [tdsqlite3_open()] +** or [tdsqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. ** If xOpen() opens a file read-only then it sets *pOutFlags to ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. @@ -1428,21 +2336,27 @@ typedef struct sqlite3_api_routines sqlite3_api_routines; ** for exclusive access. ** ** ^At least szOsFile bytes of memory are allocated by SQLite -** to hold the [sqlite3_file] structure passed as the third +** to hold the [tdsqlite3_file] structure passed as the third ** argument to xOpen. The xOpen method does not have to ** allocate the structure; it should just fill it in. Note that -** the xOpen method must set the sqlite3_file.pMethods to either -** a valid [sqlite3_io_methods] object or to NULL. xOpen must do -** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** the xOpen method must set the tdsqlite3_file.pMethods to either +** a valid [tdsqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the tdsqlite3_file.pMethods ** element will be valid after xOpen returns regardless of the success ** or failure of the xOpen call. ** -** [[sqlite3_vfs.xAccess]] +** [[tdsqlite3_vfs.xAccess]] ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] -** to test whether a file is at least readable. The file can be a -** directory. +** to test whether a file is at least readable. The SQLITE_ACCESS_READ +** flag is never actually used and is not implemented in the built-in +** VFSes of SQLite. The file is named by the second argument and can be a +** directory. The xAccess method returns [SQLITE_OK] on success or some +** non-zero error code if there is an I/O error or if the name of +** the file given in the second argument is illegal. If SQLITE_OK +** is returned, then non-zero or zero is written into *pResOut to indicate +** whether or not the file is accessible. ** ** ^SQLite will always allocate at least mxPathname+1 bytes for the ** output buffer xFullPathname. The exact size of the output buffer @@ -1481,40 +2395,40 @@ typedef struct sqlite3_api_routines sqlite3_api_routines; ** from one release to the next. Applications must not attempt to access ** any of these methods if the iVersion of the VFS is less than 3. */ -typedef struct sqlite3_vfs sqlite3_vfs; -typedef void (*sqlite3_syscall_ptr)(void); -struct sqlite3_vfs { +typedef struct tdsqlite3_vfs tdsqlite3_vfs; +typedef void (*tdsqlite3_syscall_ptr)(void); +struct tdsqlite3_vfs { int iVersion; /* Structure version number (currently 3) */ - int szOsFile; /* Size of subclassed sqlite3_file */ + int szOsFile; /* Size of subclassed tdsqlite3_file */ int mxPathname; /* Maximum file pathname length */ - sqlite3_vfs *pNext; /* Next registered VFS */ + tdsqlite3_vfs *pNext; /* Next registered VFS */ const char *zName; /* Name of this virtual file system */ void *pAppData; /* Pointer to application-specific data */ - int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int (*xOpen)(tdsqlite3_vfs*, const char *zName, tdsqlite3_file*, int flags, int *pOutFlags); - int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); - int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); - int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); - void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); - void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); - void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); - void (*xDlClose)(sqlite3_vfs*, void*); - int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); - int (*xSleep)(sqlite3_vfs*, int microseconds); - int (*xCurrentTime)(sqlite3_vfs*, double*); - int (*xGetLastError)(sqlite3_vfs*, int, char *); + int (*xDelete)(tdsqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(tdsqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(tdsqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(tdsqlite3_vfs*, const char *zFilename); + void (*xDlError)(tdsqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(tdsqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(tdsqlite3_vfs*, void*); + int (*xRandomness)(tdsqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(tdsqlite3_vfs*, int microseconds); + int (*xCurrentTime)(tdsqlite3_vfs*, double*); + int (*xGetLastError)(tdsqlite3_vfs*, int, char *); /* ** The methods above are in version 1 of the sqlite_vfs object ** definition. Those that follow are added in version 2 or later */ - int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + int (*xCurrentTimeInt64)(tdsqlite3_vfs*, tdsqlite3_int64*); /* ** The methods above are in versions 1 and 2 of the sqlite_vfs object. ** Those below are for version 3 and greater. */ - int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); - sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); - const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); + int (*xSetSystemCall)(tdsqlite3_vfs*, const char *zName, tdsqlite3_syscall_ptr); + tdsqlite3_syscall_ptr (*xGetSystemCall)(tdsqlite3_vfs*, const char *zName); + const char *(*xNextSystemCall)(tdsqlite3_vfs*, const char *zName); /* ** The methods above are in versions 1 through 3 of the sqlite_vfs object. ** New fields may be appended in future versions. The iVersion @@ -1526,7 +2440,7 @@ struct sqlite3_vfs { ** CAPI3REF: Flags for the xAccess VFS method ** ** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine +** the xAccess method of an [tdsqlite3_vfs] object. They determine ** what kind of permissions the xAccess method is looking for. ** With SQLITE_ACCESS_EXISTS, the xAccess method ** simply checks whether the file exists. @@ -1550,7 +2464,7 @@ struct sqlite3_vfs { ** CAPI3REF: Flags for the xShmLock VFS method ** ** These integer constants define the various locking operations -** allowed by the xShmLock method of [sqlite3_io_methods]. The +** allowed by the xShmLock method of [tdsqlite3_io_methods]. The ** following are the only legal combinations of flags to the ** xShmLock method: ** @@ -1576,7 +2490,7 @@ struct sqlite3_vfs { /* ** CAPI3REF: Maximum xShmLock index ** -** The xShmLock method on [sqlite3_io_methods] may use values +** The xShmLock method on [tdsqlite3_io_methods] may use values ** between 0 and this upper bound as its "offset" argument. ** The SQLite core will never attempt to acquire or release a ** lock outside of this range @@ -1587,134 +2501,134 @@ struct sqlite3_vfs { /* ** CAPI3REF: Initialize The SQLite Library ** -** ^The sqlite3_initialize() routine initializes the -** SQLite library. ^The sqlite3_shutdown() routine -** deallocates any resources that were allocated by sqlite3_initialize(). +** ^The tdsqlite3_initialize() routine initializes the +** SQLite library. ^The tdsqlite3_shutdown() routine +** deallocates any resources that were allocated by tdsqlite3_initialize(). ** These routines are designed to aid in process initialization and ** shutdown on embedded systems. Workstation applications using ** SQLite normally do not need to invoke either of these routines. ** -** A call to sqlite3_initialize() is an "effective" call if it is -** the first time sqlite3_initialize() is invoked during the lifetime of -** the process, or if it is the first time sqlite3_initialize() is invoked -** following a call to sqlite3_shutdown(). ^(Only an effective call -** of sqlite3_initialize() does any initialization. All other calls +** A call to tdsqlite3_initialize() is an "effective" call if it is +** the first time tdsqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time tdsqlite3_initialize() is invoked +** following a call to tdsqlite3_shutdown(). ^(Only an effective call +** of tdsqlite3_initialize() does any initialization. All other calls ** are harmless no-ops.)^ ** -** A call to sqlite3_shutdown() is an "effective" call if it is the first -** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only -** an effective call to sqlite3_shutdown() does any deinitialization. -** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** A call to tdsqlite3_shutdown() is an "effective" call if it is the first +** call to tdsqlite3_shutdown() since the last tdsqlite3_initialize(). ^(Only +** an effective call to tdsqlite3_shutdown() does any deinitialization. +** All other valid calls to tdsqlite3_shutdown() are harmless no-ops.)^ ** -** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() -** is not. The sqlite3_shutdown() interface must only be called from a +** The tdsqlite3_initialize() interface is threadsafe, but tdsqlite3_shutdown() +** is not. The tdsqlite3_shutdown() interface must only be called from a ** single thread. All open [database connections] must be closed and all ** other SQLite resources must be deallocated prior to invoking -** sqlite3_shutdown(). +** tdsqlite3_shutdown(). ** -** Among other things, ^sqlite3_initialize() will invoke -** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() -** will invoke sqlite3_os_end(). +** Among other things, ^tdsqlite3_initialize() will invoke +** tdsqlite3_os_init(). Similarly, ^tdsqlite3_shutdown() +** will invoke tdsqlite3_os_end(). ** -** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. -** ^If for some reason, sqlite3_initialize() is unable to initialize +** ^The tdsqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, tdsqlite3_initialize() is unable to initialize ** the library (perhaps it is unable to allocate a needed resource such ** as a mutex) it returns an [error code] other than [SQLITE_OK]. ** -** ^The sqlite3_initialize() routine is called internally by many other +** ^The tdsqlite3_initialize() routine is called internally by many other ** SQLite interfaces so that an application usually does not need to -** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] -** calls sqlite3_initialize() so the SQLite library will be automatically -** initialized when [sqlite3_open()] is called if it has not be initialized +** invoke tdsqlite3_initialize() directly. For example, [tdsqlite3_open()] +** calls tdsqlite3_initialize() so the SQLite library will be automatically +** initialized when [tdsqlite3_open()] is called if it has not be initialized ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] -** compile-time option, then the automatic calls to sqlite3_initialize() -** are omitted and the application must call sqlite3_initialize() directly +** compile-time option, then the automatic calls to tdsqlite3_initialize() +** are omitted and the application must call tdsqlite3_initialize() directly ** prior to using any other SQLite interface. For maximum portability, -** it is recommended that applications always invoke sqlite3_initialize() +** it is recommended that applications always invoke tdsqlite3_initialize() ** directly prior to using any other SQLite interface. Future releases ** of SQLite may require this. In other words, the behavior exhibited ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the ** default behavior in some future release of SQLite. ** -** The sqlite3_os_init() routine does operating-system specific -** initialization of the SQLite library. The sqlite3_os_end() -** routine undoes the effect of sqlite3_os_init(). Typical tasks +** The tdsqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The tdsqlite3_os_end() +** routine undoes the effect of tdsqlite3_os_init(). Typical tasks ** performed by these routines include allocation or deallocation ** of static resources, initialization of global variables, -** setting up a default [sqlite3_vfs] module, or setting up -** a default configuration using [sqlite3_config()]. -** -** The application should never invoke either sqlite3_os_init() -** or sqlite3_os_end() directly. The application should only invoke -** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() -** interface is called automatically by sqlite3_initialize() and -** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate -** implementations for sqlite3_os_init() and sqlite3_os_end() +** setting up a default [tdsqlite3_vfs] module, or setting up +** a default configuration using [tdsqlite3_config()]. +** +** The application should never invoke either tdsqlite3_os_init() +** or tdsqlite3_os_end() directly. The application should only invoke +** tdsqlite3_initialize() and tdsqlite3_shutdown(). The tdsqlite3_os_init() +** interface is called automatically by tdsqlite3_initialize() and +** tdsqlite3_os_end() is called by tdsqlite3_shutdown(). Appropriate +** implementations for tdsqlite3_os_init() and tdsqlite3_os_end() ** are built into SQLite when it is compiled for Unix, Windows, or OS/2. ** When [custom builds | built for other platforms] ** (using the [SQLITE_OS_OTHER=1] compile-time ** option) the application must supply a suitable implementation for -** sqlite3_os_init() and sqlite3_os_end(). An application-supplied -** implementation of sqlite3_os_init() or sqlite3_os_end() +** tdsqlite3_os_init() and tdsqlite3_os_end(). An application-supplied +** implementation of tdsqlite3_os_init() or tdsqlite3_os_end() ** must return [SQLITE_OK] on success and some other [error code] upon ** failure. */ -SQLITE_API int sqlite3_initialize(void); -SQLITE_API int sqlite3_shutdown(void); -SQLITE_API int sqlite3_os_init(void); -SQLITE_API int sqlite3_os_end(void); +SQLITE_API int tdsqlite3_initialize(void); +SQLITE_API int tdsqlite3_shutdown(void); +SQLITE_API int tdsqlite3_os_init(void); +SQLITE_API int tdsqlite3_os_end(void); /* ** CAPI3REF: Configuring The SQLite Library ** -** The sqlite3_config() interface is used to make global configuration +** The tdsqlite3_config() interface is used to make global configuration ** changes to SQLite in order to tune SQLite to the specific needs of ** the application. The default configuration is recommended for most ** applications and so this routine is usually not necessary. It is ** provided to support rare applications with unusual needs. ** -** <b>The sqlite3_config() interface is not threadsafe. The application +** <b>The tdsqlite3_config() interface is not threadsafe. The application ** must ensure that no other SQLite interfaces are invoked by other -** threads while sqlite3_config() is running.</b> +** threads while tdsqlite3_config() is running.</b> ** -** The sqlite3_config() interface +** The tdsqlite3_config() interface ** may only be invoked prior to library initialization using -** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. -** ^If sqlite3_config() is called after [sqlite3_initialize()] and before -** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. -** Note, however, that ^sqlite3_config() can be called as part of the -** implementation of an application-defined [sqlite3_os_init()]. +** [tdsqlite3_initialize()] or after shutdown by [tdsqlite3_shutdown()]. +** ^If tdsqlite3_config() is called after [tdsqlite3_initialize()] and before +** [tdsqlite3_shutdown()] then it will return SQLITE_MISUSE. +** Note, however, that ^tdsqlite3_config() can be called as part of the +** implementation of an application-defined [tdsqlite3_os_init()]. ** -** The first argument to sqlite3_config() is an integer +** The first argument to tdsqlite3_config() is an integer ** [configuration option] that determines ** what property of SQLite is to be configured. Subsequent arguments ** vary depending on the [configuration option] ** in the first argument. ** -** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^When a configuration option is set, tdsqlite3_config() returns [SQLITE_OK]. ** ^If the option is unknown or SQLite is unable to set the option ** then this routine returns a non-zero [error code]. */ -SQLITE_API int sqlite3_config(int, ...); +SQLITE_API int tdsqlite3_config(int, ...); /* ** CAPI3REF: Configure database connections -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** The sqlite3_db_config() interface is used to make configuration +** The tdsqlite3_db_config() interface is used to make configuration ** changes to a [database connection]. The interface is similar to -** [sqlite3_config()] except that the changes apply to a single +** [tdsqlite3_config()] except that the changes apply to a single ** [database connection] (specified in the first argument). ** -** The second argument to sqlite3_db_config(D,V,...) is the +** The second argument to tdsqlite3_db_config(D,V,...) is the ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code ** that indicates what aspect of the [database connection] is being configured. ** Subsequent arguments vary depending on the configuration verb. ** -** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** ^Calls to tdsqlite3_db_config() return SQLITE_OK if and only if ** the call is considered successful. */ -SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); +SQLITE_API int tdsqlite3_db_config(tdsqlite3*, int op, ...); /* ** CAPI3REF: Memory Allocation Routines @@ -1724,10 +2638,10 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); ** ** This object is used in only one place in the SQLite interface. ** A pointer to an instance of this object is the argument to -** [sqlite3_config()] when the configuration option is +** [tdsqlite3_config()] when the configuration option is ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. ** By creating an instance of this object -** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** and passing it to [tdsqlite3_config]([SQLITE_CONFIG_MALLOC]) ** during configuration, an application can specify an alternative ** memory allocation subsystem for SQLite to use for all of its ** dynamic memory needs. @@ -1754,20 +2668,20 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); ** a memory allocation given a particular requested size. Most memory ** allocators round up memory allocations at least to the next multiple ** of 8. Some allocators round up to a larger multiple or to a power of 2. -** Every memory allocation request coming in through [sqlite3_malloc()] -** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** Every memory allocation request coming in through [tdsqlite3_malloc()] +** or [tdsqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, ** that causes the corresponding memory allocation to fail. ** ** The xInit method initializes the memory allocator. For example, -** it might allocate any require mutexes or initialize internal data +** it might allocate any required mutexes or initialize internal data ** structures. The xShutdown method is invoked (indirectly) by -** [sqlite3_shutdown()] and should deallocate any resources acquired +** [tdsqlite3_shutdown()] and should deallocate any resources acquired ** by xInit. The pAppData pointer is used as the only parameter to ** xInit and xShutdown. ** ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes ** the xInit method, so the xInit method need not be threadsafe. The -** xShutdown method is only called from [sqlite3_shutdown()] so it does +** xShutdown method is only called from [tdsqlite3_shutdown()] so it does ** not need to be threadsafe either. For all other methods, SQLite ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which @@ -1779,8 +2693,8 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); ** SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). */ -typedef struct sqlite3_mem_methods sqlite3_mem_methods; -struct sqlite3_mem_methods { +typedef struct tdsqlite3_mem_methods tdsqlite3_mem_methods; +struct tdsqlite3_mem_methods { void *(*xMalloc)(int); /* Memory allocation function */ void (*xFree)(void*); /* Free a prior allocation */ void *(*xRealloc)(void*,int); /* Resize an allocation */ @@ -1796,12 +2710,12 @@ struct sqlite3_mem_methods { ** KEYWORDS: {configuration option} ** ** These constants are the available integer configuration options that -** can be passed as the first argument to the [sqlite3_config()] interface. +** can be passed as the first argument to the [tdsqlite3_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_config()] to make sure that -** the call worked. The [sqlite3_config()] interface will return a +** should check the return code from [tdsqlite3_config()] to make sure that +** the call worked. The [tdsqlite3_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** @@ -1813,7 +2727,7 @@ struct sqlite3_mem_methods { ** by a single thread. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to change the [threading mode] from its default -** value of Single-thread and so [sqlite3_config()] will return +** value of Single-thread and so [tdsqlite3_config()] will return ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD ** configuration option.</dd> ** @@ -1828,7 +2742,7 @@ struct sqlite3_mem_methods { ** [database connection] at the same time. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Multi-thread [threading mode] and -** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** [tdsqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd> ** ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt> @@ -1844,37 +2758,48 @@ struct sqlite3_mem_methods { ** ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Serialized [threading mode] and -** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** [tdsqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_SERIALIZED configuration option.</dd> ** ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt> ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is -** a pointer to an instance of the [sqlite3_mem_methods] structure. +** a pointer to an instance of the [tdsqlite3_mem_methods] structure. ** The argument specifies ** alternative low-level memory allocation routines to be used in place of ** the memory allocation routines built into SQLite.)^ ^SQLite makes -** its own private copy of the content of the [sqlite3_mem_methods] structure -** before the [sqlite3_config()] call returns.</dd> +** its own private copy of the content of the [tdsqlite3_mem_methods] structure +** before the [tdsqlite3_config()] call returns.</dd> ** ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt> ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which -** is a pointer to an instance of the [sqlite3_mem_methods] structure. -** The [sqlite3_mem_methods] +** is a pointer to an instance of the [tdsqlite3_mem_methods] structure. +** The [tdsqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines.)^ ** This option can be used to overload the default memory allocation ** routines with a wrapper that simulations memory allocation failure or ** tracks memory usage, for example. </dd> ** +** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt> +** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of +** type int, interpreted as a boolean, which if true provides a hint to +** SQLite that it should avoid large memory allocations if possible. +** SQLite will run faster if it is free to make large memory allocations, +** but some application might prefer to run slower in exchange for +** guarantees about memory fragmentation that are possible if large +** allocations are avoided. This hint is normally off. +** </dd> +** ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt> ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, ** interpreted as a boolean, which enables or disables the collection of ** memory allocation statistics. ^(When memory allocation statistics are ** disabled, the following SQLite interfaces become non-operational: ** <ul> -** <li> [sqlite3_memory_used()] -** <li> [sqlite3_memory_highwater()] -** <li> [sqlite3_soft_heap_limit64()] -** <li> [sqlite3_status64()] +** <li> [tdsqlite3_hard_heap_limit64()] +** <li> [tdsqlite3_memory_used()] +** <li> [tdsqlite3_memory_highwater()] +** <li> [tdsqlite3_soft_heap_limit64()] +** <li> [tdsqlite3_status64()] ** </ul>)^ ** ^Memory allocation statistics are enabled by default unless SQLite is ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory @@ -1882,32 +2807,14 @@ struct sqlite3_mem_methods { ** </dd> ** ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt> -** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer -** that SQLite can use for scratch memory. ^(There are three arguments -** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte -** aligned memory buffer from which the scratch allocations will be -** drawn, the size of each scratch allocation (sz), -** and the maximum number of scratch allocations (N).)^ -** The first argument must be a pointer to an 8-byte aligned buffer -** of at least sz*N bytes of memory. -** ^SQLite will not use more than one scratch buffers per thread. -** ^SQLite will never request a scratch buffer that is more than 6 -** times the database page size. -** ^If SQLite needs needs additional -** scratch memory beyond what is provided by this configuration option, then -** [sqlite3_malloc()] will be used to obtain the memory needed.<p> -** ^When the application provides any amount of scratch memory using -** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large -** [sqlite3_malloc|heap allocations]. -** This can help [Robson proof|prevent memory allocation failures] due to heap -** fragmentation in low-memory embedded systems. +** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used. ** </dd> ** ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt> ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool ** that SQLite can use for the database page cache with the default page ** cache implementation. -** This configuration option is a no-op if an application-define page +** This configuration option is a no-op if an application-defined page ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to ** 8-byte aligned memory (pMem), the size of each page cache line (sz), @@ -1922,22 +2829,21 @@ struct sqlite3_mem_methods { ** aligned block of memory of at least sz*N bytes, otherwise ** subsequent behavior is undefined. ** ^When pMem is not NULL, SQLite will strive to use the memory provided -** to satisfy page cache needs, falling back to [sqlite3_malloc()] if +** to satisfy page cache needs, falling back to [tdsqlite3_malloc()] if ** a page cache line is larger than sz bytes or if all of the pMem buffer ** is exhausted. ** ^If pMem is NULL and N is non-zero, then each database connection ** does an initial bulk allocation for page cache memory -** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or +** from [tdsqlite3_malloc()] sufficient for N cache lines if N is positive or ** of -1024*N bytes if N is negative, . ^If additional ** page cache memory is needed beyond what is provided by the initial -** allocation, then SQLite goes to [sqlite3_malloc()] separately for each +** allocation, then SQLite goes to [tdsqlite3_malloc()] separately for each ** additional cache line. </dd> ** ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt> ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer ** that SQLite will use for all of its dynamic memory allocation needs -** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and -** [SQLITE_CONFIG_PAGECACHE]. +** beyond those provided for by [SQLITE_CONFIG_PAGECACHE]. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns ** [SQLITE_ERROR] if invoked otherwise. @@ -1956,27 +2862,27 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt> ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a -** pointer to an instance of the [sqlite3_mutex_methods] structure. +** pointer to an instance of the [tdsqlite3_mutex_methods] structure. ** The argument specifies alternative low-level mutex routines to be used ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of -** the content of the [sqlite3_mutex_methods] structure before the call to -** [sqlite3_config()] returns. ^If SQLite is compiled with +** the content of the [tdsqlite3_mutex_methods] structure before the call to +** [tdsqlite3_config()] returns. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to -** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** [tdsqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will ** return [SQLITE_ERROR].</dd> ** ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt> ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which -** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The -** [sqlite3_mutex_methods] +** is a pointer to an instance of the [tdsqlite3_mutex_methods] structure. The +** [tdsqlite3_mutex_methods] ** structure is filled with the currently defined mutex routines.)^ ** This option can be used to overload the default mutex allocation ** routines with a wrapper used to track mutex usage for performance ** profiling or testing, for example. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to -** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** [tdsqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will ** return [SQLITE_ERROR].</dd> ** ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt> @@ -1986,18 +2892,18 @@ struct sqlite3_mem_methods { ** size of each lookaside buffer slot and the second is the number of ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] -** option to [sqlite3_db_config()] can be used to change the lookaside +** option to [tdsqlite3_db_config()] can be used to change the lookaside ** configuration on individual connections.)^ </dd> ** ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is -** a pointer to an [sqlite3_pcache_methods2] object. This object specifies +** a pointer to an [tdsqlite3_pcache_methods2] object. This object specifies ** the interface to a custom page cache implementation.)^ -** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd> +** ^SQLite makes a copy of the [tdsqlite3_pcache_methods2] object.</dd> ** ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which -** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of +** is a pointer to an [tdsqlite3_pcache_methods2] object. SQLite copies of ** the current page cache implementation into that object.)^ </dd> ** ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt> @@ -2006,15 +2912,15 @@ struct sqlite3_mem_methods { ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a ** function with a call signature of void(*)(void*,int,const char*), ** and a pointer to void. ^If the function pointer is not NULL, it is -** invoked by [sqlite3_log()] to process each logging event. ^If the -** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** invoked by [tdsqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [tdsqlite3_log()] interface becomes a no-op. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is ** passed through as the first parameter to the application-defined logger ** function whenever that function is invoked. ^The second parameter to ** the logger function is a copy of the first parameter to the corresponding -** [sqlite3_log()] call and is intended to be a [result code] or an +** [tdsqlite3_log()] call and is intended to be a [result code] or an ** [extended result code]. ^The third parameter passed to the logger is -** log message after formatting via [sqlite3_snprintf()]. +** log message after formatting via [tdsqlite3_snprintf()]. ** The SQLite logging interface is not reentrant; the logger function ** supplied by the application must not invoke any SQLite interface. ** In a multi-threaded application, the application-defined logger @@ -2024,8 +2930,8 @@ struct sqlite3_mem_methods { ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int. ** If non-zero, then URI handling is globally enabled. If the parameter is zero, ** then URI handling is globally disabled.)^ ^If URI handling is globally -** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], -** [sqlite3_open16()] or +** enabled, all filenames passed to [tdsqlite3_open()], [tdsqlite3_open_v2()], +** [tdsqlite3_open16()] or ** specified as part of [ATTACH] commands are interpreted as URIs, regardless ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database ** connection is opened. ^If it is globally disabled, filenames are @@ -2057,7 +2963,7 @@ struct sqlite3_mem_methods { ** <dt>SQLITE_CONFIG_SQLLOG ** <dd>This option is only available if sqlite is compiled with the ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should -** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). +** be a pointer to a function of type void(*)(void*,tdsqlite3*,const char*, int). ** The second should be of type (void*). The callback is invoked by the library ** in three separate circumstances, identified by the value passed as the ** fourth parameter. If the fourth parameter is 0, then the database connection @@ -2072,7 +2978,7 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_CONFIG_MMAP_SIZE]] ** <dt>SQLITE_CONFIG_MMAP_SIZE -** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values +** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (tdsqlite3_int64) values ** that are the default mmap size limit (the default setting for ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. ** ^The default setting can be overridden by each database connection using @@ -2123,57 +3029,88 @@ struct sqlite3_mem_methods { ** I/O required to support statement rollback. ** The default value for this setting is controlled by the ** [SQLITE_STMTJRNL_SPILL] compile-time option. +** +** [[SQLITE_CONFIG_SORTERREF_SIZE]] +** <dt>SQLITE_CONFIG_SORTERREF_SIZE +** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter +** of type (int) - the new value of the sorter-reference size threshold. +** Usually, when SQLite uses an external sort to order records according +** to an ORDER BY clause, all fields required by the caller are present in the +** sorted records. However, if SQLite determines based on the declared type +** of a table column that its values are likely to be very large - larger +** than the configured sorter-reference size threshold - then a reference +** is stored in each sorted record and the required column values loaded +** from the database as records are returned in sorted order. The default +** value for this option is to never use this optimization. Specifying a +** negative value for this option restores the default behaviour. +** This option is only available if SQLite is compiled with the +** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option. +** +** [[SQLITE_CONFIG_MEMDB_MAXSIZE]] +** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE +** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter +** [tdsqlite3_int64] parameter which is the default maximum size for an in-memory +** database created using [tdsqlite3_deserialize()]. This default maximum +** size can be adjusted up or down for individual databases using the +** [SQLITE_FCNTL_SIZE_LIMIT] [tdsqlite3_file_control|file-control]. If this +** configuration setting is never used, then the default maximum is determined +** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that +** compile-time option is not set, then the default maximum is 1073741824. ** </dl> */ #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ #define SQLITE_CONFIG_SERIALIZED 3 /* nil */ -#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ +#define SQLITE_CONFIG_MALLOC 4 /* tdsqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* tdsqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* No longer used */ #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ -#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ -#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_MUTEX 10 /* tdsqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* tdsqlite3_mutex_methods* */ /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ #define SQLITE_CONFIG_PCACHE 14 /* no-op */ #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ #define SQLITE_CONFIG_URI 17 /* int */ -#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ -#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_PCACHE2 18 /* tdsqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_GETPCACHE2 19 /* tdsqlite3_pcache_methods2* */ #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ -#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ +#define SQLITE_CONFIG_MMAP_SIZE 22 /* tdsqlite3_int64, tdsqlite3_int64 */ #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */ #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */ +#define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */ +#define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */ +#define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* tdsqlite3_int64 */ /* ** CAPI3REF: Database Connection Configuration Options ** ** These constants are the available integer configuration options that -** can be passed as the second argument to the [sqlite3_db_config()] interface. +** can be passed as the second argument to the [tdsqlite3_db_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_db_config()] to make sure that -** the call worked. ^The [sqlite3_db_config()] interface will return a +** should check the return code from [tdsqlite3_db_config()] to make sure that +** the call worked. ^The [tdsqlite3_db_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** ** <dl> +** [[SQLITE_DBCONFIG_LOOKASIDE]] ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt> ** <dd> ^This option takes three additional arguments that determine the ** [lookaside memory allocator] configuration for the [database connection]. -** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** ^The first argument (the third parameter to [tdsqlite3_db_config()] is a ** pointer to a memory buffer to use for lookaside memory. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb ** may be NULL in which case SQLite will allocate the -** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the +** lookaside buffer itself using [tdsqlite3_malloc()]. ^The second argument is the ** size of each lookaside buffer slot. ^The third argument is the number of ** slots. The size of the buffer in the first argument must be greater than ** or equal to the product of the second and third arguments. The buffer @@ -2183,11 +3120,12 @@ struct sqlite3_mem_methods { ** configuration for a database connection can only be changed when that ** connection is not currently using lookaside memory, or in other words ** when the "current value" returned by -** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. +** [tdsqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. ** Any attempt to change the lookaside memory configuration when lookaside ** memory is in use leaves the configuration unchanged and returns ** [SQLITE_BUSY].)^</dd> ** +** [[SQLITE_DBCONFIG_ENABLE_FKEY]] ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt> ** <dd> ^This option is used to enable or disable the enforcement of ** [foreign key constraints]. There should be two additional arguments. @@ -2198,6 +3136,7 @@ struct sqlite3_mem_methods { ** following this call. The second parameter may be a NULL pointer, in ** which case the FK enforcement setting is not reported back. </dd> ** +** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]] ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt> ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers]. ** There should be two additional arguments. @@ -2208,9 +3147,21 @@ struct sqlite3_mem_methods { ** following this call. The second parameter may be a NULL pointer, in ** which case the trigger setting is not reported back. </dd> ** +** [[SQLITE_DBCONFIG_ENABLE_VIEW]] +** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt> +** <dd> ^This option is used to enable or disable [CREATE VIEW | views]. +** There should be two additional arguments. +** The first argument is an integer which is 0 to disable views, +** positive to enable views or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether views are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the view setting is not reported back. </dd> +** +** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]] ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt> -** <dd> ^This option is used to enable or disable the two-argument -** version of the [fts3_tokenizer()] function which is part of the +** <dd> ^This option is used to enable or disable the +** [fts3_tokenizer()] function which is part of the ** [FTS3] full-text search engine extension. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or @@ -2221,11 +3172,12 @@ struct sqlite3_mem_methods { ** following this call. The second parameter may be a NULL pointer, in ** which case the new setting is not reported back. </dd> ** +** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]] ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt> -** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()] +** <dd> ^This option is used to enable or disable the [tdsqlite3_load_extension()] ** interface independently of the [load_extension()] SQL function. -** The [sqlite3_enable_load_extension()] API enables or disables both the -** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. +** The [tdsqlite3_enable_load_extension()] API enables or disables both the +** C-API [tdsqlite3_load_extension()] and the SQL function [load_extension()]. ** There should be two additional arguments. ** When the first argument to this interface is 1, then only the C-API is ** enabled and the SQL function remains disabled. If the first argument to @@ -2233,12 +3185,12 @@ struct sqlite3_mem_methods { ** If the first argument is -1, then no changes are made to state of either the ** C-API or the SQL function. ** The second parameter is a pointer to an integer into which -** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface +** is written 0 or 1 to indicate whether [tdsqlite3_load_extension()] interface ** is disabled or enabled following this call. The second parameter may ** be a NULL pointer, in which case the new setting is not reported back. ** </dd> ** -** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt> +** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt> ** <dd> ^This option is used to change the name of the "main" database ** schema. ^The sole argument is a pointer to a constant UTF8 string ** which will become the new schema name in place of "main". ^SQLite @@ -2247,6 +3199,163 @@ struct sqlite3_mem_methods { ** until after the database connection closes. ** </dd> ** +** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] +** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt> +** <dd> Usually, when a database in wal mode is closed or detached from a +** database handle, SQLite checks if this will mean that there are now no +** connections at all to the database. If so, it performs a checkpoint +** operation before closing the connection. This option may be used to +** override this behaviour. The first parameter passed to this operation +** is an integer - positive to disable checkpoints-on-close, or zero (the +** default) to enable them, and negative to leave the setting unchanged. +** The second parameter is a pointer to an integer +** into which is written 0 or 1 to indicate whether checkpoints-on-close +** have been disabled - 0 if they are not disabled, 1 if they are. +** </dd> +** +** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt> +** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates +** the [query planner stability guarantee] (QPSG). When the QPSG is active, +** a single SQL query statement will always use the same algorithm regardless +** of values of [bound parameters].)^ The QPSG disables some query optimizations +** that look at the values of bound parameters, which can make some queries +** slower. But the QPSG has the advantage of more predictable behavior. With +** the QPSG active, SQLite will always use the same query plan in the field as +** was used during testing in the lab. +** The first argument to this setting is an integer which is 0 to disable +** the QPSG, positive to enable QPSG, or negative to leave the setting +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether the QPSG is disabled or enabled +** following this call. +** </dd> +** +** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt> +** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not +** include output for any operations performed by trigger programs. This +** option is used to set or clear (the default) a flag that governs this +** behavior. The first parameter passed to this operation is an integer - +** positive to enable output for trigger programs, or zero to disable it, +** or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which is written +** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if +** it is not disabled, 1 if it is. +** </dd> +** +** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt> +** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run +** [VACUUM] in order to reset a database back to an empty database +** with no schema and no content. The following process works even for +** a badly corrupted database file: +** <ol> +** <li> If the database connection is newly opened, make sure it has read the +** database schema by preparing then discarding some query against the +** database, or calling tdsqlite3_table_column_metadata(), ignoring any +** errors. This step is only necessary if the application desires to keep +** the database in WAL mode after the reset if it was in WAL mode before +** the reset. +** <li> tdsqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0); +** <li> [tdsqlite3_exec](db, "[VACUUM]", 0, 0, 0); +** <li> tdsqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0); +** </ol> +** Because resetting a database is destructive and irreversible, the +** process requires the use of this obscure API and multiple steps to help +** ensure that it does not happen by accident. +** +** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt> +** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the +** "defensive" flag for a database connection. When the defensive +** flag is enabled, language features that allow ordinary SQL to +** deliberately corrupt the database file are disabled. The disabled +** features include but are not limited to the following: +** <ul> +** <li> The [PRAGMA writable_schema=ON] statement. +** <li> The [PRAGMA journal_mode=OFF] statement. +** <li> Writes to the [sqlite_dbpage] virtual table. +** <li> Direct writes to [shadow tables]. +** </ul> +** </dd> +** +** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt> +** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the +** "writable_schema" flag. This has the same effect and is logically equivalent +** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF]. +** The first argument to this setting is an integer which is 0 to disable +** the writable_schema, positive to enable writable_schema, or negative to +** leave the setting unchanged. The second parameter is a pointer to an +** integer into which is written 0 or 1 to indicate whether the writable_schema +** is enabled or disabled following this call. +** </dd> +** +** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]] +** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt> +** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates +** the legacy behavior of the [ALTER TABLE RENAME] command such it +** behaves as it did prior to [version 3.24.0] (2018-06-04). See the +** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for +** additional information. This feature can also be turned on and off +** using the [PRAGMA legacy_alter_table] statement. +** </dd> +** +** [[SQLITE_DBCONFIG_DQS_DML]] +** <dt>SQLITE_DBCONFIG_DQS_DML</td> +** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates +** the legacy [double-quoted string literal] misfeature for DML statements +** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The +** default value of this setting is determined by the [-DSQLITE_DQS] +** compile-time option. +** </dd> +** +** [[SQLITE_DBCONFIG_DQS_DDL]] +** <dt>SQLITE_DBCONFIG_DQS_DDL</td> +** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates +** the legacy [double-quoted string literal] misfeature for DDL statements, +** such as CREATE TABLE and CREATE INDEX. The +** default value of this setting is determined by the [-DSQLITE_DQS] +** compile-time option. +** </dd> +** +** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]] +** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td> +** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to +** assume that database schemas (the contents of the [sqlite_master] tables) +** are untainted by malicious content. +** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite +** takes additional defensive steps to protect the application from harm +** including: +** <ul> +** <li> Prohibit the use of SQL functions inside triggers, views, +** CHECK constraints, DEFAULT clauses, expression indexes, +** partial indexes, or generated columns +** unless those functions are tagged with [SQLITE_INNOCUOUS]. +** <li> Prohibit the use of virtual tables inside of triggers or views +** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS]. +** </ul> +** This setting defaults to "on" for legacy compatibility, however +** all applications are advised to turn it off if possible. This setting +** can also be controlled using the [PRAGMA trusted_schema] statement. +** </dd> +** +** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]] +** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td> +** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates +** the legacy file format flag. When activated, this flag causes all newly +** created database file to have a schema format version number (the 4-byte +** integer found at offset 44 into the database header) of 1. This in turn +** means that the resulting database file will be readable and writable by +** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting, +** newly created databases are generally not understandable by SQLite versions +** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there +** is now scarcely any need to generated database files that are compatible +** all the way back to version 3.0.0, and so this setting is of little +** practical use, but is provided so that SQLite can continue to claim the +** ability to generate new database files that are compatible with version +** 3.0.0. +** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on, +** the [VACUUM] command will fail with an obscure error when attempting to +** process a table with generated columns and a descending index. This is +** not considered a bug since SQLite versions 3.3.0 and earlier do not support +** either generated columns or decending indexes. +** </dd> ** </dl> */ #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ @@ -2255,21 +3364,33 @@ struct sqlite3_mem_methods { #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */ - +#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */ +#define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */ +#define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */ +#define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */ +#define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */ +#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */ +#define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */ +#define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_VIEW 1015 /* int int* */ +#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT 1016 /* int int* */ +#define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */ +#define SQLITE_DBCONFIG_MAX 1017 /* Largest DBCONFIG */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_extended_result_codes() routine enables or disables the +** ^The tdsqlite3_extended_result_codes() routine enables or disables the ** [extended result codes] feature of SQLite. ^The extended result ** codes are disabled by default for historical compatibility. */ -SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); +SQLITE_API int tdsqlite3_extended_result_codes(tdsqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) ** has a unique 64-bit signed @@ -2279,20 +3400,30 @@ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); ** the table has a column of type [INTEGER PRIMARY KEY] then that column ** is another alias for the rowid. ** -** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the -** most recent successful [INSERT] into a rowid table or [virtual table] -** on database connection D. -** ^Inserts into [WITHOUT ROWID] tables are not recorded. -** ^If no successful [INSERT]s into rowid tables -** have ever occurred on the database connection D, -** then sqlite3_last_insert_rowid(D) returns zero. -** -** ^(If an [INSERT] occurs within a trigger or within a [virtual table] -** method, then this routine will return the [rowid] of the inserted -** row as long as the trigger or virtual table method is running. -** But once the trigger or virtual table method ends, the value returned -** by this routine reverts to what it was before the trigger or virtual -** table method began.)^ +** ^The tdsqlite3_last_insert_rowid(D) interface usually returns the [rowid] of +** the most recent successful [INSERT] into a rowid table or [virtual table] +** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not +** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred +** on the database connection D, then tdsqlite3_last_insert_rowid(D) returns +** zero. +** +** As well as being set automatically as rows are inserted into database +** tables, the value returned by this function may be set explicitly by +** [tdsqlite3_set_last_insert_rowid()] +** +** Some virtual table implementations may INSERT rows into rowid tables as +** part of committing a transaction (e.g. to flush data accumulated in memory +** to disk). In this case subsequent calls to this function return the rowid +** associated with these internal INSERT operations, which leads to +** unintuitive results. Virtual table implementations that do write to rowid +** tables in this way can avoid this problem by restoring the original +** rowid value using [tdsqlite3_set_last_insert_rowid()] before returning +** control to the user. +** +** ^(If an [INSERT] occurs within a trigger then this routine will +** return the [rowid] of the inserted row as long as the trigger is +** running. Once the trigger program ends, the value returned +** by this routine reverts to what it was before the trigger was fired.)^ ** ** ^An [INSERT] that fails due to a constraint violation is not a ** successful [INSERT] and does not change the value returned by this @@ -2311,17 +3442,27 @@ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); ** [last_insert_rowid() SQL function]. ** ** If a separate thread performs a new [INSERT] on the same -** database connection while the [sqlite3_last_insert_rowid()] +** database connection while the [tdsqlite3_last_insert_rowid()] ** function is running and thus changes the last insert [rowid], -** then the value returned by [sqlite3_last_insert_rowid()] is +** then the value returned by [tdsqlite3_last_insert_rowid()] is ** unpredictable and might not equal either the old or the new ** last insert [rowid]. */ -SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); +SQLITE_API tdsqlite3_int64 tdsqlite3_last_insert_rowid(tdsqlite3*); + +/* +** CAPI3REF: Set the Last Insert Rowid value. +** METHOD: tdsqlite3 +** +** The tdsqlite3_set_last_insert_rowid(D, R) method allows the application to +** set the value returned by calling tdsqlite3_last_insert_rowid(D) to R +** without inserting a row into the database. +*/ +SQLITE_API void tdsqlite3_set_last_insert_rowid(tdsqlite3*,tdsqlite3_int64); /* ** CAPI3REF: Count The Number Of Rows Modified -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This function returns the number of rows modified, inserted or ** deleted by the most recently completed INSERT, UPDATE or DELETE @@ -2335,24 +3476,24 @@ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); ** ** Changes to a view that are intercepted by ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value -** returned by sqlite3_changes() immediately after an INSERT, UPDATE or +** returned by tdsqlite3_changes() immediately after an INSERT, UPDATE or ** DELETE statement run on a view is always zero. Only changes made to real ** tables are counted. ** -** Things are more complicated if the sqlite3_changes() function is +** Things are more complicated if the tdsqlite3_changes() function is ** executed while a trigger program is running. This may happen if the ** program uses the [changes() SQL function], or if some other callback -** function invokes sqlite3_changes() directly. Essentially: +** function invokes tdsqlite3_changes() directly. Essentially: ** ** <ul> ** <li> ^(Before entering a trigger program the value returned by -** sqlite3_changes() function is saved. After the trigger program +** tdsqlite3_changes() function is saved. After the trigger program ** has finished, the original value is restored.)^ ** ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE -** statement sets the value returned by sqlite3_changes() +** statement sets the value returned by tdsqlite3_changes() ** upon completion as normal. Of course, this value will not include -** any changes performed by sub-triggers, as the sqlite3_changes() +** any changes performed by sub-triggers, as the tdsqlite3_changes() ** value will be saved and restored after each sub-trigger has run.)^ ** </ul> ** @@ -2363,42 +3504,60 @@ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); ** program, the value returned reflects the number of rows modified by the ** previous INSERT, UPDATE or DELETE statement within the same trigger. ** -** See also the [sqlite3_total_changes()] interface, the -** [count_changes pragma], and the [changes() SQL function]. -** ** If a separate thread makes changes on the same database connection -** while [sqlite3_changes()] is running then the value returned +** while [tdsqlite3_changes()] is running then the value returned ** is unpredictable and not meaningful. +** +** See also: +** <ul> +** <li> the [tdsqlite3_total_changes()] interface +** <li> the [count_changes pragma] +** <li> the [changes() SQL function] +** <li> the [data_version pragma] +** </ul> */ -SQLITE_API int sqlite3_changes(sqlite3*); +SQLITE_API int tdsqlite3_changes(tdsqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This function returns the total number of rows inserted, modified or ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed ** since the database connection was opened, including those executed as ** part of trigger programs. ^Executing any other type of SQL statement -** does not affect the value returned by sqlite3_total_changes(). +** does not affect the value returned by tdsqlite3_total_changes(). ** ** ^Changes made as part of [foreign key actions] are included in the ** count, but those made as part of REPLACE constraint resolution are ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers ** are not counted. -** -** See also the [sqlite3_changes()] interface, the -** [count_changes pragma], and the [total_changes() SQL function]. ** +** The [tdsqlite3_total_changes(D)] interface only reports the number +** of rows that changed due to SQL statement run against database +** connection D. Any changes by other database connections are ignored. +** To detect changes against a database file from other database +** connections use the [PRAGMA data_version] command or the +** [SQLITE_FCNTL_DATA_VERSION] [file control]. +** ** If a separate thread makes changes on the same database connection -** while [sqlite3_total_changes()] is running then the value +** while [tdsqlite3_total_changes()] is running then the value ** returned is unpredictable and not meaningful. +** +** See also: +** <ul> +** <li> the [tdsqlite3_changes()] interface +** <li> the [count_changes pragma] +** <li> the [changes() SQL function] +** <li> the [data_version pragma] +** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control] +** </ul> */ -SQLITE_API int sqlite3_total_changes(sqlite3*); +SQLITE_API int tdsqlite3_total_changes(tdsqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This function causes any pending database operation to abort and ** return at its earliest opportunity. This routine is typically @@ -2409,10 +3568,10 @@ SQLITE_API int sqlite3_total_changes(sqlite3*); ** ^It is safe to call this routine from a thread different from the ** thread that is currently running the database operation. But it ** is not safe to call this routine with a [database connection] that -** is closed or might close before sqlite3_interrupt() returns. +** is closed or might close before tdsqlite3_interrupt() returns. ** ** ^If an SQL operation is very nearly finished at the time when -** sqlite3_interrupt() is called, then it might not have an opportunity +** tdsqlite3_interrupt() is called, then it might not have an opportunity ** to be interrupted and might continue to completion. ** ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. @@ -2420,21 +3579,18 @@ SQLITE_API int sqlite3_total_changes(sqlite3*); ** that is inside an explicit transaction, then the entire transaction ** will be rolled back automatically. ** -** ^The sqlite3_interrupt(D) call is in effect until all currently running +** ^The tdsqlite3_interrupt(D) call is in effect until all currently running ** SQL statements on [database connection] D complete. ^Any new SQL statements -** that are started after the sqlite3_interrupt() call and before the -** running statements reaches zero are interrupted as if they had been -** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the tdsqlite3_interrupt() call and before the +** running statement count reaches zero are interrupted as if they had been +** running prior to the tdsqlite3_interrupt() call. ^New SQL statements ** that are started after the running statement count reaches zero are -** not effected by the sqlite3_interrupt(). -** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** not effected by the tdsqlite3_interrupt(). +** ^A call to tdsqlite3_interrupt(D) that occurs when there are no running ** SQL statements is a no-op and has no effect on SQL statements -** that are started after the sqlite3_interrupt() call returns. -** -** If the database connection closes while [sqlite3_interrupt()] -** is running then bad things will likely happen. +** that are started after the tdsqlite3_interrupt() call returns. */ -SQLITE_API void sqlite3_interrupt(sqlite3*); +SQLITE_API void tdsqlite3_interrupt(tdsqlite3*); /* ** CAPI3REF: Determine If An SQL Statement Is Complete @@ -2457,40 +3613,40 @@ SQLITE_API void sqlite3_interrupt(sqlite3*); ** ^These routines do not parse the SQL statements thus ** will not detect syntactically incorrect SQL. ** -** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior -** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked -** automatically by sqlite3_complete16(). If that initialization fails, -** then the return value from sqlite3_complete16() will be non-zero +** ^(If SQLite has not been initialized using [tdsqlite3_initialize()] prior +** to invoking tdsqlite3_complete16() then tdsqlite3_initialize() is invoked +** automatically by tdsqlite3_complete16(). If that initialization fails, +** then the return value from tdsqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete.)^ ** -** The input to [sqlite3_complete()] must be a zero-terminated +** The input to [tdsqlite3_complete()] must be a zero-terminated ** UTF-8 string. ** -** The input to [sqlite3_complete16()] must be a zero-terminated +** The input to [tdsqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ -SQLITE_API int sqlite3_complete(const char *sql); -SQLITE_API int sqlite3_complete16(const void *sql); +SQLITE_API int tdsqlite3_complete(const char *sql); +SQLITE_API int tdsqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors ** KEYWORDS: {busy-handler callback} {busy handler} -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X +** ^The tdsqlite3_busy_handler(D,X,P) routine sets a callback function X ** that might be invoked with argument P whenever ** an attempt is made to access a database table associated with ** [database connection] D when another thread ** or process has the table locked. -** The sqlite3_busy_handler() interface is used to implement -** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. +** The tdsqlite3_busy_handler() interface is used to implement +** [tdsqlite3_busy_timeout()] and [PRAGMA busy_timeout]. ** ** ^If the busy callback is NULL, then [SQLITE_BUSY] ** is returned immediately upon encountering the lock. ^If the busy callback ** is not NULL, then the callback might be invoked with two arguments. ** ** ^The first argument to the busy handler is a copy of the void* pointer which -** is the third argument to sqlite3_busy_handler(). ^The second argument to +** is the third argument to tdsqlite3_busy_handler(). ^The second argument to ** the busy handler callback is the number of times that the busy handler has ** been invoked previously for the same locking event. ^If the ** busy callback returns 0, then no additional attempts are made to @@ -2519,7 +3675,7 @@ SQLITE_API int sqlite3_complete16(const void *sql); ** ** ^(There can only be a single busy handler defined for each ** [database connection]. Setting a new busy handler clears any -** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** previously set handler.)^ ^Note that calling [tdsqlite3_busy_timeout()] ** or evaluating [PRAGMA busy_timeout=N] will change the ** busy handler and thus clear any previously set busy handler. ** @@ -2531,17 +3687,17 @@ SQLITE_API int sqlite3_complete16(const void *sql); ** A busy handler must not close the database connection ** or [prepared statement] that invoked the busy handler. */ -SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); +SQLITE_API int tdsqlite3_busy_handler(tdsqlite3*,int(*)(void*,int),void*); /* ** CAPI3REF: Set A Busy Timeout -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** ^This routine sets a [tdsqlite3_busy_handler | busy handler] that sleeps ** for a specified amount of time when a table is locked. ^The handler ** will sleep multiple times until at least "ms" milliseconds of sleeping ** have accumulated. ^After at least "ms" milliseconds of sleeping, -** the handler returns 0 which causes [sqlite3_step()] to return +** the handler returns 0 which causes [tdsqlite3_step()] to return ** [SQLITE_BUSY]. ** ** ^Calling this routine with an argument less than or equal to zero @@ -2549,22 +3705,22 @@ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); ** ** ^(There can only be a single busy handler for a particular ** [database connection] at any given moment. If another busy handler -** was defined (using [sqlite3_busy_handler()]) prior to calling +** was defined (using [tdsqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared.)^ ** ** See also: [PRAGMA busy_timeout] */ -SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); +SQLITE_API int tdsqlite3_busy_timeout(tdsqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** This is a legacy interface that is preserved for backwards compatibility. ** Use of this interface is not recommended. ** ** Definition: A <b>result table</b> is memory data structure created by the -** [sqlite3_get_table()] interface. A result table records the +** [tdsqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** ** The table conceptually has a number of rows and columns. But @@ -2577,11 +3733,11 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); ** to zero-terminated strings that contain the names of the columns. ** The remaining entries all point to query results. NULL values result ** in NULL pointers. All other values are in their UTF-8 zero-terminated -** string representation as returned by [sqlite3_column_text()]. +** string representation as returned by [tdsqlite3_column_text()]. ** ** A result table might consist of one or more memory allocations. -** It is not safe to pass a result table directly to [sqlite3_free()]. -** A result table should be deallocated using [sqlite3_free_table()]. +** It is not safe to pass a result table directly to [tdsqlite3_free()]. +** A result table should be deallocated using [tdsqlite3_free_table()]. ** ** ^(As an example of the result table format, suppose a query result ** is as follows: @@ -2594,9 +3750,9 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); ** Cindy | 21 ** </pre></blockquote> ** -** There are two column (M==2) and three rows (N==3). Thus the +** There are two columns (M==2) and three rows (N==3). Thus the ** result table has 8 entries. Suppose the result table is stored -** in an array names azResult. Then azResult holds this content: +** in an array named azResult. Then azResult holds this content: ** ** <blockquote><pre> ** azResult[0] = "Name"; @@ -2609,265 +3765,188 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); ** azResult[7] = "21"; ** </pre></blockquote>)^ ** -** ^The sqlite3_get_table() function evaluates one or more +** ^The tdsqlite3_get_table() function evaluates one or more ** semicolon-separated SQL statements in the zero-terminated UTF-8 ** string of its 2nd parameter and returns a result table to the ** pointer given in its 3rd parameter. ** -** After the application has finished with the result from sqlite3_get_table(), -** it must pass the result table pointer to sqlite3_free_table() in order to +** After the application has finished with the result from tdsqlite3_get_table(), +** it must pass the result table pointer to tdsqlite3_free_table() in order to ** release the memory that was malloced. Because of the way the -** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling -** function must not try to call [sqlite3_free()] directly. Only -** [sqlite3_free_table()] is able to release the memory properly and safely. +** [tdsqlite3_malloc()] happens within tdsqlite3_get_table(), the calling +** function must not try to call [tdsqlite3_free()] directly. Only +** [tdsqlite3_free_table()] is able to release the memory properly and safely. ** -** The sqlite3_get_table() interface is implemented as a wrapper around -** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** The tdsqlite3_get_table() interface is implemented as a wrapper around +** [tdsqlite3_exec()]. The tdsqlite3_get_table() routine does not have access ** to any internal data structures of SQLite. It uses only the public ** interface defined here. As a consequence, errors that occur in the -** wrapper layer outside of the internal [sqlite3_exec()] call are not -** reflected in subsequent calls to [sqlite3_errcode()] or -** [sqlite3_errmsg()]. +** wrapper layer outside of the internal [tdsqlite3_exec()] call are not +** reflected in subsequent calls to [tdsqlite3_errcode()] or +** [tdsqlite3_errmsg()]. */ -SQLITE_API int sqlite3_get_table( - sqlite3 *db, /* An open database */ +SQLITE_API int tdsqlite3_get_table( + tdsqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ int *pnRow, /* Number of result rows written here */ int *pnColumn, /* Number of result columns written here */ char **pzErrmsg /* Error msg written here */ ); -SQLITE_API void sqlite3_free_table(char **result); +SQLITE_API void tdsqlite3_free_table(char **result); /* ** CAPI3REF: Formatted String Printing Functions ** ** These routines are work-alikes of the "printf()" family of functions ** from the standard C library. -** These routines understand most of the common K&R formatting options, -** plus some additional non-standard formats, detailed below. -** Note that some of the more obscure formatting options from recent -** C-library standards are omitted from this implementation. +** These routines understand most of the common formatting options from +** the standard library printf() +** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]). +** See the [built-in printf()] documentation for details. ** -** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their -** results into memory obtained from [sqlite3_malloc()]. +** ^The tdsqlite3_mprintf() and tdsqlite3_vmprintf() routines write their +** results into memory obtained from [tdsqlite3_malloc64()]. ** The strings returned by these two routines should be -** released by [sqlite3_free()]. ^Both routines return a -** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** released by [tdsqlite3_free()]. ^Both routines return a +** NULL pointer if [tdsqlite3_malloc64()] is unable to allocate enough ** memory to hold the resulting string. ** -** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** ^(The tdsqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by ** the first parameter. Note that the order of the ** first two parameters is reversed from snprintf().)^ This is an ** historical accident that cannot be fixed without breaking -** backwards compatibility. ^(Note also that sqlite3_snprintf() +** backwards compatibility. ^(Note also that tdsqlite3_snprintf() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer.)^ We admit that ** the number of characters written would be a more useful return -** value but we cannot change the implementation of sqlite3_snprintf() +** value but we cannot change the implementation of tdsqlite3_snprintf() ** now without breaking compatibility. ** -** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** ^As long as the buffer size is greater than zero, tdsqlite3_snprintf() ** guarantees that the buffer is always zero-terminated. ^The first ** parameter "n" is the total size of the buffer, including space for ** the zero terminator. So the longest string that can be completely ** written will be n-1 characters. ** -** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). -** -** These routines all implement some additional formatting -** options that are useful for constructing SQL statements. -** All of the usual printf() formatting options apply. In addition, there -** is are "%q", "%Q", "%w" and "%z" options. -** -** ^(The %q option works like %s in that it substitutes a nul-terminated -** string from the argument list. But %q also doubles every '\'' character. -** %q is designed for use inside a string literal.)^ By doubling each '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, assume the string variable zText contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: +** ^The tdsqlite3_vsnprintf() routine is a varargs version of tdsqlite3_snprintf(). ** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** This second example is an SQL syntax error. As a general rule you should -** always use %q instead of %s when inserting text into a string literal. -** -** ^(The %Q option works like %q except it also adds single quotes around -** the outside of the total string. Additionally, if the parameter in the -** argument list is a NULL pointer, %Q substitutes the text "NULL" (without -** single quotes).)^ So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** The code above will render a correct SQL statement in the zSQL -** variable even if the zText variable is a NULL pointer. -** -** ^(The "%w" formatting option is like "%q" except that it expects to -** be contained within double-quotes instead of single quotes, and it -** escapes the double-quote character instead of the single-quote -** character.)^ The "%w" formatting option is intended for safely inserting -** table and column names into a constructed SQL statement. -** -** ^(The "%z" formatting option works like "%s" but with the -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string.)^ +** See also: [built-in printf()], [printf() SQL function] */ -SQLITE_API char *sqlite3_mprintf(const char*,...); -SQLITE_API char *sqlite3_vmprintf(const char*, va_list); -SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); -SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); +SQLITE_API char *tdsqlite3_mprintf(const char*,...); +SQLITE_API char *tdsqlite3_vmprintf(const char*, va_list); +SQLITE_API char *tdsqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *tdsqlite3_vsnprintf(int,char*,const char*, va_list); /* ** CAPI3REF: Memory Allocation Subsystem ** ** The SQLite core uses these three routines for all of its own ** internal memory allocation needs. "Core" in the previous sentence -** does not include operating-system specific VFS implementation. The +** does not include operating-system specific [VFS] implementation. The ** Windows VFS uses native malloc() and free() for some operations. ** -** ^The sqlite3_malloc() routine returns a pointer to a block +** ^The tdsqlite3_malloc() routine returns a pointer to a block ** of memory at least N bytes in length, where N is the parameter. -** ^If sqlite3_malloc() is unable to obtain sufficient free +** ^If tdsqlite3_malloc() is unable to obtain sufficient free ** memory, it returns a NULL pointer. ^If the parameter N to -** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** tdsqlite3_malloc() is zero or negative then tdsqlite3_malloc() returns ** a NULL pointer. ** -** ^The sqlite3_malloc64(N) routine works just like -** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead +** ^The tdsqlite3_malloc64(N) routine works just like +** tdsqlite3_malloc(N) except that N is an unsigned 64-bit integer instead ** of a signed 32-bit integer. ** -** ^Calling sqlite3_free() with a pointer previously returned -** by sqlite3_malloc() or sqlite3_realloc() releases that memory so -** that it might be reused. ^The sqlite3_free() routine is +** ^Calling tdsqlite3_free() with a pointer previously returned +** by tdsqlite3_malloc() or tdsqlite3_realloc() releases that memory so +** that it might be reused. ^The tdsqlite3_free() routine is ** a no-op if is called with a NULL pointer. Passing a NULL pointer -** to sqlite3_free() is harmless. After being freed, memory +** to tdsqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. ** Memory corruption, a segmentation fault, or other severe error -** might result if sqlite3_free() is called with a non-NULL pointer that -** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** might result if tdsqlite3_free() is called with a non-NULL pointer that +** was not obtained from tdsqlite3_malloc() or tdsqlite3_realloc(). ** -** ^The sqlite3_realloc(X,N) interface attempts to resize a +** ^The tdsqlite3_realloc(X,N) interface attempts to resize a ** prior memory allocation X to be at least N bytes. -** ^If the X parameter to sqlite3_realloc(X,N) +** ^If the X parameter to tdsqlite3_realloc(X,N) ** is a NULL pointer then its behavior is identical to calling -** sqlite3_malloc(N). -** ^If the N parameter to sqlite3_realloc(X,N) is zero or +** tdsqlite3_malloc(N). +** ^If the N parameter to tdsqlite3_realloc(X,N) is zero or ** negative then the behavior is exactly the same as calling -** sqlite3_free(X). -** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation +** tdsqlite3_free(X). +** ^tdsqlite3_realloc(X,N) returns a pointer to a memory allocation ** of at least N bytes in size or NULL if insufficient memory is available. ** ^If M is the size of the prior allocation, then min(N,M) bytes ** of the prior allocation are copied into the beginning of buffer returned -** by sqlite3_realloc(X,N) and the prior allocation is freed. -** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the +** by tdsqlite3_realloc(X,N) and the prior allocation is freed. +** ^If tdsqlite3_realloc(X,N) returns NULL and N is positive, then the ** prior allocation is not freed. ** -** ^The sqlite3_realloc64(X,N) interfaces works the same as -** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead +** ^The tdsqlite3_realloc64(X,N) interfaces works the same as +** tdsqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead ** of a 32-bit signed integer. ** -** ^If X is a memory allocation previously obtained from sqlite3_malloc(), -** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then -** sqlite3_msize(X) returns the size of that memory allocation in bytes. -** ^The value returned by sqlite3_msize(X) might be larger than the number +** ^If X is a memory allocation previously obtained from tdsqlite3_malloc(), +** tdsqlite3_malloc64(), tdsqlite3_realloc(), or tdsqlite3_realloc64(), then +** tdsqlite3_msize(X) returns the size of that memory allocation in bytes. +** ^The value returned by tdsqlite3_msize(X) might be larger than the number ** of bytes requested when X was allocated. ^If X is a NULL pointer then -** sqlite3_msize(X) returns zero. If X points to something that is not +** tdsqlite3_msize(X) returns zero. If X points to something that is not ** the beginning of memory allocation, or if it points to a formerly ** valid memory allocation that has now been freed, then the behavior -** of sqlite3_msize(X) is undefined and possibly harmful. +** of tdsqlite3_msize(X) is undefined and possibly harmful. ** -** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), -** sqlite3_malloc64(), and sqlite3_realloc64() +** ^The memory returned by tdsqlite3_malloc(), tdsqlite3_realloc(), +** tdsqlite3_malloc64(), and tdsqlite3_realloc64() ** is always aligned to at least an 8 byte boundary, or to a ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time ** option is used. ** -** In SQLite version 3.5.0 and 3.5.1, it was possible to define -** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in -** implementation of these routines to be omitted. That capability -** is no longer provided. Only built-in memory allocators can be used. -** -** Prior to SQLite version 3.7.10, the Windows OS interface layer called -** the system malloc() and free() directly when converting -** filenames between the UTF-8 encoding used by SQLite -** and whatever filename encoding is used by the particular Windows -** installation. Memory allocation errors were detected, but -** they were reported back as [SQLITE_CANTOPEN] or -** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. -** -** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** The pointer arguments to [tdsqlite3_free()] and [tdsqlite3_realloc()] ** must be either NULL or else pointers obtained from a prior -** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** invocation of [tdsqlite3_malloc()] or [tdsqlite3_realloc()] that have ** not yet been released. ** ** The application must not read or write any part of ** a block of memory after it has been released using -** [sqlite3_free()] or [sqlite3_realloc()]. +** [tdsqlite3_free()] or [tdsqlite3_realloc()]. */ -SQLITE_API void *sqlite3_malloc(int); -SQLITE_API void *sqlite3_malloc64(sqlite3_uint64); -SQLITE_API void *sqlite3_realloc(void*, int); -SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64); -SQLITE_API void sqlite3_free(void*); -SQLITE_API sqlite3_uint64 sqlite3_msize(void*); +SQLITE_API void *tdsqlite3_malloc(int); +SQLITE_API void *tdsqlite3_malloc64(tdsqlite3_uint64); +SQLITE_API void *tdsqlite3_realloc(void*, int); +SQLITE_API void *tdsqlite3_realloc64(void*, tdsqlite3_uint64); +SQLITE_API void tdsqlite3_free(void*); +SQLITE_API tdsqlite3_uint64 tdsqlite3_msize(void*); /* ** CAPI3REF: Memory Allocator Statistics ** ** SQLite provides these two interfaces for reporting on the status -** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** of the [tdsqlite3_malloc()], [tdsqlite3_free()], and [tdsqlite3_realloc()] ** routines, which form the built-in memory allocation subsystem. ** -** ^The [sqlite3_memory_used()] routine returns the number of bytes +** ^The [tdsqlite3_memory_used()] routine returns the number of bytes ** of memory currently outstanding (malloced but not freed). -** ^The [sqlite3_memory_highwater()] routine returns the maximum -** value of [sqlite3_memory_used()] since the high-water mark -** was last reset. ^The values returned by [sqlite3_memory_used()] and -** [sqlite3_memory_highwater()] include any overhead -** added by SQLite in its implementation of [sqlite3_malloc()], +** ^The [tdsqlite3_memory_highwater()] routine returns the maximum +** value of [tdsqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [tdsqlite3_memory_used()] and +** [tdsqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [tdsqlite3_malloc()], ** but not overhead added by the any underlying system library -** routines that [sqlite3_malloc()] may call. +** routines that [tdsqlite3_malloc()] may call. ** ** ^The memory high-water mark is reset to the current value of -** [sqlite3_memory_used()] if and only if the parameter to -** [sqlite3_memory_highwater()] is true. ^The value returned -** by [sqlite3_memory_highwater(1)] is the high-water mark +** [tdsqlite3_memory_used()] if and only if the parameter to +** [tdsqlite3_memory_highwater()] is true. ^The value returned +** by [tdsqlite3_memory_highwater(1)] is the high-water mark ** prior to the reset. */ -SQLITE_API sqlite3_int64 sqlite3_memory_used(void); -SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); +SQLITE_API tdsqlite3_int64 tdsqlite3_memory_used(void); +SQLITE_API tdsqlite3_int64 tdsqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator @@ -2875,7 +3954,7 @@ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to ** select random [ROWID | ROWIDs] when inserting new records into a table that ** already uses the largest possible [ROWID]. The PRNG is also used for -** the build-in random() and randomblob() SQL functions. This interface allows +** the built-in random() and randomblob() SQL functions. This interface allows ** applications to access the same PRNG for other purposes. ** ** ^A call to this routine stores N bytes of randomness into buffer P. @@ -2884,23 +3963,25 @@ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); ** ^If this routine has not been previously called or if the previous ** call had N less than one or a NULL pointer for P, then the PRNG is ** seeded using randomness obtained from the xRandomness method of -** the default [sqlite3_vfs] object. +** the default [tdsqlite3_vfs] object. ** ^If the previous call to this routine had an N of 1 or more and a ** non-NULL P then the pseudo-randomness is generated -** internally and without recourse to the [sqlite3_vfs] xRandomness +** internally and without recourse to the [tdsqlite3_vfs] xRandomness ** method. */ -SQLITE_API void sqlite3_randomness(int N, void *P); +SQLITE_API void tdsqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 +** KEYWORDS: {authorizer callback} ** ** ^This routine registers an authorizer callback with a particular ** [database connection], supplied in the first argument. ** ^The authorizer callback is invoked as SQL statements are being compiled -** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], -** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various +** by [tdsqlite3_prepare()] or its variants [tdsqlite3_prepare_v2()], +** [tdsqlite3_prepare_v3()], [tdsqlite3_prepare16()], [tdsqlite3_prepare16_v2()], +** and [tdsqlite3_prepare16_v3()]. ^At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. ^The authorizer callback should @@ -2909,21 +3990,23 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be ** rejected with an error. ^If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] -** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** then the [tdsqlite3_prepare_v2()] or equivalent call that triggered ** the authorizer will fail with an error message. ** ** When the callback returns [SQLITE_OK], that means the operation ** requested is ok. ^When the callback returns [SQLITE_DENY], the -** [sqlite3_prepare_v2()] or equivalent call that triggered the +** [tdsqlite3_prepare_v2()] or equivalent call that triggered the ** authorizer will fail with an error message explaining that ** access is denied. ** ** ^The first parameter to the authorizer callback is a copy of the third -** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** parameter to the tdsqlite3_set_authorizer() interface. ^The second parameter ** to the callback is an integer [SQLITE_COPY | action code] that specifies ** the particular action to be authorized. ^The third through sixth parameters -** to the callback are zero-terminated strings that contain additional -** details about the action to be authorized. +** to the callback are either NULL pointers or zero-terminated strings +** that contain additional details about the action to be authorized. +** Applications must always be prepared to encounter a NULL pointer in any +** of the third through the sixth parameters of the authorization callback. ** ** ^If the action code is [SQLITE_READ] ** and the callback returns [SQLITE_IGNORE] then the @@ -2932,11 +4015,15 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] ** return can be used to deny an untrusted user access to individual ** columns of a table. +** ^When a table is referenced by a [SELECT] but no column values are +** extracted from that table (for example in a query like +** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback +** is invoked once for that table with a column name that is an empty string. ** ^If the action code is [SQLITE_DELETE] and the callback returns ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the ** [truncate optimization] is disabled and all rows are deleted individually. ** -** An authorizer is used when [sqlite3_prepare | preparing] +** An authorizer is used when [tdsqlite3_prepare | preparing] ** SQL statements from an untrusted source, to ensure that the SQL statements ** do not try to access data they are not allowed to see, or that they do not ** try to execute malicious statements that damage the database. For @@ -2944,37 +4031,37 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the -** user-entered SQL is being [sqlite3_prepare | prepared] that +** user-entered SQL is being [tdsqlite3_prepare | prepared] that ** disallows everything except [SELECT] statements. ** ** Applications that need to process SQL from untrusted sources -** might also consider lowering resource limits using [sqlite3_limit()] +** might also consider lowering resource limits using [tdsqlite3_limit()] ** and limiting database size using the [max_page_count] [PRAGMA] ** in addition to using an authorizer. ** ** ^(Only a single authorizer can be in place on a database connection -** at a time. Each call to sqlite3_set_authorizer overrides the +** at a time. Each call to tdsqlite3_set_authorizer overrides the ** previous call.)^ ^Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** ** The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** Note that [tdsqlite3_prepare_v2()] and [tdsqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** -** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the -** statement might be re-prepared during [sqlite3_step()] due to a +** ^When [tdsqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [tdsqlite3_step()] due to a ** schema change. Hence, the application should ensure that the -** correct authorizer callback remains in place during the [sqlite3_step()]. +** correct authorizer callback remains in place during the [tdsqlite3_step()]. ** ** ^Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()], unless -** as stated in the previous paragraph, sqlite3_step() invokes -** sqlite3_prepare_v2() to reprepare a statement after a schema change. +** [tdsqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [tdsqlite3_step()], unless +** as stated in the previous paragraph, tdsqlite3_step() invokes +** tdsqlite3_prepare_v2() to reprepare a statement after a schema change. */ -SQLITE_API int sqlite3_set_authorizer( - sqlite3*, +SQLITE_API int tdsqlite3_set_authorizer( + tdsqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData ); @@ -2982,14 +4069,14 @@ SQLITE_API int sqlite3_set_authorizer( /* ** CAPI3REF: Authorizer Return Codes ** -** The [sqlite3_set_authorizer | authorizer callback function] must +** The [tdsqlite3_set_authorizer | authorizer callback function] must ** return either [SQLITE_OK] or one of these two constants in order ** to signal SQLite whether or not the action is permitted. See the -** [sqlite3_set_authorizer | authorizer documentation] for additional +** [tdsqlite3_set_authorizer | authorizer documentation] for additional ** information. ** ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] -** returned from the [sqlite3_vtab_on_conflict()] interface. +** returned from the [tdsqlite3_vtab_on_conflict()] interface. */ #define SQLITE_DENY 1 /* Abort the SQL statement with an error */ #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ @@ -2997,7 +4084,7 @@ SQLITE_API int sqlite3_set_authorizer( /* ** CAPI3REF: Authorizer Action Codes ** -** The [sqlite3_set_authorizer()] interface registers a callback function +** The [tdsqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorize certain SQL statement actions. The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that @@ -3051,48 +4138,48 @@ SQLITE_API int sqlite3_set_authorizer( /* ** CAPI3REF: Tracing And Profiling Functions -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** These routines are deprecated. Use the [sqlite3_trace_v2()] interface +** These routines are deprecated. Use the [tdsqlite3_trace_v2()] interface ** instead of the routines described here. ** ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** -** ^The callback function registered by sqlite3_trace() is invoked at -** various times when an SQL statement is being run by [sqlite3_step()]. -** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** ^The callback function registered by tdsqlite3_trace() is invoked at +** various times when an SQL statement is being run by [tdsqlite3_step()]. +** ^The tdsqlite3_trace() callback is invoked with a UTF-8 rendering of the ** SQL statement text as the statement first begins executing. -** ^(Additional sqlite3_trace() callbacks might occur +** ^(Additional tdsqlite3_trace() callbacks might occur ** as each triggered subprogram is entered. The callbacks for triggers ** contain a UTF-8 SQL comment that identifies the trigger.)^ ** ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit -** the length of [bound parameter] expansion in the output of sqlite3_trace(). +** the length of [bound parameter] expansion in the output of tdsqlite3_trace(). ** -** ^The callback function registered by sqlite3_profile() is invoked +** ^The callback function registered by tdsqlite3_profile() is invoked ** as each SQL statement finishes. ^The profile callback contains ** the original statement text and an estimate of wall-clock time ** of how long that statement took to run. ^The profile callback ** time is in units of nanoseconds, however the current implementation ** is only capable of millisecond resolution so the six least significant ** digits in the time are meaningless. Future versions of SQLite -** might provide greater resolution on the profiler callback. The -** sqlite3_profile() function is considered experimental and is -** subject to change in future versions of SQLite. +** might provide greater resolution on the profiler callback. Invoking +** either [tdsqlite3_trace()] or [tdsqlite3_trace_v2()] will cancel the +** profile callback. */ -SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*, +SQLITE_API SQLITE_DEPRECATED void *tdsqlite3_trace(tdsqlite3*, void(*xTrace)(void*,const char*), void*); -SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, - void(*xProfile)(void*,const char*,sqlite3_uint64), void*); +SQLITE_API SQLITE_DEPRECATED void *tdsqlite3_profile(tdsqlite3*, + void(*xProfile)(void*,const char*,tdsqlite3_uint64), void*); /* ** CAPI3REF: SQL Trace Event Codes ** KEYWORDS: SQLITE_TRACE ** ** These constants identify classes of events that can be monitored -** using the [sqlite3_trace_v2()] tracing logic. The third argument -** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of +** using the [tdsqlite3_trace_v2()] tracing logic. The M argument +** to [tdsqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of ** the following constants. ^The first argument to the trace callback ** is one of the following constants. ** @@ -3101,7 +4188,7 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, ** ^A trace callback has four arguments: xCallback(T,C,P,X). ** ^The T argument is one of the integer type codes above. ** ^The C argument is a copy of the context pointer passed in as the -** fourth argument to [sqlite3_trace_v2()]. +** fourth argument to [tdsqlite3_trace_v2()]. ** The P and X arguments are pointers whose meanings depend on T. ** ** <dl> @@ -3113,13 +4200,13 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, ** [prepared statement]. ^The X argument is a pointer to a string which ** is the unexpanded SQL text of the prepared statement or an SQL comment ** that indicates the invocation of a trigger. ^The callback can compute -** the same text that would have been returned by the legacy [sqlite3_trace()] +** the same text that would have been returned by the legacy [tdsqlite3_trace()] ** interface by using the X argument when X begins with "--" and invoking -** [sqlite3_expanded_sql(P)] otherwise. +** [tdsqlite3_expanded_sql(P)] otherwise. ** ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt> ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same -** information as is provided by the [sqlite3_profile()] callback. +** information as is provided by the [tdsqlite3_profile()] callback. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument points to a 64-bit integer which is the estimated of ** the number of nanosecond that the prepared statement took to run. @@ -3145,17 +4232,17 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, /* ** CAPI3REF: SQL Trace Hook -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback +** ^The tdsqlite3_trace_v2(D,M,X,P) interface registers a trace callback ** function X against [database connection] D, using property mask M ** and context pointer P. ^If the X callback is ** NULL or if the M mask is zero, then tracing is disabled. The ** M argument should be the bitwise OR-ed combination of ** zero or more [SQLITE_TRACE] constants. ** -** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides -** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2(). +** ^Each call to either tdsqlite3_trace() or tdsqlite3_trace_v2() overrides +** (cancels) any prior calls to tdsqlite3_trace() or tdsqlite3_trace_v2(). ** ** ^The X callback is invoked whenever any of the events identified by ** mask M occur. ^The integer return value from the callback is currently @@ -3168,12 +4255,12 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, ** ^The C argument is a copy of the context pointer. ** The P and X arguments are pointers whose meanings depend on T. ** -** The sqlite3_trace_v2() interface is intended to replace the legacy -** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which +** The tdsqlite3_trace_v2() interface is intended to replace the legacy +** interfaces [tdsqlite3_trace()] and [tdsqlite3_profile()], both of which ** are deprecated. */ -SQLITE_API int sqlite3_trace_v2( - sqlite3*, +SQLITE_API int tdsqlite3_trace_v2( + tdsqlite3*, unsigned uMask, int(*xCallback)(unsigned,void*,void*,void*), void *pCtx @@ -3181,11 +4268,11 @@ SQLITE_API int sqlite3_trace_v2( /* ** CAPI3REF: Query Progress Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** ^The tdsqlite3_progress_handler(D,N,X,P) interface causes the callback ** function X to be invoked periodically during long running calls to -** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for +** [tdsqlite3_exec()], [tdsqlite3_step()] and [tdsqlite3_get_table()] for ** database connection D. An example use for this ** interface is to keep a GUI updated during a large query. ** @@ -3207,44 +4294,42 @@ SQLITE_API int sqlite3_trace_v2( ** ** The progress handler callback must not do anything that will modify ** the database connection that invoked the progress handler. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** Note that [tdsqlite3_prepare_v2()] and [tdsqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** */ -SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); +SQLITE_API void tdsqlite3_progress_handler(tdsqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection -** CONSTRUCTOR: sqlite3 +** CONSTRUCTOR: tdsqlite3 ** ** ^These routines open an SQLite database file as specified by the ** filename argument. ^The filename argument is interpreted as UTF-8 for -** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte -** order for sqlite3_open16(). ^(A [database connection] handle is usually +** tdsqlite3_open() and tdsqlite3_open_v2() and as UTF-16 in the native byte +** order for tdsqlite3_open16(). ^(A [database connection] handle is usually ** returned in *ppDb, even if an error occurs. The only exception is that -** if SQLite is unable to allocate memory to hold the [sqlite3] object, -** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** if SQLite is unable to allocate memory to hold the [tdsqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [tdsqlite3] ** object.)^ ^(If the database is opened (and/or created) successfully, then ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The -** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** [tdsqlite3_errmsg()] or [tdsqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error following a failure of any -** of the sqlite3_open() routines. +** of the tdsqlite3_open() routines. ** ** ^The default encoding will be UTF-8 for databases created using -** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases -** created using sqlite3_open16() will be UTF-16 in the native byte order. +** tdsqlite3_open() or tdsqlite3_open_v2(). ^The default encoding for databases +** created using tdsqlite3_open16() will be UTF-16 in the native byte order. ** ** Whether or not an error occurs when it is opened, resources ** associated with the [database connection] handle should be released by -** passing it to [sqlite3_close()] when it is no longer required. +** passing it to [tdsqlite3_close()] when it is no longer required. ** -** The sqlite3_open_v2() interface works like sqlite3_open() +** The tdsqlite3_open_v2() interface works like tdsqlite3_open() ** except that it accepts two additional parameters for additional control ** over the new database connection. ^(The flags parameter to -** sqlite3_open_v2() can take one of -** the following three values, optionally combined with the -** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], -** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ +** tdsqlite3_open_v2() must include, at a minimum, one of the following +** three flag combinations:)^ ** ** <dl> ** ^(<dt>[SQLITE_OPEN_READONLY]</dt> @@ -3259,30 +4344,58 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt> ** <dd>The database is opened for reading and writing, and is created if ** it does not already exist. This is the behavior that is always used for -** sqlite3_open() and sqlite3_open16().</dd>)^ +** tdsqlite3_open() and tdsqlite3_open16().</dd>)^ ** </dl> ** -** If the 3rd parameter to sqlite3_open_v2() is not one of the -** combinations shown above optionally combined with other +** In addition to the required flags, the following optional flags are +** also supported: +** +** <dl> +** ^(<dt>[SQLITE_OPEN_URI]</dt> +** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^ +** +** ^(<dt>[SQLITE_OPEN_MEMORY]</dt> +** <dd>The database will be opened as an in-memory database. The database +** is named by the "filename" argument for the purposes of cache-sharing, +** if shared cache mode is enabled, but the "filename" is otherwise ignored. +** </dd>)^ +** +** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt> +** <dd>The new database connection will use the "multi-thread" +** [threading mode].)^ This means that separate threads are allowed +** to use SQLite at the same time, as long as each thread is using +** a different [database connection]. +** +** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt> +** <dd>The new database connection will use the "serialized" +** [threading mode].)^ This means the multiple threads can safely +** attempt to use the same database connection at the same time. +** (Mutexes will block any actual concurrency, but in this mode +** there is no harm in trying.) +** +** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt> +** <dd>The database is opened [shared cache] enabled, overriding +** the default shared cache setting provided by +** [tdsqlite3_enable_shared_cache()].)^ +** +** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt> +** <dd>The database is opened [shared cache] disabled, overriding +** the default shared cache setting provided by +** [tdsqlite3_enable_shared_cache()].)^ +** +** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt> +** <dd>The database filename is not allowed to be a symbolic link</dd> +** </dl>)^ +** +** If the 3rd parameter to tdsqlite3_open_v2() is not one of the +** required combinations shown above optionally combined with other ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] ** then the behavior is undefined. ** -** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection -** opens in the multi-thread [threading mode] as long as the single-thread -** mode has not been set at compile-time or start-time. ^If the -** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens -** in the serialized [threading mode] unless single-thread was -** previously selected at compile-time or start-time. -** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be -** eligible to use [shared cache mode], regardless of whether or not shared -** cache is enabled using [sqlite3_enable_shared_cache()]. ^The -** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not -** participate in [shared cache mode] even if it is enabled. -** -** ^The fourth parameter to sqlite3_open_v2() is the name of the -** [sqlite3_vfs] object that defines the operating system interface that +** ^The fourth parameter to tdsqlite3_open_v2() is the name of the +** [tdsqlite3_vfs] object that defines the operating system interface that ** the new database connection should use. ^If the fourth parameter is -** a NULL pointer then the default [sqlite3_vfs] object is used. +** a NULL pointer then the default [tdsqlite3_vfs] object is used. ** ** ^If the filename is ":memory:", then a private, temporary in-memory database ** is created for the connection. ^This in-memory database will vanish when @@ -3296,15 +4409,15 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** on-disk database will be created. ^This private database will be ** automatically deleted as soon as the database connection is closed. ** -** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3> +** [[URI filenames in tdsqlite3_open()]] <h3>URI Filenames</h3> ** ** ^If [URI filename] interpretation is enabled, and the filename argument ** begins with "file:", then the filename is interpreted as a URI. ^URI ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is -** set in the fourth argument to sqlite3_open_v2(), or if it has +** set in the third argument to tdsqlite3_open_v2(), or if it has ** been enabled globally using the [SQLITE_CONFIG_URI] option with the -** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. -** As of SQLite version 3.7.7, URI filename interpretation is turned off +** [tdsqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. +** URI filename interpretation is turned off ** by default, but future releases of SQLite might enable URI filename ** interpretation by default. See "[URI filenames]" for additional ** information. @@ -3334,16 +4447,16 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** a VFS object that provides the operating system interface that should ** be used to access the database file on disk. ^If this option is set to ** an empty string the default VFS object is used. ^Specifying an unknown -** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is +** VFS is an error. ^If tdsqlite3_open_v2() is used and the vfs option is ** present, then the VFS specified by the option takes precedence over -** the value passed as the fourth parameter to sqlite3_open_v2(). +** the value passed as the fourth parameter to tdsqlite3_open_v2(). ** ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw", ** "rwc", or "memory". Attempting to set it to any other value is ** an error)^. ** ^If "ro" is specified, then the database is opened for read-only ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the -** third argument to sqlite3_open_v2(). ^If the mode option is set to +** third argument to tdsqlite3_open_v2(). ^If the mode option is set to ** "rw", then the database is opened for read-write (but not create) ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had ** been set. ^Value "rwc" is equivalent to setting both @@ -3351,14 +4464,14 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** set to "memory" then a pure [in-memory database] that never reads ** or writes from disk is used. ^It is an error to specify a value for ** the mode parameter that is less restrictive than that specified by -** the flags passed in the third parameter to sqlite3_open_v2(). +** the flags passed in the third parameter to tdsqlite3_open_v2(). ** ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or ** "private". ^Setting it to "shared" is equivalent to setting the ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to -** sqlite3_open_v2(). ^Setting the cache parameter to "private" is +** tdsqlite3_open_v2(). ^Setting the cache parameter to "private" is ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. -** ^If sqlite3_open_v2() is used and the "cache" parameter is present in +** ^If tdsqlite3_open_v2() is used and the "cache" parameter is present in ** a URI filename, its value overrides any behavior requested by setting ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. ** @@ -3429,28 +4542,28 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** the results are undefined. ** ** <b>Note to Windows users:</b> The encoding used for the filename argument -** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** of tdsqlite3_open() and tdsqlite3_open_v2() must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into -** sqlite3_open() or sqlite3_open_v2(). +** tdsqlite3_open() or tdsqlite3_open_v2(). ** ** <b>Note to Windows Runtime users:</b> The temporary directory must be set -** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various +** prior to calling tdsqlite3_open() or tdsqlite3_open_v2(). Otherwise, various ** features that require the use of temporary files may fail. ** -** See also: [sqlite3_temp_directory] +** See also: [tdsqlite3_temp_directory] */ -SQLITE_API int sqlite3_open( +SQLITE_API int tdsqlite3_open( const char *filename, /* Database filename (UTF-8) */ - sqlite3 **ppDb /* OUT: SQLite db handle */ + tdsqlite3 **ppDb /* OUT: SQLite db handle */ ); -SQLITE_API int sqlite3_open16( +SQLITE_API int tdsqlite3_open16( const void *filename, /* Database filename (UTF-16) */ - sqlite3 **ppDb /* OUT: SQLite db handle */ + tdsqlite3 **ppDb /* OUT: SQLite db handle */ ); -SQLITE_API int sqlite3_open_v2( +SQLITE_API int tdsqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ - sqlite3 **ppDb, /* OUT: SQLite db handle */ + tdsqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ); @@ -3458,70 +4571,129 @@ SQLITE_API int sqlite3_open_v2( /* ** CAPI3REF: Obtain Values For URI Parameters ** -** These are utility routines, useful to VFS implementations, that check -** to see if a database file was a URI that contained a specific query +** These are utility routines, useful to [VFS|custom VFS implementations], +** that check if a database file was a URI that contained a specific query ** parameter, and if so obtains the value of that query parameter. ** ** If F is the database filename pointer passed into the xOpen() method of -** a VFS implementation when the flags parameter to xOpen() has one or -** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and -** P is the name of the query parameter, then -** sqlite3_uri_parameter(F,P) returns the value of the P +** a VFS implementation or it is the return value of [tdsqlite3_db_filename()] +** and if P is the name of the query parameter, then +** tdsqlite3_uri_parameter(F,P) returns the value of the P ** parameter if it exists or a NULL pointer if P does not appear as a -** query parameter on F. If P is a query parameter of F -** has no explicit value, then sqlite3_uri_parameter(F,P) returns +** query parameter on F. If P is a query parameter of F and it +** has no explicit value, then tdsqlite3_uri_parameter(F,P) returns ** a pointer to an empty string. ** -** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean +** The tdsqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean ** parameter and returns true (1) or false (0) according to the value -** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the +** of P. The tdsqlite3_uri_boolean(F,P,B) routine returns true (1) if the ** value of query parameter P is one of "yes", "true", or "on" in any ** case or if the value begins with a non-zero number. The -** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of +** tdsqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of ** query parameter P is one of "no", "false", or "off" in any case or ** if the value begins with a numeric zero. If P is not a query -** parameter on F or if the value of P is does not match any of the -** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). +** parameter on F or if the value of P does not match any of the +** above, then tdsqlite3_uri_boolean(F,P,B) returns (B!=0). ** -** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a +** The tdsqlite3_uri_int64(F,P,D) routine converts the value of P into a ** 64-bit signed integer and returns that integer, or D if P does not ** exist. If the value of P is something other than an integer, then ** zero is returned. +** +** The tdsqlite3_uri_key(F,N) returns a pointer to the name (not +** the value) of the N-th query parameter for filename F, or a NULL +** pointer if N is less than zero or greater than the number of query +** parameters minus 1. The N value is zero-based so N should be 0 to obtain +** the name of the first query parameter, 1 for the second parameter, and +** so forth. ** -** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and -** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and -** is not a database file pathname pointer that SQLite passed into the xOpen -** VFS method, then the behavior of this routine is undefined and probably -** undesirable. +** If F is a NULL pointer, then tdsqlite3_uri_parameter(F,P) returns NULL and +** tdsqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and +** is not a database file pathname pointer that the SQLite core passed +** into the xOpen VFS method, then the behavior of this routine is undefined +** and probably undesirable. +** +** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F +** parameter can also be the name of a rollback journal file or WAL file +** in addition to the main database file. Prior to version 3.31.0, these +** routines would only work if F was the name of the main database file. +** When the F parameter is the name of the rollback journal or WAL file, +** it has access to all the same query parameters as were found on the +** main database file. +** +** See the [URI filename] documentation for additional information. */ -SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); -SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); -SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); +SQLITE_API const char *tdsqlite3_uri_parameter(const char *zFilename, const char *zParam); +SQLITE_API int tdsqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); +SQLITE_API tdsqlite3_int64 tdsqlite3_uri_int64(const char*, const char*, tdsqlite3_int64); +SQLITE_API const char *tdsqlite3_uri_key(const char *zFilename, int N); + +/* +** CAPI3REF: Translate filenames +** +** These routines are available to [VFS|custom VFS implementations] for +** translating filenames between the main database file, the journal file, +** and the WAL file. +** +** If F is the name of an sqlite database file, journal file, or WAL file +** passed by the SQLite core into the VFS, then tdsqlite3_filename_database(F) +** returns the name of the corresponding database file. +** +** If F is the name of an sqlite database file, journal file, or WAL file +** passed by the SQLite core into the VFS, or if F is a database filename +** obtained from [tdsqlite3_db_filename()], then tdsqlite3_filename_journal(F) +** returns the name of the corresponding rollback journal file. +** +** If F is the name of an sqlite database file, journal file, or WAL file +** that was passed by the SQLite core into the VFS, or if F is a database +** filename obtained from [tdsqlite3_db_filename()], then +** tdsqlite3_filename_wal(F) returns the name of the corresponding +** WAL file. +** +** In all of the above, if F is not the name of a database, journal or WAL +** filename passed into the VFS from the SQLite core and F is not the +** return value from [tdsqlite3_db_filename()], then the result is +** undefined and is likely a memory access violation. +*/ +SQLITE_API const char *tdsqlite3_filename_database(const char*); +SQLITE_API const char *tdsqlite3_filename_journal(const char*); +SQLITE_API const char *tdsqlite3_filename_wal(const char*); /* ** CAPI3REF: Error Codes And Messages -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^If the most recent sqlite3_* API call associated with -** [database connection] D failed, then the sqlite3_errcode(D) interface +** ^If the most recent tdsqlite3_* API call associated with +** [database connection] D failed, then the tdsqlite3_errcode(D) interface ** returns the numeric [result code] or [extended result code] for that ** API call. -** If the most recent API call was successful, -** then the return value from sqlite3_errcode() is undefined. -** ^The sqlite3_extended_errcode() +** ^The tdsqlite3_extended_errcode() ** interface is the same except that it always returns the ** [extended result code] even when extended result codes are ** disabled. ** -** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** The values returned by tdsqlite3_errcode() and/or +** tdsqlite3_extended_errcode() might change with each API call. +** Except, there are some interfaces that are guaranteed to never +** change the value of the error code. The error-code preserving +** interfaces are: +** +** <ul> +** <li> tdsqlite3_errcode() +** <li> tdsqlite3_extended_errcode() +** <li> tdsqlite3_errmsg() +** <li> tdsqlite3_errmsg16() +** </ul> +** +** ^The tdsqlite3_errmsg() and tdsqlite3_errmsg16() return English-language ** text that describes the error, as either UTF-8 or UTF-16 respectively. ** ^(Memory to hold the error message string is managed internally. ** The application does not need to worry about freeing the result. ** However, the error string might be overwritten or deallocated by ** subsequent calls to other SQLite interface functions.)^ ** -** ^The sqlite3_errstr() interface returns the English-language text +** ^The tdsqlite3_errstr() interface returns the English-language text ** that describes the [result code], as UTF-8. ** ^(Memory to hold the error message string is managed internally ** and must not be freed by the application)^. @@ -3532,19 +4704,19 @@ SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int ** When that happens, the second error will be reported since these ** interfaces always report the most recent result. To avoid ** this, each thread can obtain exclusive use of the [database connection] D -** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning -** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** by invoking [tdsqlite3_mutex_enter]([tdsqlite3_db_mutex](D)) before beginning +** to use D and invoking [tdsqlite3_mutex_leave]([tdsqlite3_db_mutex](D)) after ** all calls to the interfaces listed here are completed. ** ** If an interface fails with SQLITE_MISUSE, that means the interface ** was invoked incorrectly by the application. In that case, the ** error code and message may or may not be set. */ -SQLITE_API int sqlite3_errcode(sqlite3 *db); -SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); -SQLITE_API const char *sqlite3_errmsg(sqlite3*); -SQLITE_API const void *sqlite3_errmsg16(sqlite3*); -SQLITE_API const char *sqlite3_errstr(int); +SQLITE_API int tdsqlite3_errcode(tdsqlite3 *db); +SQLITE_API int tdsqlite3_extended_errcode(tdsqlite3 *db); +SQLITE_API const char *tdsqlite3_errmsg(tdsqlite3*); +SQLITE_API const void *tdsqlite3_errmsg16(tdsqlite3*); +SQLITE_API const char *tdsqlite3_errstr(int); /* ** CAPI3REF: Prepared Statement Object @@ -3561,20 +4733,20 @@ SQLITE_API const char *sqlite3_errstr(int); ** The life-cycle of a prepared statement object usually goes like this: ** ** <ol> -** <li> Create the prepared statement object using [sqlite3_prepare_v2()]. -** <li> Bind values to [parameters] using the sqlite3_bind_*() +** <li> Create the prepared statement object using [tdsqlite3_prepare_v2()]. +** <li> Bind values to [parameters] using the tdsqlite3_bind_*() ** interfaces. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the prepared statement using [sqlite3_reset()] then go back +** <li> Run the SQL by calling [tdsqlite3_step()] one or more times. +** <li> Reset the prepared statement using [tdsqlite3_reset()] then go back ** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. +** <li> Destroy the object using [tdsqlite3_finalize()]. ** </ol> */ -typedef struct sqlite3_stmt sqlite3_stmt; +typedef struct tdsqlite3_stmt tdsqlite3_stmt; /* ** CAPI3REF: Run-time Limits -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^(This interface allows the size of various constructs to be limited ** on a connection by connection basis. The first parameter is the @@ -3593,7 +4765,7 @@ typedef struct sqlite3_stmt sqlite3_stmt; ** silently truncated to the hard upper bound. ** ** ^Regardless of whether or not the limit was changed, the -** [sqlite3_limit()] interface returns the prior value of the limit. +** [tdsqlite3_limit()] interface returns the prior value of the limit. ** ^Hence, to find the current value of a limit without changing it, ** simply invoke this interface with the third parameter set to -1. ** @@ -3605,21 +4777,21 @@ typedef struct sqlite3_stmt sqlite3_stmt; ** off the Internet. The internal databases can be given the ** large, default limits. Databases managed by external sources can ** be given much smaller limits designed to prevent a denial of service -** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** attack. Developers might also want to use the [tdsqlite3_set_authorizer()] ** interface to further control untrusted SQL. The size of the database ** created by an untrusted script can be contained using the ** [max_page_count] [PRAGMA]. ** ** New run-time limit categories may be added in future releases. */ -SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); +SQLITE_API int tdsqlite3_limit(tdsqlite3*, int id, int newVal); /* ** CAPI3REF: Run-Time Limit Categories ** KEYWORDS: {limit category} {*limit categories} ** ** These constants define various performance limits -** that can be lowered at run-time using [sqlite3_limit()]. +** that can be lowered at run-time using [tdsqlite3_limit()]. ** The synopsis of the meanings of the various limits is shown below. ** Additional information is available at [limits | Limits in SQLite]. ** @@ -3643,9 +4815,9 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt> ** <dd>The maximum number of instructions in a virtual machine program -** used to implement an SQL statement. This limit is not currently -** enforced, though that might be added in some future release of -** SQLite.</dd>)^ +** used to implement an SQL statement. If [tdsqlite3_prepare_v2()] or +** the equivalent tries to allocate space for more than this many opcodes +** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^ ** ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt> ** <dd>The maximum number of arguments on a function.</dd>)^ @@ -3684,22 +4856,73 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); #define SQLITE_LIMIT_WORKER_THREADS 11 /* +** CAPI3REF: Prepare Flags +** +** These constants define various flags that can be passed into +** "prepFlags" parameter of the [tdsqlite3_prepare_v3()] and +** [tdsqlite3_prepare16_v3()] interfaces. +** +** New flags may be added in future releases of SQLite. +** +** <dl> +** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt> +** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner +** that the prepared statement will be retained for a long time and +** probably reused many times.)^ ^Without this flag, [tdsqlite3_prepare_v3()] +** and [tdsqlite3_prepare16_v3()] assume that the prepared statement will +** be used just once or at most a few times and then destroyed using +** [tdsqlite3_finalize()] relatively soon. The current implementation acts +** on this hint by avoiding the use of [lookaside memory] so as not to +** deplete the limited store of lookaside memory. Future versions of +** SQLite may act on this hint differently. +** +** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt> +** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used +** to be required for any prepared statement that wanted to use the +** [tdsqlite3_normalized_sql()] interface. However, the +** [tdsqlite3_normalized_sql()] interface is now available to all +** prepared statements, regardless of whether or not they use this +** flag. +** +** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt> +** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler +** to return an error (error code SQLITE_ERROR) if the statement uses +** any virtual tables. +** </dl> +*/ +#define SQLITE_PREPARE_PERSISTENT 0x01 +#define SQLITE_PREPARE_NORMALIZE 0x02 +#define SQLITE_PREPARE_NO_VTAB 0x04 + +/* ** CAPI3REF: Compiling An SQL Statement ** KEYWORDS: {SQL statement compiler} -** METHOD: sqlite3 -** CONSTRUCTOR: sqlite3_stmt +** METHOD: tdsqlite3 +** CONSTRUCTOR: tdsqlite3_stmt +** +** To execute an SQL statement, it must first be compiled into a byte-code +** program using one of these routines. Or, in other words, these routines +** are constructors for the [prepared statement] object. +** +** The preferred routine to use is [tdsqlite3_prepare_v2()]. The +** [tdsqlite3_prepare()] interface is legacy and should be avoided. +** [tdsqlite3_prepare_v3()] has an extra "prepFlags" option that is used +** for special purposes. ** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. +** The use of the UTF-8 interfaces is preferred, as SQLite currently +** does all parsing using UTF-8. The UTF-16 interfaces are provided +** as a convenience. The UTF-16 interfaces work by converting the +** input text into UTF-8, then invoking the corresponding UTF-8 interface. ** ** The first argument, "db", is a [database connection] obtained from a -** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or -** [sqlite3_open16()]. The database connection must not have been closed. +** prior successful call to [tdsqlite3_open()], [tdsqlite3_open_v2()] or +** [tdsqlite3_open16()]. The database connection must not have been closed. ** ** The second argument, "zSql", is the statement to be compiled, encoded -** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() -** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() -** use UTF-16. +** as either UTF-8 or UTF-16. The tdsqlite3_prepare(), tdsqlite3_prepare_v2(), +** and tdsqlite3_prepare_v3() +** interfaces use UTF-8, and tdsqlite3_prepare16(), tdsqlite3_prepare16_v2(), +** and tdsqlite3_prepare16_v3() use UTF-16. ** ** ^If the nByte argument is negative, then zSql is read up to the ** first zero terminator. ^If nByte is positive, then it is the @@ -3716,129 +4939,160 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** what remains uncompiled. ** ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be -** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** executed using [tdsqlite3_step()]. ^If there is an error, *ppStmt is set ** to NULL. ^If the input text contains no SQL (if the input is an empty ** string or a comment) then *ppStmt is set to NULL. ** The calling procedure is responsible for deleting the compiled -** SQL statement using [sqlite3_finalize()] after it has finished with it. +** SQL statement using [tdsqlite3_finalize()] after it has finished with it. ** ppStmt may not be NULL. ** -** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** ^On success, the tdsqlite3_prepare() family of routines return [SQLITE_OK]; ** otherwise an [error code] is returned. ** -** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are -** recommended for all new programs. The two older interfaces are retained -** for backwards compatibility, but their use is discouraged. -** ^In the "v2" interfaces, the prepared statement -** that is returned (the [sqlite3_stmt] object) contains a copy of the -** original SQL text. This causes the [sqlite3_step()] interface to +** The tdsqlite3_prepare_v2(), tdsqlite3_prepare_v3(), tdsqlite3_prepare16_v2(), +** and tdsqlite3_prepare16_v3() interfaces are recommended for all new programs. +** The older interfaces (tdsqlite3_prepare() and tdsqlite3_prepare16()) +** are retained for backwards compatibility, but their use is discouraged. +** ^In the "vX" interfaces, the prepared statement +** that is returned (the [tdsqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [tdsqlite3_step()] interface to ** behave differently in three ways: ** ** <ol> ** <li> ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it -** always used to do, [sqlite3_step()] will automatically recompile the SQL +** always used to do, [tdsqlite3_step()] will automatically recompile the SQL ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] -** retries will occur before sqlite3_step() gives up and returns an error. +** retries will occur before tdsqlite3_step() gives up and returns an error. ** </li> ** ** <li> -** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** ^When an error occurs, [tdsqlite3_step()] will return one of the detailed ** [error codes] or [extended error codes]. ^The legacy behavior was that -** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code -** and the application would have to make a second call to [sqlite3_reset()] +** [tdsqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [tdsqlite3_reset()] ** in order to find the underlying cause of the problem. With the "v2" prepare ** interfaces, the underlying reason for the error is returned immediately. ** </li> ** ** <li> -** ^If the specific value bound to [parameter | host parameter] in the +** ^If the specific value bound to a [parameter | host parameter] in the ** WHERE clause might influence the choice of query plan for a statement, ** then the statement will be automatically recompiled, as if there had been -** a schema change, on the first [sqlite3_step()] call following any change -** to the [sqlite3_bind_text | bindings] of that [parameter]. -** ^The specific value of WHERE-clause [parameter] might influence the +** a schema change, on the first [tdsqlite3_step()] call following any change +** to the [tdsqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of a WHERE-clause [parameter] might influence the ** choice of query plan if the parameter is the left-hand side of a [LIKE] ** or [GLOB] operator or if the parameter is compared to an indexed column -** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. +** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled. ** </li> ** </ol> +** +** <p>^tdsqlite3_prepare_v3() differs from tdsqlite3_prepare_v2() only in having +** the extra prepFlags parameter, which is a bit array consisting of zero or +** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The +** tdsqlite3_prepare_v2() interface works exactly the same as +** tdsqlite3_prepare_v3() with a zero prepFlags parameter. */ -SQLITE_API int sqlite3_prepare( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_prepare( + tdsqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int tdsqlite3_prepare_v2( + tdsqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); -SQLITE_API int sqlite3_prepare_v2( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_prepare_v3( + tdsqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); -SQLITE_API int sqlite3_prepare16( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_prepare16( + tdsqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); -SQLITE_API int sqlite3_prepare16_v2( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_prepare16_v2( + tdsqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int tdsqlite3_prepare16_v3( + tdsqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); /* ** CAPI3REF: Retrieving Statement SQL -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 +** ^The tdsqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 ** SQL text used to create [prepared statement] P if P was -** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. -** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 +** created by [tdsqlite3_prepare_v2()], [tdsqlite3_prepare_v3()], +** [tdsqlite3_prepare16_v2()], or [tdsqlite3_prepare16_v3()]. +** ^The tdsqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 ** string containing the SQL text of prepared statement P with ** [bound parameters] expanded. +** ^The tdsqlite3_normalized_sql(P) interface returns a pointer to a UTF-8 +** string containing the normalized SQL text of prepared statement P. The +** semantics used to normalize a SQL statement are unspecified and subject +** to change. At a minimum, literal values will be replaced with suitable +** placeholders. ** ** ^(For example, if a prepared statement is created using the SQL ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345 -** and parameter :xyz is unbound, then sqlite3_sql() will return -** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql() +** and parameter :xyz is unbound, then tdsqlite3_sql() will return +** the original string, "SELECT $abc,:xyz" but tdsqlite3_expanded_sql() ** will return "SELECT 2345,NULL".)^ ** -** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory +** ^The tdsqlite3_expanded_sql() interface returns NULL if insufficient memory ** is available to hold the result, or if the result would exceed the ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. ** ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time -** option causes sqlite3_expanded_sql() to always return NULL. +** option causes tdsqlite3_expanded_sql() to always return NULL. ** -** ^The string returned by sqlite3_sql(P) is managed by SQLite and is -** automatically freed when the prepared statement is finalized. -** ^The string returned by sqlite3_expanded_sql(P), on the other hand, -** is obtained from [sqlite3_malloc()] and must be free by the application -** by passing it to [sqlite3_free()]. +** ^The strings returned by tdsqlite3_sql(P) and tdsqlite3_normalized_sql(P) +** are managed by SQLite and are automatically freed when the prepared +** statement is finalized. +** ^The string returned by tdsqlite3_expanded_sql(P), on the other hand, +** is obtained from [tdsqlite3_malloc()] and must be free by the application +** by passing it to [tdsqlite3_free()]. */ -SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); -SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); +SQLITE_API const char *tdsqlite3_sql(tdsqlite3_stmt *pStmt); +SQLITE_API char *tdsqlite3_expanded_sql(tdsqlite3_stmt *pStmt); +SQLITE_API const char *tdsqlite3_normalized_sql(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If An SQL Statement Writes The Database -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** ^The tdsqlite3_stmt_readonly(X) interface returns true (non-zero) if ** and only if the [prepared statement] X makes no direct changes to ** the content of the database file. ** ** Note that [application-defined SQL functions] or ** [virtual tables] might change the database indirectly as a side effect. ** ^(For example, if an application defines a function "eval()" that -** calls [sqlite3_exec()], then the following SQL statement would +** calls [tdsqlite3_exec()], then the following SQL statement would ** change the database file through side-effects: ** ** <blockquote><pre> @@ -3846,102 +5100,119 @@ SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); ** </pre></blockquote> ** ** But because the [SELECT] statement does not change the database file -** directly, sqlite3_stmt_readonly() would still return true.)^ +** directly, tdsqlite3_stmt_readonly() would still return true.)^ ** ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], -** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** [SAVEPOINT], and [RELEASE] cause tdsqlite3_stmt_readonly() to return true, ** since the statements themselves do not actually modify the database but ** rather they control the timing of when other statements modify the ** database. ^The [ATTACH] and [DETACH] statements also cause -** sqlite3_stmt_readonly() to return true since, while those statements +** tdsqlite3_stmt_readonly() to return true since, while those statements ** change the configuration of a database connection, they do not make ** changes to the content of the database files on disk. +** ^The tdsqlite3_stmt_readonly() interface returns true for [BEGIN] since +** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and +** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so +** tdsqlite3_stmt_readonly() returns false for those commands. +*/ +SQLITE_API int tdsqlite3_stmt_readonly(tdsqlite3_stmt *pStmt); + +/* +** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement +** METHOD: tdsqlite3_stmt +** +** ^The tdsqlite3_stmt_isexplain(S) interface returns 1 if the +** prepared statement S is an EXPLAIN statement, or 2 if the +** statement S is an EXPLAIN QUERY PLAN. +** ^The tdsqlite3_stmt_isexplain(S) interface returns 0 if S is +** an ordinary statement or a NULL pointer. */ -SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_stmt_isexplain(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If A Prepared Statement Has Been Reset -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the +** ^The tdsqlite3_stmt_busy(S) interface returns true (non-zero) if the ** [prepared statement] S has been stepped at least once using -** [sqlite3_step(S)] but has neither run to completion (returned -** [SQLITE_DONE] from [sqlite3_step(S)]) nor -** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) +** [tdsqlite3_step(S)] but has neither run to completion (returned +** [SQLITE_DONE] from [tdsqlite3_step(S)]) nor +** been reset using [tdsqlite3_reset(S)]. ^The tdsqlite3_stmt_busy(S) ** interface returns false if S is a NULL pointer. If S is not a ** NULL pointer and is not a pointer to a valid [prepared statement] ** object, then the behavior is undefined and probably undesirable. ** -** This interface can be used in combination [sqlite3_next_stmt()] +** This interface can be used in combination [tdsqlite3_next_stmt()] ** to locate all prepared statements associated with a database ** connection that are in need of being reset. This can be used, ** for example, in diagnostic routines to search for prepared ** statements that are holding a transaction open. */ -SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); +SQLITE_API int tdsqlite3_stmt_busy(tdsqlite3_stmt*); /* ** CAPI3REF: Dynamically Typed Value Object -** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** KEYWORDS: {protected tdsqlite3_value} {unprotected tdsqlite3_value} ** -** SQLite uses the sqlite3_value object to represent all values +** SQLite uses the tdsqlite3_value object to represent all values ** that can be stored in a database table. SQLite uses dynamic typing -** for the values it stores. ^Values stored in sqlite3_value objects +** for the values it stores. ^Values stored in tdsqlite3_value objects ** can be integers, floating point values, strings, BLOBs, or NULL. ** -** An sqlite3_value object may be either "protected" or "unprotected". -** Some interfaces require a protected sqlite3_value. Other interfaces -** will accept either a protected or an unprotected sqlite3_value. -** Every interface that accepts sqlite3_value arguments specifies -** whether or not it requires a protected sqlite3_value. The -** [sqlite3_value_dup()] interface can be used to construct a new -** protected sqlite3_value from an unprotected sqlite3_value. +** An tdsqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected tdsqlite3_value. Other interfaces +** will accept either a protected or an unprotected tdsqlite3_value. +** Every interface that accepts tdsqlite3_value arguments specifies +** whether or not it requires a protected tdsqlite3_value. The +** [tdsqlite3_value_dup()] interface can be used to construct a new +** protected tdsqlite3_value from an unprotected tdsqlite3_value. ** ** The terms "protected" and "unprotected" refer to whether or not ** a mutex is held. An internal mutex is held for a protected -** sqlite3_value object but no mutex is held for an unprotected -** sqlite3_value object. If SQLite is compiled to be single-threaded -** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** tdsqlite3_value object but no mutex is held for an unprotected +** tdsqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [tdsqlite3_threadsafe()] returning 0) ** or if SQLite is run in one of reduced mutex modes ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] ** then there is no distinction between protected and unprotected -** sqlite3_value objects and they can be used interchangeably. However, +** tdsqlite3_value objects and they can be used interchangeably. However, ** for maximum code portability it is recommended that applications ** still make the distinction between protected and unprotected -** sqlite3_value objects even when not strictly required. +** tdsqlite3_value objects even when not strictly required. ** -** ^The sqlite3_value objects that are passed as parameters into the +** ^The tdsqlite3_value objects that are passed as parameters into the ** implementation of [application-defined SQL functions] are protected. -** ^The sqlite3_value object returned by -** [sqlite3_column_value()] is unprotected. -** Unprotected sqlite3_value objects may only be used with -** [sqlite3_result_value()] and [sqlite3_bind_value()]. -** The [sqlite3_value_blob | sqlite3_value_type()] family of -** interfaces require protected sqlite3_value objects. +** ^The tdsqlite3_value object returned by +** [tdsqlite3_column_value()] is unprotected. +** Unprotected tdsqlite3_value objects may only be used as arguments +** to [tdsqlite3_result_value()], [tdsqlite3_bind_value()], and +** [tdsqlite3_value_dup()]. +** The [tdsqlite3_value_blob | tdsqlite3_value_type()] family of +** interfaces require protected tdsqlite3_value objects. */ -typedef struct Mem sqlite3_value; +typedef struct tdsqlite3_value tdsqlite3_value; /* ** CAPI3REF: SQL Function Context Object ** ** The context in which an SQL function executes is stored in an -** sqlite3_context object. ^A pointer to an sqlite3_context object +** tdsqlite3_context object. ^A pointer to an tdsqlite3_context object ** is always first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this -** pointer through into calls to [sqlite3_result_int | sqlite3_result()], -** [sqlite3_aggregate_context()], [sqlite3_user_data()], -** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], -** and/or [sqlite3_set_auxdata()]. +** pointer through into calls to [tdsqlite3_result_int | tdsqlite3_result()], +** [tdsqlite3_aggregate_context()], [tdsqlite3_user_data()], +** [tdsqlite3_context_db_handle()], [tdsqlite3_get_auxdata()], +** and/or [tdsqlite3_set_auxdata()]. */ -typedef struct sqlite3_context sqlite3_context; +typedef struct tdsqlite3_context tdsqlite3_context; /* ** CAPI3REF: Binding Values To Prepared Statements ** KEYWORDS: {host parameter} {host parameters} {host parameter name} ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** ^(In the SQL statement text input to [tdsqlite3_prepare_v2()] and its variants, ** literals may be replaced by a [parameter] that matches one of following ** templates: ** @@ -3956,37 +5227,37 @@ typedef struct sqlite3_context sqlite3_context; ** In the templates above, NNN represents an integer literal, ** and VVV represents an alphanumeric identifier.)^ ^The values of these ** parameters (also called "host parameter names" or "SQL parameters") -** can be set using the sqlite3_bind_*() routines defined here. +** can be set using the tdsqlite3_bind_*() routines defined here. ** -** ^The first argument to the sqlite3_bind_*() routines is always -** a pointer to the [sqlite3_stmt] object returned from -** [sqlite3_prepare_v2()] or its variants. +** ^The first argument to the tdsqlite3_bind_*() routines is always +** a pointer to the [tdsqlite3_stmt] object returned from +** [tdsqlite3_prepare_v2()] or its variants. ** ** ^The second argument is the index of the SQL parameter to be set. ** ^The leftmost SQL parameter has an index of 1. ^When the same named ** SQL parameter is used more than once, second and subsequent ** occurrences have the same index as the first occurrence. ** ^The index for named parameters can be looked up using the -** [sqlite3_bind_parameter_index()] API if desired. ^The index +** [tdsqlite3_bind_parameter_index()] API if desired. ^The index ** for "?NNN" parameters is the value of NNN. -** ^The NNN value must be between 1 and the [sqlite3_limit()] +** ^The NNN value must be between 1 and the [tdsqlite3_limit()] ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). ** ** ^The third argument is the value to bind to the parameter. -** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() -** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter -** is ignored and the end result is the same as sqlite3_bind_null(). +** ^If the third parameter to tdsqlite3_bind_text() or tdsqlite3_bind_text16() +** or tdsqlite3_bind_blob() is a NULL pointer then the fourth parameter +** is ignored and the end result is the same as tdsqlite3_bind_null(). ** ** ^(In those routines that have a fourth argument, its value is the ** number of bytes in the parameter. To be clear: the value is the ** number of <u>bytes</u> in the value, not the number of characters.)^ -** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** ^If the fourth parameter to tdsqlite3_bind_text() or tdsqlite3_bind_text16() ** is negative, then the length of the string is ** the number of bytes up to the first zero terminator. -** If the fourth parameter to sqlite3_bind_blob() is negative, then +** If the fourth parameter to tdsqlite3_bind_blob() is negative, then ** the behavior is undefined. -** If a non-negative fourth parameter is provided to sqlite3_bind_text() -** or sqlite3_bind_text16() or sqlite3_bind_text64() then +** If a non-negative fourth parameter is provided to tdsqlite3_bind_text() +** or tdsqlite3_bind_text16() or tdsqlite3_bind_text64() then ** that parameter must be the byte offset ** where the NUL terminator would occur assuming the string were NUL ** terminated. If any NUL characters occur at byte offsets less than @@ -3997,74 +5268,86 @@ typedef struct sqlite3_context sqlite3_context; ** ^The fifth argument to the BLOB and string binding interfaces ** is a destructor used to dispose of the BLOB or ** string after SQLite has finished with it. ^The destructor is called -** to dispose of the BLOB or string even if the call to bind API fails. +** to dispose of the BLOB or string even if the call to the bind API fails, +** except the destructor is not called if the third parameter is a NULL +** pointer or the fourth parameter is negative. ** ^If the fifth argument is ** the special value [SQLITE_STATIC], then SQLite assumes that the ** information is in static, unmanaged space and does not need to be freed. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before -** the sqlite3_bind_*() routine returns. +** the tdsqlite3_bind_*() routine returns. ** -** ^The sixth argument to sqlite3_bind_text64() must be one of +** ^The sixth argument to tdsqlite3_bind_text64() must be one of ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] ** to specify the encoding of the text in the third parameter. If -** the sixth argument to sqlite3_bind_text64() is not one of the +** the sixth argument to tdsqlite3_bind_text64() is not one of the ** allowed values shown above, or if the text encoding is different ** from the encoding specified by the sixth parameter, then the behavior ** is undefined. ** -** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** ^The tdsqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory ** (just an integer to hold its size) while it is being processed. ** Zeroblobs are intended to serve as placeholders for BLOBs whose ** content is later written using -** [sqlite3_blob_open | incremental BLOB I/O] routines. +** [tdsqlite3_blob_open | incremental BLOB I/O] routines. ** ^A negative value for the zeroblob results in a zero-length BLOB. ** -** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** ^The tdsqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in +** [prepared statement] S to have an SQL value of NULL, but to also be +** associated with the pointer P of type T. ^D is either a NULL pointer or +** a pointer to a destructor function for P. ^SQLite will invoke the +** destructor D with a single argument of P when it is finished using +** P. The T parameter should be a static string, preferably a string +** literal. The tdsqlite3_bind_pointer() routine is part of the +** [pointer passing interface] added for SQLite 3.20.0. +** +** ^If any of the tdsqlite3_bind_*() routines are called with a NULL pointer ** for the [prepared statement] or with a prepared statement for which -** [sqlite3_step()] has been called more recently than [sqlite3_reset()], -** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** [tdsqlite3_step()] has been called more recently than [tdsqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any tdsqlite3_bind_() ** routine is passed a [prepared statement] that has been finalized, the ** result is undefined and probably harmful. ** -** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Bindings are not cleared by the [tdsqlite3_reset()] routine. ** ^Unbound parameters are interpreted as NULL. ** -** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** ^The tdsqlite3_bind_* routines return [SQLITE_OK] on success or an ** [error code] if anything goes wrong. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB -** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or +** exceeds limits imposed by [tdsqlite3_limit]([SQLITE_LIMIT_LENGTH]) or ** [SQLITE_MAX_LENGTH]. ** ^[SQLITE_RANGE] is returned if the parameter ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. ** -** See also: [sqlite3_bind_parameter_count()], -** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +** See also: [tdsqlite3_bind_parameter_count()], +** [tdsqlite3_bind_parameter_name()], and [tdsqlite3_bind_parameter_index()]. */ -SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); -SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, +SQLITE_API int tdsqlite3_bind_blob(tdsqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int tdsqlite3_bind_blob64(tdsqlite3_stmt*, int, const void*, tdsqlite3_uint64, void(*)(void*)); -SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); -SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); -SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); -SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); -SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); -SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); -SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, +SQLITE_API int tdsqlite3_bind_double(tdsqlite3_stmt*, int, double); +SQLITE_API int tdsqlite3_bind_int(tdsqlite3_stmt*, int, int); +SQLITE_API int tdsqlite3_bind_int64(tdsqlite3_stmt*, int, tdsqlite3_int64); +SQLITE_API int tdsqlite3_bind_null(tdsqlite3_stmt*, int); +SQLITE_API int tdsqlite3_bind_text(tdsqlite3_stmt*,int,const char*,int,void(*)(void*)); +SQLITE_API int tdsqlite3_bind_text16(tdsqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int tdsqlite3_bind_text64(tdsqlite3_stmt*, int, const char*, tdsqlite3_uint64, void(*)(void*), unsigned char encoding); -SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); -SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); -SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); +SQLITE_API int tdsqlite3_bind_value(tdsqlite3_stmt*, int, const tdsqlite3_value*); +SQLITE_API int tdsqlite3_bind_pointer(tdsqlite3_stmt*, int, void*, const char*,void(*)(void*)); +SQLITE_API int tdsqlite3_bind_zeroblob(tdsqlite3_stmt*, int, int n); +SQLITE_API int tdsqlite3_bind_zeroblob64(tdsqlite3_stmt*, int, tdsqlite3_uint64); /* ** CAPI3REF: Number Of SQL Parameters -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^This routine can be used to find the number of [SQL parameters] ** in a [prepared statement]. SQL parameters are tokens of the ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as -** placeholders for values that are [sqlite3_bind_blob | bound] +** placeholders for values that are [tdsqlite3_bind_blob | bound] ** to the parameters at a later time. ** ** ^(This routine actually returns the index of the largest (rightmost) @@ -4072,17 +5355,17 @@ SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); ** number of unique parameters. If parameters of the ?NNN form are used, ** there may be gaps in the list.)^ ** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_name()], and -** [sqlite3_bind_parameter_index()]. +** See also: [tdsqlite3_bind_blob|tdsqlite3_bind()], +** [tdsqlite3_bind_parameter_name()], and +** [tdsqlite3_bind_parameter_index()]. */ -SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); +SQLITE_API int tdsqlite3_bind_parameter_count(tdsqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_bind_parameter_name(P,N) interface returns +** ^The tdsqlite3_bind_parameter_name(P,N) interface returns ** the name of the N-th [SQL parameter] in the [prepared statement] P. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" @@ -4097,73 +5380,78 @@ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); ** ^If the value N is out of range or if the N-th parameter is ** nameless, then NULL is returned. ^The returned string is ** always in UTF-8 encoding even if the named parameter was -** originally specified as UTF-16 in [sqlite3_prepare16()] or -** [sqlite3_prepare16_v2()]. +** originally specified as UTF-16 in [tdsqlite3_prepare16()], +** [tdsqlite3_prepare16_v2()], or [tdsqlite3_prepare16_v3()]. ** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. +** See also: [tdsqlite3_bind_blob|tdsqlite3_bind()], +** [tdsqlite3_bind_parameter_count()], and +** [tdsqlite3_bind_parameter_index()]. */ -SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); +SQLITE_API const char *tdsqlite3_bind_parameter_name(tdsqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^Return the index of an SQL parameter given its name. ^The ** index value returned is suitable for use as the second -** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** parameter to [tdsqlite3_bind_blob|tdsqlite3_bind()]. ^A zero ** is returned if no matching parameter is found. ^The parameter ** name must be given in UTF-8 even if the original statement -** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. +** was prepared from UTF-16 text using [tdsqlite3_prepare16_v2()] or +** [tdsqlite3_prepare16_v3()]. ** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_name()]. +** See also: [tdsqlite3_bind_blob|tdsqlite3_bind()], +** [tdsqlite3_bind_parameter_count()], and +** [tdsqlite3_bind_parameter_name()]. */ -SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); +SQLITE_API int tdsqlite3_bind_parameter_index(tdsqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset -** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Contrary to the intuition of many, [tdsqlite3_reset()] does not reset +** the [tdsqlite3_bind_blob | bindings] on a [prepared statement]. ** ^Use this routine to reset all host parameters to NULL. */ -SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); +SQLITE_API int tdsqlite3_clear_bindings(tdsqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^Return the number of columns in the result set returned by the -** [prepared statement]. ^This routine returns 0 if pStmt is an SQL -** statement that does not return data (for example an [UPDATE]). +** [prepared statement]. ^If this routine returns 0, that means the +** [prepared statement] returns no data (for example an [UPDATE]). +** ^However, just because this routine returns a positive number does not +** mean that one or more rows of data will be returned. ^A SELECT statement +** will always have a positive tdsqlite3_column_count() but depending on the +** WHERE clause constraints and the table content, it might return no rows. ** -** See also: [sqlite3_data_count()] +** See also: [tdsqlite3_data_count()] */ -SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_column_count(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^These routines return the name assigned to a particular column -** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** in the result set of a [SELECT] statement. ^The tdsqlite3_column_name() ** interface returns a pointer to a zero-terminated UTF-8 string -** and sqlite3_column_name16() returns a pointer to a zero-terminated +** and tdsqlite3_column_name16() returns a pointer to a zero-terminated ** UTF-16 string. ^The first parameter is the [prepared statement] ** that implements the [SELECT] statement. ^The second parameter is the ** column number. ^The leftmost column is number 0. ** ** ^The returned string pointer is valid until either the [prepared statement] -** is destroyed by [sqlite3_finalize()] or until the statement is automatically -** reprepared by the first call to [sqlite3_step()] for a particular run +** is destroyed by [tdsqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [tdsqlite3_step()] for a particular run ** or until the next call to -** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** tdsqlite3_column_name() or tdsqlite3_column_name16() on the same column. ** -** ^If sqlite3_malloc() fails during the processing of either routine +** ^If tdsqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. ** @@ -4172,12 +5460,12 @@ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); ** then the name of the column is unspecified and may change from ** one release of SQLite to the next. */ -SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); -SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); +SQLITE_API const char *tdsqlite3_column_name(tdsqlite3_stmt*, int N); +SQLITE_API const void *tdsqlite3_column_name16(tdsqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^These routines provide a means to determine the database, table, and ** table column that is the origin of a particular result column in @@ -4187,8 +5475,8 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); ** the database name, the _table_ routines return the table name, and ** the origin_ routines return the column name. ** ^The returned string is valid until the [prepared statement] is destroyed -** using [sqlite3_finalize()] or until the statement is automatically -** reprepared by the first call to [sqlite3_step()] for a particular run +** using [tdsqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [tdsqlite3_step()] for a particular run ** or until the same information is requested ** again in a different encoding. ** @@ -4202,7 +5490,7 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); ** ** ^If the Nth column returned by the statement is an expression or ** subquery and is not a column value, then all of these functions return -** NULL. ^These routine might also return NULL if a memory allocation error +** NULL. ^These routines might also return NULL if a memory allocation error ** occurs. ^Otherwise, they return the name of the attached database, table, ** or column that query result column was extracted from. ** @@ -4212,25 +5500,21 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); ** ^These APIs are only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. ** -** If two or more threads call one or more of these routines against the same -** prepared statement and column at the same time then the results are -** undefined. -** ** If two or more threads call one or more -** [sqlite3_column_database_name | column metadata interfaces] +** [tdsqlite3_column_database_name | column metadata interfaces] ** for the same [prepared statement] and result column ** at the same time then the results are undefined. */ -SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); +SQLITE_API const char *tdsqlite3_column_database_name(tdsqlite3_stmt*,int); +SQLITE_API const void *tdsqlite3_column_database_name16(tdsqlite3_stmt*,int); +SQLITE_API const char *tdsqlite3_column_table_name(tdsqlite3_stmt*,int); +SQLITE_API const void *tdsqlite3_column_table_name16(tdsqlite3_stmt*,int); +SQLITE_API const char *tdsqlite3_column_origin_name(tdsqlite3_stmt*,int); +SQLITE_API const void *tdsqlite3_column_origin_name16(tdsqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^(The first parameter is a [prepared statement]. ** If this statement is a [SELECT] statement and the Nth column of the @@ -4258,23 +5542,25 @@ SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); ** is associated with individual values, not with the containers ** used to hold those values. */ -SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); +SQLITE_API const char *tdsqlite3_column_decltype(tdsqlite3_stmt*,int); +SQLITE_API const void *tdsqlite3_column_decltype16(tdsqlite3_stmt*,int); /* ** CAPI3REF: Evaluate An SQL Statement -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** After a [prepared statement] has been prepared using either -** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy -** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** After a [prepared statement] has been prepared using any of +** [tdsqlite3_prepare_v2()], [tdsqlite3_prepare_v3()], [tdsqlite3_prepare16_v2()], +** or [tdsqlite3_prepare16_v3()] or one of the legacy +** interfaces [tdsqlite3_prepare()] or [tdsqlite3_prepare16()], this function ** must be called one or more times to evaluate the statement. ** -** The details of the behavior of the sqlite3_step() interface depend -** on whether the statement was prepared using the newer "v2" interface -** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy -** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the -** new "v2" interface is recommended for new applications but the legacy +** The details of the behavior of the tdsqlite3_step() interface depend +** on whether the statement was prepared using the newer "vX" interfaces +** [tdsqlite3_prepare_v3()], [tdsqlite3_prepare_v2()], [tdsqlite3_prepare16_v3()], +** [tdsqlite3_prepare16_v2()] or the older legacy +** interfaces [tdsqlite3_prepare()] and [tdsqlite3_prepare16()]. The use of the +** new "vX" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** ** ^In the legacy interface, the return value will be either [SQLITE_BUSY], @@ -4290,78 +5576,79 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); ** continuing. ** ** ^[SQLITE_DONE] means that the statement has finished executing -** successfully. sqlite3_step() should not be called again on this virtual -** machine without first calling [sqlite3_reset()] to reset the virtual +** successfully. tdsqlite3_step() should not be called again on this virtual +** machine without first calling [tdsqlite3_reset()] to reset the virtual ** machine back to its initial state. ** ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] ** is returned each time a new row of data is ready for processing by the ** caller. The values may be accessed using the [column access functions]. -** sqlite3_step() is called again to retrieve the next row of data. +** tdsqlite3_step() is called again to retrieve the next row of data. ** ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint -** violation) has occurred. sqlite3_step() should not be called again on -** the VM. More information may be found by calling [sqlite3_errmsg()]. +** violation) has occurred. tdsqlite3_step() should not be called again on +** the VM. More information may be found by calling [tdsqlite3_errmsg()]. ** ^With the legacy interface, a more specific error code (for example, ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) -** can be obtained by calling [sqlite3_reset()] on the +** can be obtained by calling [tdsqlite3_reset()] on the ** [prepared statement]. ^In the "v2" interface, -** the more specific error code is returned directly by sqlite3_step(). +** the more specific error code is returned directly by tdsqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has -** already been [sqlite3_finalize | finalized] or on one that had +** already been [tdsqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** ** For all versions of SQLite up to and including 3.6.23.1, a call to -** [sqlite3_reset()] was required after sqlite3_step() returned anything +** [tdsqlite3_reset()] was required after tdsqlite3_step() returned anything ** other than [SQLITE_ROW] before any subsequent invocation of -** sqlite3_step(). Failure to reset the prepared statement using -** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from -** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], -** sqlite3_step() began -** calling [sqlite3_reset()] automatically in this circumstance rather +** tdsqlite3_step(). Failure to reset the prepared statement using +** [tdsqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** tdsqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], +** tdsqlite3_step() began +** calling [tdsqlite3_reset()] automatically in this circumstance rather ** than returning [SQLITE_MISUSE]. This is not considered a compatibility ** break because any application that ever receives an SQLITE_MISUSE error ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option ** can be used to restore the legacy behavior. ** -** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step() +** <b>Goofy Interface Alert:</b> In the legacy interface, the tdsqlite3_step() ** API always returns a generic error code, [SQLITE_ERROR], following any ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call -** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** [tdsqlite3_reset()] or [tdsqlite3_finalize()] in order to find one of the ** specific [error codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements -** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead -** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** using [tdsqlite3_prepare_v3()] or [tdsqlite3_prepare_v2()] +** or [tdsqlite3_prepare16_v2()] or [tdsqlite3_prepare16_v3()] instead +** of the legacy [tdsqlite3_prepare()] and [tdsqlite3_prepare16()] interfaces, ** then the more specific [error codes] are returned directly -** by sqlite3_step(). The use of the "v2" interface is recommended. +** by tdsqlite3_step(). The use of the "vX" interfaces is recommended. */ -SQLITE_API int sqlite3_step(sqlite3_stmt*); +SQLITE_API int tdsqlite3_step(tdsqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_data_count(P) interface returns the number of columns in the +** ^The tdsqlite3_data_count(P) interface returns the number of columns in the ** current row of the result set of [prepared statement] P. ** ^If prepared statement P does not have results ready to return -** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of -** interfaces) then sqlite3_data_count(P) returns 0. -** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. -** ^The sqlite3_data_count(P) routine returns 0 if the previous call to -** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) -** will return non-zero if previous call to [sqlite3_step](P) returned +** (via calls to the [tdsqlite3_column_int | tdsqlite3_column()] family of +** interfaces) then tdsqlite3_data_count(P) returns 0. +** ^The tdsqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** ^The tdsqlite3_data_count(P) routine returns 0 if the previous call to +** [tdsqlite3_step](P) returned [SQLITE_DONE]. ^The tdsqlite3_data_count(P) +** will return non-zero if previous call to [tdsqlite3_step](P) returned ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] ** where it always returns zero since each step of that multi-step ** pragma returns 0 columns of data. ** -** See also: [sqlite3_column_count()] +** See also: [tdsqlite3_column_count()] */ -SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_data_count(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes @@ -4398,79 +5685,118 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Result Values From A Query ** KEYWORDS: {column access functions} -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt +** +** <b>Summary:</b> +** <blockquote><table border=0 cellpadding=0 cellspacing=0> +** <tr><td><b>tdsqlite3_column_blob</b><td>→<td>BLOB result +** <tr><td><b>tdsqlite3_column_double</b><td>→<td>REAL result +** <tr><td><b>tdsqlite3_column_int</b><td>→<td>32-bit INTEGER result +** <tr><td><b>tdsqlite3_column_int64</b><td>→<td>64-bit INTEGER result +** <tr><td><b>tdsqlite3_column_text</b><td>→<td>UTF-8 TEXT result +** <tr><td><b>tdsqlite3_column_text16</b><td>→<td>UTF-16 TEXT result +** <tr><td><b>tdsqlite3_column_value</b><td>→<td>The result as an +** [tdsqlite3_value|unprotected tdsqlite3_value] object. +** <tr><td> <td> <td> +** <tr><td><b>tdsqlite3_column_bytes</b><td>→<td>Size of a BLOB +** or a UTF-8 TEXT result in bytes +** <tr><td><b>tdsqlite3_column_bytes16 </b> +** <td>→ <td>Size of UTF-16 +** TEXT in bytes +** <tr><td><b>tdsqlite3_column_type</b><td>→<td>Default +** datatype of the result +** </table></blockquote> +** +** <b>Details:</b> ** ** ^These routines return information about a single column of the current ** result row of a query. ^In every case the first argument is a pointer -** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] -** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** to the [prepared statement] that is being evaluated (the [tdsqlite3_stmt*] +** that was returned from [tdsqlite3_prepare_v2()] or one of its variants) ** and the second argument is the index of the column for which information ** should be returned. ^The leftmost column of the result set has the index 0. ** ^The number of columns in the result can be determined using -** [sqlite3_column_count()]. +** [tdsqlite3_column_count()]. ** ** If the SQL statement does not currently point to a valid row, or if the ** column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to -** [sqlite3_step()] has returned [SQLITE_ROW] and neither -** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. -** If any of these routines are called after [sqlite3_reset()] or -** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** [tdsqlite3_step()] has returned [SQLITE_ROW] and neither +** [tdsqlite3_reset()] nor [tdsqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [tdsqlite3_reset()] or +** [tdsqlite3_finalize()] or after [tdsqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. -** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** If [tdsqlite3_step()] or [tdsqlite3_reset()] or [tdsqlite3_finalize()] ** are called from a different thread while any of these routines ** are pending, then the results are undefined. ** -** ^The sqlite3_column_type() routine returns the +** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16) +** each return the value of a result column in a specific data format. If +** the result column is not initially in the requested format (for example, +** if the query returns an integer but the tdsqlite3_column_text() interface +** is used to extract the value) then an automatic type conversion is performed. +** +** ^The tdsqlite3_column_type() routine returns the ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. ^The returned value is one of [SQLITE_INTEGER], -** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value -** returned by sqlite3_column_type() is only meaningful if no type -** conversions have occurred as described below. After a type conversion, -** the value returned by sqlite3_column_type() is undefined. Future -** versions of SQLite may change the behavior of sqlite3_column_type() +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. +** The return value of tdsqlite3_column_type() can be used to decide which +** of the first six interface should be used to extract the column value. +** The value returned by tdsqlite3_column_type() is only meaningful if no +** automatic type conversions have occurred for the value in question. +** After a type conversion, the result of calling tdsqlite3_column_type() +** is undefined, though harmless. Future +** versions of SQLite may change the behavior of tdsqlite3_column_type() ** following a type conversion. ** -** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** If the result is a BLOB or a TEXT string, then the tdsqlite3_column_bytes() +** or tdsqlite3_column_bytes16() interfaces can be used to determine the size +** of that BLOB or string. +** +** ^If the result is a BLOB or UTF-8 string then the tdsqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. -** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** ^If the result is a UTF-16 string, then tdsqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. -** ^If the result is a numeric value then sqlite3_column_bytes() uses -** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** ^If the result is a numeric value then tdsqlite3_column_bytes() uses +** [tdsqlite3_snprintf()] to convert that value to a UTF-8 string and returns ** the number of bytes in that string. -** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** ^If the result is NULL, then tdsqlite3_column_bytes() returns zero. ** -** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** ^If the result is a BLOB or UTF-16 string then the tdsqlite3_column_bytes16() ** routine returns the number of bytes in that BLOB or string. -** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** ^If the result is a UTF-8 string, then tdsqlite3_column_bytes16() converts ** the string to UTF-16 and then returns the number of bytes. -** ^If the result is a numeric value then sqlite3_column_bytes16() uses -** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** ^If the result is a numeric value then tdsqlite3_column_bytes16() uses +** [tdsqlite3_snprintf()] to convert that value to a UTF-16 string and returns ** the number of bytes in that string. -** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** ^If the result is NULL, then tdsqlite3_column_bytes16() returns zero. ** -** ^The values returned by [sqlite3_column_bytes()] and -** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** ^The values returned by [tdsqlite3_column_bytes()] and +** [tdsqlite3_column_bytes16()] do not include the zero terminators at the end ** of the string. ^For clarity: the values returned by -** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** [tdsqlite3_column_bytes()] and [tdsqlite3_column_bytes16()] are the number of ** bytes in the string, not the number of characters. ** -** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** ^Strings returned by tdsqlite3_column_text() and tdsqlite3_column_text16(), ** even empty strings, are always zero-terminated. ^The return -** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. -** -** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an -** [unprotected sqlite3_value] object. In a multithreaded environment, -** an unprotected sqlite3_value object may only be used safely with -** [sqlite3_bind_value()] and [sqlite3_result_value()]. -** If the [unprotected sqlite3_value] object returned by -** [sqlite3_column_value()] is used in any other way, including calls -** to routines like [sqlite3_value_int()], [sqlite3_value_text()], -** or [sqlite3_value_bytes()], the behavior is not threadsafe. -** -** These routines attempt to convert the value where appropriate. ^For -** example, if the internal representation is FLOAT and a text result -** is requested, [sqlite3_snprintf()] is used internally to perform the +** value from tdsqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** <b>Warning:</b> ^The object returned by [tdsqlite3_column_value()] is an +** [unprotected tdsqlite3_value] object. In a multithreaded environment, +** an unprotected tdsqlite3_value object may only be used safely with +** [tdsqlite3_bind_value()] and [tdsqlite3_result_value()]. +** If the [unprotected tdsqlite3_value] object returned by +** [tdsqlite3_column_value()] is used in any other way, including calls +** to routines like [tdsqlite3_value_int()], [tdsqlite3_value_text()], +** or [tdsqlite3_value_bytes()], the behavior is not threadsafe. +** Hence, the tdsqlite3_column_value() interface +** is normally only useful within the implementation of +** [application-defined SQL functions] or [virtual tables], not within +** top-level application code. +** +** The these routines may attempt to convert the datatype of the result. +** ^For example, if the internal representation is FLOAT and a text result +** is requested, [tdsqlite3_snprintf()] is used internally to perform the ** conversion automatically. ^(The following table details the conversions ** that are applied: ** @@ -4498,20 +5824,20 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** </blockquote>)^ ** ** Note that when type conversions occur, pointers returned by prior -** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or -** sqlite3_column_text16() may be invalidated. +** calls to tdsqlite3_column_blob(), tdsqlite3_column_text(), and/or +** tdsqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** ** <ul> -** <li> The initial content is a BLOB and sqlite3_column_text() or -** sqlite3_column_text16() is called. A zero-terminator might +** <li> The initial content is a BLOB and tdsqlite3_column_text() or +** tdsqlite3_column_text16() is called. A zero-terminator might ** need to be added to the string.</li> -** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or -** sqlite3_column_text16() is called. The content must be converted +** <li> The initial content is UTF-8 text and tdsqlite3_column_bytes16() or +** tdsqlite3_column_text16() is called. The content must be converted ** to UTF-16.</li> -** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or -** sqlite3_column_text() is called. The content must be converted +** <li> The initial content is UTF-16 text and tdsqlite3_column_bytes() or +** tdsqlite3_column_text() is called. The content must be converted ** to UTF-8.</li> ** </ul> ** @@ -4525,62 +5851,76 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** in one of the following ways: ** ** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> +** <li>tdsqlite3_column_text() followed by tdsqlite3_column_bytes()</li> +** <li>tdsqlite3_column_blob() followed by tdsqlite3_column_bytes()</li> +** <li>tdsqlite3_column_text16() followed by tdsqlite3_column_bytes16()</li> ** </ul> ** -** In other words, you should call sqlite3_column_text(), -** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result -** into the desired format, then invoke sqlite3_column_bytes() or -** sqlite3_column_bytes16() to find the size of the result. Do not mix calls -** to sqlite3_column_text() or sqlite3_column_blob() with calls to -** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() -** with calls to sqlite3_column_bytes(). +** In other words, you should call tdsqlite3_column_text(), +** tdsqlite3_column_blob(), or tdsqlite3_column_text16() first to force the result +** into the desired format, then invoke tdsqlite3_column_bytes() or +** tdsqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to tdsqlite3_column_text() or tdsqlite3_column_blob() with calls to +** tdsqlite3_column_bytes16(), and do not mix calls to tdsqlite3_column_text16() +** with calls to tdsqlite3_column_bytes(). ** ** ^The pointers returned are valid until a type conversion occurs as -** described above, or until [sqlite3_step()] or [sqlite3_reset()] or -** [sqlite3_finalize()] is called. ^The memory space used to hold strings -** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned -** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into -** [sqlite3_free()]. -** -** ^(If a memory allocation error occurs during the evaluation of any -** of these routines, a default value is returned. The default value -** is either the integer 0, the floating point number 0.0, or a NULL -** pointer. Subsequent calls to [sqlite3_errcode()] will return -** [SQLITE_NOMEM].)^ -*/ -SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); -SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); -SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); -SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); -SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); -SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); +** described above, or until [tdsqlite3_step()] or [tdsqlite3_reset()] or +** [tdsqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** from [tdsqlite3_column_blob()], [tdsqlite3_column_text()], etc. into +** [tdsqlite3_free()]. +** +** As long as the input parameters are correct, these routines will only +** fail if an out-of-memory error occurs during a format conversion. +** Only the following subset of interfaces are subject to out-of-memory +** errors: +** +** <ul> +** <li> tdsqlite3_column_blob() +** <li> tdsqlite3_column_text() +** <li> tdsqlite3_column_text16() +** <li> tdsqlite3_column_bytes() +** <li> tdsqlite3_column_bytes16() +** </ul> +** +** If an out-of-memory error occurs, then the return value from these +** routines is the same as if the column had contained an SQL NULL value. +** Valid SQL NULL returns can be distinguished from out-of-memory errors +** by invoking the [tdsqlite3_errcode()] immediately after the suspect +** return value is obtained and before any +** other SQLite interface is called on the same [database connection]. +*/ +SQLITE_API const void *tdsqlite3_column_blob(tdsqlite3_stmt*, int iCol); +SQLITE_API double tdsqlite3_column_double(tdsqlite3_stmt*, int iCol); +SQLITE_API int tdsqlite3_column_int(tdsqlite3_stmt*, int iCol); +SQLITE_API tdsqlite3_int64 tdsqlite3_column_int64(tdsqlite3_stmt*, int iCol); +SQLITE_API const unsigned char *tdsqlite3_column_text(tdsqlite3_stmt*, int iCol); +SQLITE_API const void *tdsqlite3_column_text16(tdsqlite3_stmt*, int iCol); +SQLITE_API tdsqlite3_value *tdsqlite3_column_value(tdsqlite3_stmt*, int iCol); +SQLITE_API int tdsqlite3_column_bytes(tdsqlite3_stmt*, int iCol); +SQLITE_API int tdsqlite3_column_bytes16(tdsqlite3_stmt*, int iCol); +SQLITE_API int tdsqlite3_column_type(tdsqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object -** DESTRUCTOR: sqlite3_stmt +** DESTRUCTOR: tdsqlite3_stmt ** -** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^The tdsqlite3_finalize() function is called to delete a [prepared statement]. ** ^If the most recent evaluation of the statement encountered no errors -** or if the statement is never been evaluated, then sqlite3_finalize() returns +** or if the statement is never been evaluated, then tdsqlite3_finalize() returns ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then -** sqlite3_finalize(S) returns the appropriate [error code] or +** tdsqlite3_finalize(S) returns the appropriate [error code] or ** [extended error code]. ** -** ^The sqlite3_finalize(S) routine can be called at any point during +** ^The tdsqlite3_finalize(S) routine can be called at any point during ** the life cycle of [prepared statement] S: ** before statement S is ever evaluated, after -** one or more calls to [sqlite3_reset()], or after any call -** to [sqlite3_step()] regardless of whether or not the statement has +** one or more calls to [tdsqlite3_reset()], or after any call +** to [tdsqlite3_step()] regardless of whether or not the statement has ** completed execution. ** -** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** ^Invoking tdsqlite3_finalize() on a NULL pointer is a harmless no-op. ** ** The application must finalize every [prepared statement] in order to avoid ** resource leaks. It is a grievous error for the application to try to use @@ -4588,49 +5928,49 @@ SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); ** statement after it has been finalized can result in undefined and ** undesirable behavior such as segfaults and heap corruption. */ -SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_finalize(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** The sqlite3_reset() function is called to reset a [prepared statement] +** The tdsqlite3_reset() function is called to reset a [prepared statement] ** object back to its initial state, ready to be re-executed. ** ^Any SQL statement variables that had values bound to them using -** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. -** Use [sqlite3_clear_bindings()] to reset the bindings. +** the [tdsqlite3_bind_blob | tdsqlite3_bind_*() API] retain their values. +** Use [tdsqlite3_clear_bindings()] to reset the bindings. ** -** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** ^The [tdsqlite3_reset(S)] interface resets the [prepared statement] S ** back to the beginning of its program. ** -** ^If the most recent call to [sqlite3_step(S)] for the +** ^If the most recent call to [tdsqlite3_step(S)] for the ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], -** or if [sqlite3_step(S)] has never before been called on S, -** then [sqlite3_reset(S)] returns [SQLITE_OK]. +** or if [tdsqlite3_step(S)] has never before been called on S, +** then [tdsqlite3_reset(S)] returns [SQLITE_OK]. ** -** ^If the most recent call to [sqlite3_step(S)] for the +** ^If the most recent call to [tdsqlite3_step(S)] for the ** [prepared statement] S indicated an error, then -** [sqlite3_reset(S)] returns an appropriate [error code]. +** [tdsqlite3_reset(S)] returns an appropriate [error code]. ** -** ^The [sqlite3_reset(S)] interface does not change the values -** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +** ^The [tdsqlite3_reset(S)] interface does not change the values +** of any [tdsqlite3_bind_blob|bindings] on the [prepared statement] S. */ -SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_reset(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions ** KEYWORDS: {function creation routines} -** KEYWORDS: {application-defined SQL function} -** KEYWORDS: {application-defined SQL functions} -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^These functions (collectively known as "function creation routines") ** are used to add SQL functions or aggregates or to redefine the behavior -** of existing SQL functions or aggregates. The only differences between -** these routines are the text encoding expected for -** the second parameter (the name of the function being created) -** and the presence or absence of a destructor callback for -** the application data pointer. +** of existing SQL functions or aggregates. The only differences between +** the three "tdsqlite3_create_function*" routines are the text encoding +** expected for the second parameter (the name of the function being +** created) and the presence or absence of a destructor callback for +** the application data pointer. Function tdsqlite3_create_window_function() +** is similar, but allows the user to supply the extra callback functions +** needed by [aggregate window functions]. ** ** ^The first parameter is the [database connection] to which the SQL ** function is to be added. ^If an application uses more than one database @@ -4648,7 +5988,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** is the number of arguments that the SQL function or ** aggregate takes. ^If this parameter is -1, then the SQL function or ** aggregate may take any number of arguments between 0 and the limit -** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** set by [tdsqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third ** parameter is less than -1 or greater than 127 then the behavior is ** undefined. ** @@ -4656,9 +5996,9 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. The application should set this parameter to ** [SQLITE_UTF16LE] if the function implementation invokes -** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the -** implementation invokes [sqlite3_value_text16be()] on an input, or -** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8] +** [tdsqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the +** implementation invokes [tdsqlite3_value_text16be()] on an input, or +** [SQLITE_UTF16] if [tdsqlite3_value_text16()] is used, or [SQLITE_UTF8] ** otherwise. ^The same SQL function may be registered multiple times using ** different preferred text encodings, with different implementations for ** each encoding. @@ -4673,10 +6013,28 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** perform additional optimizations on deterministic functions, so use ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible. ** +** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY] +** flag, which if present prevents the function from being invoked from +** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions, +** index expressions, or the WHERE clause of partial indexes. +** +** <span style="background-color:#ffff90;"> +** For best security, the [SQLITE_DIRECTONLY] flag is recommended for +** all application-defined SQL functions that do not need to be +** used inside of triggers, view, CHECK constraints, or other elements of +** the database schema. This flags is especially recommended for SQL +** functions that have side effects or reveal internal application state. +** Without this flag, an attacker might be able to modify the schema of +** a database file to include invocations of the function with parameters +** chosen by the attacker, which the application will then execute when +** the database file is opened and read. +** </span> +** ** ^(The fifth parameter is an arbitrary pointer. The implementation of the -** function can gain access to this pointer using [sqlite3_user_data()].)^ +** function can gain access to this pointer using [tdsqlite3_user_data()].)^ ** -** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are +** ^The sixth, seventh and eighth parameters passed to the three +** "tdsqlite3_create_function*" functions, xFunc, xStep and xFinal, are ** pointers to C-language functions that implement the SQL function or ** aggregate. ^A scalar SQL function requires an implementation of the xFunc ** callback only; NULL pointers must be passed as the xStep and xFinal @@ -4685,15 +6043,24 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** SQL function or aggregate, pass NULL pointers for all three function ** callbacks. ** -** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, -** then it is destructor for the application data pointer. -** The destructor is invoked when the function is deleted, either by being -** overloaded or when the database connection closes.)^ -** ^The destructor is also invoked if the call to -** sqlite3_create_function_v2() fails. -** ^When the destructor callback of the tenth parameter is invoked, it -** is passed a single argument which is a copy of the application data -** pointer which was the fifth parameter to sqlite3_create_function_v2(). +** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue +** and xInverse) passed to tdsqlite3_create_window_function are pointers to +** C-language callbacks that implement the new function. xStep and xFinal +** must both be non-NULL. xValue and xInverse may either both be NULL, in +** which case a regular aggregate function is created, or must both be +** non-NULL, in which case the new function may be used as either an aggregate +** or aggregate window function. More details regarding the implementation +** of aggregate window functions are +** [user-defined window functions|available here]. +** +** ^(If the final parameter to tdsqlite3_create_function_v2() or +** tdsqlite3_create_window_function() is not NULL, then it is destructor for +** the application data pointer. The destructor is invoked when the function +** is deleted, either by being overloaded or when the database connection +** closes.)^ ^The destructor is also invoked if the call to +** tdsqlite3_create_function_v2() fails. ^When the destructor callback is +** invoked, it is passed a single argument which is a copy of the application +** data pointer which was the fifth parameter to tdsqlite3_create_function_v2(). ** ** ^It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of @@ -4715,35 +6082,47 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** close the database connection nor finalize or reset the prepared ** statement in which the function is running. */ -SQLITE_API int sqlite3_create_function( - sqlite3 *db, +SQLITE_API int tdsqlite3_create_function( + tdsqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*) + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*) ); -SQLITE_API int sqlite3_create_function16( - sqlite3 *db, +SQLITE_API int tdsqlite3_create_function16( + tdsqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *pApp, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*) + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*) +); +SQLITE_API int tdsqlite3_create_function_v2( + tdsqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*), + void(*xDestroy)(void*) ); -SQLITE_API int sqlite3_create_function_v2( - sqlite3 *db, +SQLITE_API int tdsqlite3_create_window_function( + tdsqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*), + void (*xValue)(tdsqlite3_context*), + void (*xInverse)(tdsqlite3_context*,int,tdsqlite3_value**), void(*xDestroy)(void*) ); @@ -4758,17 +6137,77 @@ SQLITE_API int sqlite3_create_function_v2( #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */ #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* Deprecated */ -#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ +#define SQLITE_UTF16_ALIGNED 8 /* tdsqlite3_create_collation only */ /* ** CAPI3REF: Function Flags ** ** These constants may be ORed together with the ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument -** to [sqlite3_create_function()], [sqlite3_create_function16()], or -** [sqlite3_create_function_v2()]. +** to [tdsqlite3_create_function()], [tdsqlite3_create_function16()], or +** [tdsqlite3_create_function_v2()]. +** +** <dl> +** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd> +** The SQLITE_DETERMINISTIC flag means that the new function always gives +** the same output when the input parameters are the same. +** The [abs|abs() function] is deterministic, for example, but +** [randomblob|randomblob()] is not. Functions must +** be deterministic in order to be used in certain contexts such as +** with the WHERE clause of [partial indexes] or in [generated columns]. +** SQLite might also optimize deterministic functions by factoring them +** out of inner loops. +** </dd> +** +** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd> +** The SQLITE_DIRECTONLY flag means that the function may only be invoked +** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in +** schema structures such as [CHECK constraints], [DEFAULT clauses], +** [expression indexes], [partial indexes], or [generated columns]. +** The SQLITE_DIRECTONLY flags is a security feature which is recommended +** for all [application-defined SQL functions], and especially for functions +** that have side-effects or that could potentially leak sensitive +** information. +** </dd> +** +** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd> +** The SQLITE_INNOCUOUS flag means that the function is unlikely +** to cause problems even if misused. An innocuous function should have +** no side effects and should not depend on any values other than its +** input parameters. The [abs|abs() function] is an example of an +** innocuous function. +** The [load_extension() SQL function] is not innocuous because of its +** side effects. +** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not +** exactly the same. The [random|random() function] is an example of a +** function that is innocuous but not deterministic. +** <p>Some heightened security settings +** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF]) +** disable the use of SQL functions inside views and triggers and in +** schema structures such as [CHECK constraints], [DEFAULT clauses], +** [expression indexes], [partial indexes], and [generated columns] unless +** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions +** are innocuous. Developers are advised to avoid using the +** SQLITE_INNOCUOUS flag for application-defined functions unless the +** function has been carefully audited and found to be free of potentially +** security-adverse side-effects and information-leaks. +** </dd> +** +** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd> +** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call +** [tdsqlite3_value_subtype()] to inspect the sub-types of its arguments. +** Specifying this flag makes no difference for scalar or aggregate user +** functions. However, if it is not specified for a user-defined window +** function, then any sub-types belonging to arguments passed to the window +** function may be discarded before the window function is called (i.e. +** tdsqlite3_value_subtype() will always return 0). +** </dd> +** </dl> */ -#define SQLITE_DETERMINISTIC 0x800 +#define SQLITE_DETERMINISTIC 0x000000800 +#define SQLITE_DIRECTONLY 0x000080000 +#define SQLITE_SUBTYPE 0x000100000 +#define SQLITE_INNOCUOUS 0x000200000 /* ** CAPI3REF: Deprecated Functions @@ -4781,45 +6220,87 @@ SQLITE_API int sqlite3_create_function_v2( ** these functions, we will not explain what they do. */ #ifndef SQLITE_OMIT_DEPRECATED -SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); -SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); -SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), - void*,sqlite3_int64); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_aggregate_count(tdsqlite3_context*); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_expired(tdsqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_transfer_bindings(tdsqlite3_stmt*, tdsqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_global_recover(void); +SQLITE_API SQLITE_DEPRECATED void tdsqlite3_thread_cleanup(void); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_memory_alarm(void(*)(void*,tdsqlite3_int64,int), + void*,tdsqlite3_int64); #endif /* ** CAPI3REF: Obtaining SQL Values -** METHOD: sqlite3_value -** -** The C-language implementation of SQL functions and aggregates uses -** this set of interface routines to access the parameter values on -** the function or aggregate. -** -** The xFunc (for scalar functions) or xStep (for aggregates) parameters -** to [sqlite3_create_function()] and [sqlite3_create_function16()] -** define callbacks that implement the SQL functions and aggregates. -** The 3rd parameter to these callbacks is an array of pointers to -** [protected sqlite3_value] objects. There is one [sqlite3_value] object for -** each parameter to the SQL function. These routines are used to -** extract values from the [sqlite3_value] objects. -** -** These routines work only with [protected sqlite3_value] objects. -** Any attempt to use these routines on an [unprotected sqlite3_value] -** object results in undefined behavior. +** METHOD: tdsqlite3_value +** +** <b>Summary:</b> +** <blockquote><table border=0 cellpadding=0 cellspacing=0> +** <tr><td><b>tdsqlite3_value_blob</b><td>→<td>BLOB value +** <tr><td><b>tdsqlite3_value_double</b><td>→<td>REAL value +** <tr><td><b>tdsqlite3_value_int</b><td>→<td>32-bit INTEGER value +** <tr><td><b>tdsqlite3_value_int64</b><td>→<td>64-bit INTEGER value +** <tr><td><b>tdsqlite3_value_pointer</b><td>→<td>Pointer value +** <tr><td><b>tdsqlite3_value_text</b><td>→<td>UTF-8 TEXT value +** <tr><td><b>tdsqlite3_value_text16</b><td>→<td>UTF-16 TEXT value in +** the native byteorder +** <tr><td><b>tdsqlite3_value_text16be</b><td>→<td>UTF-16be TEXT value +** <tr><td><b>tdsqlite3_value_text16le</b><td>→<td>UTF-16le TEXT value +** <tr><td> <td> <td> +** <tr><td><b>tdsqlite3_value_bytes</b><td>→<td>Size of a BLOB +** or a UTF-8 TEXT in bytes +** <tr><td><b>tdsqlite3_value_bytes16 </b> +** <td>→ <td>Size of UTF-16 +** TEXT in bytes +** <tr><td><b>tdsqlite3_value_type</b><td>→<td>Default +** datatype of the value +** <tr><td><b>tdsqlite3_value_numeric_type </b> +** <td>→ <td>Best numeric datatype of the value +** <tr><td><b>tdsqlite3_value_nochange </b> +** <td>→ <td>True if the column is unchanged in an UPDATE +** against a virtual table. +** <tr><td><b>tdsqlite3_value_frombind </b> +** <td>→ <td>True if value originated from a [bound parameter] +** </table></blockquote> +** +** <b>Details:</b> +** +** These routines extract type, size, and content information from +** [protected tdsqlite3_value] objects. Protected tdsqlite3_value objects +** are used to pass parameter information into the functions that +** implement [application-defined SQL functions] and [virtual tables]. +** +** These routines work only with [protected tdsqlite3_value] objects. +** Any attempt to use these routines on an [unprotected tdsqlite3_value] +** is not threadsafe. ** ** ^These routines work just like the corresponding [column access functions] -** except that these routines take a single [protected sqlite3_value] object -** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** except that these routines take a single [protected tdsqlite3_value] object +** pointer instead of a [tdsqlite3_stmt*] pointer and an integer column number. ** -** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** ^The tdsqlite3_value_text16() interface extracts a UTF-16 string ** in the native byte-order of the host machine. ^The -** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** tdsqlite3_value_text16be() and tdsqlite3_value_text16le() interfaces ** extract UTF-16 strings as big-endian and little-endian respectively. ** -** ^(The sqlite3_value_numeric_type() interface attempts to apply +** ^If [tdsqlite3_value] object V was initialized +** using [tdsqlite3_bind_pointer(S,I,P,X,D)] or [tdsqlite3_result_pointer(C,P,X,D)] +** and if X and Y are strings that compare equal according to strcmp(X,Y), +** then tdsqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise, +** tdsqlite3_value_pointer(V,Y) returns a NULL. The tdsqlite3_bind_pointer() +** routine is part of the [pointer passing interface] added for SQLite 3.20.0. +** +** ^(The tdsqlite3_value_type(V) interface returns the +** [SQLITE_INTEGER | datatype code] for the initial datatype of the +** [tdsqlite3_value] object V. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^ +** Other interfaces might change the datatype for an tdsqlite3_value object. +** For example, if the datatype is initially SQLITE_INTEGER and +** tdsqlite3_value_text(V) is called to extract a text value for that +** integer, then subsequent calls to tdsqlite3_value_type(V) might return +** SQLITE_TEXT. Whether or not a persistent internal datatype conversion +** occurs is undefined and may change from one release of SQLite to the next. +** +** ^(The tdsqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other @@ -4827,136 +6308,175 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6 ** then the conversion is performed. Otherwise no conversion occurs. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ ** +** ^Within the [xUpdate] method of a [virtual table], the +** tdsqlite3_value_nochange(X) interface returns true if and only if +** the column corresponding to X is unchanged by the UPDATE operation +** that the xUpdate method call was invoked to implement and if +** and the prior [xColumn] method call that was invoked to extracted +** the value for that column returned without setting a result (probably +** because it queried [tdsqlite3_vtab_nochange()] and found that the column +** was unchanging). ^Within an [xUpdate] method, any value for which +** tdsqlite3_value_nochange(X) is true will in all other respects appear +** to be a NULL value. If tdsqlite3_value_nochange(X) is invoked anywhere other +** than within an [xUpdate] method call for an UPDATE statement, then +** the return value is arbitrary and meaningless. +** +** ^The tdsqlite3_value_frombind(X) interface returns non-zero if the +** value X originated from one of the [tdsqlite3_bind_int|tdsqlite3_bind()] +** interfaces. ^If X comes from an SQL literal value, or a table column, +** or an expression, then tdsqlite3_value_frombind(X) returns zero. +** ** Please pay particular attention to the fact that the pointer returned -** from [sqlite3_value_blob()], [sqlite3_value_text()], or -** [sqlite3_value_text16()] can be invalidated by a subsequent call to -** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], -** or [sqlite3_value_text16()]. +** from [tdsqlite3_value_blob()], [tdsqlite3_value_text()], or +** [tdsqlite3_value_text16()] can be invalidated by a subsequent call to +** [tdsqlite3_value_bytes()], [tdsqlite3_value_bytes16()], [tdsqlite3_value_text()], +** or [tdsqlite3_value_text16()]. ** ** These routines must be called from the same thread as -** the SQL function that supplied the [sqlite3_value*] parameters. -*/ -SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); -SQLITE_API int sqlite3_value_bytes(sqlite3_value*); -SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); -SQLITE_API double sqlite3_value_double(sqlite3_value*); -SQLITE_API int sqlite3_value_int(sqlite3_value*); -SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); -SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); -SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); -SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); -SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); -SQLITE_API int sqlite3_value_type(sqlite3_value*); -SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); +** the SQL function that supplied the [tdsqlite3_value*] parameters. +** +** As long as the input parameter is correct, these routines can only +** fail if an out-of-memory error occurs during a format conversion. +** Only the following subset of interfaces are subject to out-of-memory +** errors: +** +** <ul> +** <li> tdsqlite3_value_blob() +** <li> tdsqlite3_value_text() +** <li> tdsqlite3_value_text16() +** <li> tdsqlite3_value_text16le() +** <li> tdsqlite3_value_text16be() +** <li> tdsqlite3_value_bytes() +** <li> tdsqlite3_value_bytes16() +** </ul> +** +** If an out-of-memory error occurs, then the return value from these +** routines is the same as if the column had contained an SQL NULL value. +** Valid SQL NULL returns can be distinguished from out-of-memory errors +** by invoking the [tdsqlite3_errcode()] immediately after the suspect +** return value is obtained and before any +** other SQLite interface is called on the same [database connection]. +*/ +SQLITE_API const void *tdsqlite3_value_blob(tdsqlite3_value*); +SQLITE_API double tdsqlite3_value_double(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_int(tdsqlite3_value*); +SQLITE_API tdsqlite3_int64 tdsqlite3_value_int64(tdsqlite3_value*); +SQLITE_API void *tdsqlite3_value_pointer(tdsqlite3_value*, const char*); +SQLITE_API const unsigned char *tdsqlite3_value_text(tdsqlite3_value*); +SQLITE_API const void *tdsqlite3_value_text16(tdsqlite3_value*); +SQLITE_API const void *tdsqlite3_value_text16le(tdsqlite3_value*); +SQLITE_API const void *tdsqlite3_value_text16be(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_bytes(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_bytes16(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_type(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_numeric_type(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_nochange(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_frombind(tdsqlite3_value*); /* ** CAPI3REF: Finding The Subtype Of SQL Values -** METHOD: sqlite3_value +** METHOD: tdsqlite3_value ** -** The sqlite3_value_subtype(V) function returns the subtype for +** The tdsqlite3_value_subtype(V) function returns the subtype for ** an [application-defined SQL function] argument V. The subtype ** information can be used to pass a limited amount of context from -** one SQL function to another. Use the [sqlite3_result_subtype()] +** one SQL function to another. Use the [tdsqlite3_result_subtype()] ** routine to set the subtype for the return value of an SQL function. -** -** SQLite makes no use of subtype itself. It merely passes the subtype -** from the result of one [application-defined SQL function] into the -** input of another. */ -SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); +SQLITE_API unsigned int tdsqlite3_value_subtype(tdsqlite3_value*); /* ** CAPI3REF: Copy And Free SQL Values -** METHOD: sqlite3_value +** METHOD: tdsqlite3_value ** -** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] -** object D and returns a pointer to that copy. ^The [sqlite3_value] returned -** is a [protected sqlite3_value] object even if the input is not. -** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a +** ^The tdsqlite3_value_dup(V) interface makes a copy of the [tdsqlite3_value] +** object D and returns a pointer to that copy. ^The [tdsqlite3_value] returned +** is a [protected tdsqlite3_value] object even if the input is not. +** ^The tdsqlite3_value_dup(V) interface returns NULL if V is NULL or if a ** memory allocation fails. ** -** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object -** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer -** then sqlite3_value_free(V) is a harmless no-op. +** ^The tdsqlite3_value_free(V) interface frees an [tdsqlite3_value] object +** previously obtained from [tdsqlite3_value_dup()]. ^If V is a NULL pointer +** then tdsqlite3_value_free(V) is a harmless no-op. */ -SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*); -SQLITE_API void sqlite3_value_free(sqlite3_value*); +SQLITE_API tdsqlite3_value *tdsqlite3_value_dup(const tdsqlite3_value*); +SQLITE_API void tdsqlite3_value_free(tdsqlite3_value*); /* ** CAPI3REF: Obtain Aggregate Function Context -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** ** Implementations of aggregate SQL functions use this ** routine to allocate memory for storing their state. ** -** ^The first time the sqlite3_aggregate_context(C,N) routine is called -** for a particular aggregate function, SQLite -** allocates N of memory, zeroes out that memory, and returns a pointer +** ^The first time the tdsqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite allocates +** N bytes of memory, zeroes out that memory, and returns a pointer ** to the new memory. ^On second and subsequent calls to -** sqlite3_aggregate_context() for the same aggregate function instance, +** tdsqlite3_aggregate_context() for the same aggregate function instance, ** the same buffer is returned. Sqlite3_aggregate_context() is normally ** called once for each invocation of the xStep callback and then one ** last time when the xFinal callback is invoked. ^(When no rows match ** an aggregate query, the xStep() callback of the aggregate function ** implementation is never called and xFinal() is called exactly once. -** In those cases, sqlite3_aggregate_context() might be called for the +** In those cases, tdsqlite3_aggregate_context() might be called for the ** first time from within xFinal().)^ ** -** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer +** ^The tdsqlite3_aggregate_context(C,N) routine returns a NULL pointer ** when first called if N is less than or equal to zero or if a memory ** allocate error occurs. ** -** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** ^(The amount of space allocated by tdsqlite3_aggregate_context(C,N) is ** determined by the N parameter on first successful call. Changing the -** value of N in subsequent call to sqlite3_aggregate_context() within +** value of N in any subsequents call to tdsqlite3_aggregate_context() within ** the same aggregate function instance will not resize the memory ** allocation.)^ Within the xFinal callback, it is customary to set -** N=0 in calls to sqlite3_aggregate_context(C,N) so that no +** N=0 in calls to tdsqlite3_aggregate_context(C,N) so that no ** pointless memory allocations occur. ** ** ^SQLite automatically frees the memory allocated by -** sqlite3_aggregate_context() when the aggregate query concludes. +** tdsqlite3_aggregate_context() when the aggregate query concludes. ** ** The first parameter must be a copy of the -** [sqlite3_context | SQL function context] that is the first parameter +** [tdsqlite3_context | SQL function context] that is the first parameter ** to the xStep or xFinal callback routine that implements the aggregate ** function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. */ -SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); +SQLITE_API void *tdsqlite3_aggregate_context(tdsqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** -** ^The sqlite3_user_data() interface returns a copy of +** ^The tdsqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally +** of the [tdsqlite3_create_function()] +** and [tdsqlite3_create_function16()] routines that originally ** registered the application defined function. ** ** This routine must be called from the same thread in which ** the application-defined function is running. */ -SQLITE_API void *sqlite3_user_data(sqlite3_context*); +SQLITE_API void *tdsqlite3_user_data(tdsqlite3_context*); /* ** CAPI3REF: Database Connection For Functions -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** -** ^The sqlite3_context_db_handle() interface returns a copy of +** ^The tdsqlite3_context_db_handle() interface returns a copy of ** the pointer to the [database connection] (the 1st parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally +** of the [tdsqlite3_create_function()] +** and [tdsqlite3_create_function16()] routines that originally ** registered the application defined function. */ -SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); +SQLITE_API tdsqlite3 *tdsqlite3_context_db_handle(tdsqlite3_context*); /* ** CAPI3REF: Function Auxiliary Data -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** ** These functions may be used by (non-aggregate) SQL functions to ** associate metadata with argument values. If the same value is passed to @@ -4969,52 +6489,57 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); ** the compiled regular expression can be reused on multiple ** invocations of the same function. ** -** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata -** associated by the sqlite3_set_auxdata() function with the Nth argument -** value to the application-defined function. ^If there is no metadata -** associated with the function argument, this sqlite3_get_auxdata() interface +** ^The tdsqlite3_get_auxdata(C,N) interface returns a pointer to the metadata +** associated by the tdsqlite3_set_auxdata(C,N,P,X) function with the Nth argument +** value to the application-defined function. ^N is zero for the left-most +** function argument. ^If there is no metadata +** associated with the function argument, the tdsqlite3_get_auxdata(C,N) interface ** returns a NULL pointer. ** -** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th +** ^The tdsqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th ** argument of the application-defined function. ^Subsequent -** calls to sqlite3_get_auxdata(C,N) return P from the most recent -** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or +** calls to tdsqlite3_get_auxdata(C,N) return P from the most recent +** tdsqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or ** NULL if the metadata has been discarded. -** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, +** ^After each call to tdsqlite3_set_auxdata(C,N,P,X) where X is not NULL, ** SQLite will invoke the destructor function X with parameter P exactly ** once, when the metadata is discarded. ** SQLite is free to discard the metadata at any time, including: <ul> ** <li> ^(when the corresponding function parameter changes)^, or -** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the +** <li> ^(when [tdsqlite3_reset()] or [tdsqlite3_finalize()] is called for the ** SQL statement)^, or -** <li> ^(when sqlite3_set_auxdata() is invoked again on the same +** <li> ^(when tdsqlite3_set_auxdata() is invoked again on the same ** parameter)^, or -** <li> ^(during the original sqlite3_set_auxdata() call when a memory +** <li> ^(during the original tdsqlite3_set_auxdata() call when a memory ** allocation error occurs.)^ </ul> ** ** Note the last bullet in particular. The destructor X in -** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the -** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() +** tdsqlite3_set_auxdata(C,N,P,X) might be called immediately, before the +** tdsqlite3_set_auxdata() interface even returns. Hence tdsqlite3_set_auxdata() ** should be called near the end of the function implementation and the ** function implementation should not make any use of P after -** sqlite3_set_auxdata() has been called. +** tdsqlite3_set_auxdata() has been called. ** ** ^(In practice, metadata is preserved between function calls for ** function parameters that are compile-time constants, including literal ** values and [parameters] and expressions composed from the same.)^ ** +** The value of the N parameter to these interfaces should be non-negative. +** Future enhancements may make use of negative N values to define new +** kinds of function caching behavior. +** ** These routines must be called from the same thread in which ** the SQL function is running. */ -SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); -SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); +SQLITE_API void *tdsqlite3_get_auxdata(tdsqlite3_context*, int N); +SQLITE_API void tdsqlite3_set_auxdata(tdsqlite3_context*, int N, void*, void (*)(void*)); /* ** CAPI3REF: Constants Defining Special Destructor Behavior ** ** These are special values for the destructor that is passed in as the -** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** final argument to routines like [tdsqlite3_result_blob()]. ^If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant ** and will never change. It does not need to be destroyed. ^The ** SQLITE_TRANSIENT value means that the content will likely change in @@ -5024,89 +6549,89 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi ** The typedef is necessary to work around problems in certain ** C++ compilers. */ -typedef void (*sqlite3_destructor_type)(void*); -#define SQLITE_STATIC ((sqlite3_destructor_type)0) -#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) +typedef void (*tdsqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((tdsqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((tdsqlite3_destructor_type)-1) /* ** CAPI3REF: Setting The Result Of An SQL Function -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** ** These routines are used by the xFunc or xFinal callbacks that ** implement SQL functions and aggregates. See -** [sqlite3_create_function()] and [sqlite3_create_function16()] +** [tdsqlite3_create_function()] and [tdsqlite3_create_function16()] ** for additional information. ** ** These functions work very much like the [parameter binding] family of ** functions used to bind values to host parameters in prepared statements. ** Refer to the [SQL parameter] documentation for additional information. ** -** ^The sqlite3_result_blob() interface sets the result from +** ^The tdsqlite3_result_blob() interface sets the result from ** an application-defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the ** third parameter. ** -** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) +** ^The tdsqlite3_result_zeroblob(C,N) and tdsqlite3_result_zeroblob64(C,N) ** interfaces set the result of the application-defined function to be ** a BLOB containing all zero bytes and N bytes in size. ** -** ^The sqlite3_result_double() interface sets the result from +** ^The tdsqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified ** by its 2nd argument. ** -** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** ^The tdsqlite3_result_error() and tdsqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. ** ^SQLite uses the string pointed to by the -** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** 2nd parameter of tdsqlite3_result_error() or tdsqlite3_result_error16() ** as the text of an error message. ^SQLite interprets the error -** message string from sqlite3_result_error() as UTF-8. ^SQLite -** interprets the string from sqlite3_result_error16() as UTF-16 in native -** byte order. ^If the third parameter to sqlite3_result_error() -** or sqlite3_result_error16() is negative then SQLite takes as the error +** message string from tdsqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from tdsqlite3_result_error16() as UTF-16 in native +** byte order. ^If the third parameter to tdsqlite3_result_error() +** or tdsqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. -** ^If the third parameter to sqlite3_result_error() or -** sqlite3_result_error16() is non-negative then SQLite takes that many +** ^If the third parameter to tdsqlite3_result_error() or +** tdsqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. -** ^The sqlite3_result_error() and sqlite3_result_error16() +** ^The tdsqlite3_result_error() and tdsqlite3_result_error16() ** routines make a private copy of the error message text before ** they return. Hence, the calling function can deallocate or ** modify the text after they return without harm. -** ^The sqlite3_result_error_code() function changes the error code +** ^The tdsqlite3_result_error_code() function changes the error code ** returned by SQLite as a result of an error in a function. ^By default, -** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() -** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** the error code is SQLITE_ERROR. ^A subsequent call to tdsqlite3_result_error() +** or tdsqlite3_result_error16() resets the error code to SQLITE_ERROR. ** -** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an +** ^The tdsqlite3_result_error_toobig() interface causes SQLite to throw an ** error indicating that a string or BLOB is too long to represent. ** -** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an +** ^The tdsqlite3_result_error_nomem() interface causes SQLite to throw an ** error indicating that a memory allocation failed. ** -** ^The sqlite3_result_int() interface sets the return value +** ^The tdsqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. -** ^The sqlite3_result_int64() interface sets the return value +** ^The tdsqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** -** ^The sqlite3_result_null() interface sets the return value +** ^The tdsqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** -** ^The sqlite3_result_text(), sqlite3_result_text16(), -** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** ^The tdsqlite3_result_text(), tdsqlite3_result_text16(), +** tdsqlite3_result_text16le(), and tdsqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. -** ^The sqlite3_result_text64() interface sets the return value of an +** ^The tdsqlite3_result_text64() interface sets the return value of an ** application-defined function to be a text string in an encoding ** specified by the fifth (and last) parameter, which must be one ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. ** ^SQLite takes the text result from the application from -** the 2nd parameter of the sqlite3_result_text* interfaces. -** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** the 2nd parameter of the tdsqlite3_result_text* interfaces. +** ^If the 3rd parameter to the tdsqlite3_result_text* interfaces ** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. -** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** ^If the 3rd parameter to the tdsqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. If the 3rd parameter is non-negative, then it @@ -5115,82 +6640,94 @@ typedef void (*sqlite3_destructor_type)(void*); ** in the string at a byte offset that is less than the value of the 3rd ** parameter, then the resulting string will contain embedded NULs and the ** result of expressions operating on strings with embedded NULs is undefined. -** ^If the 4th parameter to the sqlite3_result_text* interfaces -** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** ^If the 4th parameter to the tdsqlite3_result_text* interfaces +** or tdsqlite3_result_blob is a non-NULL pointer, then SQLite calls that ** function as the destructor on the text or BLOB result when it has ** finished using that result. -** ^If the 4th parameter to the sqlite3_result_text* interfaces or to -** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** ^If the 4th parameter to the tdsqlite3_result_text* interfaces or to +** tdsqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite ** assumes that the text or BLOB result is in constant space and does not ** copy the content of the parameter nor call a destructor on the content ** when it has finished using that result. -** ^If the 4th parameter to the sqlite3_result_text* interfaces -** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT -** then SQLite makes a copy of the result into space obtained from -** from [sqlite3_malloc()] before it returns. +** ^If the 4th parameter to the tdsqlite3_result_text* interfaces +** or tdsqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained +** from [tdsqlite3_malloc()] before it returns. ** -** ^The sqlite3_result_value() interface sets the result of +** ^The tdsqlite3_result_value() interface sets the result of ** the application-defined function to be a copy of the -** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The -** sqlite3_result_value() interface makes a copy of the [sqlite3_value] -** so that the [sqlite3_value] specified in the parameter may change or -** be deallocated after sqlite3_result_value() returns without harm. -** ^A [protected sqlite3_value] object may always be used where an -** [unprotected sqlite3_value] object is required, so either -** kind of [sqlite3_value] object can be used with this interface. +** [unprotected tdsqlite3_value] object specified by the 2nd parameter. ^The +** tdsqlite3_result_value() interface makes a copy of the [tdsqlite3_value] +** so that the [tdsqlite3_value] specified in the parameter may change or +** be deallocated after tdsqlite3_result_value() returns without harm. +** ^A [protected tdsqlite3_value] object may always be used where an +** [unprotected tdsqlite3_value] object is required, so either +** kind of [tdsqlite3_value] object can be used with this interface. +** +** ^The tdsqlite3_result_pointer(C,P,T,D) interface sets the result to an +** SQL NULL value, just like [tdsqlite3_result_null(C)], except that it +** also associates the host-language pointer P or type T with that +** NULL value such that the pointer can be retrieved within an +** [application-defined SQL function] using [tdsqlite3_value_pointer()]. +** ^If the D parameter is not NULL, then it is a pointer to a destructor +** for the P parameter. ^SQLite invokes D with P as its only argument +** when SQLite is finished with P. The T parameter should be a static +** string and preferably a string literal. The tdsqlite3_result_pointer() +** routine is part of the [pointer passing interface] added for SQLite 3.20.0. ** ** If these routines are called from within the different thread ** than the one containing the application-defined function that received -** the [sqlite3_context] pointer, the results are undefined. -*/ -SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*, - sqlite3_uint64,void(*)(void*)); -SQLITE_API void sqlite3_result_double(sqlite3_context*, double); -SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); -SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); -SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); -SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); -SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); -SQLITE_API void sqlite3_result_int(sqlite3_context*, int); -SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); -SQLITE_API void sqlite3_result_null(sqlite3_context*); -SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, +** the [tdsqlite3_context] pointer, the results are undefined. +*/ +SQLITE_API void tdsqlite3_result_blob(tdsqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void tdsqlite3_result_blob64(tdsqlite3_context*,const void*, + tdsqlite3_uint64,void(*)(void*)); +SQLITE_API void tdsqlite3_result_double(tdsqlite3_context*, double); +SQLITE_API void tdsqlite3_result_error(tdsqlite3_context*, const char*, int); +SQLITE_API void tdsqlite3_result_error16(tdsqlite3_context*, const void*, int); +SQLITE_API void tdsqlite3_result_error_toobig(tdsqlite3_context*); +SQLITE_API void tdsqlite3_result_error_nomem(tdsqlite3_context*); +SQLITE_API void tdsqlite3_result_error_code(tdsqlite3_context*, int); +SQLITE_API void tdsqlite3_result_int(tdsqlite3_context*, int); +SQLITE_API void tdsqlite3_result_int64(tdsqlite3_context*, tdsqlite3_int64); +SQLITE_API void tdsqlite3_result_null(tdsqlite3_context*); +SQLITE_API void tdsqlite3_result_text(tdsqlite3_context*, const char*, int, void(*)(void*)); +SQLITE_API void tdsqlite3_result_text64(tdsqlite3_context*, const char*,tdsqlite3_uint64, void(*)(void*), unsigned char encoding); -SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); -SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); -SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); -SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); -SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); +SQLITE_API void tdsqlite3_result_text16(tdsqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void tdsqlite3_result_text16le(tdsqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void tdsqlite3_result_text16be(tdsqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void tdsqlite3_result_value(tdsqlite3_context*, tdsqlite3_value*); +SQLITE_API void tdsqlite3_result_pointer(tdsqlite3_context*, void*,const char*,void(*)(void*)); +SQLITE_API void tdsqlite3_result_zeroblob(tdsqlite3_context*, int n); +SQLITE_API int tdsqlite3_result_zeroblob64(tdsqlite3_context*, tdsqlite3_uint64 n); /* ** CAPI3REF: Setting The Subtype Of An SQL Function -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** -** The sqlite3_result_subtype(C,T) function causes the subtype of +** The tdsqlite3_result_subtype(C,T) function causes the subtype of ** the result from the [application-defined SQL function] with -** [sqlite3_context] C to be the value T. Only the lower 8 bits +** [tdsqlite3_context] C to be the value T. Only the lower 8 bits ** of the subtype T are preserved in current versions of SQLite; ** higher order bits are discarded. ** The number of subtype bytes preserved by SQLite might increase ** in future releases of SQLite. */ -SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); +SQLITE_API void tdsqlite3_result_subtype(tdsqlite3_context*,unsigned int); /* ** CAPI3REF: Define New Collating Sequences -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^These functions add, remove, or modify a [collation] associated ** with the [database connection] specified as the first argument. ** ** ^The name of the collation is a UTF-8 string -** for sqlite3_create_collation() and sqlite3_create_collation_v2() -** and a UTF-16 string in native byte order for sqlite3_create_collation16(). -** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** for tdsqlite3_create_collation() and tdsqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for tdsqlite3_create_collation16(). +** ^Collation names that compare equal according to [tdsqlite3_strnicmp()] are ** considered to be the same name. ** ** ^(The third argument (eTextRep) must be one of the constants: @@ -5202,7 +6739,7 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); ** <li> [SQLITE_UTF16_ALIGNED]. ** </ul>)^ ** ^The eTextRep argument determines the encoding of strings passed -** to the collating function callback, xCallback. +** to the collating function callback, xCompare. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep ** force strings to be UTF16 with native byte order. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin @@ -5211,18 +6748,19 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); ** ^The fourth argument, pArg, is an application data pointer that is passed ** through as the first argument to the collating function callback. ** -** ^The fifth argument, xCallback, is a pointer to the collating function. +** ^The fifth argument, xCompare, is a pointer to the collating function. ** ^Multiple collating functions can be registered using the same name but ** with different eTextRep parameters and SQLite will use whichever ** function requires the least amount of data transformation. -** ^If the xCallback argument is NULL then the collating function is +** ^If the xCompare argument is NULL then the collating function is ** deleted. ^When all collating functions having the same name are deleted, ** that collation is no longer usable. ** ** ^The collating function callback is invoked with a copy of the pArg ** application data pointer and with two strings in the encoding specified -** by the eTextRep argument. The collating function must return an -** integer that is negative, zero, or positive +** by the eTextRep argument. The two integer parameters to the collating +** function callback are the length of the two strings, in bytes. The collating +** function must return an integer that is negative, zero, or positive ** if the first string is less than, equal to, or greater than the second, ** respectively. A collating function must always return the same answer ** given the same inputs. If two or more collating functions are registered @@ -5239,44 +6777,44 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); ** </ol> ** ** If a collating function fails any of the above constraints and that -** collating function is registered and used, then the behavior of SQLite +** collating function is registered and used, then the behavior of SQLite ** is undefined. ** -** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** ^The tdsqlite3_create_collation_v2() works like tdsqlite3_create_collation() ** with the addition that the xDestroy callback is invoked on pArg when ** the collating function is deleted. ** ^Collating functions are deleted when they are overridden by later ** calls to the collation creation functions or when the -** [database connection] is closed using [sqlite3_close()]. +** [database connection] is closed using [tdsqlite3_close()]. ** ** ^The xDestroy callback is <u>not</u> called if the -** sqlite3_create_collation_v2() function fails. Applications that invoke -** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** tdsqlite3_create_collation_v2() function fails. Applications that invoke +** tdsqlite3_create_collation_v2() with a non-NULL xDestroy argument should ** check the return code and dispose of the application data pointer ** themselves rather than expecting SQLite to deal with it for them. ** This is different from every other SQLite interface. The inconsistency ** is unfortunate but cannot be changed without breaking backwards ** compatibility. ** -** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +** See also: [tdsqlite3_collation_needed()] and [tdsqlite3_collation_needed16()]. */ -SQLITE_API int sqlite3_create_collation( - sqlite3*, +SQLITE_API int tdsqlite3_create_collation( + tdsqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); -SQLITE_API int sqlite3_create_collation_v2( - sqlite3*, +SQLITE_API int tdsqlite3_create_collation_v2( + tdsqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDestroy)(void*) ); -SQLITE_API int sqlite3_create_collation16( - sqlite3*, +SQLITE_API int tdsqlite3_create_collation16( + tdsqlite3*, const void *zName, int eTextRep, void *pArg, @@ -5285,56 +6823,56 @@ SQLITE_API int sqlite3_create_collation16( /* ** CAPI3REF: Collation Needed Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the ** [database connection] to be invoked whenever an undefined collation ** sequence is required. ** -** ^If the function is registered using the sqlite3_collation_needed() API, +** ^If the function is registered using the tdsqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings -** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** encoded in UTF-8. ^If tdsqlite3_collation_needed16() is used, ** the names are passed as UTF-16 in machine native byte order. ** ^A call to either function replaces the existing collation-needed callback. ** ** ^(When the callback is invoked, the first argument passed is a copy -** of the second argument to sqlite3_collation_needed() or -** sqlite3_collation_needed16(). The second argument is the database +** of the second argument to tdsqlite3_collation_needed() or +** tdsqlite3_collation_needed16(). The second argument is the database ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation ** sequence function required. The fourth parameter is the name of the ** required collation sequence.)^ ** ** The callback function should register the desired collation using -** [sqlite3_create_collation()], [sqlite3_create_collation16()], or -** [sqlite3_create_collation_v2()]. +** [tdsqlite3_create_collation()], [tdsqlite3_create_collation16()], or +** [tdsqlite3_create_collation_v2()]. */ -SQLITE_API int sqlite3_collation_needed( - sqlite3*, +SQLITE_API int tdsqlite3_collation_needed( + tdsqlite3*, void*, - void(*)(void*,sqlite3*,int eTextRep,const char*) + void(*)(void*,tdsqlite3*,int eTextRep,const char*) ); -SQLITE_API int sqlite3_collation_needed16( - sqlite3*, +SQLITE_API int tdsqlite3_collation_needed16( + tdsqlite3*, void*, - void(*)(void*,sqlite3*,int eTextRep,const void*) + void(*)(void*,tdsqlite3*,int eTextRep,const void*) ); #ifdef SQLITE_HAS_CODEC /* ** Specify the key for an encrypted database. This routine should be -** called right after sqlite3_open(). +** called right after tdsqlite3_open(). ** ** The code to implement this API is not available in the public release ** of SQLite. */ -SQLITE_API int sqlite3_key( - sqlite3 *db, /* Database to be rekeyed */ +SQLITE_API int tdsqlite3_key( + tdsqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The key */ ); -SQLITE_API int sqlite3_key_v2( - sqlite3 *db, /* Database to be rekeyed */ +SQLITE_API int tdsqlite3_key_v2( + tdsqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The key */ ); @@ -5347,12 +6885,28 @@ SQLITE_API int sqlite3_key_v2( ** The code to implement this API is not available in the public release ** of SQLite. */ -SQLITE_API int sqlite3_rekey( - sqlite3 *db, /* Database to be rekeyed */ +/* BEGIN SQLCIPHER + SQLCipher usage note: + + If the current database is plaintext SQLCipher will NOT encrypt it. + If the current database is encrypted and pNew==0 or nNew==0, SQLCipher + will NOT decrypt it. + + This routine will ONLY work on an already encrypted database in order + to change the key. + + Conversion from plaintext-to-encrypted or encrypted-to-plaintext should + use an ATTACHed database and the sqlcipher_export() convenience function + as per the SQLCipher Documentation. + + END SQLCIPHER +*/ +SQLITE_API int tdsqlite3_rekey( + tdsqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The new key */ ); -SQLITE_API int sqlite3_rekey_v2( - sqlite3 *db, /* Database to be rekeyed */ +SQLITE_API int tdsqlite3_rekey_v2( + tdsqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The new key */ ); @@ -5361,7 +6915,7 @@ SQLITE_API int sqlite3_rekey_v2( ** Specify the activation key for a SEE database. Unless ** activated, none of the SEE routines will work. */ -SQLITE_API void sqlite3_activate_see( +SQLITE_API void tdsqlite3_activate_see( const char *zPassPhrase /* Activation phrase */ ); #endif @@ -5371,7 +6925,7 @@ SQLITE_API void sqlite3_activate_see( ** Specify the activation key for a CEROD database. Unless ** activated, none of the CEROD routines will work. */ -SQLITE_API void sqlite3_activate_cerod( +SQLITE_API void tdsqlite3_activate_cerod( const char *zPassPhrase /* Activation phrase */ ); #endif @@ -5379,7 +6933,7 @@ SQLITE_API void sqlite3_activate_cerod( /* ** CAPI3REF: Suspend Execution For A Short Time ** -** The sqlite3_sleep() function causes the current thread to suspend execution +** The tdsqlite3_sleep() function causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** ** If the operating system does not support sleep requests with @@ -5388,19 +6942,19 @@ SQLITE_API void sqlite3_activate_cerod( ** requested from the operating system is returned. ** ** ^SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. If the xSleep() method +** method of the default [tdsqlite3_vfs] object. If the xSleep() method ** of the default VFS is not implemented correctly, or not implemented at -** all, then the behavior of sqlite3_sleep() may deviate from the description +** all, then the behavior of tdsqlite3_sleep() may deviate from the description ** in the previous paragraphs. */ -SQLITE_API int sqlite3_sleep(int); +SQLITE_API int tdsqlite3_sleep(int); /* ** CAPI3REF: Name Of The Folder Holding Temporary Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all temporary files -** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** created by SQLite when using a built-in [tdsqlite3_vfs | VFS] ** will be placed in that directory.)^ ^If this variable ** is a NULL pointer, then SQLite performs a search for an appropriate ** temporary file directory. @@ -5422,22 +6976,22 @@ SQLITE_API int sqlite3_sleep(int); ** thereafter. ** ** ^The [temp_store_directory pragma] may modify this variable and cause -** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** it to point to memory obtained from [tdsqlite3_malloc]. ^Furthermore, ** the [temp_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from -** [sqlite3_malloc] and the pragma may attempt to free that memory -** using [sqlite3_free]. +** [tdsqlite3_malloc] and the pragma may attempt to free that memory +** using [tdsqlite3_free]. ** Hence, if this variable is modified directly, either it should be -** made NULL or made to point to memory obtained from [sqlite3_malloc] +** made NULL or made to point to memory obtained from [tdsqlite3_malloc] ** or else the use of the [temp_store_directory pragma] should be avoided. ** Except when requested by the [temp_store_directory pragma], SQLite -** does not free the memory that sqlite3_temp_directory points to. If +** does not free the memory that tdsqlite3_temp_directory points to. If ** the application wants that memory to be freed, it must do ** so itself, taking care to only do so after all [database connection] ** objects have been destroyed. ** ** <b>Note to Windows Runtime users:</b> The temporary directory must be set -** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various +** prior to calling [tdsqlite3_open] or [tdsqlite3_open_v2]. Otherwise, various ** features that require the use of temporary files may fail. Here is an ** example of how to do this using C++ with the Windows Runtime: ** @@ -5448,10 +7002,10 @@ SQLITE_API int sqlite3_sleep(int); ** memset(zPathBuf, 0, sizeof(zPathBuf)); ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf), ** NULL, NULL); -** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf); +** tdsqlite3_temp_directory = tdsqlite3_mprintf("%s", zPathBuf); ** </pre></blockquote> */ -SQLITE_API char *sqlite3_temp_directory; +SQLITE_API char *tdsqlite3_temp_directory; /* ** CAPI3REF: Name Of The Folder Holding Database Files @@ -5459,7 +7013,7 @@ SQLITE_API char *sqlite3_temp_directory; ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all database files ** specified with a relative pathname and created or accessed by -** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed +** SQLite when using a built-in windows [tdsqlite3_vfs | VFS] will be assumed ** to be relative to that directory.)^ ^If this variable is a NULL ** pointer, then SQLite assumes that all database files specified ** with a relative pathname are relative to the current directory @@ -5479,23 +7033,58 @@ SQLITE_API char *sqlite3_temp_directory; ** thereafter. ** ** ^The [data_store_directory pragma] may modify this variable and cause -** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** it to point to memory obtained from [tdsqlite3_malloc]. ^Furthermore, ** the [data_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from -** [sqlite3_malloc] and the pragma may attempt to free that memory -** using [sqlite3_free]. +** [tdsqlite3_malloc] and the pragma may attempt to free that memory +** using [tdsqlite3_free]. ** Hence, if this variable is modified directly, either it should be -** made NULL or made to point to memory obtained from [sqlite3_malloc] +** made NULL or made to point to memory obtained from [tdsqlite3_malloc] ** or else the use of the [data_store_directory pragma] should be avoided. */ -SQLITE_API char *sqlite3_data_directory; +SQLITE_API char *tdsqlite3_data_directory; + +/* +** CAPI3REF: Win32 Specific Interface +** +** These interfaces are available only on Windows. The +** [tdsqlite3_win32_set_directory] interface is used to set the value associated +** with the [tdsqlite3_temp_directory] or [tdsqlite3_data_directory] variable, to +** zValue, depending on the value of the type parameter. The zValue parameter +** should be NULL to cause the previous value to be freed via [tdsqlite3_free]; +** a non-NULL value will be copied into memory obtained from [tdsqlite3_malloc] +** prior to being used. The [tdsqlite3_win32_set_directory] interface returns +** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported, +** or [SQLITE_NOMEM] if memory could not be allocated. The value of the +** [tdsqlite3_data_directory] variable is intended to act as a replacement for +** the current directory on the sub-platforms of Win32 where that concept is +** not present, e.g. WinRT and UWP. The [tdsqlite3_win32_set_directory8] and +** [tdsqlite3_win32_set_directory16] interfaces behave exactly the same as the +** tdsqlite3_win32_set_directory interface except the string parameter must be +** UTF-8 or UTF-16, respectively. +*/ +SQLITE_API int tdsqlite3_win32_set_directory( + unsigned long type, /* Identifier for directory being set or reset */ + void *zValue /* New value for directory being set or reset */ +); +SQLITE_API int tdsqlite3_win32_set_directory8(unsigned long type, const char *zValue); +SQLITE_API int tdsqlite3_win32_set_directory16(unsigned long type, const void *zValue); + +/* +** CAPI3REF: Win32 Directory Types +** +** These macros are only available on Windows. They define the allowed values +** for the type argument to the [tdsqlite3_win32_set_directory] interface. +*/ +#define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1 +#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2 /* ** CAPI3REF: Test For Auto-Commit Mode ** KEYWORDS: {autocommit mode} -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_get_autocommit() interface returns non-zero or +** ^The tdsqlite3_get_autocommit() interface returns non-zero or ** zero if the given database connection is or is not in autocommit mode, ** respectively. ^Autocommit mode is on by default. ** ^Autocommit mode is disabled by a [BEGIN] statement. @@ -5512,51 +7101,66 @@ SQLITE_API char *sqlite3_data_directory; ** connection while this routine is running, then the return value ** is undefined. */ -SQLITE_API int sqlite3_get_autocommit(sqlite3*); +SQLITE_API int tdsqlite3_get_autocommit(tdsqlite3*); /* ** CAPI3REF: Find The Database Handle Of A Prepared Statement -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_db_handle interface returns the [database connection] handle +** ^The tdsqlite3_db_handle interface returns the [database connection] handle ** to which a [prepared statement] belongs. ^The [database connection] -** returned by sqlite3_db_handle is the same [database connection] +** returned by tdsqlite3_db_handle is the same [database connection] ** that was the first argument -** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** to the [tdsqlite3_prepare_v2()] call (or its variants) that was used to ** create the statement in the first place. */ -SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); +SQLITE_API tdsqlite3 *tdsqlite3_db_handle(tdsqlite3_stmt*); /* ** CAPI3REF: Return The Filename For A Database Connection -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename -** associated with database N of connection D. ^The main database file -** has the name "main". If there is no attached database N on the database +** ^The tdsqlite3_db_filename(D,N) interface returns a pointer to the filename +** associated with database N of connection D. +** ^If there is no attached database N on the database ** connection D, or if database N is a temporary or in-memory database, then -** a NULL pointer is returned. +** this function will return either a NULL pointer or an empty string. +** +** ^The string value returned by this routine is owned and managed by +** the database connection. ^The value will be valid until the database N +** is [DETACH]-ed or until the database connection closes. ** ** ^The filename returned by this function is the output of the ** xFullPathname method of the [VFS]. ^In other words, the filename ** will be an absolute pathname, even if the filename used ** to open the database originally was a URI or relative pathname. +** +** If the filename pointer returned by this routine is not NULL, then it +** can be used as the filename input parameter to these routines: +** <ul> +** <li> [tdsqlite3_uri_parameter()] +** <li> [tdsqlite3_uri_boolean()] +** <li> [tdsqlite3_uri_int64()] +** <li> [tdsqlite3_filename_database()] +** <li> [tdsqlite3_filename_journal()] +** <li> [tdsqlite3_filename_wal()] +** </ul> */ -SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); +SQLITE_API const char *tdsqlite3_db_filename(tdsqlite3 *db, const char *zDbName); /* ** CAPI3REF: Determine if a database is read-only -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N +** ^The tdsqlite3_db_readonly(D,N) interface returns 1 if the database N ** of connection D is read-only, 0 if it is read/write, or -1 if N is not ** the name of a database on connection D. */ -SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); +SQLITE_API int tdsqlite3_db_readonly(tdsqlite3 *db, const char *zDbName); /* ** CAPI3REF: Find the next prepared statement -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This interface returns a pointer to the next [prepared statement] after ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL @@ -5565,28 +7169,28 @@ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); ** satisfies the conditions of this routine, it returns NULL. ** ** The [database connection] pointer D in a call to -** [sqlite3_next_stmt(D,S)] must refer to an open database +** [tdsqlite3_next_stmt(D,S)] must refer to an open database ** connection and in particular must not be a NULL pointer. */ -SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); +SQLITE_API tdsqlite3_stmt *tdsqlite3_next_stmt(tdsqlite3 *pDb, tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_commit_hook() interface registers a callback +** ^The tdsqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is [COMMIT | committed]. -** ^Any callback set by a previous call to sqlite3_commit_hook() +** ^Any callback set by a previous call to tdsqlite3_commit_hook() ** for the same database connection is overridden. -** ^The sqlite3_rollback_hook() interface registers a callback +** ^The tdsqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. -** ^Any callback set by a previous call to sqlite3_rollback_hook() +** ^Any callback set by a previous call to tdsqlite3_rollback_hook() ** for the same database connection is overridden. ** ^The pArg argument is passed through to the callback. ** ^If the callback on a commit hook function returns non-zero, ** then the commit is converted into a rollback. ** -** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** ^The tdsqlite3_commit_hook(D,C,P) and tdsqlite3_rollback_hook(D,C,P) functions ** return the P argument from the previous call of the same function ** on the same [database connection] D, or NULL for ** the first call for each function on D. @@ -5595,10 +7199,10 @@ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); ** The callback implementation must not do anything that will modify ** the database connection that invoked the callback. Any actions ** to modify the database connection must be deferred until after the -** completion of the [sqlite3_step()] call that triggered the commit +** completion of the [tdsqlite3_step()] call that triggered the commit ** or rollback hook in the first place. ** Note that running any other SQL statements, including SELECT statements, -** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify +** or merely calling [tdsqlite3_prepare_v2()] and [tdsqlite3_step()] will modify ** the database connections for the meaning of "modify" in this paragraph. ** ** ^Registering a NULL function disables the callback. @@ -5615,16 +7219,16 @@ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); ** ^The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. ** -** See also the [sqlite3_update_hook()] interface. +** See also the [tdsqlite3_update_hook()] interface. */ -SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); -SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); +SQLITE_API void *tdsqlite3_commit_hook(tdsqlite3*, int(*)(void*), void*); +SQLITE_API void *tdsqlite3_rollback_hook(tdsqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_update_hook() interface registers a callback function +** ^The tdsqlite3_update_hook() interface registers a callback function ** with the [database connection] identified by the first argument ** to be invoked whenever a row is updated, inserted or deleted in ** a [rowid table]. @@ -5634,7 +7238,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); ** ^The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted in a rowid table. ** ^The first argument to the callback is a copy of the third argument -** to sqlite3_update_hook(). +** to tdsqlite3_update_hook(). ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], ** or [SQLITE_UPDATE], depending on the operation that caused the callback ** to be invoked. @@ -5648,7 +7252,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. ** ** ^In the current implementation, the update hook -** is not invoked when duplication rows are deleted because of an +** is not invoked when conflicting rows are deleted because of an ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook ** invoked when rows are deleted using the [truncate optimization]. ** The exceptions defined in this paragraph might change in a future @@ -5657,21 +7261,21 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); ** The update hook implementation must not do anything that will modify ** the database connection that invoked the update hook. Any actions ** to modify the database connection must be deferred until after the -** completion of the [sqlite3_step()] call that triggered the update hook. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** completion of the [tdsqlite3_step()] call that triggered the update hook. +** Note that [tdsqlite3_prepare_v2()] and [tdsqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** -** ^The sqlite3_update_hook(D,C,P) function +** ^The tdsqlite3_update_hook(D,C,P) function ** returns the P argument from the previous call ** on the same [database connection] D, or NULL for ** the first call on D. ** -** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()], -** and [sqlite3_preupdate_hook()] interfaces. +** See also the [tdsqlite3_commit_hook()], [tdsqlite3_rollback_hook()], +** and [tdsqlite3_preupdate_hook()] interfaces. */ -SQLITE_API void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), +SQLITE_API void *tdsqlite3_update_hook( + tdsqlite3*, + void(*)(void *,int ,char const *,char const *,tdsqlite3_int64), void* ); @@ -5689,63 +7293,70 @@ SQLITE_API void *sqlite3_update_hook( ** sharing was enabled or disabled for each thread separately. ** ** ^(The cache sharing mode set by this interface effects all subsequent -** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. -** Existing database connections continue use the sharing mode +** calls to [tdsqlite3_open()], [tdsqlite3_open_v2()], and [tdsqlite3_open16()]. +** Existing database connections continue to use the sharing mode ** that was in effect at the time they were opened.)^ ** ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled ** successfully. An [error code] is returned otherwise.)^ ** -** ^Shared cache is disabled by default. But this might change in -** future releases of SQLite. Applications that care about shared -** cache setting should set it explicitly. +** ^Shared cache is disabled by default. It is recommended that it stay +** that way. In other words, do not use this routine. This interface +** continues to be provided for historical compatibility, but its use is +** discouraged. Any use of shared cache is discouraged. If shared cache +** must be used, it is recommended that shared cache only be enabled for +** individual database connections using the [tdsqlite3_open_v2()] interface +** with the [SQLITE_OPEN_SHAREDCACHE] flag. ** ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 ** and will always return SQLITE_MISUSE. On those systems, ** shared cache mode should be enabled per-database connection via -** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. +** [tdsqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. ** ** This interface is threadsafe on processors where writing a ** 32-bit integer is atomic. ** ** See Also: [SQLite Shared-Cache Mode] */ -SQLITE_API int sqlite3_enable_shared_cache(int); +SQLITE_API int tdsqlite3_enable_shared_cache(int); /* ** CAPI3REF: Attempt To Free Heap Memory ** -** ^The sqlite3_release_memory() interface attempts to free N bytes +** ^The tdsqlite3_release_memory() interface attempts to free N bytes ** of heap memory by deallocating non-essential memory allocations ** held by the database library. Memory used to cache database ** pages to improve performance is an example of non-essential memory. -** ^sqlite3_release_memory() returns the number of bytes actually freed, +** ^tdsqlite3_release_memory() returns the number of bytes actually freed, ** which might be more or less than the amount requested. -** ^The sqlite3_release_memory() routine is a no-op returning zero +** ^The tdsqlite3_release_memory() routine is a no-op returning zero ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** -** See also: [sqlite3_db_release_memory()] +** See also: [tdsqlite3_db_release_memory()] */ -SQLITE_API int sqlite3_release_memory(int); +SQLITE_API int tdsqlite3_release_memory(int); /* ** CAPI3REF: Free Memory Used By A Database Connection -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap +** ^The tdsqlite3_db_release_memory(D) interface attempts to free as much heap ** memory as possible from database connection D. Unlike the -** [sqlite3_release_memory()] interface, this interface is in effect even +** [tdsqlite3_release_memory()] interface, this interface is in effect even ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is ** omitted. ** -** See also: [sqlite3_release_memory()] +** See also: [tdsqlite3_release_memory()] */ -SQLITE_API int sqlite3_db_release_memory(sqlite3*); +SQLITE_API int tdsqlite3_db_release_memory(tdsqlite3*); /* ** CAPI3REF: Impose A Limit On Heap Size ** -** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** These interfaces impose limits on the amount of heap memory that will be +** by all database connections within a single process. +** +** ^The tdsqlite3_soft_heap_limit64() interface sets and/or queries the ** soft limit on the amount of heap memory that may be allocated by SQLite. ** ^SQLite strives to keep heap memory utilization below the soft heap ** limit by reducing the number of pages held in the page cache @@ -5755,73 +7366,86 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*); ** an [SQLITE_NOMEM] error. In other words, the soft heap limit ** is advisory only. ** -** ^The return value from sqlite3_soft_heap_limit64() is the size of -** the soft heap limit prior to the call, or negative in the case of an -** error. ^If the argument N is negative -** then no change is made to the soft heap limit. Hence, the current -** size of the soft heap limit can be determined by invoking -** sqlite3_soft_heap_limit64() with a negative argument. -** -** ^If the argument N is zero then the soft heap limit is disabled. +** ^The tdsqlite3_hard_heap_limit64(N) interface sets a hard upper bound of +** N bytes on the amount of memory that will be allocated. ^The +** tdsqlite3_hard_heap_limit64(N) interface is similar to +** tdsqlite3_soft_heap_limit64(N) except that memory allocations will fail +** when the hard heap limit is reached. ** -** ^(The soft heap limit is not enforced in the current implementation +** ^The return value from both tdsqlite3_soft_heap_limit64() and +** tdsqlite3_hard_heap_limit64() is the size of +** the heap limit prior to the call, or negative in the case of an +** error. ^If the argument N is negative +** then no change is made to the heap limit. Hence, the current +** size of heap limits can be determined by invoking +** tdsqlite3_soft_heap_limit64(-1) or tdsqlite3_hard_heap_limit(-1). +** +** ^Setting the heap limits to zero disables the heap limiter mechanism. +** +** ^The soft heap limit may not be greater than the hard heap limit. +** ^If the hard heap limit is enabled and if tdsqlite3_soft_heap_limit(N) +** is invoked with a value of N that is greater than the hard heap limit, +** the the soft heap limit is set to the value of the hard heap limit. +** ^The soft heap limit is automatically enabled whenever the hard heap +** limit is enabled. ^When tdsqlite3_hard_heap_limit64(N) is invoked and +** the soft heap limit is outside the range of 1..N, then the soft heap +** limit is set to N. ^Invoking tdsqlite3_soft_heap_limit64(0) when the +** hard heap limit is enabled makes the soft heap limit equal to the +** hard heap limit. +** +** The memory allocation limits can also be adjusted using +** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit]. +** +** ^(The heap limits are not enforced in the current implementation ** if one or more of following conditions are true: ** ** <ul> -** <li> The soft heap limit is set to zero. +** <li> The limit value is set to zero. ** <li> Memory accounting is disabled using a combination of the -** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** [tdsqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. ** <li> An alternative page cache implementation is specified using -** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). +** [tdsqlite3_config]([SQLITE_CONFIG_PCACHE2],...). ** <li> The page cache allocates from its own memory pool supplied -** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** by [tdsqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than ** from the heap. ** </ul>)^ ** -** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), -** the soft heap limit is enforced -** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] -** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], -** the soft heap limit is enforced on every memory allocation. Without -** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced -** when memory is allocated by the page cache. Testing suggests that because -** the page cache is the predominate memory user in SQLite, most -** applications will achieve adequate soft heap limit enforcement without -** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. -** -** The circumstances under which SQLite will enforce the soft heap limit may +** The circumstances under which SQLite will enforce the heap limits may ** changes in future releases of SQLite. */ -SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); +SQLITE_API tdsqlite3_int64 tdsqlite3_soft_heap_limit64(tdsqlite3_int64 N); +SQLITE_API tdsqlite3_int64 tdsqlite3_hard_heap_limit64(tdsqlite3_int64 N); /* ** CAPI3REF: Deprecated Soft Heap Limit Interface ** DEPRECATED ** -** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** This is a deprecated version of the [tdsqlite3_soft_heap_limit64()] ** interface. This routine is provided for historical compatibility ** only. All new applications should use the -** [sqlite3_soft_heap_limit64()] interface rather than this one. +** [tdsqlite3_soft_heap_limit64()] interface rather than this one. */ -SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); +SQLITE_API SQLITE_DEPRECATED void tdsqlite3_soft_heap_limit(int N); /* ** CAPI3REF: Extract Metadata About A Column Of A Table -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns +** ^(The tdsqlite3_table_column_metadata(X,D,T,C,....) routine returns ** information about column C of table T in database D -** on [database connection] X.)^ ^The sqlite3_table_column_metadata() +** on [database connection] X.)^ ^The tdsqlite3_table_column_metadata() ** interface returns SQLITE_OK and fills in the non-NULL pointers in ** the final five arguments with appropriate values if the specified -** column exists. ^The sqlite3_table_column_metadata() interface returns -** SQLITE_ERROR and if the specified column does not exist. -** ^If the column-name parameter to sqlite3_table_column_metadata() is a +** column exists. ^The tdsqlite3_table_column_metadata() interface returns +** SQLITE_ERROR if the specified column does not exist. +** ^If the column-name parameter to tdsqlite3_table_column_metadata() is a ** NULL pointer, then this routine simply checks for the existence of the ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it -** does not. +** does not. If the table name parameter T in a call to +** tdsqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is +** undefined behavior. ** ** ^The column is identified by the second, third and fourth parameters to ** this function. ^(The second parameter is either the name of the database @@ -5874,8 +7498,8 @@ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); ** parsed, if that has not already been done, and returns an error if ** any errors are encountered while loading the schema. */ -SQLITE_API int sqlite3_table_column_metadata( - sqlite3 *db, /* Connection handle */ +SQLITE_API int tdsqlite3_table_column_metadata( + tdsqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ @@ -5888,11 +7512,11 @@ SQLITE_API int sqlite3_table_column_metadata( /* ** CAPI3REF: Load An Extension -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This interface loads an SQLite extension library from the named file. ** -** ^The sqlite3_load_extension() interface attempts to load an +** ^The tdsqlite3_load_extension() interface attempts to load an ** [SQLite extension] library contained in the file zFile. If ** the file cannot be loaded directly, attempts are made to load ** with various operating-system specific extensions added. @@ -5902,36 +7526,36 @@ SQLITE_API int sqlite3_table_column_metadata( ** ** ^The entry point is zProc. ** ^(zProc may be 0, in which case SQLite will try to come up with an -** entry point name on its own. It first tries "sqlite3_extension_init". -** If that does not work, it constructs a name "sqlite3_X_init" where the +** entry point name on its own. It first tries "tdsqlite3_extension_init". +** If that does not work, it constructs a name "tdsqlite3_X_init" where the ** X is consists of the lower-case equivalent of all ASCII alphabetic ** characters in the filename from the last "/" to the first following ** "." and omitting any initial "lib".)^ -** ^The sqlite3_load_extension() interface returns +** ^The tdsqlite3_load_extension() interface returns ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ^If an error occurs and pzErrMsg is not 0, then the -** [sqlite3_load_extension()] interface shall attempt to +** [tdsqlite3_load_extension()] interface shall attempt to ** fill *pzErrMsg with error message text stored in memory -** obtained from [sqlite3_malloc()]. The calling function -** should free this memory by calling [sqlite3_free()]. +** obtained from [tdsqlite3_malloc()]. The calling function +** should free this memory by calling [tdsqlite3_free()]. ** ** ^Extension loading must be enabled using -** [sqlite3_enable_load_extension()] or -** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) +** [tdsqlite3_enable_load_extension()] or +** [tdsqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) ** prior to calling this API, ** otherwise an error will be returned. ** ** <b>Security warning:</b> It is recommended that the ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this -** interface. The use of the [sqlite3_enable_load_extension()] interface +** interface. The use of the [tdsqlite3_enable_load_extension()] interface ** should be avoided. This will keep the SQL function [load_extension()] ** disabled and prevent SQL injections from giving attackers ** access to extension loading capabilities. ** ** See also the [load_extension() SQL function]. */ -SQLITE_API int sqlite3_load_extension( - sqlite3 *db, /* Load the extension into this database connection */ +SQLITE_API int tdsqlite3_load_extension( + tdsqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Derived from zFile if 0 */ char **pzErrMsg /* Put error message here if not 0 */ @@ -5939,30 +7563,30 @@ SQLITE_API int sqlite3_load_extension( /* ** CAPI3REF: Enable Or Disable Extension Loading -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^So as not to open security holes in older applications that are ** unprepared to deal with [extension loading], and as a means of disabling ** [extension loading] while evaluating user-entered SQL, the following API -** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** is provided to turn the [tdsqlite3_load_extension()] mechanism on and off. ** ** ^Extension loading is off by default. -** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** ^Call the tdsqlite3_enable_load_extension() routine with onoff==1 ** to turn extension loading on and call it with onoff==0 to turn ** it back off again. ** ** ^This interface enables or disables both the C-API -** [sqlite3_load_extension()] and the SQL function [load_extension()]. -** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) +** [tdsqlite3_load_extension()] and the SQL function [load_extension()]. +** ^(Use [tdsqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) ** to enable or disable only the C-API.)^ ** ** <b>Security warning:</b> It is recommended that extension loading -** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method +** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method ** rather than this interface, so the [load_extension()] SQL function ** remains disabled. This will prevent SQL injections from giving attackers ** access to extension loading capabilities. */ -SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); +SQLITE_API int tdsqlite3_enable_load_extension(tdsqlite3 *db, int onoff); /* ** CAPI3REF: Automatically Load Statically Linked Extensions @@ -5979,48 +7603,48 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); ** ** <blockquote><pre> ** int xEntryPoint( -** sqlite3 *db, +** tdsqlite3 *db, ** const char **pzErrMsg, -** const struct sqlite3_api_routines *pThunk +** const struct tdsqlite3_api_routines *pThunk ** ); ** </pre></blockquote>)^ ** ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg -** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** point to an appropriate error message (obtained from [tdsqlite3_mprintf()]) ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg ** is NULL before calling the xEntryPoint(). ^SQLite will invoke -** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any -** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], -** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** [tdsqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [tdsqlite3_open()], [tdsqlite3_open16()], +** or [tdsqlite3_open_v2()] call that provoked the xEntryPoint() will fail. ** -** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** ^Calling tdsqlite3_auto_extension(X) with an entry point X that is already ** on the list of automatic extensions is a harmless no-op. ^No entry point ** will be called more than once for each database connection that is opened. ** -** See also: [sqlite3_reset_auto_extension()] -** and [sqlite3_cancel_auto_extension()] +** See also: [tdsqlite3_reset_auto_extension()] +** and [tdsqlite3_cancel_auto_extension()] */ -SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void)); +SQLITE_API int tdsqlite3_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Cancel Automatic Extension Loading ** -** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the +** ^The [tdsqlite3_cancel_auto_extension(X)] interface unregisters the ** initialization routine X that was registered using a prior call to -** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] +** [tdsqlite3_auto_extension(X)]. ^The [tdsqlite3_cancel_auto_extension(X)] ** routine returns 1 if initialization routine X was successfully ** unregistered and it returns 0 if X was not on the list of initialization ** routines. */ -SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); +SQLITE_API int tdsqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Reset Automatic Extension Loading ** ** ^This interface disables all automatic extensions previously -** registered using [sqlite3_auto_extension()]. +** registered using [tdsqlite3_auto_extension()]. */ -SQLITE_API void sqlite3_reset_auto_extension(void); +SQLITE_API void tdsqlite3_reset_auto_extension(void); /* ** The interface to the virtual-table mechanism is currently considered @@ -6034,67 +7658,70 @@ SQLITE_API void sqlite3_reset_auto_extension(void); /* ** Structures used by the virtual table interface */ -typedef struct sqlite3_vtab sqlite3_vtab; -typedef struct sqlite3_index_info sqlite3_index_info; -typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; -typedef struct sqlite3_module sqlite3_module; +typedef struct tdsqlite3_vtab tdsqlite3_vtab; +typedef struct tdsqlite3_index_info tdsqlite3_index_info; +typedef struct tdsqlite3_vtab_cursor tdsqlite3_vtab_cursor; +typedef struct tdsqlite3_module tdsqlite3_module; /* ** CAPI3REF: Virtual Table Object -** KEYWORDS: sqlite3_module {virtual table module} +** KEYWORDS: tdsqlite3_module {virtual table module} ** ** This structure, sometimes called a "virtual table module", -** defines the implementation of a [virtual tables]. +** defines the implementation of a [virtual table]. ** This structure consists mostly of methods for the module. ** ** ^A virtual table module is created by filling in a persistent ** instance of this structure and passing a pointer to that instance -** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** to [tdsqlite3_create_module()] or [tdsqlite3_create_module_v2()]. ** ^The registration remains valid until it is replaced by a different ** module or until the [database connection] closes. The content ** of this structure must not change while it is registered with ** any database connection. */ -struct sqlite3_module { +struct tdsqlite3_module { int iVersion; - int (*xCreate)(sqlite3*, void *pAux, + int (*xCreate)(tdsqlite3*, void *pAux, int argc, const char *const*argv, - sqlite3_vtab **ppVTab, char**); - int (*xConnect)(sqlite3*, void *pAux, + tdsqlite3_vtab **ppVTab, char**); + int (*xConnect)(tdsqlite3*, void *pAux, int argc, const char *const*argv, - sqlite3_vtab **ppVTab, char**); - int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); - int (*xDisconnect)(sqlite3_vtab *pVTab); - int (*xDestroy)(sqlite3_vtab *pVTab); - int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); - int (*xClose)(sqlite3_vtab_cursor*); - int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, - int argc, sqlite3_value **argv); - int (*xNext)(sqlite3_vtab_cursor*); - int (*xEof)(sqlite3_vtab_cursor*); - int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); - int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); - int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); - int (*xBegin)(sqlite3_vtab *pVTab); - int (*xSync)(sqlite3_vtab *pVTab); - int (*xCommit)(sqlite3_vtab *pVTab); - int (*xRollback)(sqlite3_vtab *pVTab); - int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + tdsqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(tdsqlite3_vtab *pVTab, tdsqlite3_index_info*); + int (*xDisconnect)(tdsqlite3_vtab *pVTab); + int (*xDestroy)(tdsqlite3_vtab *pVTab); + int (*xOpen)(tdsqlite3_vtab *pVTab, tdsqlite3_vtab_cursor **ppCursor); + int (*xClose)(tdsqlite3_vtab_cursor*); + int (*xFilter)(tdsqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, tdsqlite3_value **argv); + int (*xNext)(tdsqlite3_vtab_cursor*); + int (*xEof)(tdsqlite3_vtab_cursor*); + int (*xColumn)(tdsqlite3_vtab_cursor*, tdsqlite3_context*, int); + int (*xRowid)(tdsqlite3_vtab_cursor*, tdsqlite3_int64 *pRowid); + int (*xUpdate)(tdsqlite3_vtab *, int, tdsqlite3_value **, tdsqlite3_int64 *); + int (*xBegin)(tdsqlite3_vtab *pVTab); + int (*xSync)(tdsqlite3_vtab *pVTab); + int (*xCommit)(tdsqlite3_vtab *pVTab); + int (*xRollback)(tdsqlite3_vtab *pVTab); + int (*xFindFunction)(tdsqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(tdsqlite3_context*,int,tdsqlite3_value**), void **ppArg); - int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + int (*xRename)(tdsqlite3_vtab *pVtab, const char *zNew); /* The methods above are in version 1 of the sqlite_module object. Those ** below are for version 2 and greater. */ - int (*xSavepoint)(sqlite3_vtab *pVTab, int); - int (*xRelease)(sqlite3_vtab *pVTab, int); - int (*xRollbackTo)(sqlite3_vtab *pVTab, int); + int (*xSavepoint)(tdsqlite3_vtab *pVTab, int); + int (*xRelease)(tdsqlite3_vtab *pVTab, int); + int (*xRollbackTo)(tdsqlite3_vtab *pVTab, int); + /* The methods above are in versions 1 and 2 of the sqlite_module object. + ** Those below are for version 3 and greater. */ + int (*xShadowName)(const char*); }; /* ** CAPI3REF: Virtual Table Indexing Information -** KEYWORDS: sqlite3_index_info +** KEYWORDS: tdsqlite3_index_info ** -** The sqlite3_index_info structure and its substructures is used as part +** The tdsqlite3_index_info structure and its substructures is used as part ** of the [virtual table] interface to ** pass information into and receive the reply from the [xBestIndex] ** method of a [virtual table module]. The fields under **Inputs** are the @@ -6125,12 +7752,12 @@ struct sqlite3_module { ** The colUsed field indicates which columns of the virtual table may be ** required by the current scan. Virtual table columns are numbered from ** zero in the order in which they appear within the CREATE TABLE statement -** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), +** passed to tdsqlite3_declare_vtab(). For the first 63 columns (columns 0-62), ** the corresponding bit is set within the colUsed mask if the column may be ** required by SQLite. If the table has at least 64 columns and any column ** to the right of the first 63 is required, then bit 63 of colUsed is also ** set. In other words, column iCol may be required if the expression -** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to +** (colUsed & ((tdsqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to ** non-zero. ** ** The [xBestIndex] method must fill aConstraintUsage[] with information @@ -6138,11 +7765,17 @@ struct sqlite3_module { ** the right-hand side of the corresponding aConstraint[] is evaluated ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit ** is true, then the constraint is assumed to be fully handled by the -** virtual table and is not checked again by SQLite.)^ +** virtual table and might not be checked again by the byte code.)^ ^(The +** aConstraintUsage[].omit flag is an optimization hint. When the omit flag +** is left in its default setting of false, the constraint will always be +** checked separately in byte code. If the omit flag is change to true, then +** the constraint may or may not be checked in byte code. In other words, +** when the omit flag is true there is no guarantee that the constraint will +** not be checked again using byte code.)^ ** ** ^The idxNum and idxPtr values are recorded and passed into the ** [xFilter] method. -** ^[sqlite3_free()] is used to free idxPtr if and only if +** ^[tdsqlite3_free()] is used to free idxPtr if and only if ** needToFreeIdxPtr is true. ** ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in @@ -6173,77 +7806,87 @@ struct sqlite3_module { ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by ** the xUpdate method are automatically rolled back by SQLite. ** -** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info +** IMPORTANT: The estimatedRows field was added to the tdsqlite3_index_info ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). ** If a virtual table extension is ** used with an SQLite version earlier than 3.8.2, the results of attempting ** to read or write the estimatedRows field are undefined (but are likely -** to included crashing the application). The estimatedRows field should -** therefore only be used if [sqlite3_libversion_number()] returns a +** to include crashing the application). The estimatedRows field should +** therefore only be used if [tdsqlite3_libversion_number()] returns a ** value greater than or equal to 3008002. Similarly, the idxFlags field ** was added for [version 3.9.0] ([dateof:3.9.0]). ** It may therefore only be used if -** sqlite3_libversion_number() returns a value greater than or equal to +** tdsqlite3_libversion_number() returns a value greater than or equal to ** 3009000. */ -struct sqlite3_index_info { +struct tdsqlite3_index_info { /* Inputs */ int nConstraint; /* Number of entries in aConstraint */ - struct sqlite3_index_constraint { + struct tdsqlite3_index_constraint { int iColumn; /* Column constrained. -1 for ROWID */ unsigned char op; /* Constraint operator */ unsigned char usable; /* True if this constraint is usable */ int iTermOffset; /* Used internally - xBestIndex should ignore */ } *aConstraint; /* Table of WHERE clause constraints */ int nOrderBy; /* Number of terms in the ORDER BY clause */ - struct sqlite3_index_orderby { + struct tdsqlite3_index_orderby { int iColumn; /* Column number */ unsigned char desc; /* True for DESC. False for ASC. */ } *aOrderBy; /* The ORDER BY clause */ /* Outputs */ - struct sqlite3_index_constraint_usage { + struct tdsqlite3_index_constraint_usage { int argvIndex; /* if >0, constraint is part of argv to xFilter */ unsigned char omit; /* Do not code a test for this constraint */ } *aConstraintUsage; int idxNum; /* Number used to identify the index */ - char *idxStr; /* String, possibly obtained from sqlite3_malloc */ - int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + char *idxStr; /* String, possibly obtained from tdsqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using tdsqlite3_free() if true */ int orderByConsumed; /* True if output is already ordered */ double estimatedCost; /* Estimated cost of using this index */ /* Fields below are only available in SQLite 3.8.2 and later */ - sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ + tdsqlite3_int64 estimatedRows; /* Estimated number of rows returned */ /* Fields below are only available in SQLite 3.9.0 and later */ int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ /* Fields below are only available in SQLite 3.10.0 and later */ - sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ + tdsqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ }; /* ** CAPI3REF: Virtual Table Scan Flags +** +** Virtual table implementations are allowed to set the +** [tdsqlite3_index_info].idxFlags field to some combination of +** these bits. */ #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */ /* ** CAPI3REF: Virtual Table Constraint Operator Codes ** -** These macros defined the allowed values for the -** [sqlite3_index_info].aConstraint[].op field. Each value represents +** These macros define the allowed values for the +** [tdsqlite3_index_info].aConstraint[].op field. Each value represents ** an operator that is part of a constraint term in the wHERE clause of ** a query that uses a [virtual table]. */ -#define SQLITE_INDEX_CONSTRAINT_EQ 2 -#define SQLITE_INDEX_CONSTRAINT_GT 4 -#define SQLITE_INDEX_CONSTRAINT_LE 8 -#define SQLITE_INDEX_CONSTRAINT_LT 16 -#define SQLITE_INDEX_CONSTRAINT_GE 32 -#define SQLITE_INDEX_CONSTRAINT_MATCH 64 -#define SQLITE_INDEX_CONSTRAINT_LIKE 65 -#define SQLITE_INDEX_CONSTRAINT_GLOB 66 -#define SQLITE_INDEX_CONSTRAINT_REGEXP 67 +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 +#define SQLITE_INDEX_CONSTRAINT_LIKE 65 +#define SQLITE_INDEX_CONSTRAINT_GLOB 66 +#define SQLITE_INDEX_CONSTRAINT_REGEXP 67 +#define SQLITE_INDEX_CONSTRAINT_NE 68 +#define SQLITE_INDEX_CONSTRAINT_ISNOT 69 +#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70 +#define SQLITE_INDEX_CONSTRAINT_ISNULL 71 +#define SQLITE_INDEX_CONSTRAINT_IS 72 +#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150 /* ** CAPI3REF: Register A Virtual Table Implementation -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^These routines are used to register a new [virtual table module] name. ** ^Module names must be registered before @@ -6258,32 +7901,55 @@ struct sqlite3_index_info { ** into the [xCreate] and [xConnect] methods of the virtual table module ** when a new virtual table is be being created or reinitialized. ** -** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** ^The tdsqlite3_create_module_v2() interface has a fifth parameter which ** is a pointer to a destructor for the pClientData. ^SQLite will ** invoke the destructor function (if it is not NULL) when SQLite ** no longer needs the pClientData pointer. ^The destructor will also -** be invoked if the call to sqlite3_create_module_v2() fails. -** ^The sqlite3_create_module() -** interface is equivalent to sqlite3_create_module_v2() with a NULL +** be invoked if the call to tdsqlite3_create_module_v2() fails. +** ^The tdsqlite3_create_module() +** interface is equivalent to tdsqlite3_create_module_v2() with a NULL ** destructor. +** +** ^If the third parameter (the pointer to the tdsqlite3_module object) is +** NULL then no new module is create and any existing modules with the +** same name are dropped. +** +** See also: [tdsqlite3_drop_modules()] */ -SQLITE_API int sqlite3_create_module( - sqlite3 *db, /* SQLite connection to register module with */ +SQLITE_API int tdsqlite3_create_module( + tdsqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ - const sqlite3_module *p, /* Methods for the module */ + const tdsqlite3_module *p, /* Methods for the module */ void *pClientData /* Client data for xCreate/xConnect */ ); -SQLITE_API int sqlite3_create_module_v2( - sqlite3 *db, /* SQLite connection to register module with */ +SQLITE_API int tdsqlite3_create_module_v2( + tdsqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ - const sqlite3_module *p, /* Methods for the module */ + const tdsqlite3_module *p, /* Methods for the module */ void *pClientData, /* Client data for xCreate/xConnect */ void(*xDestroy)(void*) /* Module destructor function */ ); /* +** CAPI3REF: Remove Unnecessary Virtual Table Implementations +** METHOD: tdsqlite3 +** +** ^The tdsqlite3_drop_modules(D,L) interface removes all virtual +** table modules from database connection D except those named on list L. +** The L parameter must be either NULL or a pointer to an array of pointers +** to strings where the array is terminated by a single NULL pointer. +** ^If the L parameter is NULL, then all virtual table modules are removed. +** +** See also: [tdsqlite3_create_module()] +*/ +SQLITE_API int tdsqlite3_drop_modules( + tdsqlite3 *db, /* Remove modules from this connection */ + const char **azKeep /* Except, do not remove the ones named here */ +); + +/* ** CAPI3REF: Virtual Table Instance Object -** KEYWORDS: sqlite3_vtab +** KEYWORDS: tdsqlite3_vtab ** ** Every [virtual table module] implementation uses a subclass ** of this object to describe a particular instance @@ -6293,29 +7959,29 @@ SQLITE_API int sqlite3_create_module_v2( ** common to all module implementations. ** ** ^Virtual tables methods can set an error message by assigning a -** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should -** take care that any prior string is freed by a call to [sqlite3_free()] +** string obtained from [tdsqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [tdsqlite3_free()] ** prior to assigning a new string to zErrMsg. ^After the error message ** is delivered up to the client application, the string will be automatically -** freed by sqlite3_free() and the zErrMsg field will be zeroed. +** freed by tdsqlite3_free() and the zErrMsg field will be zeroed. */ -struct sqlite3_vtab { - const sqlite3_module *pModule; /* The module for this virtual table */ +struct tdsqlite3_vtab { + const tdsqlite3_module *pModule; /* The module for this virtual table */ int nRef; /* Number of open cursors */ - char *zErrMsg; /* Error message from sqlite3_mprintf() */ + char *zErrMsg; /* Error message from tdsqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Virtual Table Cursor Object -** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** KEYWORDS: tdsqlite3_vtab_cursor {virtual table cursor} ** ** Every [virtual table module] implementation uses a subclass of the ** following structure to describe cursors that point into the ** [virtual table] and are used ** to loop through the virtual table. Cursors are created using the -** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed -** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** [tdsqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [tdsqlite3_module.xClose | xClose] method. Cursors are used ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods ** of the module. Each module implementation will define ** the content of a cursor structure to suit its own needs. @@ -6323,8 +7989,8 @@ struct sqlite3_vtab { ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. */ -struct sqlite3_vtab_cursor { - sqlite3_vtab *pVtab; /* Virtual table of this cursor */ +struct tdsqlite3_vtab_cursor { + tdsqlite3_vtab *pVtab; /* Virtual table of this cursor */ /* Virtual table implementations will typically add additional fields */ }; @@ -6336,11 +8002,11 @@ struct sqlite3_vtab_cursor { ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */ -SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); +SQLITE_API int tdsqlite3_declare_vtab(tdsqlite3*, const char *zSQL); /* ** CAPI3REF: Overload A Function For A Virtual Table -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^(Virtual tables can provide alternative implementations of functions ** using the [xFindFunction] method of the [virtual table module]. @@ -6355,7 +8021,7 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); ** purpose is to be a placeholder function that can be overloaded ** by a [virtual table]. */ -SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); +SQLITE_API int tdsqlite3_overload_function(tdsqlite3*, const char *zFuncName, int nArg); /* ** The interface to the virtual-table mechanism defined above (back up @@ -6372,19 +8038,19 @@ SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nA ** KEYWORDS: {BLOB handle} {BLOB handles} ** ** An instance of this object represents an open BLOB on which -** [sqlite3_blob_open | incremental BLOB I/O] can be performed. -** ^Objects of this type are created by [sqlite3_blob_open()] -** and destroyed by [sqlite3_blob_close()]. -** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** [tdsqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [tdsqlite3_blob_open()] +** and destroyed by [tdsqlite3_blob_close()]. +** ^The [tdsqlite3_blob_read()] and [tdsqlite3_blob_write()] interfaces ** can be used to read or write small subsections of the BLOB. -** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +** ^The [tdsqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. */ -typedef struct sqlite3_blob sqlite3_blob; +typedef struct tdsqlite3_blob tdsqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O -** METHOD: sqlite3 -** CONSTRUCTOR: sqlite3_blob +** METHOD: tdsqlite3 +** CONSTRUCTOR: tdsqlite3_blob ** ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located ** in row iRow, column zColumn, table zTable in database zDb; @@ -6407,7 +8073,7 @@ typedef struct sqlite3_blob sqlite3_blob; ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored ** in *ppBlob. Otherwise an [error code] is returned and, unless the error ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided -** the API is not misused, it is always safe to call [sqlite3_blob_close()] +** the API is not misused, it is always safe to call [tdsqlite3_blob_close()] ** on *ppBlob after this function it returns. ** ** This function fails with SQLITE_ERROR if any of the following are true: @@ -6428,70 +8094,80 @@ typedef struct sqlite3_blob sqlite3_blob; ** ** ^Unless it returns SQLITE_MISUSE, this function sets the ** [database connection] error code and message accessible via -** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. +** [tdsqlite3_errcode()] and [tdsqlite3_errmsg()] and related functions. ** +** A BLOB referenced by tdsqlite3_blob_open() may be read using the +** [tdsqlite3_blob_read()] interface and modified by using +** [tdsqlite3_blob_write()]. The [BLOB handle] can be moved to a +** different row of the same table using the [tdsqlite3_blob_reopen()] +** interface. However, the column, table, or database of a [BLOB handle] +** cannot be changed after the [BLOB handle] is opened. ** ** ^(If the row that a BLOB handle points to is modified by an ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects ** then the BLOB handle is marked as "expired". ** This is true if any column of the row is changed, even a column ** other than the one the BLOB handle is open on.)^ -** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** ^Calls to [tdsqlite3_blob_read()] and [tdsqlite3_blob_write()] for ** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. ** ^(Changes written into a BLOB prior to the BLOB expiring are not ** rolled back by the expiration of the BLOB. Such changes will eventually ** commit if the transaction continues to completion.)^ ** -** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** ^Use the [tdsqlite3_blob_bytes()] interface to determine the size of ** the opened blob. ^The size of a blob may not be changed by this ** interface. Use the [UPDATE] SQL command to change the size of a ** blob. ** -** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** ^The [tdsqlite3_bind_zeroblob()] and [tdsqlite3_result_zeroblob()] interfaces ** and the built-in [zeroblob] SQL function may be used to create a ** zero-filled blob to read or write using the incremental-blob interface. ** ** To avoid a resource leak, every open [BLOB handle] should eventually -** be released by a call to [sqlite3_blob_close()]. +** be released by a call to [tdsqlite3_blob_close()]. +** +** See also: [tdsqlite3_blob_close()], +** [tdsqlite3_blob_reopen()], [tdsqlite3_blob_read()], +** [tdsqlite3_blob_bytes()], [tdsqlite3_blob_write()]. */ -SQLITE_API int sqlite3_blob_open( - sqlite3*, +SQLITE_API int tdsqlite3_blob_open( + tdsqlite3*, const char *zDb, const char *zTable, const char *zColumn, - sqlite3_int64 iRow, + tdsqlite3_int64 iRow, int flags, - sqlite3_blob **ppBlob + tdsqlite3_blob **ppBlob ); /* ** CAPI3REF: Move a BLOB Handle to a New Row -** METHOD: sqlite3_blob +** METHOD: tdsqlite3_blob ** -** ^This function is used to move an existing blob handle so that it points +** ^This function is used to move an existing [BLOB handle] so that it points ** to a different row of the same database table. ^The new row is identified ** by the rowid value passed as the second argument. Only the row can be ** changed. ^The database, table and column on which the blob handle is open -** remain the same. Moving an existing blob handle to a new row can be +** remain the same. Moving an existing [BLOB handle] to a new row is ** faster than closing the existing handle and opening a new one. ** -** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** ^(The new row must meet the same criteria as for [tdsqlite3_blob_open()] - ** it must exist and there must be either a blob or text value stored in ** the nominated column.)^ ^If the new row is not present in the table, or if ** it does not contain a blob or text value, or if another error occurs, an ** SQLite error code is returned and the blob handle is considered aborted. -** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or -** [sqlite3_blob_reopen()] on an aborted blob handle immediately return -** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** ^All subsequent calls to [tdsqlite3_blob_read()], [tdsqlite3_blob_write()] or +** [tdsqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [tdsqlite3_blob_bytes()] on an aborted blob handle ** always returns zero. ** ** ^This function sets the database handle error code and message. */ -SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); +SQLITE_API int tdsqlite3_blob_reopen(tdsqlite3_blob *, tdsqlite3_int64); /* ** CAPI3REF: Close A BLOB Handle -** DESTRUCTOR: sqlite3_blob +** DESTRUCTOR: tdsqlite3_blob ** ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed ** unconditionally. Even if this routine returns an error code, the @@ -6506,15 +8182,15 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); ** Calling this function with an argument that is not a NULL pointer or an ** open blob handle results in undefined behaviour. ^Calling this routine ** with a null pointer (such as would be returned by a failed call to -** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function +** [tdsqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function ** is passed a valid open blob handle, the values returned by the -** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. +** tdsqlite3_errcode() and tdsqlite3_errmsg() functions are set before returning. */ -SQLITE_API int sqlite3_blob_close(sqlite3_blob *); +SQLITE_API int tdsqlite3_blob_close(tdsqlite3_blob *); /* ** CAPI3REF: Return The Size Of An Open BLOB -** METHOD: sqlite3_blob +** METHOD: tdsqlite3_blob ** ** ^Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. ^The @@ -6522,15 +8198,15 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** by a prior successful call to [tdsqlite3_blob_open()] and which has not +** been closed by [tdsqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. */ -SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); +SQLITE_API int tdsqlite3_blob_bytes(tdsqlite3_blob *); /* ** CAPI3REF: Read Data From A BLOB Incrementally -** METHOD: sqlite3_blob +** METHOD: tdsqlite3_blob ** ** ^(This function is used to read data from an open [BLOB handle] into a ** caller-supplied buffer. N bytes of data are copied into buffer Z @@ -6540,39 +8216,39 @@ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is ** less than zero, [SQLITE_ERROR] is returned and no data is read. ** ^The size of the blob (and hence the maximum value of N+iOffset) -** can be determined using the [sqlite3_blob_bytes()] interface. +** can be determined using the [tdsqlite3_blob_bytes()] interface. ** ** ^An attempt to read from an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ** -** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** ^(On success, tdsqlite3_blob_read() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** by a prior successful call to [tdsqlite3_blob_open()] and which has not +** been closed by [tdsqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** -** See also: [sqlite3_blob_write()]. +** See also: [tdsqlite3_blob_write()]. */ -SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); +SQLITE_API int tdsqlite3_blob_read(tdsqlite3_blob *, void *Z, int N, int iOffset); /* ** CAPI3REF: Write Data Into A BLOB Incrementally -** METHOD: sqlite3_blob +** METHOD: tdsqlite3_blob ** ** ^(This function is used to write data into an open [BLOB handle] from a ** caller-supplied buffer. N bytes of data are copied from the buffer Z ** into the open BLOB, starting at offset iOffset.)^ ** -** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** ^(On success, tdsqlite3_blob_write() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ^Unless SQLITE_MISUSE is returned, this function sets the ** [database connection] error code and message accessible via -** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. +** [tdsqlite3_errcode()] and [tdsqlite3_errmsg()] and related functions. ** ** ^If the [BLOB handle] passed as the first argument was not opened for -** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** writing (the flags parameter to [tdsqlite3_blob_open()] was zero), ** this function returns [SQLITE_READONLY]. ** ** This function may only modify the contents of the BLOB; it is @@ -6580,7 +8256,7 @@ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is written. The size of the ** BLOB (and hence the maximum value of N+iOffset) can be determined -** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less +** using the [tdsqlite3_blob_bytes()] interface. ^If N or iOffset are less ** than zero [SQLITE_ERROR] is returned and no data is written. ** ** ^An attempt to write to an expired [BLOB handle] fails with an @@ -6591,31 +8267,31 @@ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); ** or by other independent statements. ** ** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** by a prior successful call to [tdsqlite3_blob_open()] and which has not +** been closed by [tdsqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** -** See also: [sqlite3_blob_read()]. +** See also: [tdsqlite3_blob_read()]. */ -SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); +SQLITE_API int tdsqlite3_blob_write(tdsqlite3_blob *, const void *z, int n, int iOffset); /* ** CAPI3REF: Virtual File System Objects ** -** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** A virtual filesystem (VFS) is an [tdsqlite3_vfs] object ** that SQLite uses to interact ** with the underlying operating system. Most SQLite builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** -** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^The tdsqlite3_vfs_find() interface returns a pointer to a VFS given its name. ** ^Names are case sensitive. ** ^Names are zero-terminated UTF-8 strings. ** ^If there is no match, a NULL pointer is returned. ** ^If zVfsName is NULL then the default VFS is returned. ** -** ^New VFSes are registered with sqlite3_vfs_register(). +** ^New VFSes are registered with tdsqlite3_vfs_register(). ** ^Each new VFS becomes the default VFS if the makeDflt flag is set. ** ^The same VFS can be registered multiple times without injury. ** ^To make an existing VFS into the default VFS, register it again @@ -6624,13 +8300,13 @@ SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOff ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. ** -** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^Unregister a VFS with the tdsqlite3_vfs_unregister() interface. ** ^(If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary.)^ */ -SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); -SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); -SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); +SQLITE_API tdsqlite3_vfs *tdsqlite3_vfs_find(const char *zVfsName); +SQLITE_API int tdsqlite3_vfs_register(tdsqlite3_vfs*, int makeDflt); +SQLITE_API int tdsqlite3_vfs_unregister(tdsqlite3_vfs*); /* ** CAPI3REF: Mutexes @@ -6661,14 +8337,14 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex ** implementation is included with the library. In this case the ** application must supply a custom mutex implementation using the -** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function -** before calling sqlite3_initialize() or any other public sqlite3_ -** function that calls sqlite3_initialize(). +** [SQLITE_CONFIG_MUTEX] option of the tdsqlite3_config() function +** before calling tdsqlite3_initialize() or any other public tdsqlite3_ +** function that calls tdsqlite3_initialize(). ** -** ^The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() +** ^The tdsqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^The tdsqlite3_mutex_alloc() ** routine returns NULL if it is unable to allocate the requested -** mutex. The argument to sqlite3_mutex_alloc() must one of these +** mutex. The argument to tdsqlite3_mutex_alloc() must one of these ** integer constants: ** ** <ul> @@ -6689,7 +8365,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** </ul> ** ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) -** cause sqlite3_mutex_alloc() to create +** cause tdsqlite3_mutex_alloc() to create ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction @@ -6699,7 +8375,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** -** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** ^The other allowed parameters to tdsqlite3_mutex_alloc() (anything other ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return ** a pointer to a static preexisting mutex. ^Nine static mutexes are ** used by the current version of SQLite. Future versions of SQLite @@ -6709,19 +8385,19 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** SQLITE_MUTEX_RECURSIVE. ** ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST -** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** or SQLITE_MUTEX_RECURSIVE) is used then tdsqlite3_mutex_alloc() ** returns a different mutex on every call. ^For the static ** mutex types, the same mutex is returned on every call that has ** the same type number. ** -** ^The sqlite3_mutex_free() routine deallocates a previously +** ^The tdsqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. Attempting to deallocate a static ** mutex results in undefined behavior. ** -** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** ^The tdsqlite3_mutex_enter() and tdsqlite3_mutex_try() routines attempt ** to enter a mutex. ^If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** tdsqlite3_mutex_enter() will block and tdsqlite3_mutex_try() will return +** SQLITE_BUSY. ^The tdsqlite3_mutex_try() interface returns [SQLITE_OK] ** upon successful entry. ^(Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** In such cases, the @@ -6730,27 +8406,27 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined. ** ** ^(Some systems (for example, Windows 95) do not support the operation -** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** implemented by tdsqlite3_mutex_try(). On those systems, tdsqlite3_mutex_try() ** will always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable +** tdsqlite3_mutex_try() as an optimization so this is acceptable ** behavior.)^ ** -** ^The sqlite3_mutex_leave() routine exits a mutex that was +** ^The tdsqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. ** -** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or -** sqlite3_mutex_leave() is a NULL pointer, then all three routines +** ^If the argument to tdsqlite3_mutex_enter(), tdsqlite3_mutex_try(), or +** tdsqlite3_mutex_leave() is a NULL pointer, then all three routines ** behave as no-ops. ** -** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +** See also: [tdsqlite3_mutex_held()] and [tdsqlite3_mutex_notheld()]. */ -SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); -SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); -SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); -SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); -SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); +SQLITE_API tdsqlite3_mutex *tdsqlite3_mutex_alloc(int); +SQLITE_API void tdsqlite3_mutex_free(tdsqlite3_mutex*); +SQLITE_API void tdsqlite3_mutex_enter(tdsqlite3_mutex*); +SQLITE_API int tdsqlite3_mutex_try(tdsqlite3_mutex*); +SQLITE_API void tdsqlite3_mutex_leave(tdsqlite3_mutex*); /* ** CAPI3REF: Mutex Methods Object @@ -6763,41 +8439,41 @@ SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); ** implementation for specialized deployments or systems for which SQLite ** does not provide a suitable implementation. In this case, the application ** creates and populates an instance of this structure to pass -** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** to tdsqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. ** Additionally, an instance of this structure can be used as an ** output variable when querying the system for the current mutex ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. ** ** ^The xMutexInit method defined by this structure is invoked as -** part of system initialization by the sqlite3_initialize() function. +** part of system initialization by the tdsqlite3_initialize() function. ** ^The xMutexInit routine is called by SQLite exactly once for each -** effective call to [sqlite3_initialize()]. +** effective call to [tdsqlite3_initialize()]. ** ** ^The xMutexEnd method defined by this structure is invoked as -** part of system shutdown by the sqlite3_shutdown() function. The +** part of system shutdown by the tdsqlite3_shutdown() function. The ** implementation of this method is expected to release all outstanding ** resources obtained by the mutex methods implementation, especially ** those obtained by the xMutexInit method. ^The xMutexEnd() -** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** interface is invoked exactly once for each call to [tdsqlite3_shutdown()]. ** ** ^(The remaining seven methods defined by this structure (xMutexAlloc, ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and ** xMutexNotheld) implement the following interfaces (respectively): ** ** <ul> -** <li> [sqlite3_mutex_alloc()] </li> -** <li> [sqlite3_mutex_free()] </li> -** <li> [sqlite3_mutex_enter()] </li> -** <li> [sqlite3_mutex_try()] </li> -** <li> [sqlite3_mutex_leave()] </li> -** <li> [sqlite3_mutex_held()] </li> -** <li> [sqlite3_mutex_notheld()] </li> +** <li> [tdsqlite3_mutex_alloc()] </li> +** <li> [tdsqlite3_mutex_free()] </li> +** <li> [tdsqlite3_mutex_enter()] </li> +** <li> [tdsqlite3_mutex_try()] </li> +** <li> [tdsqlite3_mutex_leave()] </li> +** <li> [tdsqlite3_mutex_held()] </li> +** <li> [tdsqlite3_mutex_notheld()] </li> ** </ul>)^ ** -** The only difference is that the public sqlite3_XXX functions enumerated +** The only difference is that the public tdsqlite3_XXX functions enumerated ** above silently ignore any invocations that pass a NULL pointer instead ** of a valid mutex handle. The implementations of the methods defined -** by this structure are not required to handle this case, the results +** by this structure are not required to handle this case. The results ** of passing a NULL pointer instead of a valid mutex handle are undefined ** (i.e. it is acceptable to provide an implementation that segfaults if ** it is passed a NULL pointer). @@ -6807,33 +8483,33 @@ SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); ** intervening calls to xMutexEnd(). Second and subsequent calls to ** xMutexInit() must be no-ops. ** -** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** xMutexInit() must not use SQLite memory allocation ([tdsqlite3_malloc()] ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite ** memory allocation for a fast or recursive mutex. ** -** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** ^SQLite will invoke the xMutexEnd() method when [tdsqlite3_shutdown()] is ** called, but only if the prior call to xMutexInit returned SQLITE_OK. ** If xMutexInit fails in any way, it is expected to clean up after itself ** prior to returning. */ -typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; -struct sqlite3_mutex_methods { +typedef struct tdsqlite3_mutex_methods tdsqlite3_mutex_methods; +struct tdsqlite3_mutex_methods { int (*xMutexInit)(void); int (*xMutexEnd)(void); - sqlite3_mutex *(*xMutexAlloc)(int); - void (*xMutexFree)(sqlite3_mutex *); - void (*xMutexEnter)(sqlite3_mutex *); - int (*xMutexTry)(sqlite3_mutex *); - void (*xMutexLeave)(sqlite3_mutex *); - int (*xMutexHeld)(sqlite3_mutex *); - int (*xMutexNotheld)(sqlite3_mutex *); + tdsqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(tdsqlite3_mutex *); + void (*xMutexEnter)(tdsqlite3_mutex *); + int (*xMutexTry)(tdsqlite3_mutex *); + void (*xMutexLeave)(tdsqlite3_mutex *); + int (*xMutexHeld)(tdsqlite3_mutex *); + int (*xMutexNotheld)(tdsqlite3_mutex *); }; /* ** CAPI3REF: Mutex Verification Routines ** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** The tdsqlite3_mutex_held() and tdsqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. The SQLite core only @@ -6850,24 +8526,24 @@ struct sqlite3_mutex_methods { ** versions of these routines, it should at least provide stubs that always ** return true so that one does not get spurious assertion failures. ** -** If the argument to sqlite3_mutex_held() is a NULL pointer then +** If the argument to tdsqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. This seems counter-intuitive since ** clearly the mutex cannot be held if it does not exist. But ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the -** call to sqlite3_mutex_held() to fail, so a non-zero return is -** the appropriate thing to do. The sqlite3_mutex_notheld() +** call to tdsqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. The tdsqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ #ifndef NDEBUG -SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); -SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); +SQLITE_API int tdsqlite3_mutex_held(tdsqlite3_mutex*); +SQLITE_API int tdsqlite3_mutex_notheld(tdsqlite3_mutex*); #endif /* ** CAPI3REF: Mutex Types ** -** The [sqlite3_mutex_alloc()] interface takes a single argument +** The [tdsqlite3_mutex_alloc()] interface takes a single argument ** which is one of these integer constants. ** ** The set of static mutexes may change from one SQLite release to the @@ -6877,13 +8553,13 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 #define SQLITE_MUTEX_STATIC_MASTER 2 -#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM 3 /* tdsqlite3_malloc() */ #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ -#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ -#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* tdsqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* tdsqlite3_randomness() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ -#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* tdsqlite3PageMalloc() */ #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */ @@ -6893,22 +8569,23 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); /* ** CAPI3REF: Retrieve the mutex for a database connection -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^This interface returns a pointer the [sqlite3_mutex] object that +** ^This interface returns a pointer the [tdsqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** ^If the [threading mode] is Single-thread or Multi-thread then this ** routine returns a NULL pointer. */ -SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); +SQLITE_API tdsqlite3_mutex *tdsqlite3_db_mutex(tdsqlite3*); /* ** CAPI3REF: Low-Level Control Of Database Files -** METHOD: sqlite3 +** METHOD: tdsqlite3 +** KEYWORDS: {file control} ** -** ^The [sqlite3_file_control()] interface makes a direct call to the -** xFileControl method for the [sqlite3_io_methods] object associated +** ^The [tdsqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [tdsqlite3_io_methods] object associated ** with a particular database identified by the second argument. ^The ** name of the database is "main" for the main database or "temp" for the ** TEMP database, or the name that appears after the AS keyword for @@ -6920,28 +8597,35 @@ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); ** the xFileControl method. ^The return value of the xFileControl ** method becomes the return value of this routine. ** -** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes -** a pointer to the underlying [sqlite3_file] object to be written into -** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER -** case is a short-circuit path which does not actually invoke the -** underlying sqlite3_io_methods.xFileControl method. +** A few opcodes for [tdsqlite3_file_control()] are handled directly +** by the SQLite core and never invoke the +** tdsqlite3_io_methods.xFileControl method. +** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes +** a pointer to the underlying [tdsqlite3_file] object to be written into +** the space pointed to by the 4th parameter. The +** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns +** the [tdsqlite3_file] object associated with the journal file instead of +** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns +** a pointer to the underlying [tdsqlite3_vfs] object for the file. +** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter +** from the pager. ** ** ^If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. ^This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might +** code is not remembered and will not be recalled by [tdsqlite3_errcode()] +** or [tdsqlite3_errmsg()]. The underlying xFileControl method might ** also return SQLITE_ERROR. There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. ** -** See also: [SQLITE_FCNTL_LOCKSTATE] +** See also: [file control opcodes] */ -SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); +SQLITE_API int tdsqlite3_file_control(tdsqlite3*, const char *zDbName, int op, void*); /* ** CAPI3REF: Testing Interface ** -** ^The sqlite3_test_control() interface is used to read out internal +** ^The tdsqlite3_test_control() interface is used to read out internal ** state of SQLite and to inject faults into SQLite for testing ** purposes. ^The first parameter is an operation code that determines ** the number, meaning, and operation of all subsequent parameters. @@ -6955,23 +8639,23 @@ SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void* ** Unlike most of the SQLite API, this function is not guaranteed to ** operate consistently from one release to the next. */ -SQLITE_API int sqlite3_test_control(int op, ...); +SQLITE_API int tdsqlite3_test_control(int op, ...); /* ** CAPI3REF: Testing Interface Operation Codes ** ** These constants are the valid operation code parameters used -** as the first argument to [sqlite3_test_control()]. +** as the first argument to [tdsqlite3_test_control()]. ** ** These parameters and their meanings are subject to change ** without notice. These values are for testing purposes only. ** Applications should not use any of these parameters or the -** [sqlite3_test_control()] interface. +** [tdsqlite3_test_control()] interface. */ #define SQLITE_TESTCTRL_FIRST 5 #define SQLITE_TESTCTRL_PRNG_SAVE 5 #define SQLITE_TESTCTRL_PRNG_RESTORE 6 -#define SQLITE_TESTCTRL_PRNG_RESET 7 +#define SQLITE_TESTCTRL_PRNG_RESET 7 /* NOT USED */ #define SQLITE_TESTCTRL_BITVEC_TEST 8 #define SQLITE_TESTCTRL_FAULT_INSTALL 9 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 @@ -6980,8 +8664,9 @@ SQLITE_API int sqlite3_test_control(int op, ...); #define SQLITE_TESTCTRL_ALWAYS 13 #define SQLITE_TESTCTRL_RESERVE 14 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15 -#define SQLITE_TESTCTRL_ISKEYWORD 16 -#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 +#define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */ +#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */ +#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */ #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19 @@ -6991,7 +8676,194 @@ SQLITE_API int sqlite3_test_control(int op, ...); #define SQLITE_TESTCTRL_ISINIT 23 #define SQLITE_TESTCTRL_SORTER_MMAP 24 #define SQLITE_TESTCTRL_IMPOSTER 25 -#define SQLITE_TESTCTRL_LAST 25 +#define SQLITE_TESTCTRL_PARSER_COVERAGE 26 +#define SQLITE_TESTCTRL_RESULT_INTREAL 27 +#define SQLITE_TESTCTRL_PRNG_SEED 28 +#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS 29 +#define SQLITE_TESTCTRL_LAST 29 /* Largest TESTCTRL */ + +/* +** CAPI3REF: SQL Keyword Checking +** +** These routines provide access to the set of SQL language keywords +** recognized by SQLite. Applications can uses these routines to determine +** whether or not a specific identifier needs to be escaped (for example, +** by enclosing in double-quotes) so as not to confuse the parser. +** +** The tdsqlite3_keyword_count() interface returns the number of distinct +** keywords understood by SQLite. +** +** The tdsqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and +** makes *Z point to that keyword expressed as UTF8 and writes the number +** of bytes in the keyword into *L. The string that *Z points to is not +** zero-terminated. The tdsqlite3_keyword_name(N,Z,L) routine returns +** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z +** or L are NULL or invalid pointers then calls to +** tdsqlite3_keyword_name(N,Z,L) result in undefined behavior. +** +** The tdsqlite3_keyword_check(Z,L) interface checks to see whether or not +** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero +** if it is and zero if not. +** +** The parser used by SQLite is forgiving. It is often possible to use +** a keyword as an identifier as long as such use does not result in a +** parsing ambiguity. For example, the statement +** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and +** creates a new table named "BEGIN" with three columns named +** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid +** using keywords as identifiers. Common techniques used to avoid keyword +** name collisions include: +** <ul> +** <li> Put all identifier names inside double-quotes. This is the official +** SQL way to escape identifier names. +** <li> Put identifier names inside [...]. This is not standard SQL, +** but it is what SQL Server does and so lots of programmers use this +** technique. +** <li> Begin every identifier with the letter "Z" as no SQL keywords start +** with "Z". +** <li> Include a digit somewhere in every identifier name. +** </ul> +** +** Note that the number of keywords understood by SQLite can depend on +** compile-time options. For example, "VACUUM" is not a keyword if +** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also, +** new keywords may be added to future releases of SQLite. +*/ +SQLITE_API int tdsqlite3_keyword_count(void); +SQLITE_API int tdsqlite3_keyword_name(int,const char**,int*); +SQLITE_API int tdsqlite3_keyword_check(const char*,int); + +/* +** CAPI3REF: Dynamic String Object +** KEYWORDS: {dynamic string} +** +** An instance of the tdsqlite3_str object contains a dynamically-sized +** string under construction. +** +** The lifecycle of an tdsqlite3_str object is as follows: +** <ol> +** <li> ^The tdsqlite3_str object is created using [tdsqlite3_str_new()]. +** <li> ^Text is appended to the tdsqlite3_str object using various +** methods, such as [tdsqlite3_str_appendf()]. +** <li> ^The tdsqlite3_str object is destroyed and the string it created +** is returned using the [tdsqlite3_str_finish()] interface. +** </ol> +*/ +typedef struct tdsqlite3_str tdsqlite3_str; + +/* +** CAPI3REF: Create A New Dynamic String Object +** CONSTRUCTOR: tdsqlite3_str +** +** ^The [tdsqlite3_str_new(D)] interface allocates and initializes +** a new [tdsqlite3_str] object. To avoid memory leaks, the object returned by +** [tdsqlite3_str_new()] must be freed by a subsequent call to +** [tdsqlite3_str_finish(X)]. +** +** ^The [tdsqlite3_str_new(D)] interface always returns a pointer to a +** valid [tdsqlite3_str] object, though in the event of an out-of-memory +** error the returned object might be a special singleton that will +** silently reject new text, always return SQLITE_NOMEM from +** [tdsqlite3_str_errcode()], always return 0 for +** [tdsqlite3_str_length()], and always return NULL from +** [tdsqlite3_str_finish(X)]. It is always safe to use the value +** returned by [tdsqlite3_str_new(D)] as the tdsqlite3_str parameter +** to any of the other [tdsqlite3_str] methods. +** +** The D parameter to [tdsqlite3_str_new(D)] may be NULL. If the +** D parameter in [tdsqlite3_str_new(D)] is not NULL, then the maximum +** length of the string contained in the [tdsqlite3_str] object will be +** the value set for [tdsqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead +** of [SQLITE_MAX_LENGTH]. +*/ +SQLITE_API tdsqlite3_str *tdsqlite3_str_new(tdsqlite3*); + +/* +** CAPI3REF: Finalize A Dynamic String +** DESTRUCTOR: tdsqlite3_str +** +** ^The [tdsqlite3_str_finish(X)] interface destroys the tdsqlite3_str object X +** and returns a pointer to a memory buffer obtained from [tdsqlite3_malloc64()] +** that contains the constructed string. The calling application should +** pass the returned value to [tdsqlite3_free()] to avoid a memory leak. +** ^The [tdsqlite3_str_finish(X)] interface may return a NULL pointer if any +** errors were encountered during construction of the string. ^The +** [tdsqlite3_str_finish(X)] interface will also return a NULL pointer if the +** string in [tdsqlite3_str] object X is zero bytes long. +*/ +SQLITE_API char *tdsqlite3_str_finish(tdsqlite3_str*); + +/* +** CAPI3REF: Add Content To A Dynamic String +** METHOD: tdsqlite3_str +** +** These interfaces add content to an tdsqlite3_str object previously obtained +** from [tdsqlite3_str_new()]. +** +** ^The [tdsqlite3_str_appendf(X,F,...)] and +** [tdsqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf] +** functionality of SQLite to append formatted text onto the end of +** [tdsqlite3_str] object X. +** +** ^The [tdsqlite3_str_append(X,S,N)] method appends exactly N bytes from string S +** onto the end of the [tdsqlite3_str] object X. N must be non-negative. +** S must contain at least N non-zero bytes of content. To append a +** zero-terminated string in its entirety, use the [tdsqlite3_str_appendall()] +** method instead. +** +** ^The [tdsqlite3_str_appendall(X,S)] method appends the complete content of +** zero-terminated string S onto the end of [tdsqlite3_str] object X. +** +** ^The [tdsqlite3_str_appendchar(X,N,C)] method appends N copies of the +** single-byte character C onto the end of [tdsqlite3_str] object X. +** ^This method can be used, for example, to add whitespace indentation. +** +** ^The [tdsqlite3_str_reset(X)] method resets the string under construction +** inside [tdsqlite3_str] object X back to zero bytes in length. +** +** These methods do not return a result code. ^If an error occurs, that fact +** is recorded in the [tdsqlite3_str] object and can be recovered by a +** subsequent call to [tdsqlite3_str_errcode(X)]. +*/ +SQLITE_API void tdsqlite3_str_appendf(tdsqlite3_str*, const char *zFormat, ...); +SQLITE_API void tdsqlite3_str_vappendf(tdsqlite3_str*, const char *zFormat, va_list); +SQLITE_API void tdsqlite3_str_append(tdsqlite3_str*, const char *zIn, int N); +SQLITE_API void tdsqlite3_str_appendall(tdsqlite3_str*, const char *zIn); +SQLITE_API void tdsqlite3_str_appendchar(tdsqlite3_str*, int N, char C); +SQLITE_API void tdsqlite3_str_reset(tdsqlite3_str*); + +/* +** CAPI3REF: Status Of A Dynamic String +** METHOD: tdsqlite3_str +** +** These interfaces return the current status of an [tdsqlite3_str] object. +** +** ^If any prior errors have occurred while constructing the dynamic string +** in tdsqlite3_str X, then the [tdsqlite3_str_errcode(X)] method will return +** an appropriate error code. ^The [tdsqlite3_str_errcode(X)] method returns +** [SQLITE_NOMEM] following any out-of-memory error, or +** [SQLITE_TOOBIG] if the size of the dynamic string exceeds +** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors. +** +** ^The [tdsqlite3_str_length(X)] method returns the current length, in bytes, +** of the dynamic string under construction in [tdsqlite3_str] object X. +** ^The length returned by [tdsqlite3_str_length(X)] does not include the +** zero-termination byte. +** +** ^The [tdsqlite3_str_value(X)] method returns a pointer to the current +** content of the dynamic string under construction in X. The value +** returned by [tdsqlite3_str_value(X)] is managed by the tdsqlite3_str object X +** and might be freed or altered by any subsequent method on the same +** [tdsqlite3_str] object. Applications must not used the pointer returned +** [tdsqlite3_str_value(X)] after any subsequent method call on the same +** object. ^Applications may change the content of the string returned +** by [tdsqlite3_str_value(X)] as long as they do not write into any bytes +** outside the range of 0 to [tdsqlite3_str_length(X)] and do not read or +** write any byte after any subsequent tdsqlite3_str method call. +*/ +SQLITE_API int tdsqlite3_str_errcode(tdsqlite3_str*); +SQLITE_API int tdsqlite3_str_length(tdsqlite3_str*); +SQLITE_API char *tdsqlite3_str_value(tdsqlite3_str*); /* ** CAPI3REF: SQLite Runtime Status @@ -7010,20 +8882,20 @@ SQLITE_API int sqlite3_test_control(int op, ...); ** ^(Other parameters record only the highwater mark and not the current ** value. For these latter parameters nothing is written into *pCurrent.)^ ** -** ^The sqlite3_status() and sqlite3_status64() routines return +** ^The tdsqlite3_status() and tdsqlite3_status64() routines return ** SQLITE_OK on success and a non-zero [error code] on failure. ** ** If either the current value or the highwater mark is too large to ** be represented by a 32-bit integer, then the values returned by -** sqlite3_status() are undefined. +** tdsqlite3_status() are undefined. ** -** See also: [sqlite3_db_status()] +** See also: [tdsqlite3_db_status()] */ -SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); -SQLITE_API int sqlite3_status64( +SQLITE_API int tdsqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); +SQLITE_API int tdsqlite3_status64( int op, - sqlite3_int64 *pCurrent, - sqlite3_int64 *pHighwater, + tdsqlite3_int64 *pCurrent, + tdsqlite3_int64 *pHighwater, int resetFlag ); @@ -7033,24 +8905,23 @@ SQLITE_API int sqlite3_status64( ** KEYWORDS: {status parameters} ** ** These integer constants designate various run-time status parameters -** that can be returned by [sqlite3_status()]. +** that can be returned by [tdsqlite3_status()]. ** ** <dl> ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt> ** <dd>This parameter is the current amount of memory checked out -** using [sqlite3_malloc()], either directly or indirectly. The -** figure includes calls made to [sqlite3_malloc()] by the application -** and internal memory usage by the SQLite library. Scratch memory -** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache +** using [tdsqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [tdsqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Auxiliary page-cache ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in ** this parameter. The amount returned is the sum of the allocation -** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^ +** sizes as reported by the xSize method in [tdsqlite3_mem_methods].</dd>)^ ** ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt> ** <dd>This parameter records the largest memory allocation request -** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** handed to [tdsqlite3_malloc()] or [tdsqlite3_realloc()] (or their ** internal equivalents). Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. +** *pHighwater parameter to [tdsqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt> @@ -7067,7 +8938,7 @@ SQLITE_API int sqlite3_status64( ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt> ** <dd>This parameter returns the number of bytes of page cache ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] -** buffer and where forced to overflow to [sqlite3_malloc()]. The +** buffer and where forced to overflow to [tdsqlite3_malloc()]. The ** returned value includes allocations that overflowed because they ** where too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because @@ -7075,33 +8946,18 @@ SQLITE_API int sqlite3_status64( ** ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt> ** <dd>This parameter records the largest memory allocation request -** handed to [pagecache memory allocator]. Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. +** handed to the [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [tdsqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** -** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt> -** <dd>This parameter returns the number of allocations used out of the -** [scratch memory allocator] configured using -** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not -** in bytes. Since a single thread may only have one scratch allocation -** outstanding at time, this parameter also reports the number of threads -** using scratch memory at the same time.</dd>)^ +** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt> +** <dd>No longer used.</dd> ** ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt> -** <dd>This parameter returns the number of bytes of scratch memory -** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] -** buffer and where forced to overflow to [sqlite3_malloc()]. The values -** returned include overflows because the requested allocation was too -** larger (that is, because the requested allocation was larger than the -** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer -** slots were available. -** </dd>)^ +** <dd>No longer used.</dd> ** -** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt> -** <dd>This parameter records the largest memory allocation request -** handed to [scratch memory allocator]. Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. -** The value written into the *pCurrent parameter is undefined.</dd>)^ +** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt> +** <dd>No longer used.</dd> ** ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt> ** <dd>The *pHighwater parameter records the deepest parser stack. @@ -7114,17 +8970,17 @@ SQLITE_API int sqlite3_status64( #define SQLITE_STATUS_MEMORY_USED 0 #define SQLITE_STATUS_PAGECACHE_USED 1 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 -#define SQLITE_STATUS_SCRATCH_USED 3 -#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 +#define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */ +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */ #define SQLITE_STATUS_MALLOC_SIZE 5 #define SQLITE_STATUS_PARSER_STACK 6 #define SQLITE_STATUS_PAGECACHE_SIZE 7 -#define SQLITE_STATUS_SCRATCH_SIZE 8 +#define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */ #define SQLITE_STATUS_MALLOC_COUNT 9 /* ** CAPI3REF: Database Connection Status -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This interface is used to retrieve runtime status information ** about a single [database connection]. ^The first argument is the @@ -7140,24 +8996,24 @@ SQLITE_API int sqlite3_status64( ** the resetFlg is true, then the highest instantaneous value is ** reset back down to the current value. ** -** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** ^The tdsqlite3_db_status() routine returns SQLITE_OK on success and a ** non-zero [error code] on failure. ** -** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +** See also: [tdsqlite3_status()] and [tdsqlite3_stmt_status()]. */ -SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); +SQLITE_API int tdsqlite3_db_status(tdsqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); /* ** CAPI3REF: Status Parameters for database connections ** KEYWORDS: {SQLITE_DBSTATUS options} ** ** These constants are the available integer "verbs" that can be passed as -** the second argument to the [sqlite3_db_status()] interface. +** the second argument to the [tdsqlite3_db_status()] interface. ** ** New verbs may be added in future releases of SQLite. Existing verbs ** might be discontinued. Applications should check the return code from -** [sqlite3_db_status()] to make sure that the call worked. -** The [sqlite3_db_status()] interface will return a non-zero error code +** [tdsqlite3_db_status()] to make sure that the call worked. +** The [tdsqlite3_db_status()] interface will return a non-zero error code ** if a discontinued or unsupported verb is invoked. ** ** <dl> @@ -7166,7 +9022,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** checked out.</dd>)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt> -** <dd>This parameter returns the number malloc attempts that were +** <dd>This parameter returns the number of malloc attempts that were ** satisfied using lookaside memory. Only the high-water value is meaningful; ** the current value is always zero.)^ ** @@ -7242,6 +9098,15 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. ** </dd> ** +** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt> +** <dd>This parameter returns the number of dirty cache entries that have +** been written to disk in the middle of a transaction due to the page +** cache overflowing. Transactions are more efficient if they are written +** to disk all at once. When pages spill mid-transaction, that introduces +** additional overhead. This parameter can be used help identify +** inefficiencies that can be resolved by increasing the cache size. +** </dd> +** ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt> ** <dd>This parameter returns zero for the current value if and only if ** all foreign key constraints (deferred or immediate) have been @@ -7261,12 +9126,13 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r #define SQLITE_DBSTATUS_CACHE_WRITE 9 #define SQLITE_DBSTATUS_DEFERRED_FKS 10 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 -#define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */ +#define SQLITE_DBSTATUS_CACHE_SPILL 12 +#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */ /* ** CAPI3REF: Prepared Statement Status -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^(Each prepared statement maintains various ** [SQLITE_STMTSTATUS counters] that measure the number @@ -7286,16 +9152,16 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** ^If the resetFlg is true, then the counter is reset to zero after this ** interface call returns. ** -** See also: [sqlite3_status()] and [sqlite3_db_status()]. +** See also: [tdsqlite3_status()] and [tdsqlite3_db_status()]. */ -SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); +SQLITE_API int tdsqlite3_stmt_status(tdsqlite3_stmt*, int op,int resetFlg); /* ** CAPI3REF: Status Parameters for prepared statements ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} ** ** These preprocessor macros define integer codes that name counter -** values associated with the [sqlite3_stmt_status()] interface. +** values associated with the [tdsqlite3_stmt_status()] interface. ** The meanings of the various counters are as follows: ** ** <dl> @@ -7324,6 +9190,24 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); ** used as a proxy for the total work done by the prepared statement. ** If the number of virtual machine operations exceeds 2147483647 ** then the value returned by this statement status code is undefined. +** +** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt> +** <dd>^This is the number of times that the prepare statement has been +** automatically regenerated due to schema changes or changes to +** [bound parameters] that might affect the query plan. +** +** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt> +** <dd>^This is the number of times that the prepared statement has +** been run. A single "run" for the purposes of this counter is one +** or more calls to [tdsqlite3_step()] followed by a call to [tdsqlite3_reset()]. +** The counter is incremented on the first [tdsqlite3_step()] call of each +** cycle. +** +** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt> +** <dd>^This is the approximate number of bytes of heap memory +** used to store the prepared statement. ^This value is not actually +** a counter, and so the resetFlg parameter to tdsqlite3_stmt_status() +** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED. ** </dd> ** </dl> */ @@ -7331,32 +9215,35 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); #define SQLITE_STMTSTATUS_SORT 2 #define SQLITE_STMTSTATUS_AUTOINDEX 3 #define SQLITE_STMTSTATUS_VM_STEP 4 +#define SQLITE_STMTSTATUS_REPREPARE 5 +#define SQLITE_STMTSTATUS_RUN 6 +#define SQLITE_STMTSTATUS_MEMUSED 99 /* ** CAPI3REF: Custom Page Cache Object ** -** The sqlite3_pcache type is opaque. It is implemented by +** The tdsqlite3_pcache type is opaque. It is implemented by ** the pluggable module. The SQLite core has no knowledge of ** its size or internal structure and never deals with the -** sqlite3_pcache object except by holding and passing pointers +** tdsqlite3_pcache object except by holding and passing pointers ** to the object. ** -** See [sqlite3_pcache_methods2] for additional information. +** See [tdsqlite3_pcache_methods2] for additional information. */ -typedef struct sqlite3_pcache sqlite3_pcache; +typedef struct tdsqlite3_pcache tdsqlite3_pcache; /* ** CAPI3REF: Custom Page Cache Object ** -** The sqlite3_pcache_page object represents a single page in the +** The tdsqlite3_pcache_page object represents a single page in the ** page cache. The page cache will allocate instances of this ** object. Various methods of the page cache use pointers to instances ** of this object as parameters or as their return value. ** -** See [sqlite3_pcache_methods2] for additional information. +** See [tdsqlite3_pcache_methods2] for additional information. */ -typedef struct sqlite3_pcache_page sqlite3_pcache_page; -struct sqlite3_pcache_page { +typedef struct tdsqlite3_pcache_page tdsqlite3_pcache_page; +struct tdsqlite3_pcache_page { void *pBuf; /* The content of the page */ void *pExtra; /* Extra information associated with the page */ }; @@ -7365,9 +9252,9 @@ struct sqlite3_pcache_page { ** CAPI3REF: Application Defined Page Cache. ** KEYWORDS: {page cache} ** -** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can +** ^(The [tdsqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can ** register an alternative page cache implementation by passing in an -** instance of the sqlite3_pcache_methods2 structure.)^ +** instance of the tdsqlite3_pcache_methods2 structure.)^ ** In many applications, most of the heap memory allocated by ** SQLite is used for the page cache. ** By implementing a @@ -7381,16 +9268,16 @@ struct sqlite3_pcache_page { ** extreme measure that is only needed by the most demanding applications. ** The built-in page cache is recommended for most uses. ** -** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an -** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** ^(The contents of the tdsqlite3_pcache_methods2 structure are copied to an +** internal buffer by SQLite within the call to [tdsqlite3_config]. Hence ** the application may discard the parameter after the call to -** [sqlite3_config()] returns.)^ +** [tdsqlite3_config()] returns.)^ ** ** [[the xInit() page cache method]] ** ^(The xInit() method is called once for each effective -** call to [sqlite3_initialize()])^ +** call to [tdsqlite3_initialize()])^ ** (usually only once during the lifetime of the process). ^(The xInit() -** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ +** method is passed a copy of the tdsqlite3_pcache_methods2.pArg value.)^ ** The intent of the xInit() method is to set up global data structures ** required by the custom page cache implementation. ** ^(If the xInit() method is NULL, then the @@ -7398,14 +9285,14 @@ struct sqlite3_pcache_page { ** page cache.)^ ** ** [[the xShutdown() page cache method]] -** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** ^The xShutdown() method is called by [tdsqlite3_shutdown()]. ** It can be used to clean up ** any outstanding resources before process shutdown, if required. ** ^The xShutdown() method may be NULL. ** ** ^SQLite automatically serializes calls to the xInit method, ** so the xInit method need not be threadsafe. ^The -** xShutdown method is only called from [sqlite3_shutdown()] so it does +** xShutdown method is only called from [tdsqlite3_shutdown()] so it does ** not need to be threadsafe either. All other methods must be threadsafe ** in multithreaded applications. ** @@ -7449,10 +9336,10 @@ struct sqlite3_pcache_page { ** ** [[the xFetch() page cache methods]] ** The xFetch() method locates a page in the cache and returns a pointer to -** an sqlite3_pcache_page object associated with that page, or a NULL pointer. -** The pBuf element of the returned sqlite3_pcache_page object will be a +** an tdsqlite3_pcache_page object associated with that page, or a NULL pointer. +** The pBuf element of the returned tdsqlite3_pcache_page object will be a ** pointer to a buffer of szPage bytes used to store the content of a -** single database page. The pExtra element of sqlite3_pcache_page will be +** single database page. The pExtra element of tdsqlite3_pcache_page will be ** a pointer to the szExtra bytes of extra storage that SQLite has requested ** for each entry in the page cache. ** @@ -7477,7 +9364,7 @@ struct sqlite3_pcache_page { ** ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite ** will only use a createFlag of 2 after a prior call with a createFlag of 1 -** failed.)^ In between the to xFetch() calls, SQLite may +** failed.)^ In between the xFetch() calls, SQLite may ** attempt to unpin one or more cache pages by spilling the content of ** pinned pages to disk and synching the operating system disk cache. ** @@ -7510,8 +9397,8 @@ struct sqlite3_pcache_page { ** [[the xDestroy() page cache method]] ** ^The xDestroy() method is used to delete a cache allocated by xCreate(). ** All resources associated with the specified cache should be freed. ^After -** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] -** handle invalid, and will not use it with any other sqlite3_pcache_methods2 +** calling the xDestroy() method, SQLite considers the [tdsqlite3_pcache*] +** handle invalid, and will not use it with any other tdsqlite3_pcache_methods2 ** functions. ** ** [[the xShrink() page cache method]] @@ -7520,56 +9407,56 @@ struct sqlite3_pcache_page { ** is not obligated to free any memory, but well-behaved implementations should ** do their best. */ -typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; -struct sqlite3_pcache_methods2 { +typedef struct tdsqlite3_pcache_methods2 tdsqlite3_pcache_methods2; +struct tdsqlite3_pcache_methods2 { int iVersion; void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); - sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); - void (*xCachesize)(sqlite3_pcache*, int nCachesize); - int (*xPagecount)(sqlite3_pcache*); - sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); - void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); - void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, + tdsqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); + void (*xCachesize)(tdsqlite3_pcache*, int nCachesize); + int (*xPagecount)(tdsqlite3_pcache*); + tdsqlite3_pcache_page *(*xFetch)(tdsqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(tdsqlite3_pcache*, tdsqlite3_pcache_page*, int discard); + void (*xRekey)(tdsqlite3_pcache*, tdsqlite3_pcache_page*, unsigned oldKey, unsigned newKey); - void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); - void (*xDestroy)(sqlite3_pcache*); - void (*xShrink)(sqlite3_pcache*); + void (*xTruncate)(tdsqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(tdsqlite3_pcache*); + void (*xShrink)(tdsqlite3_pcache*); }; /* ** This is the obsolete pcache_methods object that has now been replaced -** by sqlite3_pcache_methods2. This object is not used by SQLite. It is +** by tdsqlite3_pcache_methods2. This object is not used by SQLite. It is ** retained in the header file for backwards compatibility only. */ -typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; -struct sqlite3_pcache_methods { +typedef struct tdsqlite3_pcache_methods tdsqlite3_pcache_methods; +struct tdsqlite3_pcache_methods { void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); - sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); - void (*xCachesize)(sqlite3_pcache*, int nCachesize); - int (*xPagecount)(sqlite3_pcache*); - void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); - void (*xUnpin)(sqlite3_pcache*, void*, int discard); - void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); - void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); - void (*xDestroy)(sqlite3_pcache*); + tdsqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(tdsqlite3_pcache*, int nCachesize); + int (*xPagecount)(tdsqlite3_pcache*); + void *(*xFetch)(tdsqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(tdsqlite3_pcache*, void*, int discard); + void (*xRekey)(tdsqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(tdsqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(tdsqlite3_pcache*); }; /* ** CAPI3REF: Online Backup Object ** -** The sqlite3_backup object records state information about an ongoing -** online backup operation. ^The sqlite3_backup object is created by -** a call to [sqlite3_backup_init()] and is destroyed by a call to -** [sqlite3_backup_finish()]. +** The tdsqlite3_backup object records state information about an ongoing +** online backup operation. ^The tdsqlite3_backup object is created by +** a call to [tdsqlite3_backup_init()] and is destroyed by a call to +** [tdsqlite3_backup_finish()]. ** ** See Also: [Using the SQLite Online Backup API] */ -typedef struct sqlite3_backup sqlite3_backup; +typedef struct tdsqlite3_backup tdsqlite3_backup; /* ** CAPI3REF: Online Backup API. @@ -7590,63 +9477,63 @@ typedef struct sqlite3_backup sqlite3_backup; ** ** ^(To perform a backup operation: ** <ol> -** <li><b>sqlite3_backup_init()</b> is called once to initialize the +** <li><b>tdsqlite3_backup_init()</b> is called once to initialize the ** backup, -** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer +** <li><b>tdsqlite3_backup_step()</b> is called one or more times to transfer ** the data between the two databases, and finally -** <li><b>sqlite3_backup_finish()</b> is called to release all resources +** <li><b>tdsqlite3_backup_finish()</b> is called to release all resources ** associated with the backup operation. ** </ol>)^ -** There should be exactly one call to sqlite3_backup_finish() for each -** successful call to sqlite3_backup_init(). +** There should be exactly one call to tdsqlite3_backup_finish() for each +** successful call to tdsqlite3_backup_init(). ** -** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b> +** [[tdsqlite3_backup_init()]] <b>tdsqlite3_backup_init()</b> ** -** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** ^The D and N arguments to tdsqlite3_backup_init(D,N,S,M) are the ** [database connection] associated with the destination database ** and the database name, respectively. ** ^The database name is "main" for the main database, "temp" for the ** temporary database, or the name specified after the AS keyword in ** an [ATTACH] statement for an attached database. ** ^The S and M arguments passed to -** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** tdsqlite3_backup_init(D,N,S,M) identify the [database connection] ** and database name of the source database, respectively. ** ^The source and destination [database connections] (parameters S and D) -** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** must be different or else tdsqlite3_backup_init(D,N,S,M) will fail with ** an error. ** -** ^A call to sqlite3_backup_init() will fail, returning NULL, if +** ^A call to tdsqlite3_backup_init() will fail, returning NULL, if ** there is already a read or read-write transaction open on the ** destination database. ** -** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** ^If an error occurs within tdsqlite3_backup_init(D,N,S,M), then NULL is ** returned and an error code and error message are stored in the ** destination [database connection] D. -** ^The error code and message for the failed call to sqlite3_backup_init() -** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or -** [sqlite3_errmsg16()] functions. -** ^A successful call to sqlite3_backup_init() returns a pointer to an -** [sqlite3_backup] object. -** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and -** sqlite3_backup_finish() functions to perform the specified backup +** ^The error code and message for the failed call to tdsqlite3_backup_init() +** can be retrieved using the [tdsqlite3_errcode()], [tdsqlite3_errmsg()], and/or +** [tdsqlite3_errmsg16()] functions. +** ^A successful call to tdsqlite3_backup_init() returns a pointer to an +** [tdsqlite3_backup] object. +** ^The [tdsqlite3_backup] object may be used with the tdsqlite3_backup_step() and +** tdsqlite3_backup_finish() functions to perform the specified backup ** operation. ** -** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b> +** [[tdsqlite3_backup_step()]] <b>tdsqlite3_backup_step()</b> ** -** ^Function sqlite3_backup_step(B,N) will copy up to N pages between -** the source and destination databases specified by [sqlite3_backup] object B. +** ^Function tdsqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [tdsqlite3_backup] object B. ** ^If N is negative, all remaining source pages are copied. -** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** ^If tdsqlite3_backup_step(B,N) successfully copies N pages and there ** are still more pages to be copied, then the function returns [SQLITE_OK]. -** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** ^If tdsqlite3_backup_step(B,N) successfully finishes copying all pages ** from source to destination, then it returns [SQLITE_DONE]. -** ^If an error occurs while running sqlite3_backup_step(B,N), +** ^If an error occurs while running tdsqlite3_backup_step(B,N), ** then an [error code] is returned. ^As well as [SQLITE_OK] and -** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_DONE], a call to tdsqlite3_backup_step() may return [SQLITE_READONLY], ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. ** -** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +** ^(The tdsqlite3_backup_step() might return [SQLITE_READONLY] if ** <ol> ** <li> the destination database was opened read-only, or ** <li> the destination database is using write-ahead-log journaling @@ -7655,76 +9542,76 @@ typedef struct sqlite3_backup sqlite3_backup; ** destination and source page sizes differ. ** </ol>)^ ** -** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then -** the [sqlite3_busy_handler | busy-handler function] +** ^If tdsqlite3_backup_step() cannot obtain a required file-system lock, then +** the [tdsqlite3_busy_handler | busy-handler function] ** is invoked (if one is specified). ^If the ** busy-handler returns non-zero before the lock is available, then ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to -** sqlite3_backup_step() can be retried later. ^If the source +** tdsqlite3_backup_step() can be retried later. ^If the source ** [database connection] -** is being used to write to the source database when sqlite3_backup_step() +** is being used to write to the source database when tdsqlite3_backup_step() ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this -** case the call to sqlite3_backup_step() can be retried later on. ^(If +** case the call to tdsqlite3_backup_step() can be retried later on. ^(If ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or ** [SQLITE_READONLY] is returned, then -** there is no point in retrying the call to sqlite3_backup_step(). These +** there is no point in retrying the call to tdsqlite3_backup_step(). These ** errors are considered fatal.)^ The application must accept ** that the backup operation has failed and pass the backup operation handle -** to the sqlite3_backup_finish() to release associated resources. +** to the tdsqlite3_backup_finish() to release associated resources. ** -** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** ^The first call to tdsqlite3_backup_step() obtains an exclusive lock ** on the destination file. ^The exclusive lock is not released until either -** sqlite3_backup_finish() is called or the backup operation is complete -** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to -** sqlite3_backup_step() obtains a [shared lock] on the source database that -** lasts for the duration of the sqlite3_backup_step() call. +** tdsqlite3_backup_finish() is called or the backup operation is complete +** and tdsqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** tdsqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the tdsqlite3_backup_step() call. ** ^Because the source database is not locked between calls to -** sqlite3_backup_step(), the source database may be modified mid-way +** tdsqlite3_backup_step(), the source database may be modified mid-way ** through the backup process. ^If the source database is modified by an ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be automatically -** restarted by the next call to sqlite3_backup_step(). ^If the source +** restarted by the next call to tdsqlite3_backup_step(). ^If the source ** database is modified by the using the same database connection as is used ** by the backup operation, then the backup database is automatically ** updated at the same time. ** -** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b> +** [[tdsqlite3_backup_finish()]] <b>tdsqlite3_backup_finish()</b> ** -** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** When tdsqlite3_backup_step() has returned [SQLITE_DONE], or when the ** application wishes to abandon the backup operation, the application -** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). -** ^The sqlite3_backup_finish() interfaces releases all -** resources associated with the [sqlite3_backup] object. -** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** should destroy the [tdsqlite3_backup] by passing it to tdsqlite3_backup_finish(). +** ^The tdsqlite3_backup_finish() interfaces releases all +** resources associated with the [tdsqlite3_backup] object. +** ^If tdsqlite3_backup_step() has not yet returned [SQLITE_DONE], then any ** active write-transaction on the destination database is rolled back. -** The [sqlite3_backup] object is invalid -** and may not be used following a call to sqlite3_backup_finish(). +** The [tdsqlite3_backup] object is invalid +** and may not be used following a call to tdsqlite3_backup_finish(). ** -** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no -** sqlite3_backup_step() errors occurred, regardless or whether or not -** sqlite3_backup_step() completed. +** ^The value returned by tdsqlite3_backup_finish is [SQLITE_OK] if no +** tdsqlite3_backup_step() errors occurred, regardless or whether or not +** tdsqlite3_backup_step() completed. ** ^If an out-of-memory condition or IO error occurred during any prior -** sqlite3_backup_step() call on the same [sqlite3_backup] object, then -** sqlite3_backup_finish() returns the corresponding [error code]. +** tdsqlite3_backup_step() call on the same [tdsqlite3_backup] object, then +** tdsqlite3_backup_finish() returns the corresponding [error code]. ** -** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from tdsqlite3_backup_step() ** is not a permanent error and does not affect the return value of -** sqlite3_backup_finish(). +** tdsqlite3_backup_finish(). ** -** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]] -** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b> +** [[tdsqlite3_backup_remaining()]] [[tdsqlite3_backup_pagecount()]] +** <b>tdsqlite3_backup_remaining() and tdsqlite3_backup_pagecount()</b> ** -** ^The sqlite3_backup_remaining() routine returns the number of pages still -** to be backed up at the conclusion of the most recent sqlite3_backup_step(). -** ^The sqlite3_backup_pagecount() routine returns the total number of pages +** ^The tdsqlite3_backup_remaining() routine returns the number of pages still +** to be backed up at the conclusion of the most recent tdsqlite3_backup_step(). +** ^The tdsqlite3_backup_pagecount() routine returns the total number of pages ** in the source database at the conclusion of the most recent -** sqlite3_backup_step(). +** tdsqlite3_backup_step(). ** ^(The values returned by these functions are only updated by -** sqlite3_backup_step(). If the source database is modified in a way that +** tdsqlite3_backup_step(). If the source database is modified in a way that ** changes the size of the source database or the number of pages remaining, -** those changes are not reflected in the output of sqlite3_backup_pagecount() -** and sqlite3_backup_remaining() until after the next -** sqlite3_backup_step().)^ +** those changes are not reflected in the output of tdsqlite3_backup_pagecount() +** and tdsqlite3_backup_remaining() until after the next +** tdsqlite3_backup_step().)^ ** ** <b>Concurrent Usage of Database Handles</b> ** @@ -7736,8 +9623,8 @@ typedef struct sqlite3_backup sqlite3_backup; ** ** However, the application must guarantee that the destination ** [database connection] is not passed to any other API (by any thread) after -** sqlite3_backup_init() is called and before the corresponding call to -** sqlite3_backup_finish(). SQLite does not currently check to see +** tdsqlite3_backup_init() is called and before the corresponding call to +** tdsqlite3_backup_finish(). SQLite does not currently check to see ** if the application incorrectly accesses the destination [database connection] ** and so no error code is reported, but the operations may malfunction ** nevertheless. Use of the destination database connection while a @@ -7748,29 +9635,29 @@ typedef struct sqlite3_backup sqlite3_backup; ** is not accessed while the backup is running. In practice this means ** that the application must guarantee that the disk file being ** backed up to is not accessed by any connection within the process, -** not just the specific connection that was passed to sqlite3_backup_init(). +** not just the specific connection that was passed to tdsqlite3_backup_init(). ** -** The [sqlite3_backup] object itself is partially threadsafe. Multiple -** threads may safely make multiple concurrent calls to sqlite3_backup_step(). -** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** The [tdsqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to tdsqlite3_backup_step(). +** However, the tdsqlite3_backup_remaining() and tdsqlite3_backup_pagecount() ** APIs are not strictly speaking threadsafe. If they are invoked at the -** same time as another thread is invoking sqlite3_backup_step() it is +** same time as another thread is invoking tdsqlite3_backup_step() it is ** possible that they return invalid values. */ -SQLITE_API sqlite3_backup *sqlite3_backup_init( - sqlite3 *pDest, /* Destination database handle */ +SQLITE_API tdsqlite3_backup *tdsqlite3_backup_init( + tdsqlite3 *pDest, /* Destination database handle */ const char *zDestName, /* Destination database name */ - sqlite3 *pSource, /* Source database handle */ + tdsqlite3 *pSource, /* Source database handle */ const char *zSourceName /* Source database name */ ); -SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); -SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); -SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); -SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); +SQLITE_API int tdsqlite3_backup_step(tdsqlite3_backup *p, int nPage); +SQLITE_API int tdsqlite3_backup_finish(tdsqlite3_backup *p); +SQLITE_API int tdsqlite3_backup_remaining(tdsqlite3_backup *p); +SQLITE_API int tdsqlite3_backup_pagecount(tdsqlite3_backup *p); /* ** CAPI3REF: Unlock Notification -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^When running in shared-cache mode, a database operation may fail with ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or @@ -7791,17 +9678,17 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** identity of the database connection (the blocking connection) that ** has locked the required resource is stored internally. ^After an ** application receives an SQLITE_LOCKED error, it may call the -** sqlite3_unlock_notify() method with the blocked connection handle as +** tdsqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked ** when the blocking connections current transaction is concluded. ^The -** callback is invoked from within the [sqlite3_step] or [sqlite3_close] -** call that concludes the blocking connections transaction. +** callback is invoked from within the [tdsqlite3_step] or [tdsqlite3_close] +** call that concludes the blocking connection's transaction. ** -** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** ^(If tdsqlite3_unlock_notify() is called in a multi-threaded application, ** there is a chance that the blocking connection will have already -** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** concluded its transaction by the time tdsqlite3_unlock_notify() is invoked. ** If this happens, then the specified callback is invoked immediately, -** from within the call to sqlite3_unlock_notify().)^ +** from within the call to tdsqlite3_unlock_notify().)^ ** ** ^If the blocked connection is attempting to obtain a write-lock on a ** shared-cache table, and more than one other connection currently holds @@ -7809,19 +9696,19 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** the other connections to use as the blocking connection. ** ** ^(There may be at most one unlock-notify callback registered by a -** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection. If tdsqlite3_unlock_notify() is called when the ** blocked connection already has a registered unlock-notify callback, -** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** then the new callback replaces the old.)^ ^If tdsqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing ** unlock-notify callback is canceled. ^The blocked connections ** unlock-notify callback may also be canceled by closing the blocked -** connection using [sqlite3_close()]. +** connection using [tdsqlite3_close()]. ** ** The unlock-notify callback is not reentrant. If an application invokes -** any sqlite3_xxx API functions from within an unlock-notify callback, a +** any tdsqlite3_xxx API functions from within an unlock-notify callback, a ** crash or deadlock may be the result. ** -** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** ^Unless deadlock is detected (see below), tdsqlite3_unlock_notify() always ** returns SQLITE_OK. ** ** <b>Callback Invocation Details</b> @@ -7833,7 +9720,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** an unlock-notify callback is a pointer to an array of void* pointers, ** and the second is the number of entries in the array. ** -** When a blocking connections transaction is concluded, there may be +** When a blocking connection's transaction is concluded, there may be ** more than one blocked connection that has registered for an unlock-notify ** callback. ^If two or more such blocked connections have specified the ** same callback function, then instead of invoking the callback function @@ -7852,8 +9739,8 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** Y is waiting on connection X's transaction, then neither connection ** will proceed and the system may remain deadlocked indefinitely. ** -** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock -** detection. ^If a given call to sqlite3_unlock_notify() would put the +** To avoid this scenario, the tdsqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to tdsqlite3_unlock_notify() would put the ** system in a deadlocked state, then SQLITE_LOCKED is returned and no ** unlock-notify callback is registered. The system is said to be in ** a deadlocked state if connection A has registered for an unlock-notify @@ -7867,24 +9754,24 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** ** <b>The "DROP TABLE" Exception</b> ** -** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost -** always appropriate to call sqlite3_unlock_notify(). There is however, +** When a call to [tdsqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call tdsqlite3_unlock_notify(). There is however, ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, ** SQLite checks if there are any currently executing SELECT statements ** that belong to the same connection. If there are, SQLITE_LOCKED is ** returned. In this case there is no "blocking connection", so invoking -** sqlite3_unlock_notify() results in the unlock-notify callback being +** tdsqlite3_unlock_notify() results in the unlock-notify callback being ** invoked immediately. If the application then re-attempts the "DROP TABLE" ** or "DROP INDEX" query, an infinite loop might be the result. ** ** One way around this problem is to check the extended error code returned -** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** by an tdsqlite3_step() call. ^(If there is a blocking connection, then the ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in ** the special "DROP TABLE/INDEX" case, the extended error code is just ** SQLITE_LOCKED.)^ */ -SQLITE_API int sqlite3_unlock_notify( - sqlite3 *pBlocked, /* Waiting connection */ +SQLITE_API int tdsqlite3_unlock_notify( + tdsqlite3 *pBlocked, /* Waiting connection */ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ void *pNotifyArg /* Argument to pass to xNotify */ ); @@ -7893,82 +9780,82 @@ SQLITE_API int sqlite3_unlock_notify( /* ** CAPI3REF: String Comparison ** -** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications +** ^The [tdsqlite3_stricmp()] and [tdsqlite3_strnicmp()] APIs allow applications ** and extensions to compare the contents of two buffers containing UTF-8 ** strings in a case-independent fashion, using the same definition of "case ** independence" that SQLite uses internally when comparing identifiers. */ -SQLITE_API int sqlite3_stricmp(const char *, const char *); -SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); +SQLITE_API int tdsqlite3_stricmp(const char *, const char *); +SQLITE_API int tdsqlite3_strnicmp(const char *, const char *, int); /* ** CAPI3REF: String Globbing * -** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if +** ^The [tdsqlite3_strglob(P,X)] interface returns zero if and only if ** string X matches the [GLOB] pattern P. ** ^The definition of [GLOB] pattern matching used in -** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the -** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function +** [tdsqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the +** SQL dialect understood by SQLite. ^The [tdsqlite3_strglob(P,X)] function ** is case sensitive. ** ** Note that this routine returns zero on a match and non-zero if the strings -** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +** do not match, the same as [tdsqlite3_stricmp()] and [tdsqlite3_strnicmp()]. ** -** See also: [sqlite3_strlike()]. +** See also: [tdsqlite3_strlike()]. */ -SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); +SQLITE_API int tdsqlite3_strglob(const char *zGlob, const char *zStr); /* ** CAPI3REF: String LIKE Matching * -** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if +** ^The [tdsqlite3_strlike(P,X,E)] interface returns zero if and only if ** string X matches the [LIKE] pattern P with escape character E. ** ^The definition of [LIKE] pattern matching used in -** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" +** [tdsqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without -** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0. -** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case +** the ESCAPE clause, set the E parameter of [tdsqlite3_strlike(P,X,E)] to 0. +** ^As with the LIKE operator, the [tdsqlite3_strlike(P,X,E)] function is case ** insensitive - equivalent upper and lower case ASCII characters match ** one another. ** -** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though +** ^The [tdsqlite3_strlike(P,X,E)] function matches Unicode characters, though ** only ASCII characters are case folded. ** ** Note that this routine returns zero on a match and non-zero if the strings -** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +** do not match, the same as [tdsqlite3_stricmp()] and [tdsqlite3_strnicmp()]. ** -** See also: [sqlite3_strglob()]. +** See also: [tdsqlite3_strglob()]. */ -SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); +SQLITE_API int tdsqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); /* ** CAPI3REF: Error Logging Interface ** -** ^The [sqlite3_log()] interface writes a message into the [error log] -** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^The [tdsqlite3_log()] interface writes a message into the [error log] +** established by the [SQLITE_CONFIG_LOG] option to [tdsqlite3_config()]. ** ^If logging is enabled, the zFormat string and subsequent arguments are -** used with [sqlite3_snprintf()] to generate the final output string. +** used with [tdsqlite3_snprintf()] to generate the final output string. ** -** The sqlite3_log() interface is intended for use by extensions such as +** The tdsqlite3_log() interface is intended for use by extensions such as ** virtual tables, collating functions, and SQL functions. While there is -** nothing to prevent an application from calling sqlite3_log(), doing so +** nothing to prevent an application from calling tdsqlite3_log(), doing so ** is considered bad form. ** ** The zFormat string must not be NULL. ** -** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** To avoid deadlocks and other threading problems, the tdsqlite3_log() routine ** will not use dynamically allocated memory. The log message is stored in ** a fixed-length buffer on the stack. If the log message is longer than ** a few hundred characters, it will be truncated to the length of the ** buffer. */ -SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); +SQLITE_API void tdsqlite3_log(int iErrCode, const char *zFormat, ...); /* ** CAPI3REF: Write-Ahead Log Commit Hook -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The [sqlite3_wal_hook()] function is used to register a callback that +** ^The [tdsqlite3_wal_hook()] function is used to register a callback that ** is invoked each time data is committed to a database in wal mode. ** ** ^(The callback is invoked by SQLite after the commit has taken place and @@ -7976,7 +9863,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); ** may read, write or [checkpoint] the database as required. ** ** ^The first parameter passed to the callback function when it is invoked -** is a copy of the third parameter passed to sqlite3_wal_hook() when +** is a copy of the third parameter passed to tdsqlite3_wal_hook() when ** registering the callback. ^The second is a copy of the database handle. ** ^The third parameter is the name of the database that was written to - ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter @@ -7992,24 +9879,24 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); ** are undefined. ** ** A single database handle may have at most a single write-ahead log callback -** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** registered at one time. ^Calling [tdsqlite3_wal_hook()] replaces any ** previously registered write-ahead log callback. ^Note that the -** [sqlite3_wal_autocheckpoint()] interface and the -** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will -** overwrite any prior [sqlite3_wal_hook()] settings. +** [tdsqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [tdsqlite3_wal_hook()] and will +** overwrite any prior [tdsqlite3_wal_hook()] settings. */ -SQLITE_API void *sqlite3_wal_hook( - sqlite3*, - int(*)(void *,sqlite3*,const char*,int), +SQLITE_API void *tdsqlite3_wal_hook( + tdsqlite3*, + int(*)(void *,tdsqlite3*,const char*,int), void* ); /* ** CAPI3REF: Configure an auto-checkpoint -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around -** [sqlite3_wal_hook()] that causes any database on [database connection] D +** ^The [tdsqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [tdsqlite3_wal_hook()] that causes any database on [database connection] D ** to automatically [checkpoint] ** after committing a transaction if there are N or ** more frames in the [write-ahead log] file. ^Passing zero or @@ -8017,15 +9904,15 @@ SQLITE_API void *sqlite3_wal_hook( ** checkpoints entirely. ** ** ^The callback registered by this function replaces any existing callback -** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback -** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** registered using [tdsqlite3_wal_hook()]. ^Likewise, registering a callback +** using [tdsqlite3_wal_hook()] disables the automatic checkpoint mechanism ** configured by this function. ** ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface ** from SQL. ** ** ^Checkpoints initiated by this mechanism are -** [sqlite3_wal_checkpoint_v2|PASSIVE]. +** [tdsqlite3_wal_checkpoint_v2|PASSIVE]. ** ** ^Every new [database connection] defaults to having the auto-checkpoint ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] @@ -8033,35 +9920,35 @@ SQLITE_API void *sqlite3_wal_hook( ** is only necessary if the default setting is found to be suboptimal ** for a particular application. */ -SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); +SQLITE_API int tdsqlite3_wal_autocheckpoint(tdsqlite3 *db, int N); /* ** CAPI3REF: Checkpoint a database -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to -** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ +** ^(The tdsqlite3_wal_checkpoint(D,X) is equivalent to +** [tdsqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ ** -** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the +** In brief, tdsqlite3_wal_checkpoint(D,X) causes the content in the ** [write-ahead log] for database X on [database connection] D to be ** transferred into the database file and for the write-ahead log to ** be reset. See the [checkpointing] documentation for addition ** information. ** ** This interface used to be the only way to cause a checkpoint to -** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()] +** occur. But then the newer and more powerful [tdsqlite3_wal_checkpoint_v2()] ** interface was added. This interface is retained for backwards ** compatibility and as a convenience for applications that need to manually ** start a callback but which do not need the full power (and corresponding -** complication) of [sqlite3_wal_checkpoint_v2()]. +** complication) of [tdsqlite3_wal_checkpoint_v2()]. */ -SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); +SQLITE_API int tdsqlite3_wal_checkpoint(tdsqlite3 *db, const char *zDb); /* ** CAPI3REF: Checkpoint a database -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint +** ^(The tdsqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint ** operation on database X of [database connection] D in mode M. Status ** information is written back into integers pointed to by L and C.)^ ** ^(The M parameter must be a valid [checkpoint mode]:)^ @@ -8077,7 +9964,7 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); ** ** <dt>SQLITE_CHECKPOINT_FULL<dd> ** ^This mode blocks (it invokes the -** [sqlite3_busy_handler|busy-handler callback]) until there is no +** [tdsqlite3_busy_handler|busy-handler callback]) until there is no ** database writer and all readers are reading from the most recent database ** snapshot. ^It then checkpoints all frames in the log file and syncs the ** database file. ^This mode blocks new database writers while it is pending, @@ -8142,15 +10029,15 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); ** attached database, SQLITE_ERROR is returned to the caller. ** ** ^Unless it returns SQLITE_MISUSE, -** the sqlite3_wal_checkpoint_v2() interface +** the tdsqlite3_wal_checkpoint_v2() interface ** sets the error information that is queried by -** [sqlite3_errcode()] and [sqlite3_errmsg()]. +** [tdsqlite3_errcode()] and [tdsqlite3_errmsg()]. ** ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface ** from SQL. */ -SQLITE_API int sqlite3_wal_checkpoint_v2( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_wal_checkpoint_v2( + tdsqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ @@ -8162,8 +10049,8 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( ** KEYWORDS: {checkpoint mode} ** ** These constants define all valid values for the "checkpoint mode" passed -** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface. -** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the +** as the third parameter to the [tdsqlite3_wal_checkpoint_v2()] interface. +** See the [tdsqlite3_wal_checkpoint_v2()] documentation for details on the ** meaning of each of these checkpoint modes. */ #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ @@ -8181,25 +10068,32 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( ** If this interface is invoked outside the context of an xConnect or ** xCreate virtual table method then the behavior is undefined. ** -** At present, there is only one option that may be configured using -** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options -** may be added in the future. +** In the call tdsqlite3_vtab_config(D,C,...) the D parameter is the +** [database connection] in which the virtual table is being created and +** which is passed in as the first argument to the [xConnect] or [xCreate] +** method that is invoking tdsqlite3_vtab_config(). The C parameter is one +** of the [virtual table configuration options]. The presence and meaning +** of parameters after C depend on which [virtual table configuration option] +** is used. */ -SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); +SQLITE_API int tdsqlite3_vtab_config(tdsqlite3*, int op, ...); /* ** CAPI3REF: Virtual Table Configuration Options +** KEYWORDS: {virtual table configuration options} +** KEYWORDS: {virtual table configuration option} ** ** These macros define the various options to the -** [sqlite3_vtab_config()] interface that [virtual table] implementations +** [tdsqlite3_vtab_config()] interface that [virtual table] implementations ** can use to customize and optimize their behavior. ** ** <dl> -** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT +** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]] +** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt> ** <dd>Calls of the form -** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, +** [tdsqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, ** where X is an integer. If X is zero, then the [virtual table] whose -** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not +** [xCreate] or [xConnect] method invoked [tdsqlite3_vtab_config()] does not ** support constraints. In this configuration (which is the default) if ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been @@ -8218,15 +10112,37 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); ** ** Virtual table implementations that are required to handle OR REPLACE ** must do so within the [xUpdate] method. If a call to the -** [sqlite3_vtab_on_conflict()] function indicates that the current ON +** [tdsqlite3_vtab_on_conflict()] function indicates that the current ON ** CONFLICT policy is REPLACE, the virtual table implementation should ** silently replace the appropriate rows within the xUpdate callback and ** return SQLITE_OK. Or, if this is not possible, it may return ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT ** constraint handling. +** </dd> +** +** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt> +** <dd>Calls of the form +** [tdsqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the +** the [xConnect] or [xCreate] methods of a [virtual table] implmentation +** prohibits that virtual table from being used from within triggers and +** views. +** </dd> +** +** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt> +** <dd>Calls of the form +** [tdsqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the +** the [xConnect] or [xCreate] methods of a [virtual table] implmentation +** identify that virtual table as being safe to use from within triggers +** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the +** virtual table can do no serious harm even if it is controlled by a +** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS +** flag unless absolutely necessary. +** </dd> ** </dl> */ #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 +#define SQLITE_VTAB_INNOCUOUS 2 +#define SQLITE_VTAB_DIRECTONLY 3 /* ** CAPI3REF: Determine The Virtual Table Conflict Policy @@ -8238,22 +10154,56 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); ** of the SQL statement that triggered the call to the [xUpdate] method of the ** [virtual table]. */ -SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); +SQLITE_API int tdsqlite3_vtab_on_conflict(tdsqlite3 *); + +/* +** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE +** +** If the tdsqlite3_vtab_nochange(X) routine is called within the [xColumn] +** method of a [virtual table], then it returns true if and only if the +** column is being fetched as part of an UPDATE operation during which the +** column value will not change. Applications might use this to substitute +** a return value that is less expensive to compute and that the corresponding +** [xUpdate] method understands as a "no-change" value. +** +** If the [xColumn] method calls tdsqlite3_vtab_nochange() and finds that +** the column is not changed by the UPDATE statement, then the xColumn +** method can optionally return without setting a result, without calling +** any of the [tdsqlite3_result_int|tdsqlite3_result_xxxxx() interfaces]. +** In that case, [tdsqlite3_value_nochange(X)] will return true for the +** same column in the [xUpdate] method. +*/ +SQLITE_API int tdsqlite3_vtab_nochange(tdsqlite3_context*); + +/* +** CAPI3REF: Determine The Collation For a Virtual Table Constraint +** +** This function may only be called from within a call to the [xBestIndex] +** method of a [virtual table]. +** +** The first argument must be the tdsqlite3_index_info object that is the +** first parameter to the xBestIndex() method. The second argument must be +** an index into the aConstraint[] array belonging to the tdsqlite3_index_info +** structure passed to xBestIndex. This function returns a pointer to a buffer +** containing the name of the collation sequence for the corresponding +** constraint. +*/ +SQLITE_API SQLITE_EXPERIMENTAL const char *tdsqlite3_vtab_collation(tdsqlite3_index_info*,int); /* ** CAPI3REF: Conflict resolution modes ** KEYWORDS: {conflict resolution mode} ** -** These constants are returned by [sqlite3_vtab_on_conflict()] to +** These constants are returned by [tdsqlite3_vtab_on_conflict()] to ** inform a [virtual table] implementation what the [ON CONFLICT] mode ** is for the SQL statement being evaluated. ** ** Note that the [SQLITE_IGNORE] constant is also used as a potential -** return value from the [sqlite3_set_authorizer()] callback and that +** return value from the [tdsqlite3_set_authorizer()] callback and that ** [SQLITE_ABORT] is also a [result code]. */ #define SQLITE_ROLLBACK 1 -/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ +/* #define SQLITE_IGNORE 2 // Also used by tdsqlite3_authorizer() callback */ #define SQLITE_FAIL 3 /* #define SQLITE_ABORT 4 // Also an error code */ #define SQLITE_REPLACE 5 @@ -8263,8 +10213,8 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); ** KEYWORDS: {scanstatus options} ** ** The following constants can be used for the T parameter to the -** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a -** different metric for sqlite3_stmt_scanstatus() to return. +** [tdsqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a +** different metric for tdsqlite3_stmt_scanstatus() to return. ** ** When the value returned to V is a string, space to hold that string is ** managed by the prepared statement S and will be automatically freed when @@ -8272,15 +10222,15 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); ** ** <dl> ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt> -** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be +** <dd>^The [tdsqlite3_int64] variable pointed to by the V parameter will be ** set to the total number of times that the X-th loop has run.</dd> ** ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt> -** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set +** <dd>^The [tdsqlite3_int64] variable pointed to by the V parameter will be set ** to the total number of rows examined by all iterations of the X-th loop.</dd> ** ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt> -** <dd>^The "double" variable pointed to by the T parameter will be set to the +** <dd>^The "double" variable pointed to by the V parameter will be set to the ** query planner's estimate for the average number of rows output from each ** iteration of the X-th loop. If the query planner's estimates was accurate, ** then this value will approximate the quotient NVISIT/NLOOP and the @@ -8288,17 +10238,17 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); ** be the NLOOP value for the current loop. ** ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt> -** <dd>^The "const char *" variable pointed to by the T parameter will be set +** <dd>^The "const char *" variable pointed to by the V parameter will be set ** to a zero-terminated UTF-8 string containing the name of the index or table ** used for the X-th loop. ** ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt> -** <dd>^The "const char *" variable pointed to by the T parameter will be set +** <dd>^The "const char *" variable pointed to by the V parameter will be set ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] ** description for the X-th loop. ** ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt> -** <dd>^The "int" variable pointed to by the T parameter will be set to the +** <dd>^The "int" variable pointed to by the V parameter will be set to the ** "select-id" for the X-th loop. The select-id identifies which query or ** subquery the loop is part of. The main query has a select-id of zero. ** The select-id is the same value as is output in the first column @@ -8314,7 +10264,7 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); /* ** CAPI3REF: Prepared Statement Scan Status -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** This interface returns information about the predicted and measured ** performance for pStmt. Advanced applications can use this @@ -8341,10 +10291,10 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); ** as if the loop did not exist - it returns non-zero and leave the variable ** that pOut points to unchanged. ** -** See also: [sqlite3_stmt_scanstatus_reset()] +** See also: [tdsqlite3_stmt_scanstatus_reset()] */ -SQLITE_API int sqlite3_stmt_scanstatus( - sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ +SQLITE_API int tdsqlite3_stmt_scanstatus( + tdsqlite3_stmt *pStmt, /* Prepared statement for which info desired */ int idx, /* Index of loop to report on */ int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ void *pOut /* Result written here */ @@ -8352,24 +10302,24 @@ SQLITE_API int sqlite3_stmt_scanstatus( /* ** CAPI3REF: Zero Scan-Status Counters -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^Zero all [sqlite3_stmt_scanstatus()] related event counters. +** ^Zero all [tdsqlite3_stmt_scanstatus()] related event counters. ** ** This API is only available if the library is built with pre-processor ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined. */ -SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); +SQLITE_API void tdsqlite3_stmt_scanstatus_reset(tdsqlite3_stmt*); /* ** CAPI3REF: Flush caches to disk mid-transaction ** ** ^If a write-transaction is open on [database connection] D when the -** [sqlite3_db_cacheflush(D)] interface invoked, any dirty +** [tdsqlite3_db_cacheflush(D)] interface invoked, any dirty ** pages in the pager-cache that are not currently in use are written out ** to disk. A dirty page may be in use if a database cursor created by an ** active SQL statement is reading from it, or if it is page 1 of a database -** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)] +** file (page 1 is always "in use"). ^The [tdsqlite3_db_cacheflush(D)] ** interface flushes caches for all schemas - "main", "temp", and ** any [attached] databases. ** @@ -8386,12 +10336,12 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); ** example an IO error or out-of-memory condition), then processing is ** abandoned and an SQLite [error code] is returned to the caller immediately. ** -** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK. +** ^Otherwise, if no error occurs, [tdsqlite3_db_cacheflush()] returns SQLITE_OK. ** ** ^This function does not set the database handle error code or message -** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions. +** returned by the [tdsqlite3_errcode()] and [tdsqlite3_errmsg()] functions. */ -SQLITE_API int sqlite3_db_cacheflush(sqlite3*); +SQLITE_API int tdsqlite3_db_cacheflush(tdsqlite3*); /* ** CAPI3REF: The pre-update hook. @@ -8399,20 +10349,20 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); ** ^These interfaces are only available if SQLite is compiled using the ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option. ** -** ^The [sqlite3_preupdate_hook()] interface registers a callback function +** ^The [tdsqlite3_preupdate_hook()] interface registers a callback function ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation -** on a [rowid table]. +** on a database table. ** ^At most one preupdate hook may be registered at a time on a single -** [database connection]; each call to [sqlite3_preupdate_hook()] overrides +** [database connection]; each call to [tdsqlite3_preupdate_hook()] overrides ** the previous setting. -** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()] +** ^The preupdate hook is disabled by invoking [tdsqlite3_preupdate_hook()] ** with a NULL pointer as the second parameter. -** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as +** ^The third parameter to [tdsqlite3_preupdate_hook()] is passed through as ** the first parameter to callbacks. ** -** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate -** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID] -** tables. +** ^The preupdate hook only fires for changes to real database tables; the +** preupdate hook is not invoked for changes to [virtual tables] or to +** system tables like sqlite_master or sqlite_stat1. ** ** ^The second parameter to the preupdate callback is a pointer to ** the [database connection] that registered the preupdate hook. @@ -8426,15 +10376,19 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); ** databases.)^ ** ^The fifth parameter to the preupdate callback is the name of the ** table that is being modified. -** ^The sixth parameter to the preupdate callback is the initial [rowid] of the -** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is -** undefined for SQLITE_INSERT changes. -** ^The seventh parameter to the preupdate callback is the final [rowid] of -** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is -** undefined for SQLITE_DELETE changes. -** -** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()], -** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces +** +** For an UPDATE or DELETE operation on a [rowid table], the sixth +** parameter passed to the preupdate callback is the initial [rowid] of the +** row being modified or deleted. For an INSERT operation on a rowid table, +** or any operation on a WITHOUT ROWID table, the value of the sixth +** parameter is undefined. For an INSERT or UPDATE on a rowid table the +** seventh parameter is the final rowid value of the row being inserted +** or updated. The value of the seventh parameter passed to the callback +** function is not defined for operations on WITHOUT ROWID tables, or for +** INSERT operations on rowid tables. +** +** The [tdsqlite3_preupdate_old()], [tdsqlite3_preupdate_new()], +** [tdsqlite3_preupdate_count()], and [tdsqlite3_preupdate_depth()] interfaces ** provide additional information about a preupdate event. These routines ** may only be called from within a preupdate callback. Invoking any of ** these routines from outside of a preupdate callback or with a @@ -8442,52 +10396,54 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); ** to the preupdate callback results in undefined and probably undesirable ** behavior. ** -** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns +** ^The [tdsqlite3_preupdate_count(D)] interface returns the number of columns ** in the row that is being inserted, updated, or deleted. ** -** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to -** a [protected sqlite3_value] that contains the value of the Nth column of +** ^The [tdsqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to +** a [protected tdsqlite3_value] that contains the value of the Nth column of ** the table row before it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the -** behavior is undefined. The [sqlite3_value] that P points to +** behavior is undefined. The [tdsqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** -** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to -** a [protected sqlite3_value] that contains the value of the Nth column of +** ^The [tdsqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to +** a [protected tdsqlite3_value] that contains the value of the Nth column of ** the table row after it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the -** behavior is undefined. The [sqlite3_value] that P points to +** behavior is undefined. The [tdsqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** -** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate +** ^The [tdsqlite3_preupdate_depth(D)] interface returns 0 if the preupdate ** callback was invoked as a result of a direct insert, update, or delete ** operation; or 1 for inserts, updates, or deletes invoked by top-level ** triggers; or 2 for changes resulting from triggers called by top-level ** triggers; and so forth. ** -** See also: [sqlite3_update_hook()] +** See also: [tdsqlite3_update_hook()] */ -SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_preupdate_hook( - sqlite3 *db, +#if defined(SQLITE_ENABLE_PREUPDATE_HOOK) +SQLITE_API void *tdsqlite3_preupdate_hook( + tdsqlite3 *db, void(*xPreUpdate)( void *pCtx, /* Copy of third arg to preupdate_hook() */ - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ int op, /* SQLITE_UPDATE, DELETE or INSERT */ char const *zDb, /* Database name */ char const *zName, /* Table name */ - sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ - sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ + tdsqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ + tdsqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ ), void* ); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_count(sqlite3 *); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_depth(sqlite3 *); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); +SQLITE_API int tdsqlite3_preupdate_old(tdsqlite3 *, int, tdsqlite3_value **); +SQLITE_API int tdsqlite3_preupdate_count(tdsqlite3 *); +SQLITE_API int tdsqlite3_preupdate_depth(tdsqlite3 *); +SQLITE_API int tdsqlite3_preupdate_new(tdsqlite3 *, int, tdsqlite3_value **); +#endif /* ** CAPI3REF: Low-level system error code @@ -8495,16 +10451,15 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_new(sqlite3 *, int, sqlite3 ** ^Attempt to return the underlying operating system error code or error ** number that caused the most recent I/O error or failure to open a file. ** The return value is OS-dependent. For example, on unix systems, after -** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be +** [tdsqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be ** called to get back the underlying "errno" that caused the problem, such ** as ENOSPC, EAUTH, EISDIR, and so forth. */ -SQLITE_API int sqlite3_system_errno(sqlite3*); +SQLITE_API int tdsqlite3_system_errno(tdsqlite3*); /* ** CAPI3REF: Database Snapshot -** KEYWORDS: {snapshot} -** EXPERIMENTAL +** KEYWORDS: {snapshot} {tdsqlite3_snapshot} ** ** An instance of the snapshot object records the state of a [WAL mode] ** database for some specific point in history. @@ -8517,65 +10472,96 @@ SQLITE_API int sqlite3_system_errno(sqlite3*); ** Subsequent changes to the database from other connections are not seen ** by the reader until a new read transaction is started. ** -** The sqlite3_snapshot object records state information about an historical +** The tdsqlite3_snapshot object records state information about an historical ** version of the database file so that it is possible to later open a new read ** transaction that sees that historical version of the database rather than ** the most recent version. -** -** The constructor for this object is [sqlite3_snapshot_get()]. The -** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer -** to an historical snapshot (if possible). The destructor for -** sqlite3_snapshot objects is [sqlite3_snapshot_free()]. */ -typedef struct sqlite3_snapshot sqlite3_snapshot; +typedef struct tdsqlite3_snapshot { + unsigned char hidden[48]; +} tdsqlite3_snapshot; /* ** CAPI3REF: Record A Database Snapshot -** EXPERIMENTAL +** CONSTRUCTOR: tdsqlite3_snapshot ** -** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a -** new [sqlite3_snapshot] object that records the current state of +** ^The [tdsqlite3_snapshot_get(D,S,P)] interface attempts to make a +** new [tdsqlite3_snapshot] object that records the current state of ** schema S in database connection D. ^On success, the -** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly -** created [sqlite3_snapshot] object into *P and returns SQLITE_OK. -** ^If schema S of [database connection] D is not a [WAL mode] database -** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)] -** leaves the *P value unchanged and returns an appropriate [error code]. -** -** The [sqlite3_snapshot] object returned from a successful call to -** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()] +** [tdsqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly +** created [tdsqlite3_snapshot] object into *P and returns SQLITE_OK. +** If there is not already a read-transaction open on schema S when +** this function is called, one is opened automatically. +** +** The following must be true for this function to succeed. If any of +** the following statements are false when tdsqlite3_snapshot_get() is +** called, SQLITE_ERROR is returned. The final value of *P is undefined +** in this case. +** +** <ul> +** <li> The database handle must not be in [autocommit mode]. +** +** <li> Schema S of [database connection] D must be a [WAL mode] database. +** +** <li> There must not be a write transaction open on schema S of database +** connection D. +** +** <li> One or more transactions must have been written to the current wal +** file since it was created on disk (by any connection). This means +** that a snapshot cannot be taken on a wal mode database with no wal +** file immediately after it is first opened. At least one transaction +** must be written to it first. +** </ul> +** +** This function may also return SQLITE_NOMEM. If it is called with the +** database handle in autocommit mode but fails for some other reason, +** whether or not a read transaction is opened on schema S is undefined. +** +** The [tdsqlite3_snapshot] object returned from a successful call to +** [tdsqlite3_snapshot_get()] must be freed using [tdsqlite3_snapshot_free()] ** to avoid a memory leak. ** -** The [sqlite3_snapshot_get()] interface is only available when the -** SQLITE_ENABLE_SNAPSHOT compile-time option is used. +** The [tdsqlite3_snapshot_get()] interface is only available when the +** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( - sqlite3 *db, +SQLITE_API SQLITE_EXPERIMENTAL int tdsqlite3_snapshot_get( + tdsqlite3 *db, const char *zSchema, - sqlite3_snapshot **ppSnapshot + tdsqlite3_snapshot **ppSnapshot ); /* ** CAPI3REF: Start a read transaction on an historical snapshot -** EXPERIMENTAL -** -** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a -** read transaction for schema S of -** [database connection] D such that the read transaction -** refers to historical [snapshot] P, rather than the most -** recent change to the database. -** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success -** or an appropriate [error code] if it fails. -** -** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be -** the first operation following the [BEGIN] that takes the schema S -** out of [autocommit mode]. -** ^In other words, schema S must not currently be in -** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the -** database connection D must be out of [autocommit mode]. -** ^A [snapshot] will fail to open if it has been overwritten by a -** [checkpoint]. -** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the +** METHOD: tdsqlite3_snapshot +** +** ^The [tdsqlite3_snapshot_open(D,S,P)] interface either starts a new read +** transaction or upgrades an existing one for schema S of +** [database connection] D such that the read transaction refers to +** historical [snapshot] P, rather than the most recent change to the +** database. ^The [tdsqlite3_snapshot_open()] interface returns SQLITE_OK +** on success or an appropriate [error code] if it fails. +** +** ^In order to succeed, the database connection must not be in +** [autocommit mode] when [tdsqlite3_snapshot_open(D,S,P)] is called. If there +** is already a read transaction open on schema S, then the database handle +** must have no active statements (SELECT statements that have been passed +** to tdsqlite3_step() but not tdsqlite3_reset() or tdsqlite3_finalize()). +** SQLITE_ERROR is returned if either of these conditions is violated, or +** if schema S does not exist, or if the snapshot object is invalid. +** +** ^A call to tdsqlite3_snapshot_open() will fail to open if the specified +** snapshot has been overwritten by a [checkpoint]. In this case +** SQLITE_ERROR_SNAPSHOT is returned. +** +** If there is already a read transaction open when this function is +** invoked, then the same read transaction remains open (on the same +** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT +** is returned. If another error code - for example SQLITE_PROTOCOL or an +** SQLITE_IOERR error code - is returned, then the final state of the +** read transaction is undefined. If SQLITE_OK is returned, then the +** read transaction is now open on database snapshot P. +** +** ^(A call to [tdsqlite3_snapshot_open(D,S,P)] will fail if the ** database connection D does not know that the database file for ** schema S is in [WAL mode]. A database connection might not know ** that the database file is in [WAL mode] if there has been no prior @@ -8584,40 +10570,40 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( ** (Hint: Run "[PRAGMA application_id]" against a newly opened ** database connection in order to make it ready to use snapshots.) ** -** The [sqlite3_snapshot_open()] interface is only available when the -** SQLITE_ENABLE_SNAPSHOT compile-time option is used. +** The [tdsqlite3_snapshot_open()] interface is only available when the +** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( - sqlite3 *db, +SQLITE_API SQLITE_EXPERIMENTAL int tdsqlite3_snapshot_open( + tdsqlite3 *db, const char *zSchema, - sqlite3_snapshot *pSnapshot + tdsqlite3_snapshot *pSnapshot ); /* ** CAPI3REF: Destroy a snapshot -** EXPERIMENTAL +** DESTRUCTOR: tdsqlite3_snapshot ** -** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P. -** The application must eventually free every [sqlite3_snapshot] object +** ^The [tdsqlite3_snapshot_free(P)] interface destroys [tdsqlite3_snapshot] P. +** The application must eventually free every [tdsqlite3_snapshot] object ** using this routine to avoid a memory leak. ** -** The [sqlite3_snapshot_free()] interface is only available when the -** SQLITE_ENABLE_SNAPSHOT compile-time option is used. +** The [tdsqlite3_snapshot_free()] interface is only available when the +** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); +SQLITE_API SQLITE_EXPERIMENTAL void tdsqlite3_snapshot_free(tdsqlite3_snapshot*); /* ** CAPI3REF: Compare the ages of two snapshot handles. -** EXPERIMENTAL +** METHOD: tdsqlite3_snapshot ** -** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages +** The tdsqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages ** of two valid snapshot handles. ** ** If the two snapshot handles are not associated with the same database ** file, the result of the comparison is undefined. ** ** Additionally, the result of the comparison is only valid if both of the -** snapshot handles were obtained by calling sqlite3_snapshot_get() since the +** snapshot handles were obtained by calling tdsqlite3_snapshot_get() since the ** last time the wal file was deleted. The wal file is deleted when the ** database is changed back to rollback mode or when the number of database ** clients drops to zero. If either snapshot handle was obtained before the @@ -8627,13 +10613,163 @@ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); ** Otherwise, this API returns a negative value if P1 refers to an older ** snapshot than P2, zero if the two handles refer to the same database ** snapshot, and a positive value if P1 is a newer snapshot than P2. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_SNAPSHOT] option. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int tdsqlite3_snapshot_cmp( + tdsqlite3_snapshot *p1, + tdsqlite3_snapshot *p2 +); + +/* +** CAPI3REF: Recover snapshots from a wal file +** METHOD: tdsqlite3_snapshot +** +** If a [WAL file] remains on disk after all database connections close +** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control] +** or because the last process to have the database opened exited without +** calling [tdsqlite3_close()]) and a new connection is subsequently opened +** on that database and [WAL file], the [tdsqlite3_snapshot_open()] interface +** will only be able to open the last transaction added to the WAL file +** even though the WAL file contains other valid transactions. +** +** This function attempts to scan the WAL file associated with database zDb +** of database handle db and make all valid snapshots available to +** tdsqlite3_snapshot_open(). It is an error if there is already a read +** transaction open on the database, or if the database is not a WAL mode +** database. +** +** SQLITE_OK is returned if successful, or an SQLite error code otherwise. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_SNAPSHOT] option. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int tdsqlite3_snapshot_recover(tdsqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Serialize a database +** +** The tdsqlite3_serialize(D,S,P,F) interface returns a pointer to memory +** that is a serialization of the S database on [database connection] D. +** If P is not a NULL pointer, then the size of the database in bytes +** is written into *P. +** +** For an ordinary on-disk database file, the serialization is just a +** copy of the disk file. For an in-memory database or a "TEMP" database, +** the serialization is the same sequence of bytes which would be written +** to disk if that database where backed up to disk. +** +** The usual case is that tdsqlite3_serialize() copies the serialization of +** the database into memory obtained from [tdsqlite3_malloc64()] and returns +** a pointer to that memory. The caller is responsible for freeing the +** returned value to avoid a memory leak. However, if the F argument +** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations +** are made, and the tdsqlite3_serialize() function will return a pointer +** to the contiguous memory representation of the database that SQLite +** is currently using for that database, or NULL if the no such contiguous +** memory representation of the database exists. A contiguous memory +** representation of the database will usually only exist if there has +** been a prior call to [tdsqlite3_deserialize(D,S,...)] with the same +** values of D and S. +** The size of the database is written into *P even if the +** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy +** of the database exists. +** +** A call to tdsqlite3_serialize(D,S,P,F) might return NULL even if the +** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory +** allocation error occurs. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_DESERIALIZE] option. +*/ +SQLITE_API unsigned char *tdsqlite3_serialize( + tdsqlite3 *db, /* The database connection */ + const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */ + tdsqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */ + unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */ +); + +/* +** CAPI3REF: Flags for tdsqlite3_serialize +** +** Zero or more of the following constants can be OR-ed together for +** the F argument to [tdsqlite3_serialize(D,S,P,F)]. +** +** SQLITE_SERIALIZE_NOCOPY means that [tdsqlite3_serialize()] will return +** a pointer to contiguous in-memory database that it is currently using, +** without making a copy of the database. If SQLite is not currently using +** a contiguous in-memory database, then this option causes +** [tdsqlite3_serialize()] to return a NULL pointer. SQLite will only be +** using a contiguous in-memory database if it has been initialized by a +** prior call to [tdsqlite3_deserialize()]. +*/ +#define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */ + +/* +** CAPI3REF: Deserialize a database +** +** The tdsqlite3_deserialize(D,S,P,N,M,F) interface causes the +** [database connection] D to disconnect from database S and then +** reopen S as an in-memory database based on the serialization contained +** in P. The serialized database P is N bytes in size. M is the size of +** the buffer P, which might be larger than N. If M is larger than N, and +** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is +** permitted to add content to the in-memory database as long as the total +** size does not exceed M bytes. +** +** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will +** invoke tdsqlite3_free() on the serialization buffer when the database +** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then +** SQLite will try to increase the buffer size using tdsqlite3_realloc64() +** if writes on the database cause it to grow larger than M bytes. +** +** The tdsqlite3_deserialize() interface will fail with SQLITE_BUSY if the +** database is currently in a read transaction or is involved in a backup +** operation. +** +** If tdsqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the +** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then +** [tdsqlite3_free()] is invoked on argument P prior to returning. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_DESERIALIZE] option. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( - sqlite3_snapshot *p1, - sqlite3_snapshot *p2 +SQLITE_API int tdsqlite3_deserialize( + tdsqlite3 *db, /* The database connection */ + const char *zSchema, /* Which DB to reopen with the deserialization */ + unsigned char *pData, /* The serialized database content */ + tdsqlite3_int64 szDb, /* Number bytes in the deserialization */ + tdsqlite3_int64 szBuf, /* Total size of buffer pData[] */ + unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */ ); /* +** CAPI3REF: Flags for tdsqlite3_deserialize() +** +** The following are allowed values for 6th argument (the F argument) to +** the [tdsqlite3_deserialize(D,S,P,N,M,F)] interface. +** +** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization +** in the P argument is held in memory obtained from [tdsqlite3_malloc64()] +** and that SQLite should take ownership of this memory and automatically +** free it when it has finished using it. Without this flag, the caller +** is responsible for freeing any dynamically allocated memory. +** +** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to +** grow the size of the database using calls to [tdsqlite3_realloc64()]. This +** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used. +** Without this flag, the deserialized database cannot increase in size beyond +** the number of bytes specified by the M parameter. +** +** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database +** should be treated as read-only. +*/ +#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call tdsqlite3_free() on close */ +#define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using tdsqlite3_realloc64() */ +#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */ + +/* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ @@ -8646,7 +10782,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( #endif #endif /* SQLITE3_H */ -/******** Begin file sqlite3rtree.h *********/ +/******** Begin file tdsqlite3rtree.h *********/ /* ** 2010 August 30 ** @@ -8668,16 +10804,16 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( extern "C" { #endif -typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; -typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; +typedef struct tdsqlite3_rtree_geometry tdsqlite3_rtree_geometry; +typedef struct tdsqlite3_rtree_query_info tdsqlite3_rtree_query_info; /* The double-precision datatype used by RTree depends on the ** SQLITE_RTREE_INT_ONLY compile-time option. */ #ifdef SQLITE_RTREE_INT_ONLY - typedef sqlite3_int64 sqlite3_rtree_dbl; + typedef tdsqlite3_int64 tdsqlite3_rtree_dbl; #else - typedef double sqlite3_rtree_dbl; + typedef double tdsqlite3_rtree_dbl; #endif /* @@ -8686,10 +10822,10 @@ typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; ** ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...) */ -SQLITE_API int sqlite3_rtree_geometry_callback( - sqlite3 *db, +SQLITE_API int tdsqlite3_rtree_geometry_callback( + tdsqlite3 *db, const char *zGeom, - int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*), + int (*xGeom)(tdsqlite3_rtree_geometry*, int, tdsqlite3_rtree_dbl*,int*), void *pContext ); @@ -8698,10 +10834,10 @@ SQLITE_API int sqlite3_rtree_geometry_callback( ** A pointer to a structure of the following type is passed as the first ** argument to callbacks registered using rtree_geometry_callback(). */ -struct sqlite3_rtree_geometry { +struct tdsqlite3_rtree_geometry { void *pContext; /* Copy of pContext passed to s_r_g_c() */ int nParam; /* Size of array aParam[] */ - sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ + tdsqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ void *pUser; /* Callback implementation user data */ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ }; @@ -8712,10 +10848,10 @@ struct sqlite3_rtree_geometry { ** ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...) */ -SQLITE_API int sqlite3_rtree_query_callback( - sqlite3 *db, +SQLITE_API int tdsqlite3_rtree_query_callback( + tdsqlite3 *db, const char *zQueryFunc, - int (*xQueryFunc)(sqlite3_rtree_query_info*), + int (*xQueryFunc)(tdsqlite3_rtree_query_info*), void *pContext, void (*xDestructor)(void*) ); @@ -8724,34 +10860,34 @@ SQLITE_API int sqlite3_rtree_query_callback( /* ** A pointer to a structure of the following type is passed as the ** argument to scored geometry callback registered using -** sqlite3_rtree_query_callback(). +** tdsqlite3_rtree_query_callback(). ** ** Note that the first 5 fields of this structure are identical to -** sqlite3_rtree_geometry. This structure is a subclass of -** sqlite3_rtree_geometry. +** tdsqlite3_rtree_geometry. This structure is a subclass of +** tdsqlite3_rtree_geometry. */ -struct sqlite3_rtree_query_info { +struct tdsqlite3_rtree_query_info { void *pContext; /* pContext from when function registered */ int nParam; /* Number of function parameters */ - sqlite3_rtree_dbl *aParam; /* value of function parameters */ + tdsqlite3_rtree_dbl *aParam; /* value of function parameters */ void *pUser; /* callback can use this, if desired */ void (*xDelUser)(void*); /* function to free pUser */ - sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ + tdsqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ unsigned int *anQueue; /* Number of pending entries in the queue */ int nCoord; /* Number of coordinates */ int iLevel; /* Level of current node or entry */ int mxLevel; /* The largest iLevel value in the tree */ - sqlite3_int64 iRowid; /* Rowid for current entry */ - sqlite3_rtree_dbl rParentScore; /* Score of parent node */ + tdsqlite3_int64 iRowid; /* Rowid for current entry */ + tdsqlite3_rtree_dbl rParentScore; /* Score of parent node */ int eParentWithin; /* Visibility of parent node */ - int eWithin; /* OUT: Visiblity */ - sqlite3_rtree_dbl rScore; /* OUT: Write the score here */ + int eWithin; /* OUT: Visibility */ + tdsqlite3_rtree_dbl rScore; /* OUT: Write the score here */ /* The following fields are only available in 3.8.11 and later */ - sqlite3_value **apSqlParam; /* Original SQL values of parameters */ + tdsqlite3_value **apSqlParam; /* Original SQL values of parameters */ }; /* -** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin. +** Allowed values for tdsqlite3_rtree_query.eWithin and .eParentWithin. */ #define NOT_WITHIN 0 /* Object completely outside of query region */ #define PARTLY_WITHIN 1 /* Object partially overlaps query region */ @@ -8764,8 +10900,8 @@ struct sqlite3_rtree_query_info { #endif /* ifndef _SQLITE3RTREE_H_ */ -/******** End of sqlite3rtree.h *********/ -/******** Begin file sqlite3session.h *********/ +/******** End of tdsqlite3rtree.h *********/ +/******** Begin file tdsqlite3session.h *********/ #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) #define __SQLITESESSION_H_ 1 @@ -8780,16 +10916,23 @@ extern "C" { /* ** CAPI3REF: Session Object Handle +** +** An instance of this object is a [session] that can be used to +** record changes to a database. */ -typedef struct sqlite3_session sqlite3_session; +typedef struct tdsqlite3_session tdsqlite3_session; /* ** CAPI3REF: Changeset Iterator Handle +** +** An instance of this object acts as a cursor for iterating +** over the elements of a [changeset] or [patchset]. */ -typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; +typedef struct tdsqlite3_changeset_iter tdsqlite3_changeset_iter; /* ** CAPI3REF: Create A New Session Object +** CONSTRUCTOR: tdsqlite3_session ** ** Create a new session object attached to database handle db. If successful, ** a pointer to the new object is written to *ppSession and SQLITE_OK is @@ -8800,13 +10943,13 @@ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; ** database handle. ** ** Session objects created using this function should be deleted using the -** [sqlite3session_delete()] function before the database handle that they +** [tdsqlite3session_delete()] function before the database handle that they ** are attached to is itself closed. If the database handle is closed before ** the session object is deleted, then the results of calling any session -** module function, including [sqlite3session_delete()] on the session object +** module function, including [tdsqlite3session_delete()] on the session object ** are undefined. ** -** Because the session module uses the [sqlite3_preupdate_hook()] API, it +** Because the session module uses the [tdsqlite3_preupdate_hook()] API, it ** is not possible for an application to register a pre-update hook on a ** database handle that has one or more session objects attached. Nor is ** it possible to create a session object attached to a database handle for @@ -8818,34 +10961,36 @@ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; ** attached database. It is not an error if database zDb is not attached ** to the database when the session object is created. */ -int sqlite3session_create( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3session_create( + tdsqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (e.g. "main") */ - sqlite3_session **ppSession /* OUT: New session object */ + tdsqlite3_session **ppSession /* OUT: New session object */ ); /* ** CAPI3REF: Delete A Session Object +** DESTRUCTOR: tdsqlite3_session ** ** Delete a session object previously allocated using -** [sqlite3session_create()]. Once a session object has been deleted, the +** [tdsqlite3session_create()]. Once a session object has been deleted, the ** results of attempting to use pSession with any other session module ** function are undefined. ** ** Session objects must be deleted before the database handle to which they ** are attached is closed. Refer to the documentation for -** [sqlite3session_create()] for details. +** [tdsqlite3session_create()] for details. */ -void sqlite3session_delete(sqlite3_session *pSession); +SQLITE_API void tdsqlite3session_delete(tdsqlite3_session *pSession); /* ** CAPI3REF: Enable Or Disable A Session Object +** METHOD: tdsqlite3_session ** ** Enable or disable the recording of changes by a session object. When ** enabled, a session object records changes made to the database. When ** disabled - it does not. A newly created session object is enabled. -** Refer to the documentation for [sqlite3session_changeset()] for further +** Refer to the documentation for [tdsqlite3session_changeset()] for further ** details regarding how enabling and disabling a session object affects ** the eventual changesets. ** @@ -8856,10 +11001,11 @@ void sqlite3session_delete(sqlite3_session *pSession); ** The return value indicates the final state of the session object: 0 if ** the session is disabled, or 1 if it is enabled. */ -int sqlite3session_enable(sqlite3_session *pSession, int bEnable); +SQLITE_API int tdsqlite3session_enable(tdsqlite3_session *pSession, int bEnable); /* ** CAPI3REF: Set Or Clear the Indirect Change Flag +** METHOD: tdsqlite3_session ** ** Each change recorded by a session object is marked as either direct or ** indirect. A change is marked as indirect if either: @@ -8885,15 +11031,16 @@ int sqlite3session_enable(sqlite3_session *pSession, int bEnable); ** The return value indicates the final state of the indirect flag: 0 if ** it is clear, or 1 if it is set. */ -int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); +SQLITE_API int tdsqlite3session_indirect(tdsqlite3_session *pSession, int bIndirect); /* ** CAPI3REF: Attach A Table To A Session Object +** METHOD: tdsqlite3_session ** ** If argument zTab is not NULL, then it is the name of a table to attach ** to the session object passed as the first argument. All subsequent changes ** made to the table while the session object is enabled will be recorded. See -** documentation for [sqlite3session_changeset()] for further details. +** documentation for [tdsqlite3session_changeset()] for further details. ** ** Or, if argument zTab is NULL, then changes are recorded for all tables ** in the database. If additional tables are added to the database (by @@ -8914,23 +11061,53 @@ int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); ** ** SQLITE_OK is returned if the call completes without error. Or, if an error ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. -*/ -int sqlite3session_attach( - sqlite3_session *pSession, /* Session object */ +** +** <h3>Special sqlite_stat1 Handling</h3> +** +** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to +** some of the rules above. In SQLite, the schema of sqlite_stat1 is: +** <pre> +** CREATE TABLE sqlite_stat1(tbl,idx,stat) +** </pre> +** +** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are +** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes +** are recorded for rows for which (idx IS NULL) is true. However, for such +** rows a zero-length blob (SQL value X'') is stored in the changeset or +** patchset instead of a NULL value. This allows such changesets to be +** manipulated by legacy implementations of tdsqlite3changeset_invert(), +** concat() and similar. +** +** The tdsqlite3changeset_apply() function automatically converts the +** zero-length blob back to a NULL value when updating the sqlite_stat1 +** table. However, if the application calls tdsqlite3changeset_new(), +** tdsqlite3changeset_old() or tdsqlite3changeset_conflict on a changeset +** iterator directly (including on a changeset iterator passed to a +** conflict-handler callback) then the X'' value is returned. The application +** must translate X'' to NULL itself if required. +** +** Legacy (older than 3.22.0) versions of the sessions module cannot capture +** changes made to the sqlite_stat1 table. Legacy versions of the +** tdsqlite3changeset_apply() function silently ignore any modifications to the +** sqlite_stat1 table that are part of a changeset or patchset. +*/ +SQLITE_API int tdsqlite3session_attach( + tdsqlite3_session *pSession, /* Session object */ const char *zTab /* Table name */ ); /* ** CAPI3REF: Set a table filter on a Session Object. +** METHOD: tdsqlite3_session ** ** The second argument (xFilter) is the "filter callback". For changes to rows ** in tables that are not attached to the Session object, the filter is called ** to determine whether changes to the table's rows should be tracked or not. -** If xFilter returns 0, changes is not tracked. Note that once a table is +** If xFilter returns 0, changes are not tracked. Note that once a table is ** attached, xFilter will not be called again. */ -void sqlite3session_table_filter( - sqlite3_session *pSession, /* Session object */ +SQLITE_API void tdsqlite3session_table_filter( + tdsqlite3_session *pSession, /* Session object */ int(*xFilter)( void *pCtx, /* Copy of third arg to _filter_table() */ const char *zTab /* Table name */ @@ -8940,6 +11117,7 @@ void sqlite3session_table_filter( /* ** CAPI3REF: Generate A Changeset From A Session Object +** METHOD: tdsqlite3_session ** ** Obtain a changeset containing changes to the tables attached to the ** session object passed as the first argument. If successful, @@ -8969,8 +11147,8 @@ void sqlite3session_table_filter( ** DELETE change only. ** ** The contents of a changeset may be traversed using an iterator created -** using the [sqlite3changeset_start()] API. A changeset may be applied to -** a database with a compatible schema using the [sqlite3changeset_apply()] +** using the [tdsqlite3changeset_start()] API. A changeset may be applied to +** a database with a compatible schema using the [tdsqlite3changeset_apply()] ** API. ** ** Within a changeset generated by this function, all changes related to a @@ -8978,12 +11156,12 @@ void sqlite3session_table_filter( ** a changeset or when applying a changeset to a database, all changes related ** to a single table are processed before moving on to the next table. Tables ** are sorted in the same order in which they were attached (or auto-attached) -** to the sqlite3_session object. The order in which the changes related to +** to the tdsqlite3_session object. The order in which the changes related to ** a single table are stored is undefined. ** ** Following a successful call to this function, it is the responsibility of ** the caller to eventually free the buffer that *ppChangeset points to using -** [sqlite3_free()]. +** [tdsqlite3_free()]. ** ** <h3>Changeset Generation</h3> ** @@ -9031,7 +11209,7 @@ void sqlite3session_table_filter( ** active, the resulting changeset will contain an UPDATE change instead of ** a DELETE and an INSERT. ** -** When a session object is disabled (see the [sqlite3session_enable()] API), +** When a session object is disabled (see the [tdsqlite3session_enable()] API), ** it does not accumulate records when rows are inserted, updated or deleted. ** This may appear to have some counter-intuitive effects if a single row ** is written to more than once during a session. For example, if a row @@ -9042,18 +11220,19 @@ void sqlite3session_table_filter( ** another field of the same row is updated while the session is enabled, the ** resulting changeset will contain an UPDATE change that updates both fields. */ -int sqlite3session_changeset( - sqlite3_session *pSession, /* Session object */ +SQLITE_API int tdsqlite3session_changeset( + tdsqlite3_session *pSession, /* Session object */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ); /* -** CAPI3REF: Load The Difference Between Tables Into A Session +** CAPI3REF: Load The Difference Between Tables Into A Session +** METHOD: tdsqlite3_session ** ** If it is not already attached to the session object passed as the first ** argument, this function attaches table zTbl in the same manner as the -** [sqlite3session_attach()] function. If zTbl does not exist, or if it +** [tdsqlite3session_attach()] function. If zTbl does not exist, or if it ** does not have a primary key, this function is a no-op (but does not return ** an error). ** @@ -9086,25 +11265,26 @@ int sqlite3session_changeset( ** the from-table, a DELETE record is added to the session object. ** ** <li> For each row (primary key) that exists in both tables, but features -** different in each, an UPDATE record is added to the session. +** different non-PK values in each, an UPDATE record is added to the +** session. ** </ul> ** ** To clarify, if this function is called and then a changeset constructed -** using [sqlite3session_changeset()], then after applying that changeset to +** using [tdsqlite3session_changeset()], then after applying that changeset to ** database zFrom the contents of the two compatible tables would be ** identical. ** ** It an error if database zFrom does not exist or does not contain the ** required compatible table. ** -** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite +** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to free this buffer using -** sqlite3_free(). +** tdsqlite3_free(). */ -int sqlite3session_diff( - sqlite3_session *pSession, +SQLITE_API int tdsqlite3session_diff( + tdsqlite3_session *pSession, const char *zFromDb, const char *zTbl, char **pzErrMsg @@ -9113,6 +11293,7 @@ int sqlite3session_diff( /* ** CAPI3REF: Generate A Patchset From A Session Object +** METHOD: tdsqlite3_session ** ** The differences between a patchset and a changeset are that: ** @@ -9124,25 +11305,25 @@ int sqlite3session_diff( ** </ul> ** ** A patchset blob may be used with up to date versions of all -** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), +** tdsqlite3changeset_xxx API functions except for tdsqlite3changeset_invert(), ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly, ** attempting to use a patchset blob with old versions of the -** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. +** tdsqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. ** ** Because the non-primary key "old.*" fields are omitted, no ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset -** is passed to the sqlite3changeset_apply() API. Other conflict types work +** is passed to the tdsqlite3changeset_apply() API. Other conflict types work ** in the same way as for changesets. ** ** Changes within a patchset are ordered in the same way as for changesets -** generated by the sqlite3session_changeset() function (i.e. all changes for +** generated by the tdsqlite3session_changeset() function (i.e. all changes for ** a single table are grouped together, tables appear in the order in which ** they were attached to the session object). */ -int sqlite3session_patchset( - sqlite3_session *pSession, /* Session object */ - int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ - void **ppPatchset /* OUT: Buffer containing changeset */ +SQLITE_API int tdsqlite3session_patchset( + tdsqlite3_session *pSession, /* Session object */ + int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */ + void **ppPatchset /* OUT: Buffer containing patchset */ ); /* @@ -9153,17 +11334,18 @@ int sqlite3session_patchset( ** more changes have been recorded, return zero. ** ** Even if this function returns zero, it is possible that calling -** [sqlite3session_changeset()] on the session handle may still return a +** [tdsqlite3session_changeset()] on the session handle may still return a ** changeset that contains no changes. This can happen when a row in ** an attached table is modified and then later on the original values ** are restored. However, if this function returns non-zero, then it is -** guaranteed that a call to sqlite3session_changeset() will return a +** guaranteed that a call to tdsqlite3session_changeset() will return a ** changeset containing zero changes. */ -int sqlite3session_isempty(sqlite3_session *pSession); +SQLITE_API int tdsqlite3session_isempty(tdsqlite3_session *pSession); /* ** CAPI3REF: Create An Iterator To Traverse A Changeset +** CONSTRUCTOR: tdsqlite3_changeset_iter ** ** Create an iterator used to iterate through the contents of a changeset. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK @@ -9174,49 +11356,76 @@ int sqlite3session_isempty(sqlite3_session *pSession); ** iterator created by this function: ** ** <ul> -** <li> [sqlite3changeset_next()] -** <li> [sqlite3changeset_op()] -** <li> [sqlite3changeset_new()] -** <li> [sqlite3changeset_old()] +** <li> [tdsqlite3changeset_next()] +** <li> [tdsqlite3changeset_op()] +** <li> [tdsqlite3changeset_new()] +** <li> [tdsqlite3changeset_old()] ** </ul> ** ** It is the responsibility of the caller to eventually destroy the iterator -** by passing it to [sqlite3changeset_finalize()]. The buffer containing the +** by passing it to [tdsqlite3changeset_finalize()]. The buffer containing the ** changeset (pChangeset) must remain valid until after the iterator is ** destroyed. ** ** Assuming the changeset blob was created by one of the -** [sqlite3session_changeset()], [sqlite3changeset_concat()] or -** [sqlite3changeset_invert()] functions, all changes within the changeset +** [tdsqlite3session_changeset()], [tdsqlite3changeset_concat()] or +** [tdsqlite3changeset_invert()] functions, all changes within the changeset ** that apply to a single table are grouped together. This means that when ** an application iterates through a changeset using an iterator created by ** this function, all changes that relate to a single table are visited ** consecutively. There is no chance that the iterator will visit a change ** the applies to table X, then one for table Y, and then later on visit ** another change for table X. +** +** The behavior of tdsqlite3changeset_start_v2() and its streaming equivalent +** may be modified by passing a combination of +** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter. +** +** Note that the tdsqlite3changeset_start_v2() API is still <b>experimental</b> +** and therefore subject to change. */ -int sqlite3changeset_start( - sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ +SQLITE_API int tdsqlite3changeset_start( + tdsqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ int nChangeset, /* Size of changeset blob in bytes */ void *pChangeset /* Pointer to blob containing changeset */ ); +SQLITE_API int tdsqlite3changeset_start_v2( + tdsqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ + int nChangeset, /* Size of changeset blob in bytes */ + void *pChangeset, /* Pointer to blob containing changeset */ + int flags /* SESSION_CHANGESETSTART_* flags */ +); + +/* +** CAPI3REF: Flags for tdsqlite3changeset_start_v2 +** +** The following flags may passed via the 4th parameter to +** [tdsqlite3changeset_start_v2] and [tdsqlite3changeset_start_v2_strm]: +** +** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd> +** Invert the changeset while iterating through it. This is equivalent to +** inverting a changeset using tdsqlite3changeset_invert() before applying it. +** It is an error to specify this flag with a patchset. +*/ +#define SQLITE_CHANGESETSTART_INVERT 0x0002 /* ** CAPI3REF: Advance A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** -** This function may only be used with iterators created by function -** [sqlite3changeset_start()]. If it is called on an iterator passed to -** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE +** This function may only be used with iterators created by the function +** [tdsqlite3changeset_start()]. If it is called on an iterator passed to +** a conflict-handler callback by [tdsqlite3changeset_apply()], SQLITE_MISUSE ** is returned and the call has no effect. ** -** Immediately after an iterator is created by sqlite3changeset_start(), it +** Immediately after an iterator is created by tdsqlite3changeset_start(), it ** does not point to any change in the changeset. Assuming the changeset ** is not empty, the first call to this function advances the iterator to ** point to the first change in the changeset. Each subsequent call advances ** the iterator to point to the next change in the changeset (if any). If ** no error occurs and the iterator points to a valid change after a call -** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. +** to tdsqlite3changeset_next() has advanced it, SQLITE_ROW is returned. ** Otherwise, if all changes in the changeset have already been visited, ** SQLITE_DONE is returned. ** @@ -9224,26 +11433,27 @@ int sqlite3changeset_start( ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or ** SQLITE_NOMEM. */ -int sqlite3changeset_next(sqlite3_changeset_iter *pIter); +SQLITE_API int tdsqlite3changeset_next(tdsqlite3_changeset_iter *pIter); /* ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** The pIter argument passed to this function may either be an iterator -** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator -** created by [sqlite3changeset_start()]. In the latter case, the most recent -** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this +** passed to a conflict-handler by [tdsqlite3changeset_apply()], or an iterator +** created by [tdsqlite3changeset_start()]. In the latter case, the most recent +** call to [tdsqlite3changeset_next()] must have returned [SQLITE_ROW]. If this ** is not the case, this function returns [SQLITE_MISUSE]. ** ** If argument pzTab is not NULL, then *pzTab is set to point to a ** nul-terminated utf-8 encoded string containing the name of the table ** affected by the current change. The buffer remains valid until either -** sqlite3changeset_next() is called on the iterator or until the +** tdsqlite3changeset_next() is called on the iterator or until the ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is ** set to the number of columns in the table affected by the change. If -** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change +** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change ** is an indirect change, or false (0) otherwise. See the documentation for -** [sqlite3session_indirect()] for a description of direct and indirect +** [tdsqlite3session_indirect()] for a description of direct and indirect ** changes. Finally, if pOp is not NULL, then *pOp is set to one of ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the ** type of change that the iterator currently points to. @@ -9252,8 +11462,8 @@ int sqlite3changeset_next(sqlite3_changeset_iter *pIter); ** SQLite error code is returned. The values of the output variables may not ** be trusted in this case. */ -int sqlite3changeset_op( - sqlite3_changeset_iter *pIter, /* Iterator object */ +SQLITE_API int tdsqlite3changeset_op( + tdsqlite3_changeset_iter *pIter, /* Iterator object */ const char **pzTab, /* OUT: Pointer to table name */ int *pnCol, /* OUT: Number of columns in table */ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ @@ -9262,6 +11472,7 @@ int sqlite3changeset_op( /* ** CAPI3REF: Obtain The Primary Key Definition Of A Table +** METHOD: tdsqlite3_changeset_iter ** ** For each modified table, a changeset includes the following: ** @@ -9285,19 +11496,20 @@ int sqlite3changeset_op( ** SQLITE_OK is returned and the output variables populated as described ** above. */ -int sqlite3changeset_pk( - sqlite3_changeset_iter *pIter, /* Iterator object */ +SQLITE_API int tdsqlite3changeset_pk( + tdsqlite3_changeset_iter *pIter, /* Iterator object */ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ int *pnCol /* OUT: Number of entries in output array */ ); /* ** CAPI3REF: Obtain old.* Values From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** The pIter argument passed to this function may either be an iterator -** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator -** created by [sqlite3changeset_start()]. In the latter case, the most recent -** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. +** passed to a conflict-handler by [tdsqlite3changeset_apply()], or an iterator +** created by [tdsqlite3changeset_start()]. In the latter case, the most recent +** call to [tdsqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. @@ -9307,7 +11519,7 @@ int sqlite3changeset_pk( ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected -** sqlite3_value object containing the iVal'th value from the vector of +** tdsqlite3_value object containing the iVal'th value from the vector of ** original row values stored as part of the UPDATE or DELETE change and ** returns SQLITE_OK. The name of the function comes from the fact that this ** is similar to the "old.*" columns available to update or delete triggers. @@ -9315,19 +11527,20 @@ int sqlite3changeset_pk( ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ -int sqlite3changeset_old( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_old( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ - sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ + tdsqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain new.* Values From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** The pIter argument passed to this function may either be an iterator -** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator -** created by [sqlite3changeset_start()]. In the latter case, the most recent -** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. +** passed to a conflict-handler by [tdsqlite3changeset_apply()], or an iterator +** created by [tdsqlite3changeset_start()]. In the latter case, the most recent +** call to [tdsqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. @@ -9337,7 +11550,7 @@ int sqlite3changeset_old( ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected -** sqlite3_value object containing the iVal'th value from the vector of +** tdsqlite3_value object containing the iVal'th value from the vector of ** new row values stored as part of the UPDATE or INSERT change and ** returns SQLITE_OK. If the change is an UPDATE and does not include ** a new value for the requested column, *ppValue is set to NULL and @@ -9348,17 +11561,18 @@ int sqlite3changeset_old( ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ -int sqlite3changeset_new( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_new( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ - sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ + tdsqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** This function should only be used with iterator objects passed to a -** conflict-handler callback by [sqlite3changeset_apply()] with either +** conflict-handler callback by [tdsqlite3changeset_apply()] with either ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue ** is set to NULL. @@ -9368,21 +11582,22 @@ int sqlite3changeset_new( ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected -** sqlite3_value object containing the iVal'th value from the +** tdsqlite3_value object containing the iVal'th value from the ** "conflicting row" associated with the current conflict-handler callback ** and returns SQLITE_OK. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ -int sqlite3changeset_conflict( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_conflict( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ - sqlite3_value **ppValue /* OUT: Value from conflicting row */ + tdsqlite3_value **ppValue /* OUT: Value from conflicting row */ ); /* ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations +** METHOD: tdsqlite3_changeset_iter ** ** This function may only be called with an iterator passed to an ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case @@ -9391,40 +11606,43 @@ int sqlite3changeset_conflict( ** ** In all other cases this function returns SQLITE_MISUSE. */ -int sqlite3changeset_fk_conflicts( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_fk_conflicts( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int *pnOut /* OUT: Number of FK violations */ ); /* ** CAPI3REF: Finalize A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** This function is used to finalize an iterator allocated with -** [sqlite3changeset_start()]. +** [tdsqlite3changeset_start()]. ** ** This function should only be called on iterators created using the -** [sqlite3changeset_start()] function. If an application calls this +** [tdsqlite3changeset_start()] function. If an application calls this ** function with an iterator passed to a conflict-handler by -** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the +** [tdsqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the ** call has no effect. ** -** If an error was encountered within a call to an sqlite3changeset_xxx() -** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an -** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding +** If an error was encountered within a call to an tdsqlite3changeset_xxx() +** function (for example an [SQLITE_CORRUPT] in [tdsqlite3changeset_next()] or an +** [SQLITE_NOMEM] in [tdsqlite3changeset_new()]) then an error code corresponding ** to that error is returned by this function. Otherwise, SQLITE_OK is ** returned. This is to allow the following pattern (pseudo-code): ** -** sqlite3changeset_start(); -** while( SQLITE_ROW==sqlite3changeset_next() ){ +** <pre> +** tdsqlite3changeset_start(); +** while( SQLITE_ROW==tdsqlite3changeset_next() ){ ** // Do something with change. ** } -** rc = sqlite3changeset_finalize(); +** rc = tdsqlite3changeset_finalize(); ** if( rc!=SQLITE_OK ){ ** // An error has occurred ** } +** </pre> */ -int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); +SQLITE_API int tdsqlite3changeset_finalize(tdsqlite3_changeset_iter *pIter); /* ** CAPI3REF: Invert A Changeset @@ -9447,14 +11665,14 @@ int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are ** zeroed and an SQLite error code returned. ** -** It is the responsibility of the caller to eventually call sqlite3_free() +** It is the responsibility of the caller to eventually call tdsqlite3_free() ** on the *ppOut pointer to free the buffer allocation following a successful ** call to this function. ** ** WARNING/TODO: This function currently assumes that the input is a valid ** changeset. If it is not, the results are undefined. */ -int sqlite3changeset_invert( +SQLITE_API int tdsqlite3changeset_invert( int nIn, const void *pIn, /* Input changeset */ int *pnOut, void **ppOut /* OUT: Inverse of input */ ); @@ -9467,23 +11685,25 @@ int sqlite3changeset_invert( ** changeset A followed by changeset B. ** ** This function combines the two input changesets using an -** sqlite3_changegroup object. Calling it produces similar results as the +** tdsqlite3_changegroup object. Calling it produces similar results as the ** following code fragment: ** -** sqlite3_changegroup *pGrp; -** rc = sqlite3_changegroup_new(&pGrp); -** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA); -** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB); +** <pre> +** tdsqlite3_changegroup *pGrp; +** rc = tdsqlite3_changegroup_new(&pGrp); +** if( rc==SQLITE_OK ) rc = tdsqlite3changegroup_add(pGrp, nA, pA); +** if( rc==SQLITE_OK ) rc = tdsqlite3changegroup_add(pGrp, nB, pB); ** if( rc==SQLITE_OK ){ -** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); +** rc = tdsqlite3changegroup_output(pGrp, pnOut, ppOut); ** }else{ ** *ppOut = 0; ** *pnOut = 0; ** } +** </pre> ** -** Refer to the sqlite3_changegroup documentation below for details. +** Refer to the tdsqlite3_changegroup documentation below for details. */ -int sqlite3changeset_concat( +SQLITE_API int tdsqlite3changeset_concat( int nA, /* Number of bytes in buffer pA */ void *pA, /* Pointer to buffer containing changeset A */ int nB, /* Number of bytes in buffer pB */ @@ -9495,48 +11715,53 @@ int sqlite3changeset_concat( /* ** CAPI3REF: Changegroup Handle +** +** A changegroup is an object used to combine two or more +** [changesets] or [patchsets] */ -typedef struct sqlite3_changegroup sqlite3_changegroup; +typedef struct tdsqlite3_changegroup tdsqlite3_changegroup; /* ** CAPI3REF: Create A New Changegroup Object +** CONSTRUCTOR: tdsqlite3_changegroup ** -** An sqlite3_changegroup object is used to combine two or more changesets +** An tdsqlite3_changegroup object is used to combine two or more changesets ** (or patchsets) into a single changeset (or patchset). A single changegroup ** object may combine changesets or patchsets, but not both. The output is ** always in the same format as the input. ** ** If successful, this function returns SQLITE_OK and populates (*pp) with -** a pointer to a new sqlite3_changegroup object before returning. The caller +** a pointer to a new tdsqlite3_changegroup object before returning. The caller ** should eventually free the returned object using a call to -** sqlite3changegroup_delete(). If an error occurs, an SQLite error code +** tdsqlite3changegroup_delete(). If an error occurs, an SQLite error code ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL. ** -** The usual usage pattern for an sqlite3_changegroup object is as follows: +** The usual usage pattern for an tdsqlite3_changegroup object is as follows: ** ** <ul> -** <li> It is created using a call to sqlite3changegroup_new(). +** <li> It is created using a call to tdsqlite3changegroup_new(). ** ** <li> Zero or more changesets (or patchsets) are added to the object -** by calling sqlite3changegroup_add(). +** by calling tdsqlite3changegroup_add(). ** ** <li> The result of combining all input changesets together is obtained -** by the application via a call to sqlite3changegroup_output(). +** by the application via a call to tdsqlite3changegroup_output(). ** -** <li> The object is deleted using a call to sqlite3changegroup_delete(). +** <li> The object is deleted using a call to tdsqlite3changegroup_delete(). ** </ul> ** ** Any number of calls to add() and output() may be made between the calls to ** new() and delete(), and in any order. ** -** As well as the regular sqlite3changegroup_add() and -** sqlite3changegroup_output() functions, also available are the streaming -** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm(). +** As well as the regular tdsqlite3changegroup_add() and +** tdsqlite3changegroup_output() functions, also available are the streaming +** versions tdsqlite3changegroup_add_strm() and tdsqlite3changegroup_output_strm(). */ -int sqlite3changegroup_new(sqlite3_changegroup **pp); +SQLITE_API int tdsqlite3changegroup_new(tdsqlite3_changegroup **pp); /* ** CAPI3REF: Add A Changeset To A Changegroup +** METHOD: tdsqlite3_changegroup ** ** Add all changes within the changeset (or patchset) in buffer pData (size ** nData bytes) to the changegroup. @@ -9605,23 +11830,24 @@ int sqlite3changegroup_new(sqlite3_changegroup **pp); ** case, this function fails with SQLITE_SCHEMA. If the input changeset ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is ** returned. Or, if an out-of-memory condition occurs during processing, this -** function returns SQLITE_NOMEM. In all cases, if an error occurs the -** final contents of the changegroup is undefined. +** function returns SQLITE_NOMEM. In all cases, if an error occurs the state +** of the final contents of the changegroup is undefined. ** ** If no error occurs, SQLITE_OK is returned. */ -int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); +SQLITE_API int tdsqlite3changegroup_add(tdsqlite3_changegroup*, int nData, void *pData); /* ** CAPI3REF: Obtain A Composite Changeset From A Changegroup +** METHOD: tdsqlite3_changegroup ** ** Obtain a buffer containing a changeset (or patchset) representing the ** current contents of the changegroup. If the inputs to the changegroup ** were themselves changesets, the output is a changeset. Or, if the ** inputs were patchsets, the output is also a patchset. ** -** As with the output of the sqlite3session_changeset() and -** sqlite3session_patchset() functions, all changes related to a single +** As with the output of the tdsqlite3session_changeset() and +** tdsqlite3session_patchset() functions, all changes related to a single ** table are grouped together in the output of this function. Tables appear ** in the same order as for the very first changeset added to the changegroup. ** If the second or subsequent changesets added to the changegroup contain @@ -9634,35 +11860,35 @@ int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); ** is returned and the output variables are set to the size of and a ** pointer to the output buffer, respectively. In this case it is the ** responsibility of the caller to eventually free the buffer using a -** call to sqlite3_free(). +** call to tdsqlite3_free(). */ -int sqlite3changegroup_output( - sqlite3_changegroup*, +SQLITE_API int tdsqlite3changegroup_output( + tdsqlite3_changegroup*, int *pnData, /* OUT: Size of output buffer in bytes */ void **ppData /* OUT: Pointer to output buffer */ ); /* ** CAPI3REF: Delete A Changegroup Object +** DESTRUCTOR: tdsqlite3_changegroup */ -void sqlite3changegroup_delete(sqlite3_changegroup*); +SQLITE_API void tdsqlite3changegroup_delete(tdsqlite3_changegroup*); /* ** CAPI3REF: Apply A Changeset To A Database ** -** Apply a changeset to a database. This function attempts to update the -** "main" database attached to handle db with the changes found in the -** changeset passed via the second and third arguments. +** Apply a changeset or patchset to a database. These functions attempt to +** update the "main" database attached to handle db with the changes found in +** the changeset passed via the second and third arguments. ** -** The fourth argument (xFilter) passed to this function is the "filter +** The fourth argument (xFilter) passed to these functions is the "filter ** callback". If it is not NULL, then for each table affected by at least one ** change in the changeset, the filter callback is invoked with ** the table name as the second argument, and a copy of the context pointer -** passed as the sixth argument to this function as the first. If the "filter -** callback" returns zero, then no attempt is made to apply any changes to -** the table. Otherwise, if the return value is non-zero or the xFilter -** argument to this function is NULL, all changes related to the table are -** attempted. +** passed as the sixth argument as the first. If the "filter callback" +** returns zero, then no attempt is made to apply any changes to the table. +** Otherwise, if the return value is non-zero or the xFilter argument to +** is NULL, all changes related to the table are attempted. ** ** For each table that is not excluded by the filter callback, this function ** tests that the target database contains a compatible table. A table is @@ -9671,7 +11897,7 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** <ul> ** <li> The table has the same name as the name recorded in the ** changeset, and -** <li> The table has the same number of columns as recorded in the +** <li> The table has at least as many columns as recorded in the ** changeset, and ** <li> The table has primary key columns in the same position as ** recorded in the changeset. @@ -9679,13 +11905,13 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** ** If there is no compatible table, it is not an error, but none of the ** changes associated with the table are applied. A warning message is issued -** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most +** via the tdsqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most ** one such warning is issued for each table in the changeset. ** ** For each change for which there is a compatible table, an attempt is made ** to modify the table contents according to the UPDATE, INSERT or DELETE ** change. If a change cannot be applied cleanly, the conflict handler -** function passed as the fifth argument to sqlite3changeset_apply() may be +** function passed as the fifth argument to tdsqlite3changeset_apply() may be ** invoked. A description of exactly when the conflict handler is invoked for ** each type of change is below. ** @@ -9699,15 +11925,15 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** if the second argument passed to the conflict handler is either ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler ** returns an illegal value, any changes already made are rolled back and -** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different -** actions are taken by sqlite3changeset_apply() depending on the value +** the call to tdsqlite3changeset_apply() returns SQLITE_MISUSE. Different +** actions are taken by tdsqlite3changeset_apply() depending on the value ** returned by each invocation of the conflict-handler function. Refer to ** the documentation for the three ** [SQLITE_CHANGESET_OMIT|available return values] for details. ** ** <dl> ** <dt>DELETE Changes<dd> -** For each DELETE change, this function checks if the target database +** For each DELETE change, the function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all non-primary key columns also match the values stored in @@ -9716,7 +11942,11 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** If a row with matching primary key values is found, but one or more of ** the non-primary key fields contains a value different from the original ** row value stored in the changeset, the conflict-handler function is -** invoked with [SQLITE_CHANGESET_DATA] as the second argument. +** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the +** database table has more columns than are recorded in the changeset, +** only the values of those non-primary key fields are compared against +** the current database contents - any trailing database table columns +** are ignored. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] @@ -9731,7 +11961,9 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** ** <dt>INSERT Changes<dd> ** For each INSERT change, an attempt is made to insert the new row into -** the database. +** the database. If the changeset row contains fewer fields than the +** database table, the trailing fields are populated with their default +** values. ** ** If the attempt to insert the row fails because the database already ** contains a row with the same primary key values, the conflict handler @@ -9746,16 +11978,16 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** [SQLITE_CHANGESET_REPLACE]. ** ** <dt>UPDATE Changes<dd> -** For each UPDATE change, this function checks if the target database +** For each UPDATE change, the function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values -** stored in all non-primary key columns also match the values stored in -** the changeset the row is updated within the target database. +** stored in all modified non-primary key columns also match the values +** stored in the changeset the row is updated within the target database. ** ** If a row with matching primary key values is found, but one or more of -** the non-primary key fields contains a value different from an original -** row value stored in the changeset, the conflict-handler function is -** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since +** the modified non-primary key fields contains a value different from an +** original row value stored in the changeset, the conflict-handler function +** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since ** UPDATE changes only contain values for non-primary key fields that are ** to be modified, only those fields need to match the original values to ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. @@ -9774,17 +12006,34 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** ** It is safe to execute SQL statements, including those that write to the ** table that the callback related to, from within the xConflict callback. -** This can be used to further customize the applications conflict +** This can be used to further customize the application's conflict ** resolution strategy. ** -** All changes made by this function are enclosed in a savepoint transaction. +** All changes made by these functions are enclosed in a savepoint transaction. ** If any other error (aside from a constraint failure when attempting to ** write to the target database) occurs, then the savepoint transaction is ** rolled back, restoring the target database to its original state, and an ** SQLite error code returned. -*/ -int sqlite3changeset_apply( - sqlite3 *db, /* Apply change to "main" db of this handle */ +** +** If the output parameters (ppRebase) and (pnRebase) are non-NULL and +** the input is a changeset (not a patchset), then tdsqlite3changeset_apply_v2() +** may set (*ppRebase) to point to a "rebase" that may be used with the +** tdsqlite3_rebaser APIs buffer before returning. In this case (*pnRebase) +** is set to the size of the buffer in bytes. It is the responsibility of the +** caller to eventually free any such buffer using tdsqlite3_free(). The buffer +** is only allocated and populated if one or more conflicts were encountered +** while applying the patchset. See comments surrounding the tdsqlite3_rebaser +** APIs for further details. +** +** The behavior of tdsqlite3changeset_apply_v2() and its streaming equivalent +** may be modified by passing a combination of +** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter. +** +** Note that the tdsqlite3changeset_apply_v2() API is still <b>experimental</b> +** and therefore subject to change. +*/ +SQLITE_API int tdsqlite3changeset_apply( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ int(*xFilter)( @@ -9794,10 +12043,51 @@ int sqlite3changeset_apply( int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); +SQLITE_API int tdsqlite3changeset_apply_v2( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, /* OUT: Rebase data */ + int flags /* SESSION_CHANGESETAPPLY_* flags */ +); + +/* +** CAPI3REF: Flags for tdsqlite3changeset_apply_v2 +** +** The following flags may passed via the 9th parameter to +** [tdsqlite3changeset_apply_v2] and [tdsqlite3changeset_apply_v2_strm]: +** +** <dl> +** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd> +** Usually, the sessions module encloses all operations performed by +** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The +** SAVEPOINT is committed if the changeset or patchset is successfully +** applied, or rolled back if an error occurs. Specifying this flag +** causes the sessions module to omit this savepoint. In this case, if the +** caller has an open transaction or savepoint when apply_v2() is called, +** it may revert the partially applied changeset by rolling it back. +** +** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd> +** Invert the changeset before applying it. This is equivalent to inverting +** a changeset using tdsqlite3changeset_invert() before applying it. It is +** an error to specify this flag with a patchset. +*/ +#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001 +#define SQLITE_CHANGESETAPPLY_INVERT 0x0002 /* ** CAPI3REF: Constants Passed To The Conflict Handler @@ -9821,7 +12111,7 @@ int sqlite3changeset_apply( ** required PRIMARY KEY fields is not present in the database. ** ** There is no conflicting row in this case. The results of invoking the -** sqlite3changeset_conflict() API are undefined. +** tdsqlite3changeset_conflict() API are undefined. ** ** <dt>SQLITE_CHANGESET_CONFLICT<dd> ** CHANGESET_CONFLICT is passed as the second argument to the conflict @@ -9841,8 +12131,8 @@ int sqlite3changeset_apply( ** CHANGESET_ABORT, the changeset is rolled back. ** ** No current or conflicting row information is provided. The only function -** it is possible to call on the supplied sqlite3_changeset_iter handle -** is sqlite3changeset_fk_conflicts(). +** it is possible to call on the supplied tdsqlite3_changeset_iter handle +** is tdsqlite3changeset_fk_conflicts(). ** ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd> ** If any other constraint violation occurs while applying a change (i.e. @@ -9850,7 +12140,7 @@ int sqlite3changeset_apply( ** invoked with CHANGESET_CONSTRAINT as the second argument. ** ** There is no conflicting row in this case. The results of invoking the -** sqlite3changeset_conflict() API are undefined. +** tdsqlite3changeset_conflict() API are undefined. ** ** </dl> */ @@ -9875,7 +12165,7 @@ int sqlite3changeset_apply( ** This value may only be returned if the second argument to the conflict ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this ** is not the case, any changes applied so far are rolled back and the -** call to sqlite3changeset_apply() returns SQLITE_MISUSE. +** call to tdsqlite3changeset_apply() returns SQLITE_MISUSE. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict ** handler, then the conflicting row is either updated or deleted, depending @@ -9888,13 +12178,168 @@ int sqlite3changeset_apply( ** ** <dt>SQLITE_CHANGESET_ABORT<dd> ** If this value is returned, any changes applied so far are rolled back -** and the call to sqlite3changeset_apply() returns SQLITE_ABORT. +** and the call to tdsqlite3changeset_apply() returns SQLITE_ABORT. ** </dl> */ #define SQLITE_CHANGESET_OMIT 0 #define SQLITE_CHANGESET_REPLACE 1 #define SQLITE_CHANGESET_ABORT 2 +/* +** CAPI3REF: Rebasing changesets +** EXPERIMENTAL +** +** Suppose there is a site hosting a database in state S0. And that +** modifications are made that move that database to state S1 and a +** changeset recorded (the "local" changeset). Then, a changeset based +** on S0 is received from another site (the "remote" changeset) and +** applied to the database. The database is then in state +** (S1+"remote"), where the exact state depends on any conflict +** resolution decisions (OMIT or REPLACE) made while applying "remote". +** Rebasing a changeset is to update it to take those conflict +** resolution decisions into account, so that the same conflicts +** do not have to be resolved elsewhere in the network. +** +** For example, if both the local and remote changesets contain an +** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)": +** +** local: INSERT INTO t1 VALUES(1, 'v1'); +** remote: INSERT INTO t1 VALUES(1, 'v2'); +** +** and the conflict resolution is REPLACE, then the INSERT change is +** removed from the local changeset (it was overridden). Or, if the +** conflict resolution was "OMIT", then the local changeset is modified +** to instead contain: +** +** UPDATE t1 SET b = 'v2' WHERE a=1; +** +** Changes within the local changeset are rebased as follows: +** +** <dl> +** <dt>Local INSERT<dd> +** This may only conflict with a remote INSERT. If the conflict +** resolution was OMIT, then add an UPDATE change to the rebased +** changeset. Or, if the conflict resolution was REPLACE, add +** nothing to the rebased changeset. +** +** <dt>Local DELETE<dd> +** This may conflict with a remote UPDATE or DELETE. In both cases the +** only possible resolution is OMIT. If the remote operation was a +** DELETE, then add no change to the rebased changeset. If the remote +** operation was an UPDATE, then the old.* fields of change are updated +** to reflect the new.* values in the UPDATE. +** +** <dt>Local UPDATE<dd> +** This may conflict with a remote UPDATE or DELETE. If it conflicts +** with a DELETE, and the conflict resolution was OMIT, then the update +** is changed into an INSERT. Any undefined values in the new.* record +** from the update change are filled in using the old.* values from +** the conflicting DELETE. Or, if the conflict resolution was REPLACE, +** the UPDATE change is simply omitted from the rebased changeset. +** +** If conflict is with a remote UPDATE and the resolution is OMIT, then +** the old.* values are rebased using the new.* values in the remote +** change. Or, if the resolution is REPLACE, then the change is copied +** into the rebased changeset with updates to columns also updated by +** the conflicting remote UPDATE removed. If this means no columns would +** be updated, the change is omitted. +** </dl> +** +** A local change may be rebased against multiple remote changes +** simultaneously. If a single key is modified by multiple remote +** changesets, they are combined as follows before the local changeset +** is rebased: +** +** <ul> +** <li> If there has been one or more REPLACE resolutions on a +** key, it is rebased according to a REPLACE. +** +** <li> If there have been no REPLACE resolutions on a key, then +** the local changeset is rebased according to the most recent +** of the OMIT resolutions. +** </ul> +** +** Note that conflict resolutions from multiple remote changesets are +** combined on a per-field basis, not per-row. This means that in the +** case of multiple remote UPDATE operations, some fields of a single +** local change may be rebased for REPLACE while others are rebased for +** OMIT. +** +** In order to rebase a local changeset, the remote changeset must first +** be applied to the local database using tdsqlite3changeset_apply_v2() and +** the buffer of rebase information captured. Then: +** +** <ol> +** <li> An tdsqlite3_rebaser object is created by calling +** tdsqlite3rebaser_create(). +** <li> The new object is configured with the rebase buffer obtained from +** tdsqlite3changeset_apply_v2() by calling tdsqlite3rebaser_configure(). +** If the local changeset is to be rebased against multiple remote +** changesets, then tdsqlite3rebaser_configure() should be called +** multiple times, in the same order that the multiple +** tdsqlite3changeset_apply_v2() calls were made. +** <li> Each local changeset is rebased by calling tdsqlite3rebaser_rebase(). +** <li> The tdsqlite3_rebaser object is deleted by calling +** tdsqlite3rebaser_delete(). +** </ol> +*/ +typedef struct tdsqlite3_rebaser tdsqlite3_rebaser; + +/* +** CAPI3REF: Create a changeset rebaser object. +** EXPERIMENTAL +** +** Allocate a new changeset rebaser object. If successful, set (*ppNew) to +** point to the new object and return SQLITE_OK. Otherwise, if an error +** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) +** to NULL. +*/ +SQLITE_API int tdsqlite3rebaser_create(tdsqlite3_rebaser **ppNew); + +/* +** CAPI3REF: Configure a changeset rebaser object. +** EXPERIMENTAL +** +** Configure the changeset rebaser object to rebase changesets according +** to the conflict resolutions described by buffer pRebase (size nRebase +** bytes), which must have been obtained from a previous call to +** tdsqlite3changeset_apply_v2(). +*/ +SQLITE_API int tdsqlite3rebaser_configure( + tdsqlite3_rebaser*, + int nRebase, const void *pRebase +); + +/* +** CAPI3REF: Rebase a changeset +** EXPERIMENTAL +** +** Argument pIn must point to a buffer containing a changeset nIn bytes +** in size. This function allocates and populates a buffer with a copy +** of the changeset rebased according to the configuration of the +** rebaser object passed as the first argument. If successful, (*ppOut) +** is set to point to the new buffer containing the rebased changeset and +** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the +** responsibility of the caller to eventually free the new buffer using +** tdsqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut) +** are set to zero and an SQLite error code returned. +*/ +SQLITE_API int tdsqlite3rebaser_rebase( + tdsqlite3_rebaser*, + int nIn, const void *pIn, + int *pnOut, void **ppOut +); + +/* +** CAPI3REF: Delete a changeset rebaser object. +** EXPERIMENTAL +** +** Delete the changeset rebaser object and all associated resources. There +** should be one call to this function for each successful invocation +** of tdsqlite3rebaser_create(). +*/ +SQLITE_API void tdsqlite3rebaser_delete(tdsqlite3_rebaser *p); + /* ** CAPI3REF: Streaming Versions of API functions. ** @@ -9903,18 +12348,19 @@ int sqlite3changeset_apply( ** ** <table border=1 style="margin-left:8ex;margin-right:8ex"> ** <tr><th>Streaming function<th>Non-streaming equivalent</th> -** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply] -** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat] -** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert] -** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start] -** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset] -** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset] +** <tr><td>tdsqlite3changeset_apply_strm<td>[tdsqlite3changeset_apply] +** <tr><td>tdsqlite3changeset_apply_strm_v2<td>[tdsqlite3changeset_apply_v2] +** <tr><td>tdsqlite3changeset_concat_strm<td>[tdsqlite3changeset_concat] +** <tr><td>tdsqlite3changeset_invert_strm<td>[tdsqlite3changeset_invert] +** <tr><td>tdsqlite3changeset_start_strm<td>[tdsqlite3changeset_start] +** <tr><td>tdsqlite3session_changeset_strm<td>[tdsqlite3session_changeset] +** <tr><td>tdsqlite3session_patchset_strm<td>[tdsqlite3session_patchset] ** </table> ** ** Non-streaming functions that accept changesets (or patchsets) as input ** require that the entire changeset be stored in a single buffer in memory. ** Similarly, those that return a changeset or patchset do so by returning -** a pointer to a single large buffer allocated using sqlite3_malloc(). +** a pointer to a single large buffer allocated using tdsqlite3_malloc(). ** Normally this is convenient. However, if an application running in a ** low-memory environment is required to handle very large changesets, the ** large contiguous memory allocations required can become onerous. @@ -9947,7 +12393,7 @@ int sqlite3changeset_apply( ** an error, all processing is abandoned and the streaming API function ** returns a copy of the error code to the caller. ** -** In the case of sqlite3changeset_start_strm(), the xInput callback may be +** In the case of tdsqlite3changeset_start_strm(), the xInput callback may be ** invoked by the sessions module at any point during the lifetime of the ** iterator. If such an xInput callback returns an error, the iterator enters ** an error state, whereby all subsequent calls to iterator functions @@ -9984,8 +12430,8 @@ int sqlite3changeset_apply( ** parameter set to a value less than or equal to zero. Other than this, ** no guarantees are made as to the size of the chunks of data returned. */ -int sqlite3changeset_apply_strm( - sqlite3 *db, /* Apply change to "main" db of this handle */ +SQLITE_API int tdsqlite3changeset_apply_strm( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ void *pIn, /* First arg for xInput */ int(*xFilter)( @@ -9995,11 +12441,28 @@ int sqlite3changeset_apply_strm( int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); -int sqlite3changeset_concat_strm( +SQLITE_API int tdsqlite3changeset_apply_v2_strm( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +); +SQLITE_API int tdsqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, int (*xInputB)(void *pIn, void *pData, int *pnData), @@ -10007,36 +12470,88 @@ int sqlite3changeset_concat_strm( int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3changeset_invert_strm( +SQLITE_API int tdsqlite3changeset_invert_strm( int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3changeset_start_strm( - sqlite3_changeset_iter **pp, +SQLITE_API int tdsqlite3changeset_start_strm( + tdsqlite3_changeset_iter **pp, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); -int sqlite3session_changeset_strm( - sqlite3_session *pSession, +SQLITE_API int tdsqlite3changeset_start_v2_strm( + tdsqlite3_changeset_iter **pp, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int flags +); +SQLITE_API int tdsqlite3session_changeset_strm( + tdsqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3session_patchset_strm( - sqlite3_session *pSession, +SQLITE_API int tdsqlite3session_patchset_strm( + tdsqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3changegroup_add_strm(sqlite3_changegroup*, +SQLITE_API int tdsqlite3changegroup_add_strm(tdsqlite3_changegroup*, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); -int sqlite3changegroup_output_strm(sqlite3_changegroup*, +SQLITE_API int tdsqlite3changegroup_output_strm(tdsqlite3_changegroup*, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); +SQLITE_API int tdsqlite3rebaser_rebase_strm( + tdsqlite3_rebaser *pRebaser, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut +); +/* +** CAPI3REF: Configure global parameters +** +** The tdsqlite3session_config() interface is used to make global configuration +** changes to the sessions module in order to tune it to the specific needs +** of the application. +** +** The tdsqlite3session_config() interface is not threadsafe. If it is invoked +** while any other thread is inside any other sessions method then the +** results are undefined. Furthermore, if it is invoked after any sessions +** related objects have been created, the results are also undefined. +** +** The first argument to the tdsqlite3session_config() function must be one +** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The +** interpretation of the (void*) value passed as the second parameter and +** the effect of calling this function depends on the value of the first +** parameter. +** +** <dl> +** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd> +** By default, the sessions module streaming interfaces attempt to input +** and output data in approximately 1 KiB chunks. This operand may be used +** to set and query the value of this configuration setting. The pointer +** passed as the second argument must point to a value of type (int). +** If this value is greater than 0, it is used as the new streaming data +** chunk size for both input and output. Before returning, the (int) value +** pointed to by pArg is set to the final value of the streaming interface +** chunk size. +** </dl> +** +** This function returns SQLITE_OK if successful, or an SQLite error code +** otherwise. +*/ +SQLITE_API int tdsqlite3session_config(int op, void *pArg); + +/* +** CAPI3REF: Values for tdsqlite3session_config(). +*/ +#define SQLITE_SESSION_CONFIG_STRMSIZE 1 /* ** Make sure we can call this stuff from C++. @@ -10047,7 +12562,7 @@ int sqlite3changegroup_output_strm(sqlite3_changegroup*, #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */ -/******** End of sqlite3session.h *********/ +/******** End of tdsqlite3session.h *********/ /******** Begin file fts5.h *********/ /* ** 2014 May 31 @@ -10081,7 +12596,7 @@ extern "C" { ** CUSTOM AUXILIARY FUNCTIONS ** ** Virtual table implementations may overload SQL functions by implementing -** the sqlite3_module.xFindFunction() method. +** the tdsqlite3_module.xFindFunction() method. */ typedef struct Fts5ExtensionApi Fts5ExtensionApi; @@ -10091,9 +12606,9 @@ typedef struct Fts5PhraseIter Fts5PhraseIter; typedef void (*fts5_extension_function)( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ - sqlite3_context *pCtx, /* Context for returning result/error */ + tdsqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ - sqlite3_value **apVal /* Array of trailing arguments */ + tdsqlite3_value **apVal /* Array of trailing arguments */ ); struct Fts5PhraseIter { @@ -10170,12 +12685,8 @@ struct Fts5PhraseIter { ** ** Usually, output parameter *piPhrase is set to the phrase number, *piCol ** to the column in which it occurs and *piOff the token offset of the -** first token of the phrase. The exception is if the table was created -** with the offsets=0 option specified. In this case *piOff is always -** set to -1. -** -** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) -** if an error occurs. +** first token of the phrase. Returns SQLITE_OK if successful, or an error +** code (i.e. SQLITE_NOMEM) if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. @@ -10213,10 +12724,10 @@ struct Fts5PhraseIter { ** ** xSetAuxdata(pFts5, pAux, xDelete) ** -** Save the pointer passed as the second argument as the extension functions +** Save the pointer passed as the second argument as the extension function's ** "auxiliary data". The pointer may then be retrieved by the current or any ** future invocation of the same fts5 extension function made as part of -** of the same MATCH query using the xGetAuxdata() API. +** the same MATCH query using the xGetAuxdata() API. ** ** Each extension function is allocated a single auxiliary data slot for ** each FTS query (MATCH expression). If the extension function is invoked @@ -10231,7 +12742,7 @@ struct Fts5PhraseIter { ** The xDelete callback, if one is specified, is also invoked on the ** auxiliary data pointer after the FTS5 query has finished. ** -** If an error (e.g. an OOM condition) occurs within this function, an +** If an error (e.g. an OOM condition) occurs within this function, ** the auxiliary data is set to NULL and an error code returned. If the ** xDelete parameter was not NULL, it is invoked on the auxiliary data ** pointer before returning. @@ -10322,8 +12833,8 @@ struct Fts5ExtensionApi { void *(*xUserData)(Fts5Context*); int (*xColumnCount)(Fts5Context*); - int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); - int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); + int (*xRowCount)(Fts5Context*, tdsqlite3_int64 *pnRow); + int (*xColumnTotalSize)(Fts5Context*, int iCol, tdsqlite3_int64 *pnToken); int (*xTokenize)(Fts5Context*, const char *pText, int nText, /* Text to tokenize */ @@ -10337,7 +12848,7 @@ struct Fts5ExtensionApi { int (*xInstCount)(Fts5Context*, int *pnInst); int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); - sqlite3_int64 (*xRowid)(Fts5Context*); + tdsqlite3_int64 (*xRowid)(Fts5Context*); int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); @@ -10455,8 +12966,8 @@ struct Fts5ExtensionApi { ** ** There are several ways to approach this in FTS5: ** -** <ol><li> By mapping all synonyms to a single token. In this case, the -** In the above example, this means that the tokenizer returns the +** <ol><li> By mapping all synonyms to a single token. In this case, using +** the above example, this means that the tokenizer returns the ** same token for inputs "first" and "1st". Say that token is in ** fact "first", so that when the user inserts the document "I won ** 1st place" entries are added to the index for tokens "i", "won", @@ -10464,11 +12975,11 @@ struct Fts5ExtensionApi { ** the tokenizer substitutes "first" for "1st" and the query works ** as expected. ** -** <li> By adding multiple synonyms for a single term to the FTS index. -** In this case, when tokenizing query text, the tokenizer may -** provide multiple synonyms for a single term within the document. -** FTS5 then queries the index for each synonym individually. For -** example, faced with the query: +** <li> By querying the index for all synonyms of each query term +** separately. In this case, when tokenizing query text, the +** tokenizer may provide multiple synonyms for a single term +** within the document. FTS5 then queries the index for each +** synonym individually. For example, faced with the query: ** ** <codeblock> ** ... MATCH 'first place'</codeblock> @@ -10492,9 +13003,9 @@ struct Fts5ExtensionApi { ** "place". ** ** This way, even if the tokenizer does not provide synonyms -** when tokenizing query text (it should not - to do would be +** when tokenizing query text (it should not - to do so would be ** inefficient), it doesn't matter if the user queries for -** 'first + place' or '1st + place', as there are entires in the +** 'first + place' or '1st + place', as there are entries in the ** FTS index corresponding to both forms of the first token. ** </ol> ** @@ -10522,7 +13033,7 @@ struct Fts5ExtensionApi { ** extra data to the FTS index or require FTS5 to query for multiple terms, ** so it is efficient in terms of disk space and query speed. However, it ** does not support prefix queries very well. If, as suggested above, the -** token "first" is subsituted for "1st" by the tokenizer, then the query: +** token "first" is substituted for "1st" by the tokenizer, then the query: ** ** <codeblock> ** ... MATCH '1s*'</codeblock> @@ -10637,8 +13148,9 @@ struct fts5_api { ** Include the configuration header output by 'configure' if we're using the ** autoconf-based build */ -#ifdef _HAVE_SQLITE_CONFIG_H -#include "config.h" +#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H) +/* #include "config.h" */ +#define SQLITECONFIG_H 1 #endif /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ @@ -10732,7 +13244,7 @@ struct fts5_api { ** Not currently enforced. */ #ifndef SQLITE_MAX_VDBE_OP -# define SQLITE_MAX_VDBE_OP 25000 +# define SQLITE_MAX_VDBE_OP 250000000 #endif /* @@ -10893,15 +13405,15 @@ struct fts5_api { ** So we have to define the macros in different ways depending on the ** compiler. */ -#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ +#if defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ +# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) +#elif defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) #elif !defined(__GNUC__) /* Works for compilers other than LLVM */ # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) -#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ -# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) -# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) #else /* Generates a warning - but it always works */ # define SQLITE_INT_TO_PTR(X) ((void*)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(X)) @@ -10930,6 +13442,7 @@ struct fts5_api { # include <intrin.h> # pragma intrinsic(_byteswap_ushort) # pragma intrinsic(_byteswap_ulong) +# pragma intrinsic(_byteswap_uint64) # pragma intrinsic(_ReadWriteBarrier) # else # include <cmnintrin.h> @@ -10947,6 +13460,11 @@ struct fts5_api { ** ** Older versions of SQLite used an optional THREADSAFE macro. ** We support that for legacy. +** +** To ensure that the correct value of "THREADSAFE" is reported when querying +** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this +** logic is partially replicated in ctime.c. If it is updated here, it should +** also be updated there. */ #if !defined(SQLITE_THREADSAFE) # if defined(THREADSAFE) @@ -11064,8 +13582,8 @@ struct fts5_api { ** */ #ifdef SQLITE_COVERAGE_TEST -SQLITE_PRIVATE void sqlite3Coverage(int); -# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } +SQLITE_PRIVATE void tdsqlite3Coverage(int); +# define testcase(X) if( X ){ tdsqlite3Coverage(__LINE__); } #else # define testcase(X) #endif @@ -11122,6 +13640,41 @@ SQLITE_PRIVATE void sqlite3Coverage(int); #endif /* +** The harmless(X) macro indicates that expression X is usually false +** but can be true without causing any problems, but we don't know of +** any way to cause X to be true. +** +** In debugging and testing builds, this macro will abort if X is ever +** true. In this way, developers are alerted to a possible test case +** that causes X to be true. If a harmless macro ever fails, that is +** an opportunity to change the macro into a testcase() and add a new +** test case to the test suite. +** +** For normal production builds, harmless(X) is a no-op, since it does +** not matter whether expression X is true or false. +*/ +#ifdef SQLITE_DEBUG +# define harmless(X) assert(!(X)); +#else +# define harmless(X) +#endif + +/* +** Some conditionals are optimizations only. In other words, if the +** conditionals are replaced with a constant 1 (true) or 0 (false) then +** the correct answer is still obtained, though perhaps not as quickly. +** +** The following macros mark these optimizations conditionals. +*/ +#if defined(SQLITE_MUTATION_TEST) +# define OK_IF_ALWAYS_TRUE(X) (1) +# define OK_IF_ALWAYS_FALSE(X) (0) +#else +# define OK_IF_ALWAYS_TRUE(X) (X) +# define OK_IF_ALWAYS_FALSE(X) (X) +#endif + +/* ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is ** defined. We need to defend against those failures when testing with ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches @@ -11141,8 +13694,8 @@ SQLITE_PRIVATE void sqlite3Coverage(int); */ #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \ (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) - extern int sqlite3OSTrace; -# define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X + extern int tdsqlite3OSTrace; +# define OSTRACE(X) if( tdsqlite3OSTrace ) tdsqlite3DebugPrintf X # define SQLITE_HAVE_OS_TRACE #else # define OSTRACE(X) @@ -11150,7 +13703,7 @@ SQLITE_PRIVATE void sqlite3Coverage(int); #endif /* -** Is the sqlite3ErrName() function needed in the build? Currently, +** Is the tdsqlite3ErrName() function needed in the build? Currently, ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when ** OSTRACE is enabled), and by several "test*.c" files (which are ** compiled using SQLITE_TEST). @@ -11235,7 +13788,7 @@ struct Hash { unsigned int count; /* Number of entries in this table */ HashElem *first; /* The first element of the array */ struct _ht { /* the hash table */ - int count; /* Number of entries with this hash */ + unsigned int count; /* Number of entries with this hash */ HashElem *chain; /* Pointer to first entry with this hash */ } *ht; }; @@ -11255,10 +13808,10 @@ struct HashElem { /* ** Access routines. To delete, insert a NULL pointer. */ -SQLITE_PRIVATE void sqlite3HashInit(Hash*); -SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData); -SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey); -SQLITE_PRIVATE void sqlite3HashClear(Hash*); +SQLITE_PRIVATE void tdsqlite3HashInit(Hash*); +SQLITE_PRIVATE void *tdsqlite3HashInsert(Hash*, const char *pKey, void *pData); +SQLITE_PRIVATE void *tdsqlite3HashFind(const Hash*, const char *pKey); +SQLITE_PRIVATE void tdsqlite3HashClear(Hash*); /* ** Macros for looping over all elements of a hash table. The idiom is @@ -11315,150 +13868,160 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); #define TK_AS 24 #define TK_WITHOUT 25 #define TK_COMMA 26 -#define TK_OR 27 -#define TK_AND 28 -#define TK_IS 29 -#define TK_MATCH 30 -#define TK_LIKE_KW 31 -#define TK_BETWEEN 32 -#define TK_IN 33 -#define TK_ISNULL 34 -#define TK_NOTNULL 35 -#define TK_NE 36 -#define TK_EQ 37 -#define TK_GT 38 -#define TK_LE 39 -#define TK_LT 40 -#define TK_GE 41 -#define TK_ESCAPE 42 -#define TK_BITAND 43 -#define TK_BITOR 44 -#define TK_LSHIFT 45 -#define TK_RSHIFT 46 -#define TK_PLUS 47 -#define TK_MINUS 48 -#define TK_STAR 49 -#define TK_SLASH 50 -#define TK_REM 51 -#define TK_CONCAT 52 -#define TK_COLLATE 53 -#define TK_BITNOT 54 -#define TK_ID 55 -#define TK_INDEXED 56 -#define TK_ABORT 57 -#define TK_ACTION 58 -#define TK_AFTER 59 -#define TK_ANALYZE 60 -#define TK_ASC 61 -#define TK_ATTACH 62 -#define TK_BEFORE 63 -#define TK_BY 64 -#define TK_CASCADE 65 -#define TK_CAST 66 -#define TK_COLUMNKW 67 -#define TK_CONFLICT 68 -#define TK_DATABASE 69 -#define TK_DESC 70 -#define TK_DETACH 71 -#define TK_EACH 72 -#define TK_FAIL 73 -#define TK_FOR 74 -#define TK_IGNORE 75 -#define TK_INITIALLY 76 -#define TK_INSTEAD 77 -#define TK_NO 78 -#define TK_KEY 79 -#define TK_OF 80 -#define TK_OFFSET 81 -#define TK_PRAGMA 82 -#define TK_RAISE 83 -#define TK_RECURSIVE 84 -#define TK_REPLACE 85 -#define TK_RESTRICT 86 -#define TK_ROW 87 -#define TK_TRIGGER 88 -#define TK_VACUUM 89 -#define TK_VIEW 90 -#define TK_VIRTUAL 91 -#define TK_WITH 92 -#define TK_REINDEX 93 -#define TK_RENAME 94 -#define TK_CTIME_KW 95 -#define TK_ANY 96 -#define TK_STRING 97 -#define TK_JOIN_KW 98 -#define TK_CONSTRAINT 99 -#define TK_DEFAULT 100 -#define TK_NULL 101 -#define TK_PRIMARY 102 -#define TK_UNIQUE 103 -#define TK_CHECK 104 -#define TK_REFERENCES 105 -#define TK_AUTOINCR 106 -#define TK_ON 107 -#define TK_INSERT 108 -#define TK_DELETE 109 -#define TK_UPDATE 110 -#define TK_SET 111 -#define TK_DEFERRABLE 112 -#define TK_FOREIGN 113 -#define TK_DROP 114 -#define TK_UNION 115 -#define TK_ALL 116 -#define TK_EXCEPT 117 -#define TK_INTERSECT 118 -#define TK_SELECT 119 -#define TK_VALUES 120 -#define TK_DISTINCT 121 -#define TK_DOT 122 -#define TK_FROM 123 -#define TK_JOIN 124 -#define TK_USING 125 -#define TK_ORDER 126 -#define TK_GROUP 127 -#define TK_HAVING 128 -#define TK_LIMIT 129 -#define TK_WHERE 130 -#define TK_INTO 131 -#define TK_FLOAT 132 -#define TK_BLOB 133 -#define TK_INTEGER 134 -#define TK_VARIABLE 135 -#define TK_CASE 136 -#define TK_WHEN 137 -#define TK_THEN 138 -#define TK_ELSE 139 -#define TK_INDEX 140 -#define TK_ALTER 141 -#define TK_ADD 142 -#define TK_TO_TEXT 143 -#define TK_TO_BLOB 144 -#define TK_TO_NUMERIC 145 -#define TK_TO_INT 146 -#define TK_TO_REAL 147 -#define TK_ISNOT 148 -#define TK_END_OF_FILE 149 -#define TK_UNCLOSED_STRING 150 -#define TK_FUNCTION 151 -#define TK_COLUMN 152 -#define TK_AGG_FUNCTION 153 -#define TK_AGG_COLUMN 154 -#define TK_UMINUS 155 -#define TK_UPLUS 156 -#define TK_REGISTER 157 -#define TK_VECTOR 158 -#define TK_SELECT_COLUMN 159 -#define TK_ASTERISK 160 -#define TK_SPAN 161 -#define TK_SPACE 162 -#define TK_ILLEGAL 163 - -/* The token codes above must all fit in 8 bits */ -#define TKFLG_MASK 0xff - -/* Flags that can be added to a token code when it is not -** being stored in a u8: */ -#define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */ +#define TK_ABORT 27 +#define TK_ACTION 28 +#define TK_AFTER 29 +#define TK_ANALYZE 30 +#define TK_ASC 31 +#define TK_ATTACH 32 +#define TK_BEFORE 33 +#define TK_BY 34 +#define TK_CASCADE 35 +#define TK_CAST 36 +#define TK_CONFLICT 37 +#define TK_DATABASE 38 +#define TK_DESC 39 +#define TK_DETACH 40 +#define TK_EACH 41 +#define TK_FAIL 42 +#define TK_OR 43 +#define TK_AND 44 +#define TK_IS 45 +#define TK_MATCH 46 +#define TK_LIKE_KW 47 +#define TK_BETWEEN 48 +#define TK_IN 49 +#define TK_ISNULL 50 +#define TK_NOTNULL 51 +#define TK_NE 52 +#define TK_EQ 53 +#define TK_GT 54 +#define TK_LE 55 +#define TK_LT 56 +#define TK_GE 57 +#define TK_ESCAPE 58 +#define TK_ID 59 +#define TK_COLUMNKW 60 +#define TK_DO 61 +#define TK_FOR 62 +#define TK_IGNORE 63 +#define TK_INITIALLY 64 +#define TK_INSTEAD 65 +#define TK_NO 66 +#define TK_KEY 67 +#define TK_OF 68 +#define TK_OFFSET 69 +#define TK_PRAGMA 70 +#define TK_RAISE 71 +#define TK_RECURSIVE 72 +#define TK_REPLACE 73 +#define TK_RESTRICT 74 +#define TK_ROW 75 +#define TK_ROWS 76 +#define TK_TRIGGER 77 +#define TK_VACUUM 78 +#define TK_VIEW 79 +#define TK_VIRTUAL 80 +#define TK_WITH 81 +#define TK_NULLS 82 +#define TK_FIRST 83 +#define TK_LAST 84 +#define TK_CURRENT 85 +#define TK_FOLLOWING 86 +#define TK_PARTITION 87 +#define TK_PRECEDING 88 +#define TK_RANGE 89 +#define TK_UNBOUNDED 90 +#define TK_EXCLUDE 91 +#define TK_GROUPS 92 +#define TK_OTHERS 93 +#define TK_TIES 94 +#define TK_GENERATED 95 +#define TK_ALWAYS 96 +#define TK_REINDEX 97 +#define TK_RENAME 98 +#define TK_CTIME_KW 99 +#define TK_ANY 100 +#define TK_BITAND 101 +#define TK_BITOR 102 +#define TK_LSHIFT 103 +#define TK_RSHIFT 104 +#define TK_PLUS 105 +#define TK_MINUS 106 +#define TK_STAR 107 +#define TK_SLASH 108 +#define TK_REM 109 +#define TK_CONCAT 110 +#define TK_COLLATE 111 +#define TK_BITNOT 112 +#define TK_ON 113 +#define TK_INDEXED 114 +#define TK_STRING 115 +#define TK_JOIN_KW 116 +#define TK_CONSTRAINT 117 +#define TK_DEFAULT 118 +#define TK_NULL 119 +#define TK_PRIMARY 120 +#define TK_UNIQUE 121 +#define TK_CHECK 122 +#define TK_REFERENCES 123 +#define TK_AUTOINCR 124 +#define TK_INSERT 125 +#define TK_DELETE 126 +#define TK_UPDATE 127 +#define TK_SET 128 +#define TK_DEFERRABLE 129 +#define TK_FOREIGN 130 +#define TK_DROP 131 +#define TK_UNION 132 +#define TK_ALL 133 +#define TK_EXCEPT 134 +#define TK_INTERSECT 135 +#define TK_SELECT 136 +#define TK_VALUES 137 +#define TK_DISTINCT 138 +#define TK_DOT 139 +#define TK_FROM 140 +#define TK_JOIN 141 +#define TK_USING 142 +#define TK_ORDER 143 +#define TK_GROUP 144 +#define TK_HAVING 145 +#define TK_LIMIT 146 +#define TK_WHERE 147 +#define TK_INTO 148 +#define TK_NOTHING 149 +#define TK_FLOAT 150 +#define TK_BLOB 151 +#define TK_INTEGER 152 +#define TK_VARIABLE 153 +#define TK_CASE 154 +#define TK_WHEN 155 +#define TK_THEN 156 +#define TK_ELSE 157 +#define TK_INDEX 158 +#define TK_ALTER 159 +#define TK_ADD 160 +#define TK_WINDOW 161 +#define TK_OVER 162 +#define TK_FILTER 163 +#define TK_COLUMN 164 +#define TK_AGG_FUNCTION 165 +#define TK_AGG_COLUMN 166 +#define TK_TRUEFALSE 167 +#define TK_ISNOT 168 +#define TK_FUNCTION 169 +#define TK_UMINUS 170 +#define TK_UPLUS 171 +#define TK_TRUTH 172 +#define TK_REGISTER 173 +#define TK_VECTOR 174 +#define TK_SELECT_COLUMN 175 +#define TK_IF_NULL_ROW 176 +#define TK_ASTERISK 177 +#define TK_SPAN 178 +#define TK_SPACE 179 +#define TK_ILLEGAL 180 /************** End of parse.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ @@ -11469,6 +14032,18 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); #include <stddef.h> /* +** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY. +** This allows better measurements of where memcpy() is used when running +** cachegrind. But this macro version of memcpy() is very slow so it +** should not be used in production. This is a performance measurement +** hack only. +*/ +#ifdef SQLITE_INLINE_MEMCPY +# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\ + int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);} +#endif + +/* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point */ @@ -11477,7 +14052,7 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); # define float sqlite_int64 # define LONGDOUBLE_TYPE sqlite_int64 # ifndef SQLITE_BIG_DBL -# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) +# define SQLITE_BIG_DBL (((tdsqlite3_int64)1)<<50) # endif # define SQLITE_OMIT_DATETIME_FUNCS 1 # define SQLITE_OMIT_TRACE 1 @@ -11524,7 +14099,6 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); */ #ifndef SQLITE_TEMP_STORE # define SQLITE_TEMP_STORE 1 -# define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */ #endif /* @@ -11552,9 +14126,28 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); ** pagecaches for each database connection. A positive number is the ** number of pages. A negative number N translations means that a buffer ** of -1024*N bytes is allocated and used for as many pages as it will hold. +** +** The default value of "20" was choosen to minimize the run-time of the +** speedtest1 test program with options: --shrink-memory --reprepare */ #ifndef SQLITE_DEFAULT_PCACHE_INITSZ -# define SQLITE_DEFAULT_PCACHE_INITSZ 100 +# define SQLITE_DEFAULT_PCACHE_INITSZ 20 +#endif + +/* +** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option. +*/ +#ifndef SQLITE_DEFAULT_SORTERREF_SIZE +# define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff +#endif + +/* +** The compile-time options SQLITE_MMAP_READWRITE and +** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another. +** You must choose one or the other (or neither) but not both. +*/ +#if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) +#error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE #endif /* @@ -11695,7 +14288,8 @@ typedef INT16_TYPE LogEst; # if defined(__SIZEOF_POINTER__) # define SQLITE_PTRSIZE __SIZEOF_POINTER__ # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \ - defined(_M_ARM) || defined(__arm__) || defined(__x86) + defined(_M_ARM) || defined(__arm__) || defined(__x86) || \ + (defined(__TOS_AIX__) && !defined(__64BIT__)) # define SQLITE_PTRSIZE 4 # else # define SQLITE_PTRSIZE 8 @@ -11729,34 +14323,38 @@ typedef INT16_TYPE LogEst; ** ** For best performance, an attempt is made to guess at the byte-order ** using C-preprocessor macros. If that is unsuccessful, or if -** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined +** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined ** at run-time. */ -#if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \ - defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ - defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ - defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER) -# define SQLITE_BYTEORDER 1234 -# define SQLITE_BIGENDIAN 0 -# define SQLITE_LITTLEENDIAN 1 -# define SQLITE_UTF16NATIVE SQLITE_UTF16LE +#ifndef SQLITE_BYTEORDER +# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \ + defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ + defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ + defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64) +# define SQLITE_BYTEORDER 1234 +# elif defined(sparc) || defined(__ppc__) || \ + defined(__ARMEB__) || defined(__AARCH64EB__) +# define SQLITE_BYTEORDER 4321 +# else +# define SQLITE_BYTEORDER 0 +# endif #endif -#if (defined(sparc) || defined(__ppc__)) \ - && !defined(SQLITE_RUNTIME_BYTEORDER) -# define SQLITE_BYTEORDER 4321 +#if SQLITE_BYTEORDER==4321 # define SQLITE_BIGENDIAN 1 # define SQLITE_LITTLEENDIAN 0 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE -#endif -#if !defined(SQLITE_BYTEORDER) +#elif SQLITE_BYTEORDER==1234 +# define SQLITE_BIGENDIAN 0 +# define SQLITE_LITTLEENDIAN 1 +# define SQLITE_UTF16NATIVE SQLITE_UTF16LE +#else # ifdef SQLITE_AMALGAMATION - const int sqlite3one = 1; + const int tdsqlite3one = 1; # else - extern const int sqlite3one; + extern const int tdsqlite3one; # endif -# define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */ -# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) -# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) +# define SQLITE_BIGENDIAN (*(char *)(&tdsqlite3one)==0) +# define SQLITE_LITTLEENDIAN (*(char *)(&tdsqlite3one)==1) # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) #endif @@ -11819,7 +14417,6 @@ typedef INT16_TYPE LogEst; # else # define SQLITE_MAX_MMAP_SIZE 0 # endif -# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */ #endif /* @@ -11829,7 +14426,6 @@ typedef INT16_TYPE LogEst; */ #ifndef SQLITE_DEFAULT_MMAP_SIZE # define SQLITE_DEFAULT_MMAP_SIZE 0 -# define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */ #endif #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE # undef SQLITE_DEFAULT_MMAP_SIZE @@ -11837,24 +14433,10 @@ typedef INT16_TYPE LogEst; #endif /* -** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined. -** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also -** define SQLITE_ENABLE_STAT3_OR_STAT4 -*/ -#ifdef SQLITE_ENABLE_STAT4 -# undef SQLITE_ENABLE_STAT3 -# define SQLITE_ENABLE_STAT3_OR_STAT4 1 -#elif SQLITE_ENABLE_STAT3 -# define SQLITE_ENABLE_STAT3_OR_STAT4 1 -#elif SQLITE_ENABLE_STAT3_OR_STAT4 -# undef SQLITE_ENABLE_STAT3_OR_STAT4 -#endif - -/* ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not ** the Select query generator tracing logic is turned on. */ -#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE) +#if defined(SQLITE_ENABLE_SELECTTRACE) # define SELECTTRACE_ENABLED 1 #else # define SELECTTRACE_ENABLED 0 @@ -11871,9 +14453,10 @@ typedef INT16_TYPE LogEst; */ typedef struct BusyHandler BusyHandler; struct BusyHandler { - int (*xFunc)(void *,int); /* The busy callback */ - void *pArg; /* First arg to busy callback */ - int nBusy; /* Incremented with each busy call */ + int (*xBusyHandler)(void *,int); /* The busy callback */ + void *pBusyArg; /* First arg to busy callback */ + int nBusy; /* Incremented with each busy call */ + u8 bExtraFileArg; /* Include tdsqlite3_file as callback arg */ }; /* @@ -11906,14 +14489,14 @@ struct BusyHandler { #define IsPowerOfTwo(X) (((X)&((X)-1))==0) /* -** The following value as a destructor means to use sqlite3DbFree(). -** The sqlite3DbFree() routine requires two parameters instead of the +** The following value as a destructor means to use tdsqlite3DbFree(). +** The tdsqlite3DbFree() routine requires two parameters instead of the ** one parameter that destructors normally want. So we have to introduce ** this magic value that the code knows to handle differently. Any ** pointer will work here as long as it is distinct from SQLITE_STATIC ** and SQLITE_TRANSIENT. */ -#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize) +#define SQLITE_DYNAMIC ((tdsqlite3_destructor_type)tdsqlite3MallocSize) /* ** When SQLITE_OMIT_WSD is defined, it means that the target platform does @@ -11931,14 +14514,14 @@ struct BusyHandler { */ #ifdef SQLITE_OMIT_WSD #define SQLITE_WSD const - #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) - #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) -SQLITE_API int sqlite3_wsd_init(int N, int J); -SQLITE_API void *sqlite3_wsd_find(void *K, int L); + #define GLOBAL(t,v) (*(t*)tdsqlite3_wsd_find((void*)&(v), sizeof(v))) + #define tdsqlite3GlobalConfig GLOBAL(struct Sqlite3Config, tdsqlite3Config) +SQLITE_API int tdsqlite3_wsd_init(int N, int J); +SQLITE_API void *tdsqlite3_wsd_find(void *K, int L); #else #define SQLITE_WSD #define GLOBAL(t,v) v - #define sqlite3GlobalConfig sqlite3Config + #define tdsqlite3GlobalConfig tdsqlite3Config #endif /* @@ -11973,7 +14556,6 @@ typedef struct Db Db; typedef struct Schema Schema; typedef struct Expr Expr; typedef struct ExprList ExprList; -typedef struct ExprSpan ExprSpan; typedef struct FKey FKey; typedef struct FuncDestructor FuncDestructor; typedef struct FuncDef FuncDef; @@ -11990,13 +14572,14 @@ typedef struct NameContext NameContext; typedef struct Parse Parse; typedef struct PreUpdate PreUpdate; typedef struct PrintfArguments PrintfArguments; +typedef struct RenameToken RenameToken; typedef struct RowSet RowSet; typedef struct Savepoint Savepoint; typedef struct Select Select; typedef struct SQLiteThread SQLiteThread; typedef struct SelectDest SelectDest; typedef struct SrcList SrcList; -typedef struct StrAccum StrAccum; +typedef struct tdsqlite3_str StrAccum; /* Internal alias for tdsqlite3_str */ typedef struct Table Table; typedef struct TableLock TableLock; typedef struct Token Token; @@ -12005,12 +14588,49 @@ typedef struct Trigger Trigger; typedef struct TriggerPrg TriggerPrg; typedef struct TriggerStep TriggerStep; typedef struct UnpackedRecord UnpackedRecord; +typedef struct Upsert Upsert; typedef struct VTable VTable; typedef struct VtabCtx VtabCtx; typedef struct Walker Walker; typedef struct WhereInfo WhereInfo; +typedef struct Window Window; typedef struct With With; + +/* +** The bitmask datatype defined below is used for various optimizations. +** +** Changing this from a 64-bit to a 32-bit type limits the number of +** tables in a join to 32 instead of 64. But it also reduces the size +** of the library by 738 bytes on ix86. +*/ +#ifdef SQLITE_BITMASK_TYPE + typedef SQLITE_BITMASK_TYPE Bitmask; +#else + typedef u64 Bitmask; +#endif + +/* +** The number of bits in a Bitmask. "BMS" means "BitMask Size". +*/ +#define BMS ((int)(sizeof(Bitmask)*8)) + +/* +** A bit in a Bitmask +*/ +#define MASKBIT(n) (((Bitmask)1)<<(n)) +#define MASKBIT64(n) (((u64)1)<<(n)) +#define MASKBIT32(n) (((unsigned int)1)<<(n)) +#define ALLBITS ((Bitmask)-1) + +/* A VList object records a mapping between parameters/variables/wildcards +** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer +** variable number associated with that parameter. See the format description +** on the tdsqlite3VListAdd() routine for more information. A VList is really +** just an array of integers. +*/ +typedef int VList; + /* ** Defer sourcing vdbe.h and btree.h until after the "u8" and ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque @@ -12062,16 +14682,16 @@ typedef struct BtShared BtShared; typedef struct BtreePayload BtreePayload; -SQLITE_PRIVATE int sqlite3BtreeOpen( - sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ +SQLITE_PRIVATE int tdsqlite3BtreeOpen( + tdsqlite3_vfs *pVfs, /* VFS to use with this b-tree */ const char *zFilename, /* Name of database file to open */ - sqlite3 *db, /* Associated database connection */ + tdsqlite3 *db, /* Associated database connection */ Btree **ppBtree, /* Return open Btree* here */ int flags, /* Flags */ int vfsFlags /* Flags passed through to VFS open */ ); -/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the +/* The flags parameter to tdsqlite3BtreeOpen can be the bitwise or of the ** following values. ** ** NOTE: These values must match the corresponding PAGER_ values in @@ -12082,46 +14702,46 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */ #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */ -SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); -SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int); +SQLITE_PRIVATE int tdsqlite3BtreeClose(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeSetCacheSize(Btree*,int); +SQLITE_PRIVATE int tdsqlite3BtreeSetSpillSize(Btree*,int); #if SQLITE_MAX_MMAP_SIZE>0 -SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64); -#endif -SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned); -SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); -SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); -SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); -SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*); -SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*); -SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p); -SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); -SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); -SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int); -SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); -SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int); -SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); -SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); -SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); -SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); -SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); -SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); +SQLITE_PRIVATE int tdsqlite3BtreeSetMmapLimit(Btree*,tdsqlite3_int64); +#endif +SQLITE_PRIVATE int tdsqlite3BtreeSetPagerFlags(Btree*,unsigned); +SQLITE_PRIVATE int tdsqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); +SQLITE_PRIVATE int tdsqlite3BtreeGetPageSize(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeMaxPageCount(Btree*,int); +SQLITE_PRIVATE u32 tdsqlite3BtreeLastPage(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeSecureDelete(Btree*,int); +SQLITE_PRIVATE int tdsqlite3BtreeGetOptimalReserve(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeGetReserveNoMutex(Btree *p); +SQLITE_PRIVATE int tdsqlite3BtreeSetAutoVacuum(Btree *, int); +SQLITE_PRIVATE int tdsqlite3BtreeGetAutoVacuum(Btree *); +SQLITE_PRIVATE int tdsqlite3BtreeBeginTrans(Btree*,int,int*); +SQLITE_PRIVATE int tdsqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); +SQLITE_PRIVATE int tdsqlite3BtreeCommitPhaseTwo(Btree*, int); +SQLITE_PRIVATE int tdsqlite3BtreeCommit(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeRollback(Btree*,int,int); +SQLITE_PRIVATE int tdsqlite3BtreeBeginStmt(Btree*,int); +SQLITE_PRIVATE int tdsqlite3BtreeCreateTable(Btree*, int*, int flags); +SQLITE_PRIVATE int tdsqlite3BtreeIsInTrans(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeIsInReadTrans(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeIsInBackup(Btree*); +SQLITE_PRIVATE void *tdsqlite3BtreeSchema(Btree *, int, void(*)(void *)); +SQLITE_PRIVATE int tdsqlite3BtreeSchemaLocked(Btree *pBtree); #ifndef SQLITE_OMIT_SHARED_CACHE -SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); +SQLITE_PRIVATE int tdsqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); #endif -SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); +SQLITE_PRIVATE int tdsqlite3BtreeSavepoint(Btree *, int, int); -SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); -SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); -SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); +SQLITE_PRIVATE const char *tdsqlite3BtreeGetFilename(Btree *); +SQLITE_PRIVATE const char *tdsqlite3BtreeGetJournalname(Btree *); +SQLITE_PRIVATE int tdsqlite3BtreeCopyFile(Btree *, Btree *); -SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); +SQLITE_PRIVATE int tdsqlite3BtreeIncrVacuum(Btree *); -/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR +/* The flags parameter to tdsqlite3BtreeCreateTable can be the bitwise OR ** of the flags shown below. ** ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. @@ -12134,18 +14754,18 @@ SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ #define BTREE_BLOBKEY 2 /* Table has keys only - no data */ -SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); -SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); -SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int); +SQLITE_PRIVATE int tdsqlite3BtreeDropTable(Btree*, int, int*); +SQLITE_PRIVATE int tdsqlite3BtreeClearTable(Btree*, int, int*); +SQLITE_PRIVATE int tdsqlite3BtreeClearTableOfCursor(BtCursor*); +SQLITE_PRIVATE int tdsqlite3BtreeTripAllCursors(Btree*, int, int); -SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); -SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); +SQLITE_PRIVATE void tdsqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); +SQLITE_PRIVATE int tdsqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); -SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); +SQLITE_PRIVATE int tdsqlite3BtreeNewDb(Btree *p); /* -** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta +** The second parameter to tdsqlite3BtreeGetMeta or tdsqlite3BtreeUpdateMeta ** should be one of the following values. The integer values are assigned ** to constants so that the offset of the corresponding field in an ** SQLite database header may be found using the following formula: @@ -12173,7 +14793,7 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); #define BTREE_DATA_VERSION 15 /* A virtual meta-value */ /* -** Kinds of hints that can be passed into the sqlite3BtreeCursorHint() +** Kinds of hints that can be passed into the tdsqlite3BtreeCursorHint() ** interface. ** ** BTREE_HINT_RANGE (arguments: Expr*, Mem*) @@ -12203,7 +14823,7 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); /* ** Values that may be OR'd together to form the argument to the -** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint(): +** BTREE_HINT_FLAGS hint for tdsqlite3BtreeCursorHint(): ** ** The BTREE_BULKLOAD flag is set on index cursors when the index is going ** to be filled with content that is already in sorted order. @@ -12218,7 +14838,7 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */ /* -** Flags passed as the third argument to sqlite3BtreeCursor(). +** Flags passed as the third argument to tdsqlite3BtreeCursor(). ** ** For read-only cursors the wrFlag argument is always zero. For read-write ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just @@ -12243,49 +14863,66 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); #define BTREE_WRCSR 0x00000004 /* read-write cursor */ #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */ -SQLITE_PRIVATE int sqlite3BtreeCursor( +SQLITE_PRIVATE int tdsqlite3BtreeCursor( Btree*, /* BTree containing table to open */ int iTable, /* Index of root page */ int wrFlag, /* 1 for writing. 0 for read-only */ struct KeyInfo*, /* First argument to compare function */ BtCursor *pCursor /* Space to write cursor structure */ ); -SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); -SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); -SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned); +SQLITE_PRIVATE BtCursor *tdsqlite3BtreeFakeValidCursor(void); +SQLITE_PRIVATE int tdsqlite3BtreeCursorSize(void); +SQLITE_PRIVATE void tdsqlite3BtreeCursorZero(BtCursor*); +SQLITE_PRIVATE void tdsqlite3BtreeCursorHintFlags(BtCursor*, unsigned); #ifdef SQLITE_ENABLE_CURSOR_HINTS -SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...); +SQLITE_PRIVATE void tdsqlite3BtreeCursorHint(BtCursor*, int, ...); #endif -SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( +SQLITE_PRIVATE int tdsqlite3BtreeCloseCursor(BtCursor*); +SQLITE_PRIVATE int tdsqlite3BtreeMovetoUnpacked( BtCursor*, UnpackedRecord *pUnKey, i64 intKey, int bias, int *pRes ); -SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*); -SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags); +SQLITE_PRIVATE int tdsqlite3BtreeCursorHasMoved(BtCursor*); +SQLITE_PRIVATE int tdsqlite3BtreeCursorRestore(BtCursor*, int*); +SQLITE_PRIVATE int tdsqlite3BtreeDelete(BtCursor*, u8 flags); -/* Allowed flags for the 2nd argument to sqlite3BtreeDelete() */ +/* Allowed flags for tdsqlite3BtreeDelete() and tdsqlite3BtreeInsert() */ #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */ #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */ +#define BTREE_APPEND 0x08 /* Insert is likely an append */ /* An instance of the BtreePayload object describes the content of a single ** entry in either an index or table btree. ** ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain -** an arbitrary key and no data. These btrees have pKey,nKey set to their -** key and pData,nData,nZero set to zero. +** an arbitrary key and no data. These btrees have pKey,nKey set to the +** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem +** fields give an array of Mem objects that are a decomposition of the key. +** The nMem field might be zero, indicating that no decomposition is available. ** ** Table btrees (used for rowid tables) contain an integer rowid used as ** the key and passed in the nKey field. The pKey field is zero. ** pData,nData hold the content of the new entry. nZero extra zero bytes ** are appended to the end of the content when constructing the entry. +** The aMem,nMem fields are uninitialized for table btrees. +** +** Field usage summary: +** +** Table BTrees Index Btrees ** -** This object is used to pass information into sqlite3BtreeInsert(). The +** pKey always NULL encoded key +** nKey the ROWID length of pKey +** pData data not used +** aMem not used decomposed key value +** nMem not used entries in aMem +** nData length of pData not used +** nZero extra zeros after pData not used +** +** This object is used to pass information into tdsqlite3BtreeInsert(). The ** same information used to be passed as five separate parameters. But placing ** the information into this object helps to keep the interface more ** organized and understandable, and it also helps the resulting code to @@ -12293,53 +14930,63 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags); */ struct BtreePayload { const void *pKey; /* Key content for indexes. NULL for tables */ - sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */ - const void *pData; /* Data for tables. NULL for indexes */ + tdsqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */ + const void *pData; /* Data for tables. */ + tdsqlite3_value *aMem; /* First of nMem value in the unpacked pKey */ + u16 nMem; /* Number of aMem[] value. Might be zero */ int nData; /* Size of pData. 0 if none. */ int nZero; /* Extra zero data appended after pData,nData */ }; -SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload, - int bias, int seekResult); -SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); -SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); -SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes); -SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes); -SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); -SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt); -SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); - -SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); -SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload, + int flags, int seekResult); +SQLITE_PRIVATE int tdsqlite3BtreeFirst(BtCursor*, int *pRes); +SQLITE_PRIVATE int tdsqlite3BtreeLast(BtCursor*, int *pRes); +SQLITE_PRIVATE int tdsqlite3BtreeNext(BtCursor*, int flags); +SQLITE_PRIVATE int tdsqlite3BtreeEof(BtCursor*); +SQLITE_PRIVATE int tdsqlite3BtreePrevious(BtCursor*, int flags); +SQLITE_PRIVATE i64 tdsqlite3BtreeIntegerKey(BtCursor*); +SQLITE_PRIVATE void tdsqlite3BtreeCursorPin(BtCursor*); +SQLITE_PRIVATE void tdsqlite3BtreeCursorUnpin(BtCursor*); +#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC +SQLITE_PRIVATE i64 tdsqlite3BtreeOffset(BtCursor*); +#endif +SQLITE_PRIVATE int tdsqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE const void *tdsqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt); +SQLITE_PRIVATE u32 tdsqlite3BtreePayloadSize(BtCursor*); +SQLITE_PRIVATE tdsqlite3_int64 tdsqlite3BtreeMaxRecordSize(BtCursor*); + +SQLITE_PRIVATE char *tdsqlite3BtreeIntegrityCheck(tdsqlite3*,Btree*,int*aRoot,int nRoot,int,int*); +SQLITE_PRIVATE struct Pager *tdsqlite3BtreePager(Btree*); +SQLITE_PRIVATE i64 tdsqlite3BtreeRowCountEst(BtCursor*); #ifndef SQLITE_OMIT_INCRBLOB -SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); -SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *); +SQLITE_PRIVATE int tdsqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE int tdsqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE void tdsqlite3BtreeIncrblobCursor(BtCursor *); #endif -SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); -SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); -SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask); -SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt); -SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void); +SQLITE_PRIVATE void tdsqlite3BtreeClearCursor(BtCursor *); +SQLITE_PRIVATE int tdsqlite3BtreeSetVersion(Btree *pBt, int iVersion); +SQLITE_PRIVATE int tdsqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask); +SQLITE_PRIVATE int tdsqlite3BtreeIsReadonly(Btree *pBt); +SQLITE_PRIVATE int tdsqlite3HeaderSizeBtree(void); #ifndef NDEBUG -SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); +SQLITE_PRIVATE int tdsqlite3BtreeCursorIsValid(BtCursor*); #endif +SQLITE_PRIVATE int tdsqlite3BtreeCursorIsValidNN(BtCursor*); #ifndef SQLITE_OMIT_BTREECOUNT -SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); +SQLITE_PRIVATE int tdsqlite3BtreeCount(tdsqlite3*, BtCursor*, i64*); #endif #ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); -SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeCursorInfo(BtCursor*, int*, int); +SQLITE_PRIVATE void tdsqlite3BtreeCursorList(Btree*); #endif #ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); +SQLITE_PRIVATE int tdsqlite3BtreeCheckpoint(Btree*, int, int *, int *); #endif /* @@ -12348,38 +14995,38 @@ SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); ** Enter and Leave procedures no-ops. */ #ifndef SQLITE_OMIT_SHARED_CACHE -SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); -SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); -SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*); -SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*); +SQLITE_PRIVATE void tdsqlite3BtreeEnter(Btree*); +SQLITE_PRIVATE void tdsqlite3BtreeEnterAll(tdsqlite3*); +SQLITE_PRIVATE int tdsqlite3BtreeSharable(Btree*); +SQLITE_PRIVATE void tdsqlite3BtreeEnterCursor(BtCursor*); +SQLITE_PRIVATE int tdsqlite3BtreeConnectionCount(Btree*); #else -# define sqlite3BtreeEnter(X) -# define sqlite3BtreeEnterAll(X) -# define sqlite3BtreeSharable(X) 0 -# define sqlite3BtreeEnterCursor(X) -# define sqlite3BtreeConnectionCount(X) 1 +# define tdsqlite3BtreeEnter(X) +# define tdsqlite3BtreeEnterAll(X) +# define tdsqlite3BtreeSharable(X) 0 +# define tdsqlite3BtreeEnterCursor(X) +# define tdsqlite3BtreeConnectionCount(X) 1 #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE -SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); -SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); -SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); +SQLITE_PRIVATE void tdsqlite3BtreeLeave(Btree*); +SQLITE_PRIVATE void tdsqlite3BtreeLeaveCursor(BtCursor*); +SQLITE_PRIVATE void tdsqlite3BtreeLeaveAll(tdsqlite3*); #ifndef NDEBUG /* These routines are used inside assert() statements only. */ -SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); -SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); -SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); +SQLITE_PRIVATE int tdsqlite3BtreeHoldsMutex(Btree*); +SQLITE_PRIVATE int tdsqlite3BtreeHoldsAllMutexes(tdsqlite3*); +SQLITE_PRIVATE int tdsqlite3SchemaMutexHeld(tdsqlite3*,int,Schema*); #endif #else -# define sqlite3BtreeLeave(X) -# define sqlite3BtreeLeaveCursor(X) -# define sqlite3BtreeLeaveAll(X) +# define tdsqlite3BtreeLeave(X) +# define tdsqlite3BtreeLeaveCursor(X) +# define tdsqlite3BtreeLeaveAll(X) -# define sqlite3BtreeHoldsMutex(X) 1 -# define sqlite3BtreeHoldsAllMutexes(X) 1 -# define sqlite3SchemaMutexHeld(X,Y,Z) 1 +# define tdsqlite3BtreeHoldsMutex(X) 1 +# define tdsqlite3BtreeHoldsAllMutexes(X) 1 +# define tdsqlite3SchemaMutexHeld(X,Y,Z) 1 #endif @@ -12421,7 +15068,7 @@ typedef struct Vdbe Vdbe; ** The names of the following types declared in vdbeInt.h are required ** for the VdbeOp definition. */ -typedef struct Mem Mem; +typedef struct tdsqlite3_value Mem; typedef struct SubProgram SubProgram; /* @@ -12432,8 +15079,7 @@ typedef struct SubProgram SubProgram; struct VdbeOp { u8 opcode; /* What operation to perform */ signed char p4type; /* One of the P4_xxx constants for p4 */ - u8 notUsed1; - u8 p5; /* Fifth parameter is an unsigned character */ + u16 p5; /* Fifth parameter is an unsigned 16-bit integer */ int p1; /* First operand */ int p2; /* Second parameter (often the jump destination) */ int p3; /* The third parameter */ @@ -12444,7 +15090,7 @@ struct VdbeOp { i64 *pI64; /* Used when p4type is P4_INT64 */ double *pReal; /* Used when p4type is P4_REAL */ FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ - sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */ + tdsqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */ CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ Mem *pMem; /* Used when p4type is P4_MEM */ VTable *pVtab; /* Used when p4type is P4_VTAB */ @@ -12455,7 +15101,7 @@ struct VdbeOp { #ifdef SQLITE_ENABLE_CURSOR_HINTS Expr *pExpr; /* Used when p4type is P4_EXPR */ #endif - int (*xAdvance)(BtCursor *, int *); + int (*xAdvance)(BtCursor *, int); } p4; #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS char *zComment; /* Comment to improve readability */ @@ -12465,7 +15111,8 @@ struct VdbeOp { u64 cycles; /* Total time spent executing this instruction */ #endif #ifdef SQLITE_VDBE_COVERAGE - int iSrcLine; /* Source-code line that generated this opcode */ + u32 iSrcLine; /* Source-code line that generated this opcode + ** with flags in the upper 8 bits */ #endif }; typedef struct VdbeOp VdbeOp; @@ -12479,6 +15126,7 @@ struct SubProgram { int nOp; /* Elements in aOp[] */ int nMem; /* Number of memory cells required */ int nCsr; /* Number of cursors required */ + u8 *aOnce; /* Array of OP_Once flags */ void *token; /* id that may be used to recursive triggers */ SubProgram *pNext; /* Next sub-program already visited */ }; @@ -12498,25 +15146,27 @@ typedef struct VdbeOpList VdbeOpList; /* ** Allowed values of VdbeOp.p4type */ -#define P4_NOTUSED 0 /* The P4 parameter is not used */ -#define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ -#define P4_STATIC (-2) /* Pointer to a static string */ -#define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ -#define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ -#define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ -#define P4_EXPR (-7) /* P4 is a pointer to an Expr tree */ -#define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ -#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */ -#define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ -#define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ -#define P4_REAL (-12) /* P4 is a 64-bit floating point value */ -#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ -#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ -#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ -#define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ -#define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */ -#define P4_TABLE (-20) /* P4 is a pointer to a Table structure */ -#define P4_FUNCCTX (-21) /* P4 is a pointer to an sqlite3_context object */ +#define P4_NOTUSED 0 /* The P4 parameter is not used */ +#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */ +#define P4_STATIC (-1) /* Pointer to a static string */ +#define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */ +#define P4_INT32 (-3) /* P4 is a 32-bit signed integer */ +#define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */ +#define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */ +#define P4_TABLE (-6) /* P4 is a pointer to a Table structure */ +/* Above do not own any resources. Must free those below */ +#define P4_FREE_IF_LE (-7) +#define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */ +#define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */ +#define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */ +#define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */ +#define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */ +#define P4_VTAB (-12) /* P4 is a pointer to an tdsqlite3_vtab structure */ +#define P4_REAL (-13) /* P4 is a 64-bit floating point value */ +#define P4_INT64 (-14) /* P4 is a 64-bit signed integer */ +#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ +#define P4_FUNCCTX (-16) /* P4 is a pointer to an tdsqlite3_context object */ +#define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */ /* Error message codes for OP_Halt */ #define P5_ConstraintNotNull 1 @@ -12544,12 +15194,11 @@ typedef struct VdbeOpList VdbeOpList; #endif /* -** The following macro converts a relative address in the p2 field -** of a VdbeOp structure into a negative number so that -** sqlite3VdbeAddOpList() knows that the address is relative. Calling -** the macro again restores the address. +** The following macro converts a label returned by tdsqlite3VdbeMakeLabel() +** into an index into the Parse.aLabel[] array that contains the resolved +** address of that label. */ -#define ADDR(X) (-1-(X)) +#define ADDR(X) (~(X)) /* ** The makefile scans the vdbe.c source file and creates the "opcodes.h" @@ -12562,166 +15211,179 @@ typedef struct VdbeOpList VdbeOpList; #define OP_Savepoint 0 #define OP_AutoCommit 1 #define OP_Transaction 2 -#define OP_SorterNext 3 -#define OP_PrevIfOpen 4 -#define OP_NextIfOpen 5 -#define OP_Prev 6 -#define OP_Next 7 -#define OP_Checkpoint 8 -#define OP_JournalMode 9 -#define OP_Vacuum 10 -#define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */ -#define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */ -#define OP_Goto 13 -#define OP_Gosub 14 -#define OP_InitCoroutine 15 -#define OP_Yield 16 -#define OP_MustBeInt 17 -#define OP_Jump 18 +#define OP_SorterNext 3 /* jump */ +#define OP_Prev 4 /* jump */ +#define OP_Next 5 /* jump */ +#define OP_Checkpoint 6 +#define OP_JournalMode 7 +#define OP_Vacuum 8 +#define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */ +#define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */ +#define OP_Goto 11 /* jump */ +#define OP_Gosub 12 /* jump */ +#define OP_InitCoroutine 13 /* jump */ +#define OP_Yield 14 /* jump */ +#define OP_MustBeInt 15 /* jump */ +#define OP_Jump 16 /* jump */ +#define OP_Once 17 /* jump */ +#define OP_If 18 /* jump */ #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */ -#define OP_Once 20 -#define OP_If 21 -#define OP_IfNot 22 -#define OP_SeekLT 23 /* synopsis: key=r[P3@P4] */ -#define OP_SeekLE 24 /* synopsis: key=r[P3@P4] */ -#define OP_SeekGE 25 /* synopsis: key=r[P3@P4] */ -#define OP_SeekGT 26 /* synopsis: key=r[P3@P4] */ -#define OP_Or 27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */ -#define OP_And 28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */ -#define OP_NoConflict 29 /* synopsis: key=r[P3@P4] */ -#define OP_NotFound 30 /* synopsis: key=r[P3@P4] */ -#define OP_Found 31 /* synopsis: key=r[P3@P4] */ -#define OP_SeekRowid 32 /* synopsis: intkey=r[P3] */ -#define OP_NotExists 33 /* synopsis: intkey=r[P3] */ -#define OP_IsNull 34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */ -#define OP_NotNull 35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */ -#define OP_Ne 36 /* same as TK_NE, synopsis: IF r[P3]!=r[P1] */ -#define OP_Eq 37 /* same as TK_EQ, synopsis: IF r[P3]==r[P1] */ -#define OP_Gt 38 /* same as TK_GT, synopsis: IF r[P3]>r[P1] */ -#define OP_Le 39 /* same as TK_LE, synopsis: IF r[P3]<=r[P1] */ -#define OP_Lt 40 /* same as TK_LT, synopsis: IF r[P3]<r[P1] */ -#define OP_Ge 41 /* same as TK_GE, synopsis: IF r[P3]>=r[P1] */ -#define OP_ElseNotEq 42 /* same as TK_ESCAPE */ -#define OP_BitAnd 43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */ -#define OP_BitOr 44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */ -#define OP_ShiftLeft 45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */ -#define OP_ShiftRight 46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */ -#define OP_Add 47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */ -#define OP_Subtract 48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */ -#define OP_Multiply 49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */ -#define OP_Divide 50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */ -#define OP_Remainder 51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */ -#define OP_Concat 52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */ -#define OP_Last 53 -#define OP_BitNot 54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */ -#define OP_SorterSort 55 -#define OP_Sort 56 -#define OP_Rewind 57 -#define OP_IdxLE 58 /* synopsis: key=r[P3@P4] */ -#define OP_IdxGT 59 /* synopsis: key=r[P3@P4] */ -#define OP_IdxLT 60 /* synopsis: key=r[P3@P4] */ -#define OP_IdxGE 61 /* synopsis: key=r[P3@P4] */ -#define OP_RowSetRead 62 /* synopsis: r[P3]=rowset(P1) */ -#define OP_RowSetTest 63 /* synopsis: if r[P3] in rowset(P1) goto P2 */ -#define OP_Program 64 -#define OP_FkIfZero 65 /* synopsis: if fkctr[P1]==0 goto P2 */ -#define OP_IfPos 66 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ -#define OP_IfNotZero 67 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */ -#define OP_DecrJumpZero 68 /* synopsis: if (--r[P1])==0 goto P2 */ -#define OP_IncrVacuum 69 -#define OP_VNext 70 -#define OP_Init 71 /* synopsis: Start at P2 */ -#define OP_Return 72 -#define OP_EndCoroutine 73 -#define OP_HaltIfNull 74 /* synopsis: if r[P3]=null halt */ -#define OP_Halt 75 -#define OP_Integer 76 /* synopsis: r[P2]=P1 */ -#define OP_Int64 77 /* synopsis: r[P2]=P4 */ -#define OP_String 78 /* synopsis: r[P2]='P4' (len=P1) */ -#define OP_Null 79 /* synopsis: r[P2..P3]=NULL */ -#define OP_SoftNull 80 /* synopsis: r[P1]=NULL */ -#define OP_Blob 81 /* synopsis: r[P2]=P4 (len=P1) */ -#define OP_Variable 82 /* synopsis: r[P2]=parameter(P1,P4) */ -#define OP_Move 83 /* synopsis: r[P2@P3]=r[P1@P3] */ -#define OP_Copy 84 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ -#define OP_SCopy 85 /* synopsis: r[P2]=r[P1] */ -#define OP_IntCopy 86 /* synopsis: r[P2]=r[P1] */ -#define OP_ResultRow 87 /* synopsis: output=r[P1@P2] */ -#define OP_CollSeq 88 -#define OP_Function0 89 /* synopsis: r[P3]=func(r[P2@P5]) */ -#define OP_Function 90 /* synopsis: r[P3]=func(r[P2@P5]) */ -#define OP_AddImm 91 /* synopsis: r[P1]=r[P1]+P2 */ -#define OP_RealAffinity 92 -#define OP_Cast 93 /* synopsis: affinity(r[P1]) */ -#define OP_Permutation 94 -#define OP_Compare 95 /* synopsis: r[P1@P3] <-> r[P2@P3] */ -#define OP_Column 96 /* synopsis: r[P3]=PX */ -#define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */ -#define OP_Affinity 98 /* synopsis: affinity(r[P1@P2]) */ -#define OP_MakeRecord 99 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ -#define OP_Count 100 /* synopsis: r[P2]=count() */ -#define OP_ReadCookie 101 -#define OP_SetCookie 102 -#define OP_ReopenIdx 103 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenRead 104 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenWrite 105 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenAutoindex 106 /* synopsis: nColumn=P2 */ -#define OP_OpenEphemeral 107 /* synopsis: nColumn=P2 */ -#define OP_SorterOpen 108 -#define OP_SequenceTest 109 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */ -#define OP_OpenPseudo 110 /* synopsis: P3 columns in r[P2] */ -#define OP_Close 111 -#define OP_ColumnsUsed 112 -#define OP_Sequence 113 /* synopsis: r[P2]=cursor[P1].ctr++ */ -#define OP_NewRowid 114 /* synopsis: r[P2]=rowid */ -#define OP_Insert 115 /* synopsis: intkey=r[P3] data=r[P2] */ -#define OP_InsertInt 116 /* synopsis: intkey=P3 data=r[P2] */ -#define OP_Delete 117 -#define OP_ResetCount 118 -#define OP_SorterCompare 119 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ -#define OP_SorterData 120 /* synopsis: r[P2]=data */ -#define OP_RowKey 121 /* synopsis: r[P2]=key */ -#define OP_RowData 122 /* synopsis: r[P2]=data */ -#define OP_Rowid 123 /* synopsis: r[P2]=rowid */ -#define OP_NullRow 124 -#define OP_SorterInsert 125 -#define OP_IdxInsert 126 /* synopsis: key=r[P2] */ -#define OP_IdxDelete 127 /* synopsis: key=r[P2@P3] */ -#define OP_Seek 128 /* synopsis: Move P3 to P1.rowid */ -#define OP_IdxRowid 129 /* synopsis: r[P2]=rowid */ -#define OP_Destroy 130 -#define OP_Clear 131 -#define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ -#define OP_ResetSorter 133 -#define OP_CreateIndex 134 /* synopsis: r[P2]=root iDb=P1 */ -#define OP_CreateTable 135 /* synopsis: r[P2]=root iDb=P1 */ -#define OP_ParseSchema 136 -#define OP_LoadAnalysis 137 -#define OP_DropTable 138 -#define OP_DropIndex 139 -#define OP_DropTrigger 140 -#define OP_IntegrityCk 141 -#define OP_RowSetAdd 142 /* synopsis: rowset(P1)=r[P2] */ -#define OP_Param 143 -#define OP_FkCounter 144 /* synopsis: fkctr[P1]+=P2 */ -#define OP_MemMax 145 /* synopsis: r[P1]=max(r[P1],r[P2]) */ -#define OP_OffsetLimit 146 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ -#define OP_AggStep0 147 /* synopsis: accum=r[P3] step(r[P2@P5]) */ -#define OP_AggStep 148 /* synopsis: accum=r[P3] step(r[P2@P5]) */ -#define OP_AggFinal 149 /* synopsis: accum=r[P1] N=P2 */ -#define OP_Expire 150 -#define OP_TableLock 151 /* synopsis: iDb=P1 root=P2 write=P3 */ -#define OP_VBegin 152 -#define OP_VCreate 153 -#define OP_VDestroy 154 -#define OP_VOpen 155 -#define OP_VColumn 156 /* synopsis: r[P3]=vcolumn(P2) */ -#define OP_VRename 157 -#define OP_Pagecount 158 -#define OP_MaxPgcnt 159 -#define OP_CursorHint 160 -#define OP_Noop 161 -#define OP_Explain 162 +#define OP_IfNot 20 /* jump */ +#define OP_IfNullRow 21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */ +#define OP_SeekLT 22 /* jump, synopsis: key=r[P3@P4] */ +#define OP_SeekLE 23 /* jump, synopsis: key=r[P3@P4] */ +#define OP_SeekGE 24 /* jump, synopsis: key=r[P3@P4] */ +#define OP_SeekGT 25 /* jump, synopsis: key=r[P3@P4] */ +#define OP_IfNotOpen 26 /* jump, synopsis: if( !csr[P1] ) goto P2 */ +#define OP_IfNoHope 27 /* jump, synopsis: key=r[P3@P4] */ +#define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */ +#define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */ +#define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */ +#define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */ +#define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */ +#define OP_Last 33 /* jump */ +#define OP_IfSmaller 34 /* jump */ +#define OP_SorterSort 35 /* jump */ +#define OP_Sort 36 /* jump */ +#define OP_Rewind 37 /* jump */ +#define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */ +#define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */ +#define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */ +#define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */ +#define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */ +#define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */ +#define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */ +#define OP_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */ +#define OP_Program 46 /* jump */ +#define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */ +#define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ +#define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */ +#define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */ +#define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */ +#define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */ +#define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */ +#define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */ +#define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */ +#define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */ +#define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */ +#define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */ +#define OP_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */ +#define OP_IncrVacuum 60 /* jump */ +#define OP_VNext 61 /* jump */ +#define OP_Init 62 /* jump, synopsis: Start at P2 */ +#define OP_PureFunc 63 /* synopsis: r[P3]=func(r[P2@P5]) */ +#define OP_Function 64 /* synopsis: r[P3]=func(r[P2@P5]) */ +#define OP_Return 65 +#define OP_EndCoroutine 66 +#define OP_HaltIfNull 67 /* synopsis: if r[P3]=null halt */ +#define OP_Halt 68 +#define OP_Integer 69 /* synopsis: r[P2]=P1 */ +#define OP_Int64 70 /* synopsis: r[P2]=P4 */ +#define OP_String 71 /* synopsis: r[P2]='P4' (len=P1) */ +#define OP_Null 72 /* synopsis: r[P2..P3]=NULL */ +#define OP_SoftNull 73 /* synopsis: r[P1]=NULL */ +#define OP_Blob 74 /* synopsis: r[P2]=P4 (len=P1) */ +#define OP_Variable 75 /* synopsis: r[P2]=parameter(P1,P4) */ +#define OP_Move 76 /* synopsis: r[P2@P3]=r[P1@P3] */ +#define OP_Copy 77 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ +#define OP_SCopy 78 /* synopsis: r[P2]=r[P1] */ +#define OP_IntCopy 79 /* synopsis: r[P2]=r[P1] */ +#define OP_ResultRow 80 /* synopsis: output=r[P1@P2] */ +#define OP_CollSeq 81 +#define OP_AddImm 82 /* synopsis: r[P1]=r[P1]+P2 */ +#define OP_RealAffinity 83 +#define OP_Cast 84 /* synopsis: affinity(r[P1]) */ +#define OP_Permutation 85 +#define OP_Compare 86 /* synopsis: r[P1@P3] <-> r[P2@P3] */ +#define OP_IsTrue 87 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */ +#define OP_Offset 88 /* synopsis: r[P3] = sqlite_offset(P1) */ +#define OP_Column 89 /* synopsis: r[P3]=PX */ +#define OP_Affinity 90 /* synopsis: affinity(r[P1@P2]) */ +#define OP_MakeRecord 91 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ +#define OP_Count 92 /* synopsis: r[P2]=count() */ +#define OP_ReadCookie 93 +#define OP_SetCookie 94 +#define OP_ReopenIdx 95 /* synopsis: root=P2 iDb=P3 */ +#define OP_OpenRead 96 /* synopsis: root=P2 iDb=P3 */ +#define OP_OpenWrite 97 /* synopsis: root=P2 iDb=P3 */ +#define OP_OpenDup 98 +#define OP_OpenAutoindex 99 /* synopsis: nColumn=P2 */ +#define OP_OpenEphemeral 100 /* synopsis: nColumn=P2 */ +#define OP_BitAnd 101 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */ +#define OP_BitOr 102 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */ +#define OP_ShiftLeft 103 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */ +#define OP_ShiftRight 104 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */ +#define OP_Add 105 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */ +#define OP_Subtract 106 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */ +#define OP_Multiply 107 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */ +#define OP_Divide 108 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */ +#define OP_Remainder 109 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */ +#define OP_Concat 110 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */ +#define OP_SorterOpen 111 +#define OP_BitNot 112 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */ +#define OP_SequenceTest 113 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */ +#define OP_OpenPseudo 114 /* synopsis: P3 columns in r[P2] */ +#define OP_String8 115 /* same as TK_STRING, synopsis: r[P2]='P4' */ +#define OP_Close 116 +#define OP_ColumnsUsed 117 +#define OP_SeekHit 118 /* synopsis: seekHit=P2 */ +#define OP_Sequence 119 /* synopsis: r[P2]=cursor[P1].ctr++ */ +#define OP_NewRowid 120 /* synopsis: r[P2]=rowid */ +#define OP_Insert 121 /* synopsis: intkey=r[P3] data=r[P2] */ +#define OP_Delete 122 +#define OP_ResetCount 123 +#define OP_SorterCompare 124 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ +#define OP_SorterData 125 /* synopsis: r[P2]=data */ +#define OP_RowData 126 /* synopsis: r[P2]=data */ +#define OP_Rowid 127 /* synopsis: r[P2]=rowid */ +#define OP_NullRow 128 +#define OP_SeekEnd 129 +#define OP_SorterInsert 130 /* synopsis: key=r[P2] */ +#define OP_IdxInsert 131 /* synopsis: key=r[P2] */ +#define OP_IdxDelete 132 /* synopsis: key=r[P2@P3] */ +#define OP_DeferredSeek 133 /* synopsis: Move P3 to P1.rowid if needed */ +#define OP_IdxRowid 134 /* synopsis: r[P2]=rowid */ +#define OP_FinishSeek 135 +#define OP_Destroy 136 +#define OP_Clear 137 +#define OP_ResetSorter 138 +#define OP_CreateBtree 139 /* synopsis: r[P2]=root iDb=P1 flags=P3 */ +#define OP_SqlExec 140 +#define OP_ParseSchema 141 +#define OP_LoadAnalysis 142 +#define OP_DropTable 143 +#define OP_DropIndex 144 +#define OP_DropTrigger 145 +#define OP_IntegrityCk 146 +#define OP_RowSetAdd 147 /* synopsis: rowset(P1)=r[P2] */ +#define OP_Param 148 +#define OP_FkCounter 149 /* synopsis: fkctr[P1]+=P2 */ +#define OP_Real 150 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ +#define OP_MemMax 151 /* synopsis: r[P1]=max(r[P1],r[P2]) */ +#define OP_OffsetLimit 152 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ +#define OP_AggInverse 153 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */ +#define OP_AggStep 154 /* synopsis: accum=r[P3] step(r[P2@P5]) */ +#define OP_AggStep1 155 /* synopsis: accum=r[P3] step(r[P2@P5]) */ +#define OP_AggValue 156 /* synopsis: r[P3]=value N=P2 */ +#define OP_AggFinal 157 /* synopsis: accum=r[P1] N=P2 */ +#define OP_Expire 158 +#define OP_CursorLock 159 +#define OP_CursorUnlock 160 +#define OP_TableLock 161 /* synopsis: iDb=P1 root=P2 write=P3 */ +#define OP_VBegin 162 +#define OP_VCreate 163 +#define OP_VDestroy 164 +#define OP_VOpen 165 +#define OP_VColumn 166 /* synopsis: r[P3]=vcolumn(P2) */ +#define OP_VRename 167 +#define OP_Pagecount 168 +#define OP_MaxPgcnt 169 +#define OP_Trace 170 +#define OP_CursorHint 171 +#define OP_ReleaseReg 172 /* synopsis: release r[P1@P2] mask P3 */ +#define OP_Noop 173 +#define OP_Explain 174 +#define OP_Abortable 175 /* Properties such as "out2" or "jump" that are specified in ** comments following the "case" for each opcode in the vdbe.c @@ -12734,114 +15396,162 @@ typedef struct VdbeOpList VdbeOpList; #define OPFLG_OUT2 0x10 /* out2: P2 is an output */ #define OPFLG_OUT3 0x20 /* out3: P3 is an output */ #define OPFLG_INITIALIZER {\ -/* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\ -/* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\ -/* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\ -/* 24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\ -/* 32 */ 0x09, 0x09, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\ -/* 40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\ -/* 48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\ -/* 56 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b,\ -/* 64 */ 0x01, 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x01,\ -/* 72 */ 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10,\ -/* 80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00,\ -/* 88 */ 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\ -/* 96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\ -/* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 112 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00,\ -/* 128 */ 0x00, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10,\ -/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10,\ -/* 144 */ 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\ -/* 160 */ 0x00, 0x00, 0x00,} - -/* The sqlite3P2Values() routine is able to run faster if it knows +/* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\ +/* 8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\ +/* 16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\ +/* 24 */ 0x09, 0x09, 0x01, 0x09, 0x09, 0x09, 0x09, 0x09,\ +/* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\ +/* 40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\ +/* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\ +/* 56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00,\ +/* 64 */ 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10,\ +/* 72 */ 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10,\ +/* 80 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12,\ +/* 88 */ 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\ +/* 96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26, 0x26,\ +/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\ +/* 112 */ 0x12, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10,\ +/* 120 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\ +/* 128 */ 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10, 0x00,\ +/* 136 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\ +/* 144 */ 0x00, 0x00, 0x00, 0x06, 0x10, 0x00, 0x10, 0x04,\ +/* 152 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ +/* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ +/* 168 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ +} + +/* The tdsqlite3P2Values() routine is able to run faster if it knows ** the value of the largest JUMP opcode. The smaller the maximum ** JUMP opcode the better, so the mkopcodeh.tcl script that ** generated this include file strives to group all JUMP opcodes ** together near the beginning of the list. */ -#define SQLITE_MX_JUMP_OPCODE 71 /* Maximum JUMP opcode */ +#define SQLITE_MX_JUMP_OPCODE 62 /* Maximum JUMP opcode */ /************** End of opcodes.h *********************************************/ /************** Continuing where we left off in vdbe.h ***********************/ /* +** Additional non-public SQLITE_PREPARE_* flags +*/ +#define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */ +#define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */ + +/* ** Prototypes for the VDBE interface. See comments on the implementation ** for a description of what each of these routines does. */ -SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*); -SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*); -SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...); -SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); -SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int); +SQLITE_PRIVATE Vdbe *tdsqlite3VdbeCreate(Parse*); +SQLITE_PRIVATE Parse *tdsqlite3VdbeParser(Vdbe*); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp0(Vdbe*,int); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp1(Vdbe*,int,int); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp2(Vdbe*,int,int,int); +SQLITE_PRIVATE int tdsqlite3VdbeGoto(Vdbe*,int); +SQLITE_PRIVATE int tdsqlite3VdbeLoadString(Vdbe*,int,const char*); +SQLITE_PRIVATE void tdsqlite3VdbeMultiLoad(Vdbe*,int,const char*,...); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp3(Vdbe*,int,int,int,int); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); +SQLITE_PRIVATE int tdsqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int); +SQLITE_PRIVATE void tdsqlite3VdbeEndCoroutine(Vdbe*,int); #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) -SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N); -#else -# define sqlite3VdbeVerifyNoMallocRequired(A,B) -#endif -SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno); -SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); -SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8); -SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1); -SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2); -SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3); -SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); -SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); -SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr); -SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op); -SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); -SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*); -SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); -SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); -SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*); -SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); -SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N); +SQLITE_PRIVATE void tdsqlite3VdbeVerifyNoResultRow(Vdbe *p); +#else +# define tdsqlite3VdbeVerifyNoMallocRequired(A,B) +# define tdsqlite3VdbeVerifyNoResultRow(A) +#endif +#if defined(SQLITE_DEBUG) +SQLITE_PRIVATE void tdsqlite3VdbeVerifyAbortable(Vdbe *p, int); +#else +# define tdsqlite3VdbeVerifyAbortable(A,B) +#endif +SQLITE_PRIVATE VdbeOp *tdsqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno); +#ifndef SQLITE_OMIT_EXPLAIN +SQLITE_PRIVATE void tdsqlite3VdbeExplain(Parse*,u8,const char*,...); +SQLITE_PRIVATE void tdsqlite3VdbeExplainPop(Parse*); +SQLITE_PRIVATE int tdsqlite3VdbeExplainParent(Parse*); +# define ExplainQueryPlan(P) tdsqlite3VdbeExplain P +# define ExplainQueryPlanPop(P) tdsqlite3VdbeExplainPop(P) +# define ExplainQueryPlanParent(P) tdsqlite3VdbeExplainParent(P) +#else +# define ExplainQueryPlan(P) +# define ExplainQueryPlanPop(P) +# define ExplainQueryPlanParent(P) 0 +# define tdsqlite3ExplainBreakpoint(A,B) /*no-op*/ +#endif +#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN) +SQLITE_PRIVATE void tdsqlite3ExplainBreakpoint(const char*,const char*); +#else +# define tdsqlite3ExplainBreakpoint(A,B) /*no-op*/ +#endif +SQLITE_PRIVATE void tdsqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); +SQLITE_PRIVATE void tdsqlite3VdbeChangeOpcode(Vdbe*, int addr, u8); +SQLITE_PRIVATE void tdsqlite3VdbeChangeP1(Vdbe*, int addr, int P1); +SQLITE_PRIVATE void tdsqlite3VdbeChangeP2(Vdbe*, int addr, int P2); +SQLITE_PRIVATE void tdsqlite3VdbeChangeP3(Vdbe*, int addr, int P3); +SQLITE_PRIVATE void tdsqlite3VdbeChangeP5(Vdbe*, u16 P5); +SQLITE_PRIVATE void tdsqlite3VdbeJumpHere(Vdbe*, int addr); +SQLITE_PRIVATE int tdsqlite3VdbeChangeToNoop(Vdbe*, int addr); +SQLITE_PRIVATE int tdsqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op); #ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); -#endif -SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*); -SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); -SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); -SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); -SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); -SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); -SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8); -SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); +SQLITE_PRIVATE void tdsqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int); +#else +# define tdsqlite3VdbeReleaseRegisters(P,A,N,M,F) +#endif +SQLITE_PRIVATE void tdsqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); +SQLITE_PRIVATE void tdsqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type); +SQLITE_PRIVATE void tdsqlite3VdbeSetP4KeyInfo(Parse*, Index*); +SQLITE_PRIVATE void tdsqlite3VdbeUsesBtree(Vdbe*, int); +SQLITE_PRIVATE VdbeOp *tdsqlite3VdbeGetOp(Vdbe*, int); +SQLITE_PRIVATE int tdsqlite3VdbeMakeLabel(Parse*); +SQLITE_PRIVATE void tdsqlite3VdbeRunOnlyOnce(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeReusable(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeDelete(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeClearObject(tdsqlite3*,Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeMakeReady(Vdbe*,Parse*); +SQLITE_PRIVATE int tdsqlite3VdbeFinalize(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeResolveLabel(Vdbe*, int); +SQLITE_PRIVATE int tdsqlite3VdbeCurrentAddr(Vdbe*); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int tdsqlite3VdbeAssertMayAbort(Vdbe *, int); +#endif +SQLITE_PRIVATE void tdsqlite3VdbeResetStepResult(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeRewind(Vdbe*); +SQLITE_PRIVATE int tdsqlite3VdbeReset(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeSetNumCols(Vdbe*,int); +SQLITE_PRIVATE int tdsqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); +SQLITE_PRIVATE void tdsqlite3VdbeCountChanges(Vdbe*); +SQLITE_PRIVATE tdsqlite3 *tdsqlite3VdbeDb(Vdbe*); +SQLITE_PRIVATE u8 tdsqlite3VdbePrepareFlags(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8); +#ifdef SQLITE_ENABLE_NORMALIZE +SQLITE_PRIVATE void tdsqlite3VdbeAddDblquoteStr(tdsqlite3*,Vdbe*,const char*); +SQLITE_PRIVATE int tdsqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*); +#endif +SQLITE_PRIVATE void tdsqlite3VdbeSwap(Vdbe*,Vdbe*); +SQLITE_PRIVATE VdbeOp *tdsqlite3VdbeTakeOpArray(Vdbe*, int*, int*); +SQLITE_PRIVATE tdsqlite3_value *tdsqlite3VdbeGetBoundValue(Vdbe*, int, u8); +SQLITE_PRIVATE void tdsqlite3VdbeSetVarmask(Vdbe*, int); #ifndef SQLITE_OMIT_TRACE -SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*); +SQLITE_PRIVATE char *tdsqlite3VdbeExpandSql(Vdbe*, const char*); #endif -SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); +SQLITE_PRIVATE int tdsqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); +SQLITE_PRIVATE int tdsqlite3BlobCompare(const Mem*, const Mem*); -SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); -SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); -SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int); -SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **); +SQLITE_PRIVATE void tdsqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); +SQLITE_PRIVATE int tdsqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); +SQLITE_PRIVATE int tdsqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int); +SQLITE_PRIVATE UnpackedRecord *tdsqlite3VdbeAllocUnpackedRecord(KeyInfo*); typedef int (*RecordCompare)(int,const void*,UnpackedRecord*); -SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*); +SQLITE_PRIVATE RecordCompare tdsqlite3VdbeFindCompare(UnpackedRecord*); -#ifndef SQLITE_OMIT_TRIGGER -SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); -#endif +SQLITE_PRIVATE void tdsqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); +SQLITE_PRIVATE int tdsqlite3VdbeHasSubProgram(Vdbe*); + +SQLITE_PRIVATE int tdsqlite3NotPureFunc(tdsqlite3_context*); /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on ** each VDBE opcode. @@ -12851,12 +15561,12 @@ SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); ** generator. */ #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS -SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); -# define VdbeComment(X) sqlite3VdbeComment X -SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); -# define VdbeNoopComment(X) sqlite3VdbeNoopComment X +SQLITE_PRIVATE void tdsqlite3VdbeComment(Vdbe*, const char*, ...); +# define VdbeComment(X) tdsqlite3VdbeComment X +SQLITE_PRIVATE void tdsqlite3VdbeNoopComment(Vdbe*, const char*, ...); +# define VdbeNoopComment(X) tdsqlite3VdbeNoopComment X # ifdef SQLITE_ENABLE_MODULE_COMMENTS -# define VdbeModuleComment(X) sqlite3VdbeNoopComment X +# define VdbeModuleComment(X) tdsqlite3VdbeNoopComment X # else # define VdbeModuleComment(X) # endif @@ -12883,30 +15593,63 @@ SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); ** ** VdbeCoverageNeverTaken(v) // Previous branch is never taken ** +** VdbeCoverageNeverNull(v) // Previous three-way branch is only +** // taken on the first two ways. The +** // NULL option is not possible +** +** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested +** // in distingishing equal and not-equal. +** ** Every VDBE branch operation must be tagged with one of the macros above. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch() ** routine in vdbe.c, alerting the developer to the missed tag. +** +** During testing, the test application will invoke +** tdsqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback +** routine that is invoked as each bytecode branch is taken. The callback +** contains the sqlite3.c source line number ov the VdbeCoverage macro and +** flags to indicate whether or not the branch was taken. The test application +** is responsible for keeping track of this and reporting byte-code branches +** that are never taken. +** +** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the +** vdbe.c source file for additional information. */ #ifdef SQLITE_VDBE_COVERAGE -SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int); -# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__) -# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__) -# define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2); -# define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1); +SQLITE_PRIVATE void tdsqlite3VdbeSetLineNumber(Vdbe*,int); +# define VdbeCoverage(v) tdsqlite3VdbeSetLineNumber(v,__LINE__) +# define VdbeCoverageIf(v,x) if(x)tdsqlite3VdbeSetLineNumber(v,__LINE__) +# define VdbeCoverageAlwaysTaken(v) \ + tdsqlite3VdbeSetLineNumber(v,__LINE__|0x5000000); +# define VdbeCoverageNeverTaken(v) \ + tdsqlite3VdbeSetLineNumber(v,__LINE__|0x6000000); +# define VdbeCoverageNeverNull(v) \ + tdsqlite3VdbeSetLineNumber(v,__LINE__|0x4000000); +# define VdbeCoverageNeverNullIf(v,x) \ + if(x)tdsqlite3VdbeSetLineNumber(v,__LINE__|0x4000000); +# define VdbeCoverageEqNe(v) \ + tdsqlite3VdbeSetLineNumber(v,__LINE__|0x8000000); # define VDBE_OFFSET_LINENO(x) (__LINE__+x) #else # define VdbeCoverage(v) # define VdbeCoverageIf(v,x) # define VdbeCoverageAlwaysTaken(v) # define VdbeCoverageNeverTaken(v) +# define VdbeCoverageNeverNull(v) +# define VdbeCoverageNeverNullIf(v,x) +# define VdbeCoverageEqNe(v) # define VDBE_OFFSET_LINENO(x) 0 #endif #ifdef SQLITE_ENABLE_STMT_SCANSTATUS -SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*); +SQLITE_PRIVATE void tdsqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*); #else -# define sqlite3VdbeScanStatus(a,b,c,d,e) +# define tdsqlite3VdbeScanStatus(a,b,c,d,e) +#endif + +#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) +SQLITE_PRIVATE void tdsqlite3VdbePrintOp(FILE*, int, VdbeOp*); #endif #endif /* SQLITE_VDBE_H */ @@ -12937,7 +15680,7 @@ SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const ch /* ** Default maximum size for persistent journal files. A negative ** value means no limit. This value may be overridden using the -** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". +** tdsqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". */ #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 @@ -12970,7 +15713,7 @@ typedef struct PgHdr DbPage; #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) /* -** Allowed values for the flags parameter to sqlite3PagerOpen(). +** Allowed values for the flags parameter to tdsqlite3PagerOpen(). ** ** NOTE: These values must match the corresponding BTREE_ values in btree.h. */ @@ -12978,7 +15721,7 @@ typedef struct PgHdr DbPage; #define PAGER_MEMORY 0x0002 /* In-memory database */ /* -** Valid values for the second argument to sqlite3PagerLockingMode(). +** Valid values for the second argument to tdsqlite3PagerLockingMode(). */ #define PAGER_LOCKINGMODE_QUERY -1 #define PAGER_LOCKINGMODE_NORMAL 0 @@ -13000,13 +15743,13 @@ typedef struct PgHdr DbPage; #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ /* -** Flags that make up the mask passed to sqlite3PagerGet(). +** Flags that make up the mask passed to tdsqlite3PagerGet(). */ #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */ #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */ /* -** Flags for sqlite3PagerSetFlags() +** Flags for tdsqlite3PagerSetFlags() ** ** Value constraints (enforced via assert()): ** PAGER_FULLFSYNC == SQLITE_FullFSync @@ -13030,8 +15773,8 @@ typedef struct PgHdr DbPage; */ /* Open and close a Pager connection. */ -SQLITE_PRIVATE int sqlite3PagerOpen( - sqlite3_vfs*, +SQLITE_PRIVATE int tdsqlite3PagerOpen( + tdsqlite3_vfs*, Pager **ppPager, const char*, int, @@ -13039,110 +15782,120 @@ SQLITE_PRIVATE int sqlite3PagerOpen( int, void(*)(DbPage*) ); -SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); +SQLITE_PRIVATE int tdsqlite3PagerClose(Pager *pPager, tdsqlite3*); +SQLITE_PRIVATE int tdsqlite3PagerReadFileheader(Pager*, int, unsigned char*); /* Functions used to configure a Pager object. */ -SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); -SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int); +SQLITE_PRIVATE void tdsqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *); +SQLITE_PRIVATE int tdsqlite3PagerSetPagesize(Pager*, u32*, int); #ifdef SQLITE_HAS_CODEC -SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*); -#endif -SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); -SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); -SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int); -SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64); -SQLITE_PRIVATE void sqlite3PagerShrink(Pager*); -SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned); -SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); -SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int); -SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*); -SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*); -SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); -SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); -SQLITE_PRIVATE int sqlite3PagerFlush(Pager*); +SQLITE_PRIVATE void tdsqlite3PagerAlignReserve(Pager*,Pager*); +#endif +SQLITE_PRIVATE int tdsqlite3PagerMaxPageCount(Pager*, int); +SQLITE_PRIVATE void tdsqlite3PagerSetCachesize(Pager*, int); +SQLITE_PRIVATE int tdsqlite3PagerSetSpillsize(Pager*, int); +SQLITE_PRIVATE void tdsqlite3PagerSetMmapLimit(Pager *, tdsqlite3_int64); +SQLITE_PRIVATE void tdsqlite3PagerShrink(Pager*); +SQLITE_PRIVATE void tdsqlite3PagerSetFlags(Pager*,unsigned); +SQLITE_PRIVATE int tdsqlite3PagerLockingMode(Pager *, int); +SQLITE_PRIVATE int tdsqlite3PagerSetJournalMode(Pager *, int); +SQLITE_PRIVATE int tdsqlite3PagerGetJournalMode(Pager*); +SQLITE_PRIVATE int tdsqlite3PagerOkToChangeJournalMode(Pager*); +SQLITE_PRIVATE i64 tdsqlite3PagerJournalSizeLimit(Pager *, i64); +SQLITE_PRIVATE tdsqlite3_backup **tdsqlite3PagerBackupPtr(Pager*); +SQLITE_PRIVATE int tdsqlite3PagerFlush(Pager*); /* Functions used to obtain and release page references. */ -SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); -SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); -SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); -SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); -SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*); +SQLITE_PRIVATE int tdsqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); +SQLITE_PRIVATE DbPage *tdsqlite3PagerLookup(Pager *pPager, Pgno pgno); +SQLITE_PRIVATE void tdsqlite3PagerRef(DbPage*); +SQLITE_PRIVATE void tdsqlite3PagerUnref(DbPage*); +SQLITE_PRIVATE void tdsqlite3PagerUnrefNotNull(DbPage*); +SQLITE_PRIVATE void tdsqlite3PagerUnrefPageOne(DbPage*); /* Operations on page references. */ -SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); -SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); -SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); -SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); -SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); -SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); +SQLITE_PRIVATE int tdsqlite3PagerWrite(DbPage*); +SQLITE_PRIVATE void tdsqlite3PagerDontWrite(DbPage*); +SQLITE_PRIVATE int tdsqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); +SQLITE_PRIVATE int tdsqlite3PagerPageRefcount(DbPage*); +SQLITE_PRIVATE void *tdsqlite3PagerGetData(DbPage *); +SQLITE_PRIVATE void *tdsqlite3PagerGetExtra(DbPage *); /* Functions used to manage pager transactions and savepoints. */ -SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*); -SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); -SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); -SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); -SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster); -SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); -SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); -SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); -SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); -SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); +SQLITE_PRIVATE void tdsqlite3PagerPagecount(Pager*, int*); +SQLITE_PRIVATE int tdsqlite3PagerBegin(Pager*, int exFlag, int); +SQLITE_PRIVATE int tdsqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); +SQLITE_PRIVATE int tdsqlite3PagerExclusiveLock(Pager*); +SQLITE_PRIVATE int tdsqlite3PagerSync(Pager *pPager, const char *zMaster); +SQLITE_PRIVATE int tdsqlite3PagerCommitPhaseTwo(Pager*); +SQLITE_PRIVATE int tdsqlite3PagerRollback(Pager*); +SQLITE_PRIVATE int tdsqlite3PagerOpenSavepoint(Pager *pPager, int n); +SQLITE_PRIVATE int tdsqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); +SQLITE_PRIVATE int tdsqlite3PagerSharedLock(Pager *pPager); #ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*); -SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); -SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager); +SQLITE_PRIVATE int tdsqlite3PagerCheckpoint(Pager *pPager, tdsqlite3*, int, int*, int*); +SQLITE_PRIVATE int tdsqlite3PagerWalSupported(Pager *pPager); +SQLITE_PRIVATE int tdsqlite3PagerWalCallback(Pager *pPager); +SQLITE_PRIVATE int tdsqlite3PagerOpenWal(Pager *pPager, int *pisOpen); +SQLITE_PRIVATE int tdsqlite3PagerCloseWal(Pager *pPager, tdsqlite3*); # ifdef SQLITE_ENABLE_SNAPSHOT -SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot); -SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot); +SQLITE_PRIVATE int tdsqlite3PagerSnapshotGet(Pager *pPager, tdsqlite3_snapshot **ppSnapshot); +SQLITE_PRIVATE int tdsqlite3PagerSnapshotOpen(Pager *pPager, tdsqlite3_snapshot *pSnapshot); +SQLITE_PRIVATE int tdsqlite3PagerSnapshotRecover(Pager *pPager); +SQLITE_PRIVATE int tdsqlite3PagerSnapshotCheck(Pager *pPager, tdsqlite3_snapshot *pSnapshot); +SQLITE_PRIVATE void tdsqlite3PagerSnapshotUnlock(Pager *pPager); # endif -#else -# define sqlite3PagerUseWal(x) 0 +#endif + +#ifdef SQLITE_DIRECT_OVERFLOW_READ +SQLITE_PRIVATE int tdsqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno); #endif #ifdef SQLITE_ENABLE_ZIPVFS -SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager); +SQLITE_PRIVATE int tdsqlite3PagerWalFramesize(Pager *pPager); #endif /* Functions used to query pager state and configuration. */ -SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); -SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*); +SQLITE_PRIVATE u8 tdsqlite3PagerIsreadonly(Pager*); +SQLITE_PRIVATE u32 tdsqlite3PagerDataVersion(Pager*); #ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); -#endif -SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*); -SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int); -SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*); -SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); -SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*); -SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); -SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); -SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); -SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *); -SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*); -SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *); +SQLITE_PRIVATE int tdsqlite3PagerRefcount(Pager*); +#endif +SQLITE_PRIVATE int tdsqlite3PagerMemUsed(Pager*); +SQLITE_PRIVATE const char *tdsqlite3PagerFilename(const Pager*, int); +SQLITE_PRIVATE tdsqlite3_vfs *tdsqlite3PagerVfs(Pager*); +SQLITE_PRIVATE tdsqlite3_file *tdsqlite3PagerFile(Pager*); +SQLITE_PRIVATE tdsqlite3_file *tdsqlite3PagerJrnlFile(Pager*); +SQLITE_PRIVATE const char *tdsqlite3PagerJournalname(Pager*); +SQLITE_PRIVATE void *tdsqlite3PagerTempSpace(Pager*); +SQLITE_PRIVATE int tdsqlite3PagerIsMemdb(Pager*); +SQLITE_PRIVATE void tdsqlite3PagerCacheStat(Pager *, int, int, int *); +SQLITE_PRIVATE void tdsqlite3PagerClearCache(Pager*); +SQLITE_PRIVATE int tdsqlite3SectorSize(tdsqlite3_file *); +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT +SQLITE_PRIVATE void tdsqlite3PagerResetLockTimeout(Pager *pPager); +#else +# define tdsqlite3PagerResetLockTimeout(X) +#endif /* Functions used to truncate the database file. */ -SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); +SQLITE_PRIVATE void tdsqlite3PagerTruncateImage(Pager*,Pgno); -SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16); +SQLITE_PRIVATE void tdsqlite3PagerRekey(DbPage*, Pgno, u16); #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) -SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *); +SQLITE_PRIVATE void *tdsqlite3PagerCodec(DbPage *); #endif /* Functions to support testing and debugging. */ #if !defined(NDEBUG) || defined(SQLITE_TEST) -SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); -SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); +SQLITE_PRIVATE Pgno tdsqlite3PagerPagenumber(DbPage*); +SQLITE_PRIVATE int tdsqlite3PagerIswriteable(DbPage*); #endif #ifdef SQLITE_TEST -SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); -SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); +SQLITE_PRIVATE int *tdsqlite3PagerStats(Pager*); +SQLITE_PRIVATE void tdsqlite3PagerRefdump(Pager*); void disable_simulated_io_errors(void); void enable_simulated_io_errors(void); #else @@ -13181,9 +15934,10 @@ typedef struct PCache PCache; ** structure. */ struct PgHdr { - sqlite3_pcache_page *pPage; /* Pcache object page handle */ + tdsqlite3_pcache_page *pPage; /* Pcache object page handle */ void *pData; /* Page data */ void *pExtra; /* Extra content */ + PCache *pCache; /* PRIVATE: Cache that owns this page */ PgHdr *pDirty; /* Transient list of dirty sorted by pgno */ Pager *pPager; /* The pager this page is part of */ Pgno pgno; /* Page number for this page */ @@ -13193,14 +15947,15 @@ struct PgHdr { u16 flags; /* PGHDR flags defined below */ /********************************************************************** - ** Elements above are public. All that follows is private to pcache.c - ** and should not be accessed by other modules. + ** Elements above, except pCache, are public. All that follow are + ** private to pcache.c and should not be accessed by other modules. + ** pCache is grouped with the public elements for efficiency. */ i16 nRef; /* Number of users of this page */ - PCache *pCache; /* Cache that owns this page */ - PgHdr *pDirtyNext; /* Next element in list of dirty pages */ PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ + /* NB: pDirtyNext and pDirtyPrev are undefined if the + ** PgHdr object is not dirty */ }; /* Bit values for PgHdr.flags */ @@ -13215,19 +15970,19 @@ struct PgHdr { #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */ /* Initialize and shutdown the page cache subsystem */ -SQLITE_PRIVATE int sqlite3PcacheInitialize(void); -SQLITE_PRIVATE void sqlite3PcacheShutdown(void); +SQLITE_PRIVATE int tdsqlite3PcacheInitialize(void); +SQLITE_PRIVATE void tdsqlite3PcacheShutdown(void); /* Page cache buffer management: ** These routines implement SQLITE_CONFIG_PAGECACHE. */ -SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); +SQLITE_PRIVATE void tdsqlite3PCacheBufferSetup(void *, int sz, int n); /* Create a new pager cache. ** Under memory stress, invoke xStress to try to make pages clean. ** Only clean and unpinned pages can be reclaimed. */ -SQLITE_PRIVATE int sqlite3PcacheOpen( +SQLITE_PRIVATE int tdsqlite3PcacheOpen( int szPage, /* Size of every page */ int szExtra, /* Extra space associated with each page */ int bPurgeable, /* True if pages are on backing store */ @@ -13237,67 +15992,67 @@ SQLITE_PRIVATE int sqlite3PcacheOpen( ); /* Modify the page-size after the cache has been created. */ -SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int); +SQLITE_PRIVATE int tdsqlite3PcacheSetPageSize(PCache *, int); /* Return the size in bytes of a PCache object. Used to preallocate ** storage space. */ -SQLITE_PRIVATE int sqlite3PcacheSize(void); +SQLITE_PRIVATE int tdsqlite3PcacheSize(void); /* One release per successful fetch. Page is pinned until released. ** Reference counted. */ -SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag); -SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**); -SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage); -SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); +SQLITE_PRIVATE tdsqlite3_pcache_page *tdsqlite3PcacheFetch(PCache*, Pgno, int createFlag); +SQLITE_PRIVATE int tdsqlite3PcacheFetchStress(PCache*, Pgno, tdsqlite3_pcache_page**); +SQLITE_PRIVATE PgHdr *tdsqlite3PcacheFetchFinish(PCache*, Pgno, tdsqlite3_pcache_page *pPage); +SQLITE_PRIVATE void tdsqlite3PcacheRelease(PgHdr*); -SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ -SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ -SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ -SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ -SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*); +SQLITE_PRIVATE void tdsqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ +SQLITE_PRIVATE void tdsqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ +SQLITE_PRIVATE void tdsqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ +SQLITE_PRIVATE void tdsqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ +SQLITE_PRIVATE void tdsqlite3PcacheClearWritable(PCache*); /* Change a page number. Used by incr-vacuum. */ -SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); +SQLITE_PRIVATE void tdsqlite3PcacheMove(PgHdr*, Pgno); /* Remove all pages with pgno>x. Reset the cache if x==0 */ -SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); +SQLITE_PRIVATE void tdsqlite3PcacheTruncate(PCache*, Pgno x); /* Get a list of all dirty pages in the cache, sorted by page number */ -SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); +SQLITE_PRIVATE PgHdr *tdsqlite3PcacheDirtyList(PCache*); /* Reset and close the cache object */ -SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); +SQLITE_PRIVATE void tdsqlite3PcacheClose(PCache*); /* Clear flags from pages of the page cache */ -SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); +SQLITE_PRIVATE void tdsqlite3PcacheClearSyncFlags(PCache *); /* Discard the contents of the cache */ -SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); +SQLITE_PRIVATE void tdsqlite3PcacheClear(PCache*); /* Return the total number of outstanding page references */ -SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); +SQLITE_PRIVATE int tdsqlite3PcacheRefCount(PCache*); /* Increment the reference count of an existing page */ -SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); +SQLITE_PRIVATE void tdsqlite3PcacheRef(PgHdr*); -SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); +SQLITE_PRIVATE int tdsqlite3PcachePageRefcount(PgHdr*); /* Return the total number of pages stored in the cache */ -SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); +SQLITE_PRIVATE int tdsqlite3PcachePagecount(PCache*); #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) /* Iterate through all dirty pages currently stored in the cache. This ** interface is only available if SQLITE_CHECK_PAGES is defined when the ** library is built. */ -SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); +SQLITE_PRIVATE void tdsqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); #endif #if defined(SQLITE_DEBUG) /* Check invariants on a PgHdr object */ -SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*); +SQLITE_PRIVATE int tdsqlite3PcachePageSanity(PgHdr*); #endif /* Set and get the suggested cache-size for the specified pager-cache. @@ -13306,9 +16061,9 @@ SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*); ** the total number of pages cached by purgeable pager-caches to the sum ** of the suggested cache-sizes. */ -SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); +SQLITE_PRIVATE void tdsqlite3PcacheSetCachesize(PCache *, int); #ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); +SQLITE_PRIVATE int tdsqlite3PcacheGetCachesize(PCache *); #endif /* Set or get the suggested spill-size for the specified pager-cache. @@ -13316,28 +16071,32 @@ SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); ** The spill-size is the minimum number of pages in cache before the cache ** will attempt to spill dirty pages by calling xStress. */ -SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int); +SQLITE_PRIVATE int tdsqlite3PcacheSetSpillsize(PCache *, int); /* Free up as much memory as possible from the page cache */ -SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*); +SQLITE_PRIVATE void tdsqlite3PcacheShrink(PCache*); #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* Try to return memory used by the pcache module to the main memory heap */ -SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); +SQLITE_PRIVATE int tdsqlite3PcacheReleaseMemory(int); #endif #ifdef SQLITE_TEST -SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); +SQLITE_PRIVATE void tdsqlite3PcacheStats(int*,int*,int*,int*); #endif -SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); +SQLITE_PRIVATE void tdsqlite3PCacheSetDefault(void); /* Return the header size */ -SQLITE_PRIVATE int sqlite3HeaderSizePcache(void); -SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void); +SQLITE_PRIVATE int tdsqlite3HeaderSizePcache(void); +SQLITE_PRIVATE int tdsqlite3HeaderSizePcache1(void); /* Number of dirty pages as a percentage of the configured cache size */ -SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*); +SQLITE_PRIVATE int tdsqlite3PCachePercentDirty(PCache*); + +#ifdef SQLITE_DIRECT_OVERFLOW_READ +SQLITE_PRIVATE int tdsqlite3PCacheIsDirty(PCache *pCache); +#endif #endif /* _PCACHE_H_ */ @@ -13475,7 +16234,7 @@ SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*); /* ** The following values may be passed as the second argument to -** sqlite3OsLock(). The various locks exhibit the following semantics: +** tdsqlite3OsLock(). The various locks exhibit the following semantics: ** ** SHARED: Any number of processes may hold a SHARED lock simultaneously. ** RESERVED: A single process may hold a RESERVED lock on a file at @@ -13485,10 +16244,10 @@ SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*); ** SHARED locks may be obtained by other processes. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. ** -** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a +** PENDING_LOCK may not be passed directly to tdsqlite3OsLock(). Instead, a ** process that requests an EXCLUSIVE lock may actually obtain a PENDING ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to -** sqlite3OsLock(). +** tdsqlite3OsLock(). */ #define NO_LOCK 0 #define SHARED_LOCK 1 @@ -13554,66 +16313,68 @@ SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*); #ifdef SQLITE_OMIT_WSD # define PENDING_BYTE (0x40000000) #else -# define PENDING_BYTE sqlite3PendingByte +# define PENDING_BYTE tdsqlite3PendingByte #endif #define RESERVED_BYTE (PENDING_BYTE+1) #define SHARED_FIRST (PENDING_BYTE+2) #define SHARED_SIZE 510 /* -** Wrapper around OS specific sqlite3_os_init() function. +** Wrapper around OS specific tdsqlite3_os_init() function. */ -SQLITE_PRIVATE int sqlite3OsInit(void); +SQLITE_PRIVATE int tdsqlite3OsInit(void); /* -** Functions for accessing sqlite3_file methods -*/ -SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*); -SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); -SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); -SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); -SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); -SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); -SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); -SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*); +** Functions for accessing tdsqlite3_file methods +*/ +SQLITE_PRIVATE void tdsqlite3OsClose(tdsqlite3_file*); +SQLITE_PRIVATE int tdsqlite3OsRead(tdsqlite3_file*, void*, int amt, i64 offset); +SQLITE_PRIVATE int tdsqlite3OsWrite(tdsqlite3_file*, const void*, int amt, i64 offset); +SQLITE_PRIVATE int tdsqlite3OsTruncate(tdsqlite3_file*, i64 size); +SQLITE_PRIVATE int tdsqlite3OsSync(tdsqlite3_file*, int); +SQLITE_PRIVATE int tdsqlite3OsFileSize(tdsqlite3_file*, i64 *pSize); +SQLITE_PRIVATE int tdsqlite3OsLock(tdsqlite3_file*, int); +SQLITE_PRIVATE int tdsqlite3OsUnlock(tdsqlite3_file*, int); +SQLITE_PRIVATE int tdsqlite3OsCheckReservedLock(tdsqlite3_file *id, int *pResOut); +SQLITE_PRIVATE int tdsqlite3OsFileControl(tdsqlite3_file*,int,void*); +SQLITE_PRIVATE void tdsqlite3OsFileControlHint(tdsqlite3_file*,int,void*); #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 -SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); -SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); -SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); -SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int); -SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id); -SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int); -SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **); -SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *); +SQLITE_PRIVATE int tdsqlite3OsSectorSize(tdsqlite3_file *id); +SQLITE_PRIVATE int tdsqlite3OsDeviceCharacteristics(tdsqlite3_file *id); +#ifndef SQLITE_OMIT_WAL +SQLITE_PRIVATE int tdsqlite3OsShmMap(tdsqlite3_file *,int,int,int,void volatile **); +SQLITE_PRIVATE int tdsqlite3OsShmLock(tdsqlite3_file *id, int, int, int); +SQLITE_PRIVATE void tdsqlite3OsShmBarrier(tdsqlite3_file *id); +SQLITE_PRIVATE int tdsqlite3OsShmUnmap(tdsqlite3_file *id, int); +#endif /* SQLITE_OMIT_WAL */ +SQLITE_PRIVATE int tdsqlite3OsFetch(tdsqlite3_file *id, i64, int, void **); +SQLITE_PRIVATE int tdsqlite3OsUnfetch(tdsqlite3_file *, i64, void *); /* -** Functions for accessing sqlite3_vfs methods +** Functions for accessing tdsqlite3_vfs methods */ -SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); -SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); -SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); -SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); +SQLITE_PRIVATE int tdsqlite3OsOpen(tdsqlite3_vfs *, const char *, tdsqlite3_file*, int, int *); +SQLITE_PRIVATE int tdsqlite3OsDelete(tdsqlite3_vfs *, const char *, int); +SQLITE_PRIVATE int tdsqlite3OsAccess(tdsqlite3_vfs *, const char *, int, int *pResOut); +SQLITE_PRIVATE int tdsqlite3OsFullPathname(tdsqlite3_vfs *, const char *, int, char *); #ifndef SQLITE_OMIT_LOAD_EXTENSION -SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); -SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); -SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); -SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); +SQLITE_PRIVATE void *tdsqlite3OsDlOpen(tdsqlite3_vfs *, const char *); +SQLITE_PRIVATE void tdsqlite3OsDlError(tdsqlite3_vfs *, int, char *); +SQLITE_PRIVATE void (*tdsqlite3OsDlSym(tdsqlite3_vfs *, void *, const char *))(void); +SQLITE_PRIVATE void tdsqlite3OsDlClose(tdsqlite3_vfs *, void *); #endif /* SQLITE_OMIT_LOAD_EXTENSION */ -SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); -SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); -SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*); -SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); +SQLITE_PRIVATE int tdsqlite3OsRandomness(tdsqlite3_vfs *, int, char *); +SQLITE_PRIVATE int tdsqlite3OsSleep(tdsqlite3_vfs *, int); +SQLITE_PRIVATE int tdsqlite3OsGetLastError(tdsqlite3_vfs*); +SQLITE_PRIVATE int tdsqlite3OsCurrentTimeInt64(tdsqlite3_vfs *, tdsqlite3_int64*); /* ** Convenience functions for opening and closing files using -** sqlite3_malloc() to obtain space for the file-handle structure. +** tdsqlite3_malloc() to obtain space for the file-handle structure. */ -SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); -SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *); +SQLITE_PRIVATE int tdsqlite3OsOpenMalloc(tdsqlite3_vfs *, const char *, tdsqlite3_file **, int,int*); +SQLITE_PRIVATE void tdsqlite3OsCloseFree(tdsqlite3_file *); #endif /* _SQLITE_OS_H_ */ @@ -13677,19 +16438,20 @@ SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *); /* ** If this is a no-op implementation, implement everything as macros. */ -#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) -#define sqlite3_mutex_free(X) -#define sqlite3_mutex_enter(X) -#define sqlite3_mutex_try(X) SQLITE_OK -#define sqlite3_mutex_leave(X) -#define sqlite3_mutex_held(X) ((void)(X),1) -#define sqlite3_mutex_notheld(X) ((void)(X),1) -#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) -#define sqlite3MutexInit() SQLITE_OK -#define sqlite3MutexEnd() +#define tdsqlite3_mutex_alloc(X) ((tdsqlite3_mutex*)8) +#define tdsqlite3_mutex_free(X) +#define tdsqlite3_mutex_enter(X) +#define tdsqlite3_mutex_try(X) SQLITE_OK +#define tdsqlite3_mutex_leave(X) +#define tdsqlite3_mutex_held(X) ((void)(X),1) +#define tdsqlite3_mutex_notheld(X) ((void)(X),1) +#define tdsqlite3MutexAlloc(X) ((tdsqlite3_mutex*)8) +#define tdsqlite3MutexInit() SQLITE_OK +#define tdsqlite3MutexEnd() #define MUTEX_LOGIC(X) #else #define MUTEX_LOGIC(X) X +SQLITE_API int tdsqlite3_mutex_held(tdsqlite3_mutex*); #endif /* defined(SQLITE_MUTEX_OMIT) */ /************** End of mutex.h ***********************************************/ @@ -13720,7 +16482,7 @@ SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *); ** and the one-based values are used internally. */ #ifndef SQLITE_DEFAULT_SYNCHRONOUS -# define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1) +# define SQLITE_DEFAULT_SYNCHRONOUS 2 #endif #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS @@ -13751,11 +16513,11 @@ struct Db { ** ** Schema objects are automatically deallocated when the last Btree that ** references them is destroyed. The TEMP Schema is manually freed by -** sqlite3_close(). +** tdsqlite3_close(). * ** A thread must be holding a mutex on the corresponding Btree in order ** to access Schema content. This implies that the thread must also be -** holding a mutex on the sqlite3 connection pointer that owns the Btree. +** holding a mutex on the tdsqlite3 connection pointer that owns the Btree. ** For a TEMP Schema, only the connection mutex is required. */ struct Schema { @@ -13794,10 +16556,11 @@ struct Schema { #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ #define DB_UnresetViews 0x0002 /* Some views have defined column names */ #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ +#define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */ /* ** The number of different kinds of things that can be limited -** using the sqlite3_limit() interface. +** using the tdsqlite3_limit() interface. */ #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1) @@ -13820,15 +16583,47 @@ struct Schema { ** is shared by multiple database connections. Therefore, while parsing ** schema information, the Lookaside.bEnabled flag is cleared so that ** lookaside allocations are not used to construct the schema objects. +** +** New lookaside allocations are only allowed if bDisable==0. When +** bDisable is greater than zero, sz is set to zero which effectively +** disables lookaside without adding a new test for the bDisable flag +** in a performance-critical path. sz should be set by to szTrue whenever +** bDisable changes back to zero. +** +** Lookaside buffers are initially held on the pInit list. As they are +** used and freed, they are added back to the pFree list. New allocations +** come off of pFree first, then pInit as a fallback. This dual-list +** allows use to compute a high-water mark - the maximum number of allocations +** outstanding at any point in the past - by subtracting the number of +** allocations on the pInit list from the total number of allocations. +** +** Enhancement on 2019-12-12: Two-size-lookaside +** The default lookaside configuration is 100 slots of 1200 bytes each. +** The larger slot sizes are important for performance, but they waste +** a lot of space, as most lookaside allocations are less than 128 bytes. +** The two-size-lookaside enhancement breaks up the lookaside allocation +** into two pools: One of 128-byte slots and the other of the default size +** (1200-byte) slots. Allocations are filled from the small-pool first, +** failing over to the full-size pool if that does not work. Thus more +** lookaside slots are available while also using less memory. +** This enhancement can be omitted by compiling with +** SQLITE_OMIT_TWOSIZE_LOOKASIDE. */ struct Lookaside { u32 bDisable; /* Only operate the lookaside when zero */ u16 sz; /* Size of each buffer in bytes */ - u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ - int nOut; /* Number of buffers currently checked out */ - int mxOut; /* Highwater mark for nOut */ - int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ + u16 szTrue; /* True value of sz, even if disabled */ + u8 bMalloced; /* True if pStart obtained from tdsqlite3_malloc() */ + u32 nSlot; /* Number of lookaside slots allocated */ + u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ + LookasideSlot *pInit; /* List of buffers not previously used */ LookasideSlot *pFree; /* List of available buffers */ +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + LookasideSlot *pSmallInit; /* List of small buffers not prediously used */ + LookasideSlot *pSmallFree; /* List of available small buffers */ + void *pMiddle; /* First byte past end of full-size buffers and + ** the first byte of LOOKASIDE_SMALL buffers */ +#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ void *pStart; /* First byte of available memory space */ void *pEnd; /* First byte past end of available space */ }; @@ -13836,42 +16631,55 @@ struct LookasideSlot { LookasideSlot *pNext; /* Next buffer in the list of free buffers */ }; +#define DisableLookaside db->lookaside.bDisable++;db->lookaside.sz=0 +#define EnableLookaside db->lookaside.bDisable--;\ + db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue + +/* Size of the smaller allocations in two-size lookside */ +#ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE +# define LOOKASIDE_SMALL 0 +#else +# define LOOKASIDE_SMALL 128 +#endif + /* ** A hash table for built-in function definitions. (Application-defined ** functions use a regular table table from hash.h.) ** ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. -** Collisions are on the FuncDef.u.pHash chain. +** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH() +** macro to compute a hash on the function name. */ #define SQLITE_FUNC_HASH_SZ 23 struct FuncDefHash { FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */ }; +#define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ) #ifdef SQLITE_USER_AUTHENTICATION /* -** Information held in the "sqlite3" database connection object and used +** Information held in the "tdsqlite3" database connection object and used ** to manage user authentication. */ -typedef struct sqlite3_userauth sqlite3_userauth; -struct sqlite3_userauth { +typedef struct tdsqlite3_userauth tdsqlite3_userauth; +struct tdsqlite3_userauth { u8 authLevel; /* Current authentication level */ int nAuthPW; /* Size of the zAuthPW in bytes */ char *zAuthPW; /* Password used to authenticate */ char *zAuthUser; /* User name used to authenticate */ }; -/* Allowed values for sqlite3_userauth.authLevel */ +/* Allowed values for tdsqlite3_userauth.authLevel */ #define UAUTH_Unknown 0 /* Authentication not yet checked */ #define UAUTH_Fail 1 /* User authentication failed */ #define UAUTH_User 2 /* Authenticated as a normal user */ #define UAUTH_Admin 3 /* Authenticated as an administrator */ /* Functions used only by user authorization logic */ -SQLITE_PRIVATE int sqlite3UserAuthTable(const char*); -SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*); -SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*); -SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**); +SQLITE_PRIVATE int tdsqlite3UserAuthTable(const char*); +SQLITE_PRIVATE int tdsqlite3UserAuthCheckLogin(tdsqlite3*,const char*,u8*); +SQLITE_PRIVATE void tdsqlite3UserAuthInit(tdsqlite3*); +SQLITE_PRIVATE void tdsqlite3CryptFunc(tdsqlite3_context*,int,tdsqlite3_value**); #endif /* SQLITE_USER_AUTHENTICATION */ @@ -13879,37 +16687,42 @@ SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**); ** typedef for the authorization callback function. */ #ifdef SQLITE_USER_AUTHENTICATION - typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, + typedef int (*tdsqlite3_xauth)(void*,int,const char*,const char*,const char*, const char*, const char*); #else - typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, + typedef int (*tdsqlite3_xauth)(void*,int,const char*,const char*,const char*, const char*); #endif #ifndef SQLITE_OMIT_DEPRECATED /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing -** in the style of sqlite3_trace() +** in the style of tdsqlite3_trace() */ -#define SQLITE_TRACE_LEGACY 0x80 +#define SQLITE_TRACE_LEGACY 0x40 /* Use the legacy xTrace */ +#define SQLITE_TRACE_XPROFILE 0x80 /* Use the legacy xProfile */ #else -#define SQLITE_TRACE_LEGACY 0 +#define SQLITE_TRACE_LEGACY 0 +#define SQLITE_TRACE_XPROFILE 0 #endif /* SQLITE_OMIT_DEPRECATED */ +#define SQLITE_TRACE_NONLEGACY_MASK 0x0f /* Normal flags */ /* ** Each database connection is an instance of the following structure. */ -struct sqlite3 { - sqlite3_vfs *pVfs; /* OS Interface */ +struct tdsqlite3 { + tdsqlite3_vfs *pVfs; /* OS Interface */ struct Vdbe *pVdbe; /* List of active virtual machines */ CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ - sqlite3_mutex *mutex; /* Connection mutex */ + tdsqlite3_mutex *mutex; /* Connection mutex */ Db *aDb; /* All backends */ int nDb; /* Number of backends currently in use */ - int flags; /* Miscellaneous flags. See below */ + u32 mDbFlags; /* flags recording internal state */ + u64 flags; /* flags settable by pragmas. See below */ i64 lastRowid; /* ROWID of most recent insert (see above) */ i64 szMmap; /* Default mmap_size setting */ - unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ + u32 nSchemaLock; /* Do not reset the schema when non-zero */ + unsigned int openFlags; /* Flags passed to tdsqlite3_vfs.xOpen() */ int errCode; /* Most recent error code (SQLITE_*) */ int errMask; /* & result codes with this before returning */ int iSysErrno; /* Errno value from last system error */ @@ -13925,18 +16738,22 @@ struct sqlite3 { u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ u8 mTrace; /* zero or more SQLITE_TRACE flags */ + u8 noSharedCache; /* True if no shared-cache backends */ + u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */ int nextPagesize; /* Pagesize after VACUUM if >0 */ u32 magic; /* Magic number for detect library misuse */ - int nChange; /* Value returned by sqlite3_changes() */ - int nTotalChange; /* Value returned by sqlite3_total_changes() */ + int nChange; /* Value returned by tdsqlite3_changes() */ + int nTotalChange; /* Value returned by tdsqlite3_total_changes() */ int aLimit[SQLITE_N_LIMIT]; /* Limits */ int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */ - struct sqlite3InitInfo { /* Information used during initialization */ + struct tdsqlite3InitInfo { /* Information used during initialization */ int newTnum; /* Rootpage of table being initialized */ u8 iDb; /* Which db file is being initialized */ u8 busy; /* TRUE if currently initializing */ - u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ - u8 imposterTable; /* Building an imposter table */ + unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */ + unsigned imposterTable : 1; /* Building an imposter table */ + unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */ + char **azInit; /* "type", "name", and "tbl_name" columns */ } init; int nVdbeActive; /* Number of VDBEs currently running */ int nVdbeRead; /* Number of active VDBEs that read or write */ @@ -13947,36 +16764,39 @@ struct sqlite3 { void **aExtension; /* Array of shared library handles */ int (*xTrace)(u32,void*,void*,void*); /* Trace function */ void *pTraceArg; /* Argument to the trace function */ +#ifndef SQLITE_OMIT_DEPRECATED void (*xProfile)(void*,const char*,u64); /* Profiling function */ void *pProfileArg; /* Argument to profile function */ +#endif void *pCommitArg; /* Argument to xCommitCallback() */ int (*xCommitCallback)(void*); /* Invoked at every commit. */ void *pRollbackArg; /* Argument to xRollbackCallback() */ void (*xRollbackCallback)(void*); /* Invoked at every commit. */ void *pUpdateArg; void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); + Parse *pParse; /* Current parse */ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK void *pPreUpdateArg; /* First argument to xPreUpdateCallback */ - void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */ - void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64 + void (*xPreUpdateCallback)( /* Registered using tdsqlite3_preupdate_hook() */ + void*,tdsqlite3*,int,char const*,char const*,tdsqlite3_int64,tdsqlite3_int64 ); PreUpdate *pPreUpdate; /* Context for active pre-update callback */ #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifndef SQLITE_OMIT_WAL - int (*xWalCallback)(void *, sqlite3 *, const char *, int); + int (*xWalCallback)(void *, tdsqlite3 *, const char *, int); void *pWalArg; #endif - void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); - void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); + void(*xCollNeeded)(void*,tdsqlite3*,int eTextRep,const char*); + void(*xCollNeeded16)(void*,tdsqlite3*,int eTextRep,const void*); void *pCollNeededArg; - sqlite3_value *pErr; /* Most recent error message */ + tdsqlite3_value *pErr; /* Most recent error message */ union { - volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ + volatile int isInterrupted; /* True if tdsqlite3_interrupt has been called */ double notUsed1; /* Spacer */ } u1; Lookaside lookaside; /* Lookaside malloc configuration */ #ifndef SQLITE_OMIT_AUTHORIZATION - sqlite3_xauth xAuth; /* Access authorization function */ + tdsqlite3_xauth xAuth; /* Access authorization function */ void *pAuthArg; /* 1st argument to the access auth function */ #endif #ifndef SQLITE_OMIT_PROGRESS_CALLBACK @@ -13986,10 +16806,10 @@ struct sqlite3 { #endif #ifndef SQLITE_OMIT_VIRTUALTABLE int nVTrans; /* Allocated size of aVTrans */ - Hash aModule; /* populated by sqlite3_create_module() */ + Hash aModule; /* populated by tdsqlite3_create_module() */ VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ VTable **aVTrans; /* Virtual tables with open transactions */ - VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ + VTable *pDisconnect; /* Disconnect these in next tdsqlite3_prepare() */ #endif Hash aFunc; /* Hash table of connection functions */ Hash aCollSeq; /* All collating sequences */ @@ -14013,14 +16833,14 @@ struct sqlite3 { ** tried to do recently failed with an SQLITE_LOCKED error due to locks ** held by Y. */ - sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ - sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ + tdsqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ + tdsqlite3 *pUnlockConnection; /* Connection to watch for unlock */ void *pUnlockArg; /* Argument to xUnlockNotify */ void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ - sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ + tdsqlite3 *pNextBlocked; /* Next in list of all blocked connections */ #endif #ifdef SQLITE_USER_AUTHENTICATION - sqlite3_userauth auth; /* User authentication information */ + tdsqlite3_userauth auth; /* User authentication information */ #endif }; @@ -14031,6 +16851,13 @@ struct sqlite3 { #define ENC(db) ((db)->enc) /* +** A u64 constant where the lower 32 bits are all zeros. Only the +** upper 32 bits are included in the argument. Necessary because some +** C-compilers still do not accept LL integer literals. +*/ +#define HI(X) ((u64)(X)<<32) + +/* ** Possible values for the sqlite3.flags. ** ** Value constraints (enforced via assert()): @@ -14038,72 +16865,93 @@ struct sqlite3 { ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC ** SQLITE_CacheSpill == PAGER_CACHE_SPILL */ -#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ -#define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */ +#define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */ +#define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */ #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */ #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */ #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */ #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */ #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ -#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ - /* DELETE, or UPDATE and return */ - /* the count using a callback. */ +#define SQLITE_TrustedSchema 0x00000080 /* Allow unsafe functions and + ** vtabs in the schema definition */ #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ /* result set is empty */ -#define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */ -#define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */ -#define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */ -#define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */ -#define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */ -#define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */ -#define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */ -#define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */ -#define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */ -#define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */ -#define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */ -#define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */ -#define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */ -#define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */ -#define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */ -#define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */ -#define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */ -#define SQLITE_QueryOnly 0x04000000 /* Disable database changes */ -#define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */ -#define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */ -#define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */ -#define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */ +#define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */ +#define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */ +#define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */ +#define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */ +#define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */ +#define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */ +#define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */ +#define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */ +#define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */ +#define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */ +#define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */ +#define SQLITE_QueryOnly 0x00100000 /* Disable database changes */ +#define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */ +#define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */ +#define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/ +#define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */ +#define SQLITE_ResetDatabase 0x02000000 /* Reset the database */ +#define SQLITE_LegacyAlter 0x04000000 /* Legacy ALTER TABLE behaviour */ +#define SQLITE_NoSchemaError 0x08000000 /* Do not report schema parse errors*/ +#define SQLITE_Defensive 0x10000000 /* Input SQL is likely hostile */ +#define SQLITE_DqsDDL 0x20000000 /* dbl-quoted strings allowed in DDL*/ +#define SQLITE_DqsDML 0x40000000 /* dbl-quoted strings allowed in DML*/ +#define SQLITE_EnableView 0x80000000 /* Enable the use of views */ +#define SQLITE_CountRows HI(0x00001) /* Count rows changed by INSERT, */ + /* DELETE, or UPDATE and return */ + /* the count using a callback. */ +/* Flags used only if debugging */ +#ifdef SQLITE_DEBUG +#define SQLITE_SqlTrace HI(0x0100000) /* Debug print SQL as it executes */ +#define SQLITE_VdbeListing HI(0x0200000) /* Debug listings of VDBE progs */ +#define SQLITE_VdbeTrace HI(0x0400000) /* True to trace VDBE execution */ +#define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace tdsqlite3VdbeAddOp() calls */ +#define SQLITE_VdbeEQP HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */ +#define SQLITE_ParserTrace HI(0x2000000) /* PRAGMA parser_trace=ON */ +#endif + +/* +** Allowed values for sqlite3.mDbFlags +*/ +#define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */ +#define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */ +#define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */ +#define DBFLAG_VacuumInto 0x0008 /* Currently running VACUUM INTO */ +#define DBFLAG_SchemaKnownOk 0x0010 /* Schema is known to be valid */ +#define DBFLAG_InternalFunc 0x0020 /* Allow use of internal functions */ /* ** Bits of the sqlite3.dbOptFlags field that are used by the -** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to +** tdsqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to ** selectively disable various optimizations. */ #define SQLITE_QueryFlattener 0x0001 /* Query flattening */ -#define SQLITE_ColumnCache 0x0002 /* Column cache */ +#define SQLITE_WindowFunc 0x0002 /* Use xInverse for window functions */ #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */ #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */ -/* not used 0x0010 // Was: SQLITE_IdxRealAsInt */ -#define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */ -#define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */ -#define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */ -#define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */ -#define SQLITE_Transitive 0x0200 /* Transitive constraints */ -#define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */ -#define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */ -#define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */ +#define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */ +#define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */ +#define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */ +#define SQLITE_Transitive 0x0080 /* Transitive constraints */ +#define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */ +#define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */ +#define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */ +#define SQLITE_Stat4 0x0800 /* Use STAT4 data */ + /* TH3 expects the Stat4 ^^^^^^ value to be 0x0800. Don't change it */ +#define SQLITE_PushDown 0x1000 /* The push-down optimization */ +#define SQLITE_SimplifyJoin 0x2000 /* Convert LEFT JOIN to JOIN */ +#define SQLITE_SkipScan 0x4000 /* Skip-scans */ +#define SQLITE_PropagateConst 0x8000 /* The constant propagation opt */ #define SQLITE_AllOpts 0xffff /* All optimizations */ /* ** Macros for testing whether or not optimizations are enabled or disabled. */ -#ifndef SQLITE_OMIT_BUILTIN_TEST #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0) #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0) -#else -#define OptimizationDisabled(db, mask) 0 -#define OptimizationEnabled(db, mask) 1 -#endif /* ** Return true if it OK to factor constant expressions into the initialization @@ -14126,7 +16974,7 @@ struct sqlite3 { /* ** Each SQL function is defined by an instance of the following ** structure. For global built-in functions (ex: substr(), max(), count()) -** a pointer to this structure is held in the sqlite3BuiltinFunctions object. +** a pointer to this structure is held in the tdsqlite3BuiltinFunctions object. ** For per-connection application-defined functions, a pointer to this ** structure is held in the db->aHash hash table. ** @@ -14135,11 +16983,13 @@ struct sqlite3 { */ struct FuncDef { i8 nArg; /* Number of arguments. -1 means unlimited */ - u16 funcFlags; /* Some combination of SQLITE_FUNC_* */ + u32 funcFlags; /* Some combination of SQLITE_FUNC_* */ void *pUserData; /* User data parameter */ FuncDef *pNext; /* Next function with same name */ - void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */ - void (*xFinalize)(sqlite3_context*); /* Agg finalizer */ + void (*xSFunc)(tdsqlite3_context*,int,tdsqlite3_value**); /* func or agg-step */ + void (*xFinalize)(tdsqlite3_context*); /* Agg finalizer */ + void (*xValue)(tdsqlite3_context*); /* Current agg value */ + void (*xInverse)(tdsqlite3_context*,int,tdsqlite3_value**); /* inverse agg-step */ const char *zName; /* SQL name of the function. */ union { FuncDef *pHash; /* Next with a different name but the same hash */ @@ -14178,13 +17028,15 @@ struct FuncDestructor { ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API +** SQLITE_FUNC_DIRECT == SQLITE_DIRECTONLY from the API +** SQLITE_FUNC_UNSAFE == SQLITE_INNOCUOUS ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API */ #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */ #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */ #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */ #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */ -#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/ +#define SQLITE_FUNC_NEEDCOLL 0x0020 /* tdsqlite3GetFuncCollSeq() might be called*/ #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */ #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */ #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */ @@ -14194,6 +17046,22 @@ struct FuncDestructor { #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */ #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a ** single query - might change over time */ +#define SQLITE_FUNC_TEST 0x4000 /* Built-in testing functions */ +#define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */ +#define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */ +#define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */ +#define SQLITE_FUNC_DIRECT 0x00080000 /* Not for use in TRIGGERs or VIEWs */ +#define SQLITE_FUNC_SUBTYPE 0x00100000 /* Result likely to have sub-type */ +#define SQLITE_FUNC_UNSAFE 0x00200000 /* Function has side effects */ +#define SQLITE_FUNC_INLINE 0x00400000 /* Functions implemented in-line */ + +/* Identifier numbers for each in-line function */ +#define INLINEFUNC_coalesce 0 +#define INLINEFUNC_implies_nonnull_row 1 +#define INLINEFUNC_expr_implies_expr 2 +#define INLINEFUNC_expr_compare 3 +#define INLINEFUNC_affinity 4 +#define INLINEFUNC_unlikely 99 /* Default case */ /* ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are @@ -14203,17 +17071,40 @@ struct FuncDestructor { ** Used to create a scalar function definition of a function zName ** implemented by C function xFunc that accepts nArg arguments. The ** value passed as iArg is cast to a (void*) and made available -** as the user-data (sqlite3_user_data()) for the function. If +** as the user-data (tdsqlite3_user_data()) for the function. If ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. ** ** VFUNCTION(zName, nArg, iArg, bNC, xFunc) ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag. ** +** SFUNCTION(zName, nArg, iArg, bNC, xFunc) +** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and +** adds the SQLITE_DIRECTONLY flag. +** +** INLINE_FUNC(zName, nArg, iFuncId, mFlags) +** zName is the name of a function that is implemented by in-line +** byte code rather than by the usual callbacks. The iFuncId +** parameter determines the function id. The mFlags parameter is +** optional SQLITE_FUNC_ flags for this function. +** +** TEST_FUNC(zName, nArg, iFuncId, mFlags) +** zName is the name of a test-only function implemented by in-line +** byte code rather than by the usual callbacks. The iFuncId +** parameter determines the function id. The mFlags parameter is +** optional SQLITE_FUNC_ flags for this function. +** ** DFUNCTION(zName, nArg, iArg, bNC, xFunc) ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions ** and functions like sqlite_version() that can change, but not during -** a single query. +** a single query. The iArg is ignored. The user-data is always set +** to a NULL pointer. The bNC parameter is not used. +** +** PURE_DATE(zName, nArg, iArg, bNC, xFunc) +** Used for "pure" date/time functions, this macro is like DFUNCTION +** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is +** ignored and the user-data for these functions is set to an +** arbitrary non-NULL pointer. The bNC parameter is not used. ** ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) ** Used to create an aggregate function definition implemented by @@ -14221,38 +17112,58 @@ struct FuncDestructor { ** are interpreted in the same way as the first 4 parameters to ** FUNCTION(). ** +** WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse) +** Used to create an aggregate function definition implemented by +** the C functions xStep and xFinal. The first four parameters +** are interpreted in the same way as the first 4 parameters to +** FUNCTION(). +** ** LIKEFUNC(zName, nArg, pArg, flags) ** Used to create a scalar function definition of a function zName ** that accepts nArg arguments and is implemented by a call to C ** function likeFunc. Argument pArg is cast to a (void *) and made -** available as the function user-data (sqlite3_user_data()). The +** available as the function user-data (tdsqlite3_user_data()). The ** FuncDef.flags variable is set to the value passed as the flags ** parameter. */ #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ - SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} } #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \ {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ - SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} } +#define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \ + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} } +#define INLINE_FUNC(zName, nArg, iArg, mFlags) \ + {nArg, SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \ + SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} } +#define TEST_FUNC(zName, nArg, iArg, mFlags) \ + {nArg, SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \ + SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \ + SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} } #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \ - {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ - SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } + {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \ + 0, 0, xFunc, 0, 0, 0, #zName, {0} } +#define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \ + {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \ + (void*)&tdsqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} } #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \ {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\ - SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} } #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ - pArg, 0, xFunc, 0, #zName, } + pArg, 0, xFunc, 0, 0, 0, #zName, } #define LIKEFUNC(zName, nArg, arg, flags) \ {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \ - (void *)arg, 0, likeFunc, 0, #zName, {0} } -#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ - {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \ - SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}} -#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \ - {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \ - SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}} + (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} } +#define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \ + {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \ + SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}} +#define INTERNAL_FUNCTION(zName, nArg, xFunc) \ + {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \ + 0, 0, xFunc, 0, 0, 0, #zName, {0} } + /* ** All current savepoints are stored in a linked list starting at @@ -14268,7 +17179,7 @@ struct Savepoint { }; /* -** The following are used as the second parameter to sqlite3Savepoint(), +** The following are used as the second parameter to tdsqlite3Savepoint(), ** and as the P1 argument to the OP_Savepoint instruction. */ #define SAVEPOINT_BEGIN 0 @@ -14282,32 +17193,54 @@ struct Savepoint { ** hash table. */ struct Module { - const sqlite3_module *pModule; /* Callback pointers */ + const tdsqlite3_module *pModule; /* Callback pointers */ const char *zName; /* Name passed to create_module() */ + int nRefModule; /* Number of pointers to this object */ void *pAux; /* pAux passed to create_module() */ void (*xDestroy)(void *); /* Module destructor function */ Table *pEpoTab; /* Eponymous table for this module */ }; /* -** information about each column of an SQL table is held in an instance -** of this structure. +** Information about each column of an SQL table is held in an instance +** of the Column structure, in the Table.aCol[] array. +** +** Definitions: +** +** "table column index" This is the index of the column in the +** Table.aCol[] array, and also the index of +** the column in the original CREATE TABLE stmt. +** +** "storage column index" This is the index of the column in the +** record BLOB generated by the OP_MakeRecord +** opcode. The storage column index is less than +** or equal to the table column index. It is +** equal if and only if there are no VIRTUAL +** columns to the left. */ struct Column { char *zName; /* Name of this column, \000, then the type */ - Expr *pDflt; /* Default value of this column */ + Expr *pDflt; /* Default value or GENERATED ALWAYS AS value */ char *zColl; /* Collating sequence. If NULL, use the default */ u8 notNull; /* An OE_ code for handling a NOT NULL constraint */ char affinity; /* One of the SQLITE_AFF_... values */ u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */ - u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */ + u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */ }; /* Allowed values for Column.colFlags: */ -#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */ -#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */ -#define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */ +#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */ +#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */ +#define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */ +#define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */ +#define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */ +#define COLFLAG_VIRTUAL 0x0020 /* GENERATED ALWAYS AS ... VIRTUAL */ +#define COLFLAG_STORED 0x0040 /* GENERATED ALWAYS AS ... STORED */ +#define COLFLAG_NOTAVAIL 0x0080 /* STORED column not yet calculated */ +#define COLFLAG_BUSY 0x0100 /* Blocks recursion on GENERATED columns */ +#define COLFLAG_GENERATED 0x0060 /* Combo: _STORED, _VIRTUAL */ +#define COLFLAG_NOINSERT 0x0062 /* Combo: _HIDDEN, _STORED, _VIRTUAL */ /* ** A "Collating Sequence" is defined by an instance of the following @@ -14347,13 +17280,14 @@ struct CollSeq { ** Note also that the numeric types are grouped together so that testing ** for a numeric type is a single comparison. And the BLOB type is first. */ -#define SQLITE_AFF_BLOB 'A' -#define SQLITE_AFF_TEXT 'B' -#define SQLITE_AFF_NUMERIC 'C' -#define SQLITE_AFF_INTEGER 'D' -#define SQLITE_AFF_REAL 'E' +#define SQLITE_AFF_NONE 0x40 /* '@' */ +#define SQLITE_AFF_BLOB 0x41 /* 'A' */ +#define SQLITE_AFF_TEXT 0x42 /* 'B' */ +#define SQLITE_AFF_NUMERIC 0x43 /* 'C' */ +#define SQLITE_AFF_INTEGER 0x44 /* 'D' */ +#define SQLITE_AFF_REAL 0x45 /* 'E' */ -#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) +#define tdsqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) /* ** The SQLITE_AFF_MASK values masks off the significant bits of an @@ -14381,10 +17315,10 @@ struct CollSeq { ** the database schema. ** ** If the database schema is shared, then there is one instance of this -** structure for each database connection (sqlite3*) that uses the shared +** structure for each database connection (tdsqlite3*) that uses the shared ** schema. This is because each database connection requires its own unique -** instance of the sqlite3_vtab* handle used to access the virtual table -** implementation. sqlite3_vtab* handles can not be shared between +** instance of the tdsqlite3_vtab* handle used to access the virtual table +** implementation. tdsqlite3_vtab* handles can not be shared between ** database connections, even when the rest of the in-memory database ** schema is shared, as the implementation often stores the database ** connection handle passed to it via the xConnect() or xCreate() method @@ -14397,37 +17331,44 @@ struct CollSeq { ** All VTable objects that correspond to a single table in a shared ** database schema are initially stored in a linked-list pointed to by ** the Table.pVTable member variable of the corresponding Table object. -** When an sqlite3_prepare() operation is required to access the virtual +** When an tdsqlite3_prepare() operation is required to access the virtual ** table, it searches the list for the VTable that corresponds to the ** database connection doing the preparing so as to use the correct -** sqlite3_vtab* handle in the compiled query. +** tdsqlite3_vtab* handle in the compiled query. ** ** When an in-memory Table object is deleted (for example when the ** schema is being reloaded for some reason), the VTable objects are not -** deleted and the sqlite3_vtab* handles are not xDisconnect()ed +** deleted and the tdsqlite3_vtab* handles are not xDisconnect()ed ** immediately. Instead, they are moved from the Table.pVTable list to ** another linked list headed by the sqlite3.pDisconnect member of the -** corresponding sqlite3 structure. They are then deleted/xDisconnected -** next time a statement is prepared using said sqlite3*. This is done +** corresponding tdsqlite3 structure. They are then deleted/xDisconnected +** next time a statement is prepared using said tdsqlite3*. This is done ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. -** Refer to comments above function sqlite3VtabUnlockList() for an +** Refer to comments above function tdsqlite3VtabUnlockList() for an ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect ** list without holding the corresponding sqlite3.mutex mutex. ** ** The memory for objects of this type is always allocated by -** sqlite3DbMalloc(), using the connection handle stored in VTable.db as +** tdsqlite3DbMalloc(), using the connection handle stored in VTable.db as ** the first argument. */ struct VTable { - sqlite3 *db; /* Database connection associated with this table */ + tdsqlite3 *db; /* Database connection associated with this table */ Module *pMod; /* Pointer to module implementation */ - sqlite3_vtab *pVtab; /* Pointer to vtab instance */ + tdsqlite3_vtab *pVtab; /* Pointer to vtab instance */ int nRef; /* Number of pointers to this structure */ u8 bConstraint; /* True if constraints are supported */ + u8 eVtabRisk; /* Riskiness of allowing hacker access */ int iSavepoint; /* Depth of the SAVEPOINT stack */ VTable *pNext; /* Next in linked list (see above) */ }; +/* Allowed values for VTable.eVtabRisk +*/ +#define SQLITE_VTABRISK_Low 0 +#define SQLITE_VTABRISK_Normal 1 +#define SQLITE_VTABRISK_High 2 + /* ** The schema for each SQL table and view is represented in memory ** by an instance of the following structure. @@ -14442,15 +17383,16 @@ struct Table { ExprList *pCheck; /* All CHECK constraints */ /* ... also used as column name list in a VIEW */ int tnum; /* Root BTree page for this table */ + u32 nTabRef; /* Number of pointers to this Table */ + u32 tabFlags; /* Mask of TF_* values */ i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */ i16 nCol; /* Number of columns in this table */ - u16 nRef; /* Number of pointers to this Table */ + i16 nNVCol; /* Number of columns that are not VIRTUAL */ LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */ LogEst szTabRow; /* Estimated size of each table row in bytes */ #ifdef SQLITE_ENABLE_COSTMULT LogEst costMult; /* Cost multiplier for using this table */ #endif - u8 tabFlags; /* Mask of TF_* values */ u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ #ifndef SQLITE_OMIT_ALTERTABLE int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ @@ -14472,17 +17414,28 @@ struct Table { ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden, ** the TF_OOOHidden attribute would apply in this case. Such tables require -** special handling during INSERT processing. -*/ -#define TF_Readonly 0x01 /* Read-only system table */ -#define TF_Ephemeral 0x02 /* An ephemeral table */ -#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ -#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ -#define TF_Virtual 0x10 /* Is a virtual table */ -#define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */ -#define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */ -#define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */ - +** special handling during INSERT processing. The "OOO" means "Out Of Order". +** +** Constraints: +** +** TF_HasVirtual == COLFLAG_Virtual +** TF_HasStored == COLFLAG_Stored +*/ +#define TF_Readonly 0x0001 /* Read-only system table */ +#define TF_Ephemeral 0x0002 /* An ephemeral table */ +#define TF_HasPrimaryKey 0x0004 /* Table has a primary key */ +#define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */ +#define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */ +#define TF_HasVirtual 0x0020 /* Has one or more VIRTUAL columns */ +#define TF_HasStored 0x0040 /* Has one or more STORED columns */ +#define TF_HasGenerated 0x0060 /* Combo: HasVirtual + HasStored */ +#define TF_WithoutRowid 0x0080 /* No rowid. PRIMARY KEY is the key */ +#define TF_StatsUsed 0x0100 /* Query planner decisions affected by + ** Index.aiRowLogEst[] values */ +#define TF_NoVisibleRowid 0x0200 /* No user-visible "rowid" column */ +#define TF_OOOHidden 0x0400 /* Out-of-Order hidden columns */ +#define TF_HasNotNull 0x0800 /* Contains NOT NULL constraints */ +#define TF_Shadow 0x1000 /* True for a shadow table */ /* ** Test to see whether or not a table is a virtual table. This is @@ -14490,7 +17443,7 @@ struct Table { ** table support is omitted from the build. */ #ifndef SQLITE_OMIT_VIRTUALTABLE -# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) +# define IsVirtual(X) ((X)->nModuleArg) #else # define IsVirtual(X) 0 #endif @@ -14593,18 +17546,17 @@ struct FKey { #define OE_Fail 3 /* Stop the operation but leave all prior changes */ #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ - -#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ -#define OE_SetNull 7 /* Set the foreign key value to NULL */ -#define OE_SetDflt 8 /* Set the foreign key value to its default */ -#define OE_Cascade 9 /* Cascade the changes */ - -#define OE_Default 10 /* Do whatever the default action is */ +#define OE_Update 6 /* Process as a DO UPDATE in an upsert */ +#define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ +#define OE_SetNull 8 /* Set the foreign key value to NULL */ +#define OE_SetDflt 9 /* Set the foreign key value to its default */ +#define OE_Cascade 10 /* Cascade the changes */ +#define OE_Default 11 /* Do whatever the default action is */ /* ** An instance of the following structure is passed as the first -** argument to sqlite3VdbeKeyCompare and is used to control the +** argument to tdsqlite3VdbeKeyCompare and is used to control the ** comparison of the two index keys. ** ** Note that aSortOrder[] and aColl[] have nField+1 slots. There @@ -14614,14 +17566,20 @@ struct FKey { struct KeyInfo { u32 nRef; /* Number of references to this KeyInfo object */ u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ - u16 nField; /* Number of key columns in the index */ - u16 nXField; /* Number of columns beyond the key columns */ - sqlite3 *db; /* The database connection */ - u8 *aSortOrder; /* Sort order for each column. */ + u16 nKeyField; /* Number of key columns in the index */ + u16 nAllField; /* Total columns, including key plus others */ + tdsqlite3 *db; /* The database connection */ + u8 *aSortFlags; /* Sort order for each column. */ CollSeq *aColl[1]; /* Collating sequence for each term of the key */ }; /* +** Allowed bit values for entries in the KeyInfo.aSortFlags[] array. +*/ +#define KEYINFO_ORDER_DESC 0x01 /* DESC sort order */ +#define KEYINFO_ORDER_BIGNULL 0x02 /* NULL is larger than any other value */ + +/* ** This object holds a record which has been parsed out into individual ** fields, for the purposes of doing a comparison. ** @@ -14662,8 +17620,8 @@ struct UnpackedRecord { u16 nField; /* Number of entries in apMem[] */ i8 default_rc; /* Comparison result if keys are equal */ u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */ - i8 r1; /* Value to return if (lhs > rhs) */ - i8 r2; /* Value to return if (rhs < lhs) */ + i8 r1; /* Value to return if (lhs < rhs) */ + i8 r2; /* Value to return if (lhs > rhs) */ u8 eqSeen; /* True if an equality comparison has been seen */ }; @@ -14719,13 +17677,17 @@ struct Index { u16 nKeyCol; /* Number of columns forming the key */ u16 nColumn; /* Number of columns stored in the index */ u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ - unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */ + unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */ unsigned bUnordered:1; /* Use this index for == or IN queries only */ unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */ unsigned isResized:1; /* True if resizeIndexObject() has been called */ unsigned isCovering:1; /* True if this is a covering index */ unsigned noSkipScan:1; /* Do not try to use skip-scan if true */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */ + unsigned bNoQuery:1; /* Do not use this index to optimize queries */ + unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */ + unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */ +#ifdef SQLITE_ENABLE_STAT4 int nSample; /* Number of elements in aSample[] */ int nSampleCol; /* Size of IndexSample.anEq[] and so on */ tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */ @@ -14733,6 +17695,7 @@ struct Index { tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */ tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */ #endif + Bitmask colNotIdxed; /* 0 for unindexed columns in pTab */ }; /* @@ -14741,6 +17704,7 @@ struct Index { #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */ #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */ #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */ +#define SQLITE_IDXTYPE_IPK 3 /* INTEGER PRIMARY KEY index */ /* Return true if index X is a PRIMARY KEY index */ #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY) @@ -14755,7 +17719,7 @@ struct Index { #define XN_EXPR (-2) /* Indexed column is an expression */ /* -** Each sample stored in the sqlite_stat3 table is represented in memory +** Each sample stored in the sqlite_stat4 table is represented in memory ** using a structure of this type. See documentation at the top of the ** analyze.c source file for additional information. */ @@ -14768,12 +17732,20 @@ struct IndexSample { }; /* +** Possible values to use within the flags argument to tdsqlite3GetToken(). +*/ +#define SQLITE_TOKEN_QUOTED 0x1 /* Token is a quoted identifier. */ +#define SQLITE_TOKEN_KEYWORD 0x2 /* Token is a keyword. */ + +/* ** Each token coming out of the lexer is an instance of ** this structure. Tokens are also used as part of an expression. ** -** Note if Token.z==0 then Token.dyn and Token.n are undefined and -** may contain random values. Do not make any assumptions about Token.dyn -** and Token.n when Token.z==0. +** The memory that "z" points to is owned by other objects. Take care +** that the owner of the "z" string does not deallocate the string before +** the Token goes out of scope! Very often, the "z" points to some place +** in the middle of the Parse.zSql text. But it might also point to a +** static string. */ struct Token { const char *z; /* Text of the token. Not NULL-terminated! */ @@ -14905,7 +17877,11 @@ typedef int ynVar; */ struct Expr { u8 op; /* Operation performed by this node */ - char affinity; /* The affinity of the column or 0 if not a column */ + char affExpr; /* affinity, or RAISE type */ + u8 op2; /* TK_REGISTER/TK_TRUTH: original value of Expr.op + ** TK_COLUMN: the value of p5 for OP_Column + ** TK_AGG_FUNCTION: nesting depth + ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */ u32 flags; /* Various flags. EP_* See below */ union { char *zToken; /* Token value. Zero terminated and dequoted */ @@ -14936,51 +17912,70 @@ struct Expr { ** TK_REGISTER: register number ** TK_TRIGGER: 1 -> new, 0 -> old ** EP_Unlikely: 134217728 times likelihood + ** TK_IN: ephemerial table holding RHS + ** TK_SELECT_COLUMN: Number of columns on the LHS ** TK_SELECT: 1st register of result vector */ ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid. ** TK_VARIABLE: variable number (always >= 1). ** TK_SELECT_COLUMN: column of the result vector */ i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */ i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */ - u8 op2; /* TK_REGISTER: original value of Expr.op - ** TK_COLUMN: the value of p5 for OP_Column - ** TK_AGG_FUNCTION: nesting depth */ AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */ - Table *pTab; /* Table for TK_COLUMN expressions. */ + union { + Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL + ** for a column of an index on an expression */ + Window *pWin; /* EP_WinFunc: Window/Filter defn for a function */ + struct { /* TK_IN, TK_SELECT, and TK_EXISTS */ + int iAddr; /* Subroutine entry address */ + int regReturn; /* Register used to hold return address */ + } sub; + } y; }; /* ** The following are the meanings of bits in the Expr.flags field. -*/ -#define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */ -#define EP_Agg 0x000002 /* Contains one or more aggregate functions */ -#define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */ -#define EP_Error 0x000008 /* Expression contains one or more errors */ -#define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */ -#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */ -#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */ -#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */ -#define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */ -#define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */ -#define EP_IntValue 0x000400 /* Integer value contained in u.iValue */ -#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */ -#define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */ -#define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */ -#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */ -#define EP_Static 0x008000 /* Held in memory not obtained from malloc() */ -#define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */ -#define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */ -#define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */ -#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */ -#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */ -#define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */ -#define EP_Alias 0x400000 /* Is an alias for a result set column */ -#define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */ - -/* -** Combinations of two or more EP_* flags -*/ -#define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */ +** Value restrictions: +** +** EP_Agg == NC_HasAgg == SF_HasAgg +** EP_Win == NC_HasWin +*/ +#define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */ +#define EP_Distinct 0x000002 /* Aggregate function with DISTINCT keyword */ +#define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */ +#define EP_FixedCol 0x000008 /* TK_Column with a known fixed value */ +#define EP_Agg 0x000010 /* Contains one or more aggregate functions */ +#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */ +#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */ +#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */ +#define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */ +#define EP_Commuted 0x000200 /* Comparison operator has been commuted */ +#define EP_IntValue 0x000400 /* Integer value contained in u.iValue */ +#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */ +#define EP_Skip 0x001000 /* Operator does not contribute to affinity */ +#define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */ +#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */ +#define EP_Win 0x008000 /* Contains window functions */ +#define EP_MemToken 0x010000 /* Need to tdsqlite3DbFree() Expr.zToken */ +#define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */ +#define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */ +#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */ +#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */ +#define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */ +#define EP_Alias 0x400000 /* Is an alias for a result set column */ +#define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */ +#define EP_WinFunc 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */ +#define EP_Subrtn 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */ +#define EP_Quoted 0x4000000 /* TK_ID was originally quoted */ +#define EP_Static 0x8000000 /* Held in memory not obtained from malloc() */ +#define EP_IsTrue 0x10000000 /* Always has boolean value of TRUE */ +#define EP_IsFalse 0x20000000 /* Always has boolean value of FALSE */ +#define EP_FromDDL 0x40000000 /* Originates from sqlite_master */ + +/* +** The EP_Propagate mask is a set of properties that automatically propagate +** upwards into parent nodes. +*/ +#define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc) /* ** These macros can be used to test, set, or clear bits in the @@ -14990,6 +17985,8 @@ struct Expr { #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P)) #define ExprSetProperty(E,P) (E)->flags|=(P) #define ExprClearProperty(E,P) (E)->flags&=~(P) +#define ExprAlwaysTrue(E) (((E)->flags&(EP_FromJoin|EP_IsTrue))==EP_IsTrue) +#define ExprAlwaysFalse(E) (((E)->flags&(EP_FromJoin|EP_IsFalse))==EP_IsFalse) /* The ExprSetVVAProperty() macro is used for Verification, Validation, ** and Accreditation only. It works like ExprSetProperty() during VVA @@ -15011,12 +18008,24 @@ struct Expr { #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */ /* -** Flags passed to the sqlite3ExprDup() function. See the header comment -** above sqlite3ExprDup() for details. +** Flags passed to the tdsqlite3ExprDup() function. See the header comment +** above tdsqlite3ExprDup() for details. */ #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */ /* +** True if the expression passed as an argument was a function with +** an OVER() clause (a window function). +*/ +#ifdef SQLITE_OMIT_WINDOWFUNC +# define IsWindowFunc(p) 0 +#else +# define IsWindowFunc(p) ( \ + ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \ + ) +#endif + +/* ** A list of expressions. Each expression may optionally have a ** name. An expr/name combination can be used in several ways, such ** as the list of "expr AS ID" fields following a "SELECT" or in the @@ -15024,24 +18033,31 @@ struct Expr { ** also be used as the argument to a function, in which case the a.zName ** field is not used. ** -** By default the Expr.zSpan field holds a human-readable description of -** the expression that is used in the generation of error messages and -** column labels. In this case, Expr.zSpan is typically the text of a -** column expression as it exists in a SELECT statement. However, if -** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name -** of the result column in the form: DATABASE.TABLE.COLUMN. This later -** form is used for name resolution with nested FROM clauses. +** In order to try to keep memory usage down, the Expr.a.zEName field +** is used for multiple purposes: +** +** eEName Usage +** ---------- ------------------------- +** ENAME_NAME (1) the AS of result set column +** (2) COLUMN= of an UPDATE +** +** ENAME_TAB DB.TABLE.NAME used to resolve names +** of subqueries +** +** ENAME_SPAN Text of the original result set +** expression. */ struct ExprList { int nExpr; /* Number of expressions on the list */ struct ExprList_item { /* For each expression in the list */ - Expr *pExpr; /* The list of expressions */ - char *zName; /* Token associated with this expression */ - char *zSpan; /* Original text of the expression */ - u8 sortOrder; /* 1 for DESC or 0 for ASC */ + Expr *pExpr; /* The parse tree for this expression */ + char *zEName; /* Token associated with this expression */ + u8 sortFlags; /* Mask of KEYINFO_ORDER_* flags */ + unsigned eEName :2; /* Meaning of zEName */ unsigned done :1; /* A flag to indicate when processing is finished */ - unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */ unsigned reusable :1; /* Constant expression is reusable */ + unsigned bSorterRef :1; /* Defer evaluation until after sorting */ + unsigned bNulls: 1; /* True if explicit "NULLS FIRST/LAST" */ union { struct { u16 iOrderByCol; /* For ORDER BY, column number in result set */ @@ -15049,19 +18065,15 @@ struct ExprList { } x; int iConstExprReg; /* Register in which Expr value is cached */ } u; - } *a; /* Alloc a power of two greater or equal to nExpr */ + } a[1]; /* One slot for each expression in the list */ }; /* -** An instance of this structure is used by the parser to record both -** the parse tree for an expression and the span of input text for an -** expression. +** Allowed values for Expr.a.eEName */ -struct ExprSpan { - Expr *pExpr; /* The expression parse tree */ - const char *zStart; /* First character of input text */ - const char *zEnd; /* One character past the end of input text */ -}; +#define ENAME_NAME 0 /* The AS clause of a result set */ +#define ENAME_SPAN 1 /* Complete text of the result set expression */ +#define ENAME_TAB 2 /* "DB.TABLE.NAME" for the result set */ /* ** An instance of this structure can hold a simple list of identifiers, @@ -15087,31 +18099,6 @@ struct IdList { }; /* -** The bitmask datatype defined below is used for various optimizations. -** -** Changing this from a 64-bit to a 32-bit type limits the number of -** tables in a join to 32 instead of 64. But it also reduces the size -** of the library by 738 bytes on ix86. -*/ -#ifdef SQLITE_BITMASK_TYPE - typedef SQLITE_BITMASK_TYPE Bitmask; -#else - typedef u64 Bitmask; -#endif - -/* -** The number of bits in a Bitmask. "BMS" means "BitMask Size". -*/ -#define BMS ((int)(sizeof(Bitmask)*8)) - -/* -** A bit in a Bitmask -*/ -#define MASKBIT(n) (((Bitmask)1)<<(n)) -#define MASKBIT32(n) (((unsigned int)1)<<(n)) -#define ALLBITS ((Bitmask)-1) - -/* ** The following structure describes the FROM clause of a SELECT statement. ** Each table or subquery in the FROM clause is a separate element of ** the SrcList.a[] array. @@ -15124,7 +18111,7 @@ struct IdList { ** ** The jointype starts out showing the join type between the current table ** and the next table on the list. The parser builds the list this way. -** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each +** But tdsqlite3SrcListShiftJoinType() later shifts the jointypes so that each ** jointype expresses the join between the table and the previous table. ** ** In the colUsed field, the high-order bit (bit 63) is set if the table @@ -15151,10 +18138,8 @@ struct SrcList { unsigned isCorrelated :1; /* True if sub-query is correlated */ unsigned viaCoroutine :1; /* Implemented as a co-routine */ unsigned isRecursive :1; /* True for recursive reference in WITH */ + unsigned fromDDL :1; /* Comes from sqlite_master */ } fg; -#ifndef SQLITE_OMIT_EXPLAIN - u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */ -#endif int iCursor; /* The VDBE cursor number used to access this table */ Expr *pOn; /* The ON clause of a join */ IdList *pUsing; /* The USING clause of a join */ @@ -15180,7 +18165,7 @@ struct SrcList { /* -** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin() +** Flags appropriate for the wctrlFlags parameter of tdsqlite3WhereBegin() ** and the WhereInfo.wctrlFlags member. ** ** Value constraints (enforced via assert()): @@ -15197,15 +18182,15 @@ struct SrcList { #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */ #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */ #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */ -#define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */ +#define WHERE_SORTBYGROUP 0x0200 /* Support tdsqlite3WhereIsSorted() */ #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */ #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */ - /* 0x1000 not currently used */ +#define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */ /* 0x2000 not currently used */ #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */ /* 0x8000 not currently used */ -/* Allowed return values from sqlite3WhereIsDistinct() +/* Allowed return values from tdsqlite3WhereIsDistinct() */ #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */ #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */ @@ -15236,40 +18221,82 @@ struct SrcList { struct NameContext { Parse *pParse; /* The parser */ SrcList *pSrcList; /* One or more tables used to resolve names */ - ExprList *pEList; /* Optional list of result-set columns */ - AggInfo *pAggInfo; /* Information about aggregates at this level */ + union { + ExprList *pEList; /* Optional list of result-set columns */ + AggInfo *pAggInfo; /* Information about aggregates at this level */ + Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */ + } uNC; NameContext *pNext; /* Next outer name context. NULL for outermost */ int nRef; /* Number of names resolved by this context */ int nErr; /* Number of errors encountered while resolving names */ - u16 ncFlags; /* Zero or more NC_* flags defined below */ + int ncFlags; /* Zero or more NC_* flags defined below */ + Select *pWinSelect; /* SELECT statement for any window functions */ }; /* ** Allowed values for the NameContext, ncFlags field. ** ** Value constraints (all checked via assert()): -** NC_HasAgg == SF_HasAgg +** NC_HasAgg == SF_HasAgg == EP_Agg ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX -** -*/ -#define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */ -#define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */ -#define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */ -#define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */ -#define NC_HasAgg 0x0010 /* One or more aggregate functions seen */ -#define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */ -#define NC_VarSelect 0x0040 /* A correlated subquery has been seen */ -#define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */ +** NC_HasWin == EP_Win +** +*/ +#define NC_AllowAgg 0x00001 /* Aggregate functions are allowed here */ +#define NC_PartIdx 0x00002 /* True if resolving a partial index WHERE */ +#define NC_IsCheck 0x00004 /* True if resolving a CHECK constraint */ +#define NC_GenCol 0x00008 /* True for a GENERATED ALWAYS AS clause */ +#define NC_HasAgg 0x00010 /* One or more aggregate functions seen */ +#define NC_IdxExpr 0x00020 /* True if resolving columns of CREATE INDEX */ +#define NC_SelfRef 0x0002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */ +#define NC_VarSelect 0x00040 /* A correlated subquery has been seen */ +#define NC_UEList 0x00080 /* True if uNC.pEList is used */ +#define NC_UAggInfo 0x00100 /* True if uNC.pAggInfo is used */ +#define NC_UUpsert 0x00200 /* True if uNC.pUpsert is used */ +#define NC_MinMaxAgg 0x01000 /* min/max aggregates seen. See note above */ +#define NC_Complex 0x02000 /* True if a function or subquery seen */ +#define NC_AllowWin 0x04000 /* Window functions are allowed here */ +#define NC_HasWin 0x08000 /* One or more window functions seen */ +#define NC_IsDDL 0x10000 /* Resolving names in a CREATE statement */ +#define NC_InAggFunc 0x20000 /* True if analyzing arguments to an agg func */ +#define NC_FromDDL 0x40000 /* SQL text comes from sqlite_master */ + +/* +** An instance of the following object describes a single ON CONFLICT +** clause in an upsert. +** +** The pUpsertTarget field is only set if the ON CONFLICT clause includes +** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the +** conflict-target clause.) The pUpsertTargetWhere is the optional +** WHERE clause used to identify partial unique indexes. +** +** pUpsertSet is the list of column=expr terms of the UPDATE statement. +** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The +** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the +** WHERE clause is omitted. +*/ +struct Upsert { + ExprList *pUpsertTarget; /* Optional description of conflicting index */ + Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */ + ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */ + Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */ + /* The fields above comprise the parse tree for the upsert clause. + ** The fields below are used to transfer information from the INSERT + ** processing down into the UPDATE processing while generating code. + ** Upsert owns the memory allocated above, but not the memory below. */ + Index *pUpsertIdx; /* Constraint that pUpsertTarget identifies */ + SrcList *pUpsertSrc; /* Table to be updated */ + int regData; /* First register holding array of VALUES */ + int iDataCur; /* Index of the data cursor */ + int iIdxCur; /* Index of the first index cursor */ +}; /* ** An instance of the following structure contains all information ** needed to generate code for a single SELECT statement. ** -** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0. -** If there is a LIMIT clause, the parser sets nLimit to the value of the -** limit and nOffset to the value of the offset (or 0 if there is not -** offset). But later on, nLimit and nOffset become the memory locations -** in the VDBE that record the limit and offset counters. +** See the header comment on the computeLimitRegisters() routine for a +** detailed description of the meaning of the iLimit and iOffset fields. ** ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes. ** These addresses must be stored so that we can go back and fill in @@ -15282,15 +18309,13 @@ struct NameContext { ** sequences for the ORDER BY clause. */ struct Select { - ExprList *pEList; /* The fields of the result */ u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */ LogEst nSelectRow; /* Estimated number of result rows */ u32 selFlags; /* Various SF_* values */ int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */ -#if SELECTTRACE_ENABLED - char zSelName[12]; /* Symbolic name of this SELECT use for debugging */ -#endif + u32 selId; /* Unique identifier number for this SELECT */ int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */ + ExprList *pEList; /* The fields of the result */ SrcList *pSrc; /* The FROM clause */ Expr *pWhere; /* The WHERE clause */ ExprList *pGroupBy; /* The GROUP BY clause */ @@ -15299,8 +18324,11 @@ struct Select { Select *pPrior; /* Prior select in a compound select statement */ Select *pNext; /* Next select to the left in a compound */ Expr *pLimit; /* LIMIT expression. NULL means not used. */ - Expr *pOffset; /* OFFSET expression. NULL means not used. */ With *pWith; /* WITH clause attached to this select. Or NULL. */ +#ifndef SQLITE_OMIT_WINDOWFUNC + Window *pWin; /* List of window functions */ + Window *pWinDefn; /* List of named window definitions */ +#endif }; /* @@ -15312,25 +18340,28 @@ struct Select { ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX ** SF_FixedLimit == WHERE_USE_LIMIT */ -#define SF_Distinct 0x00001 /* Output should be DISTINCT */ -#define SF_All 0x00002 /* Includes the ALL keyword */ -#define SF_Resolved 0x00004 /* Identifiers have been resolved */ -#define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */ -#define SF_HasAgg 0x00010 /* Contains aggregate functions */ -#define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */ -#define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */ -#define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */ -#define SF_Compound 0x00100 /* Part of a compound query */ -#define SF_Values 0x00200 /* Synthesized from VALUES clause */ -#define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */ -#define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */ -#define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */ -#define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */ -#define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */ -#define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */ -#define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */ -#define SF_IncludeHidden 0x20000 /* Include hidden columns in output */ - +#define SF_Distinct 0x0000001 /* Output should be DISTINCT */ +#define SF_All 0x0000002 /* Includes the ALL keyword */ +#define SF_Resolved 0x0000004 /* Identifiers have been resolved */ +#define SF_Aggregate 0x0000008 /* Contains agg functions or a GROUP BY */ +#define SF_HasAgg 0x0000010 /* Contains aggregate functions */ +#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */ +#define SF_Expanded 0x0000040 /* tdsqlite3SelectExpand() called on this */ +#define SF_HasTypeInfo 0x0000080 /* FROM subqueries have Table metadata */ +#define SF_Compound 0x0000100 /* Part of a compound query */ +#define SF_Values 0x0000200 /* Synthesized from VALUES clause */ +#define SF_MultiValue 0x0000400 /* Single VALUES term with multiple rows */ +#define SF_NestedFrom 0x0000800 /* Part of a parenthesized FROM clause */ +#define SF_MinMaxAgg 0x0001000 /* Aggregate containing min() or max() */ +#define SF_Recursive 0x0002000 /* The recursive part of a recursive CTE */ +#define SF_FixedLimit 0x0004000 /* nSelectRow set by a constant LIMIT */ +#define SF_MaybeConvert 0x0008000 /* Need convertCompoundSelectToSubquery() */ +#define SF_Converted 0x0010000 /* By convertCompoundSelectToSubquery() */ +#define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */ +#define SF_ComplexResult 0x0040000 /* Result contains subquery or function */ +#define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */ +#define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */ +#define SF_View 0x0200000 /* SELECT statement is a view */ /* ** The results of a SELECT can be distributed in several ways, as defined @@ -15421,10 +18452,10 @@ struct Select { */ struct SelectDest { u8 eDest; /* How to dispose of the results. On of SRT_* above. */ - char *zAffSdst; /* Affinity used when eDest==SRT_Set */ int iSDParm; /* A parameter used by the eDest disposal method */ int iSdst; /* Base register where results are written */ int nSdst; /* Number of registers allocated */ + char *zAffSdst; /* Affinity used when eDest==SRT_Set */ ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */ }; @@ -15445,13 +18476,6 @@ struct AutoincInfo { }; /* -** Size of the column cache -*/ -#ifndef SQLITE_N_COLCACHE -# define SQLITE_N_COLCACHE 10 -#endif - -/* ** At least one instance of the following structure is created for each ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE ** statement. All such objects are stored in the linked list headed at @@ -15485,8 +18509,8 @@ struct TriggerPrg { # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0) # define DbMaskZero(M) memset((M),0,sizeof(M)) # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7)) -# define DbMaskAllZero(M) sqlite3DbMaskAllZero(M) -# define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0) +# define DbMaskAllZero(M) tdsqlite3DbMaskAllZero(M) +# define DbMaskNonZero(M) (tdsqlite3DbMaskAllZero(M)==0) #else typedef unsigned int yDbMask; # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0) @@ -15507,13 +18531,13 @@ struct TriggerPrg { ** each recursion. ** ** The nTableLock and aTableLock variables are only used if the shared-cache -** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are +** feature is enabled (if tdsqlite3Tsd()->useSharedData is true). They are ** used to store the set of table-locks required by the statement being -** compiled. Function sqlite3TableLock() is used to add entries to the +** compiled. Function tdsqlite3TableLock() is used to add entries to the ** list. */ struct Parse { - sqlite3 *db; /* The main database structure */ + tdsqlite3 *db; /* The main database structure */ char *zErrMsg; /* An error message */ Vdbe *pVdbe; /* An engine for executing database bytecode */ int rc; /* Return code from execution */ @@ -15526,19 +18550,17 @@ struct Parse { u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */ u8 okConstFactor; /* OK to factor out constants */ u8 disableLookaside; /* Number of times lookaside has been disabled */ - u8 nColCache; /* Number of entries in aColCache[] */ + u8 disableVtab; /* Disable all virtual tables for this parse */ int nRangeReg; /* Size of the temporary register block */ int iRangeReg; /* First register in temporary register block */ int nErr; /* Number of errors seen */ int nTab; /* Number of previously allocated VDBE cursors */ int nMem; /* Number of memory cells used so far */ - int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */ int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */ - int ckBase; /* Base register of data during check constraints */ - int iSelfTab; /* Table of an index whose exprs are being coded */ - int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */ - int iCacheCnt; /* Counter used to generate aColCache[].lru values */ - int nLabel; /* Number of labels used */ + int iSelfTab; /* Table associated with an index on expr, or negative + ** of the base register during check-constraint eval */ + int nLabel; /* The *negative* of the number of labels used */ + int nLabelAlloc; /* Number of slots in aLabel */ int *aLabel; /* Space to hold the labels */ ExprList *pConstExpr;/* Constant expressions */ Token constraintName;/* Name of the constraint currently being parsed */ @@ -15547,10 +18569,7 @@ struct Parse { int regRowid; /* Register holding rowid of CREATE TABLE entry */ int regRoot; /* Register holding root page number for new objects */ int nMaxArg; /* Max args passed to user function by sub-program */ -#if SELECTTRACE_ENABLED - int nSelect; /* Number of SELECT statements seen */ - int nSelectIndent; /* How far to indent SELECTTRACE() output */ -#endif + int nSelect; /* Number of SELECT stmts. Counter for Select.selId */ #ifndef SQLITE_OMIT_SHARED_CACHE int nTableLock; /* Number of locks in aTableLock */ TableLock *aTableLock; /* Required table locks for shared-cache mode */ @@ -15558,7 +18577,8 @@ struct Parse { AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */ Parse *pToplevel; /* Parse structure for main program (or NULL) */ Table *pTriggerTab; /* Table triggers are being coded for */ - int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */ + Parse *pParentParse; /* Parent parser if this parser is nested */ + int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */ u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */ u32 oldmask; /* Mask of old.* columns referenced */ u32 newmask; /* Mask of new.* columns referenced */ @@ -15570,17 +18590,9 @@ struct Parse { ** Fields above must be initialized to zero. The fields that follow, ** down to the beginning of the recursive section, do not need to be ** initialized as they will be set before being used. The boundary is - ** determined by offsetof(Parse,aColCache). + ** determined by offsetof(Parse,aTempReg). **************************************************************************/ - struct yColCache { - int iTable; /* Table cursor number */ - i16 iColumn; /* Table column number */ - u8 tempReg; /* iReg is a temp register that needs to be freed */ - int iLevel; /* Nesting level */ - int iReg; /* Reg with value of this column. 0 means none. */ - int lru; /* Least recently used entry has the smallest value */ - } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */ int aTempReg[8]; /* Holding area for temporary registers */ Token sNameToken; /* Token with unqualified schema object name */ @@ -15593,22 +18605,25 @@ struct Parse { Token sLastToken; /* The last token parsed */ ynVar nVar; /* Number of '?' variables seen in the SQL so far */ - int nzVar; /* Number of available slots in azVar[] */ u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */ u8 explain; /* True if the EXPLAIN flag is found on the query */ +#if !(defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)) + u8 eParseMode; /* PARSE_MODE_XXX constant */ +#endif #ifndef SQLITE_OMIT_VIRTUALTABLE - u8 declareVtab; /* True if inside sqlite3_declare_vtab() */ int nVtabLock; /* Number of virtual tables to lock */ #endif int nHeight; /* Expression tree height of current sub-select */ #ifndef SQLITE_OMIT_EXPLAIN - int iSelectId; /* ID of current select for EXPLAIN output */ - int iNextSelectId; /* Next available select ID for EXPLAIN output */ + int addrExplain; /* Address of current OP_Explain opcode */ #endif - char **azVar; /* Pointers to names of parameters */ - Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */ + VList *pVList; /* Mapping between variable names and numbers */ + Vdbe *pReprepare; /* VM being reprepared (tdsqlite3Reprepare()) */ const char *zTail; /* All SQL text past the last semicolon parsed */ Table *pNewTable; /* A table being constructed by CREATE TABLE */ + Index *pNewIndex; /* An index being constructed by CREATE INDEX. + ** Also used to hold redundant UNIQUE constraints + ** during a RENAME COLUMN */ Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */ const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */ #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -15619,23 +18634,43 @@ struct Parse { TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */ With *pWith; /* Current WITH clause, or NULL */ With *pWithToFree; /* Free this WITH object at the end of the parse */ +#ifndef SQLITE_OMIT_ALTERTABLE + RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */ +#endif }; +#define PARSE_MODE_NORMAL 0 +#define PARSE_MODE_DECLARE_VTAB 1 +#define PARSE_MODE_RENAME 2 +#define PARSE_MODE_UNMAP 3 + /* ** Sizes and pointers of various parts of the Parse object. */ -#define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/ +#define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/ #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */ #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */ #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */ /* -** Return true if currently inside an sqlite3_declare_vtab() call. +** Return true if currently inside an tdsqlite3_declare_vtab() call. */ #ifdef SQLITE_OMIT_VIRTUALTABLE #define IN_DECLARE_VTAB 0 #else - #define IN_DECLARE_VTAB (pParse->declareVtab) + #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB) +#endif + +#if defined(SQLITE_OMIT_ALTERTABLE) + #define IN_RENAME_OBJECT 0 +#else + #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME) +#endif + +#if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE) + #define IN_SPECIAL_PARSE 0 +#else + #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL) #endif /* @@ -15661,14 +18696,13 @@ struct AuthContext { */ #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */ /* Also used in P2 (not P5) of OP_Delete */ +#define OPFLAG_NOCHNG 0x01 /* OP_VColumn nochange for UPDATE */ #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */ -#define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */ +#define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */ #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */ #define OPFLAG_APPEND 0x08 /* This is likely to be an append */ #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */ -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */ -#endif #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */ #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */ #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */ @@ -15676,15 +18710,16 @@ struct AuthContext { #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */ #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */ #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */ -#define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete: keep cursor position */ +#define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */ #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */ +#define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */ /* * Each trigger present in the database schema is stored as an instance of * struct Trigger. * * Pointers to instances of struct Trigger are stored in two ways. - * 1. In the "trigHash" hash table (part of the sqlite3* that represents the + * 1. In the "trigHash" hash table (part of the tdsqlite3* that represents the * database). This allows Trigger structures to be retrieved by name. * 2. All triggers associated with a single table form a linked list, using the * pNext member of struct Trigger. A pointer to the first element of the @@ -15752,7 +18787,7 @@ struct Trigger { * pWhere -> The WHERE clause of the UPDATE statement if one is specified. * Otherwise NULL. * pExprList -> A list of the columns to update and the expressions to update - * them to. See sqlite3Update() documentation of "pChanges" + * them to. See tdsqlite3Update() documentation of "pChanges" * argument. * */ @@ -15763,8 +18798,10 @@ struct TriggerStep { Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */ char *zTarget; /* Target table for DELETE, UPDATE, INSERT */ Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */ - ExprList *pExprList; /* SET clause for UPDATE. */ + ExprList *pExprList; /* SET clause for UPDATE */ IdList *pIdList; /* Column names for INSERT */ + Upsert *pUpsert; /* Upsert clauses on an INSERT */ + char *zSpan; /* Original SQL text of this command */ TriggerStep *pNext; /* Next in the link-list */ TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */ }; @@ -15778,7 +18815,7 @@ typedef struct DbFixer DbFixer; struct DbFixer { Parse *pParse; /* The parsing context. Error messages written here */ Schema *pSchema; /* Fix items to this schema */ - int bVarOnly; /* Check for variable references only */ + u8 bTemp; /* True for TEMP schema entries */ const char *zDb; /* Make sure all objects are contained in this database */ const char *zType; /* Type of the container - used for error messages */ const Token *pName; /* Name of the container - used for error messages */ @@ -15788,18 +18825,15 @@ struct DbFixer { ** An objected used to accumulate the text of a string where we ** do not necessarily know how big the string will be in the end. */ -struct StrAccum { - sqlite3 *db; /* Optional database for lookaside. Can be NULL */ - char *zBase; /* A base allocation. Not from malloc. */ +struct tdsqlite3_str { + tdsqlite3 *db; /* Optional database for lookaside. Can be NULL */ char *zText; /* The string collected so far */ - u32 nChar; /* Length of the string so far */ u32 nAlloc; /* Amount of space allocated in zText */ u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */ - u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */ + u32 nChar; /* Length of the string so far */ + u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */ u8 printfFlags; /* SQLITE_PRINTF flags below */ }; -#define STRACCUM_NOMEM 1 -#define STRACCUM_TOOBIG 2 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */ #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */ #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */ @@ -15809,42 +18843,48 @@ struct StrAccum { /* ** A pointer to this structure is used to communicate information -** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback. +** from tdsqlite3Init and OP_ParseSchema into the tdsqlite3InitCallback. */ typedef struct { - sqlite3 *db; /* The database being initialized */ + tdsqlite3 *db; /* The database being initialized */ char **pzErrMsg; /* Error message stored here */ int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */ int rc; /* Result code stored here */ + u32 mInitFlags; /* Flags controlling error messages */ + u32 nInitRow; /* Number of rows processed */ } InitData; /* +** Allowed values for mInitFlags +*/ +#define INITFLAG_AlterTable 0x0001 /* This is a reparse after ALTER TABLE */ + +/* ** Structure containing global configuration data for the SQLite library. ** ** This structure also contains some state information. */ struct Sqlite3Config { int bMemstat; /* True to enable memory status */ - int bCoreMutex; /* True to enable core mutexing */ - int bFullMutex; /* True to enable full mutexing */ - int bOpenUri; /* True to interpret filenames as URIs */ - int bUseCis; /* Use covering indices for full-scans */ + u8 bCoreMutex; /* True to enable core mutexing */ + u8 bFullMutex; /* True to enable full mutexing */ + u8 bOpenUri; /* True to interpret filenames as URIs */ + u8 bUseCis; /* Use covering indices for full-scans */ + u8 bSmallMalloc; /* Avoid large memory allocations if true */ + u8 bExtraSchemaChecks; /* Verify type,name,tbl_name in schema */ int mxStrlen; /* Maximum string length */ int neverCorrupt; /* Database is always well-formed */ int szLookaside; /* Default lookaside buffer size */ int nLookaside; /* Default lookaside buffer count */ int nStmtSpill; /* Stmt-journal spill-to-disk threshold */ - sqlite3_mem_methods m; /* Low-level memory allocation interface */ - sqlite3_mutex_methods mutex; /* Low-level mutex interface */ - sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */ + tdsqlite3_mem_methods m; /* Low-level memory allocation interface */ + tdsqlite3_mutex_methods mutex; /* Low-level mutex interface */ + tdsqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */ void *pHeap; /* Heap storage space */ int nHeap; /* Size of pHeap[] */ int mnReq, mxReq; /* Min and max heap requests sizes */ - sqlite3_int64 szMmap; /* mmap() space per open file */ - sqlite3_int64 mxMmap; /* Maximum value for szMmap */ - void *pScratch; /* Scratch memory */ - int szScratch; /* Size of each scratch buffer */ - int nScratch; /* Number of scratch buffers */ + tdsqlite3_int64 szMmap; /* mmap() space per open file */ + tdsqlite3_int64 mxMmap; /* Maximum value for szMmap */ void *pPage; /* Page cache memory */ int szPage; /* Size of each page in pPage[] */ int nPage; /* Number of pages in pPage[] */ @@ -15859,25 +18899,30 @@ struct Sqlite3Config { int isMallocInit; /* True after malloc is initialized */ int isPCacheInit; /* True after malloc is initialized */ int nRefInitMutex; /* Number of users of pInitMutex */ - sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */ + tdsqlite3_mutex *pInitMutex; /* Mutex used by tdsqlite3_initialize() */ void (*xLog)(void*,int,const char*); /* Function for logging */ void *pLogArg; /* First argument to xLog() */ #ifdef SQLITE_ENABLE_SQLLOG - void(*xSqllog)(void*,sqlite3*,const char*, int); + void(*xSqllog)(void*,tdsqlite3*,const char*, int); void *pSqllogArg; #endif #ifdef SQLITE_VDBE_COVERAGE /* The following callback (if not NULL) is invoked on every VDBE branch ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE. */ - void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */ + void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */ void *pVdbeBranchArg; /* 1st argument */ #endif -#ifndef SQLITE_OMIT_BUILTIN_TEST - int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */ +#ifdef SQLITE_ENABLE_DESERIALIZE + tdsqlite3_int64 mxMemdbSize; /* Default max memdb size */ +#endif +#ifndef SQLITE_UNTESTABLE + int (*xTestCallback)(int); /* Invoked by tdsqlite3FaultSim() */ #endif int bLocaltimeFault; /* True to fail localtime() calls */ int iOnceResetThreshold; /* When to reset OP_Once counters */ + u32 szSorterRef; /* Min size in bytes to use sorter-refs */ + unsigned int iPrngSeed; /* Alternative fixed seed for the PRNG */ }; /* @@ -15893,10 +18938,10 @@ struct Sqlite3Config { ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate ** that the database is definitely corrupt, only that it might be corrupt. ** For most test cases, CORRUPT_DB is set to false using a special -** sqlite3_test_control(). This enables assert() statements to prove +** tdsqlite3_test_control(). This enables assert() statements to prove ** things that are always true for well-formed databases. */ -#define CORRUPT_DB (sqlite3Config.neverCorrupt==0) +#define CORRUPT_DB (tdsqlite3Config.neverCorrupt==0) /* ** Context pointer passed down through the tree-walk. @@ -15907,26 +18952,38 @@ struct Walker { int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */ void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */ int walkerDepth; /* Number of subqueries */ - u8 eCode; /* A small processing code */ + u16 eCode; /* A small processing code */ union { /* Extra data for callback */ - NameContext *pNC; /* Naming context */ - int n; /* A counter */ - int iCur; /* A cursor number */ - SrcList *pSrcList; /* FROM clause */ - struct SrcCount *pSrcCount; /* Counting column references */ - struct CCurHint *pCCurHint; /* Used by codeCursorHint() */ - int *aiCol; /* array of column indexes */ - struct IdxCover *pIdxCover; /* Check for index coverage */ + NameContext *pNC; /* Naming context */ + int n; /* A counter */ + int iCur; /* A cursor number */ + SrcList *pSrcList; /* FROM clause */ + struct SrcCount *pSrcCount; /* Counting column references */ + struct CCurHint *pCCurHint; /* Used by codeCursorHint() */ + int *aiCol; /* array of column indexes */ + struct IdxCover *pIdxCover; /* Check for index coverage */ + struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */ + ExprList *pGroupBy; /* GROUP BY clause */ + Select *pSelect; /* HAVING to WHERE clause ctx */ + struct WindowRewrite *pRewrite; /* Window rewrite context */ + struct WhereConst *pConst; /* WHERE clause constants */ + struct RenameCtx *pRename; /* RENAME COLUMN context */ + struct Table *pTab; /* Table of generated column */ } u; }; /* Forward declarations */ -SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*); -SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*); -SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*); -SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*); -SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*); -SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*); +SQLITE_PRIVATE int tdsqlite3WalkExpr(Walker*, Expr*); +SQLITE_PRIVATE int tdsqlite3WalkExprList(Walker*, ExprList*); +SQLITE_PRIVATE int tdsqlite3WalkSelect(Walker*, Select*); +SQLITE_PRIVATE int tdsqlite3WalkSelectExpr(Walker*, Select*); +SQLITE_PRIVATE int tdsqlite3WalkSelectFrom(Walker*, Select*); +SQLITE_PRIVATE int tdsqlite3ExprWalkNoop(Walker*, Expr*); +SQLITE_PRIVATE int tdsqlite3SelectWalkNoop(Walker*, Select*); +SQLITE_PRIVATE int tdsqlite3SelectWalkFail(Walker*, Select*); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE void tdsqlite3SelectWalkAssert2(Walker*, Select*); +#endif /* ** Return code from the parse-tree walking primitives and their @@ -15954,7 +19011,7 @@ struct With { #ifdef SQLITE_DEBUG /* ** An instance of the TreeView object is used for printing the content of -** data structures on sqlite3DebugPrintf() using a tree-like view. +** data structures on tdsqlite3DebugPrintf() using a tree-like view. */ struct TreeView { int iLevel; /* Which level of the tree we are on */ @@ -15963,6 +19020,85 @@ struct TreeView { #endif /* SQLITE_DEBUG */ /* +** This object is used in various ways, most (but not all) related to window +** functions. +** +** (1) A single instance of this structure is attached to the +** the Expr.y.pWin field for each window function in an expression tree. +** This object holds the information contained in the OVER clause, +** plus additional fields used during code generation. +** +** (2) All window functions in a single SELECT form a linked-list +** attached to Select.pWin. The Window.pFunc and Window.pExpr +** fields point back to the expression that is the window function. +** +** (3) The terms of the WINDOW clause of a SELECT are instances of this +** object on a linked list attached to Select.pWinDefn. +** +** (4) For an aggregate function with a FILTER clause, an instance +** of this object is stored in Expr.y.pWin with eFrmType set to +** TK_FILTER. In this case the only field used is Window.pFilter. +** +** The uses (1) and (2) are really the same Window object that just happens +** to be accessible in two different ways. Use case (3) are separate objects. +*/ +struct Window { + char *zName; /* Name of window (may be NULL) */ + char *zBase; /* Name of base window for chaining (may be NULL) */ + ExprList *pPartition; /* PARTITION BY clause */ + ExprList *pOrderBy; /* ORDER BY clause */ + u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */ + u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */ + u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */ + u8 bImplicitFrame; /* True if frame was implicitly specified */ + u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */ + Expr *pStart; /* Expression for "<expr> PRECEDING" */ + Expr *pEnd; /* Expression for "<expr> FOLLOWING" */ + Window **ppThis; /* Pointer to this object in Select.pWin list */ + Window *pNextWin; /* Next window function belonging to this SELECT */ + Expr *pFilter; /* The FILTER expression */ + FuncDef *pFunc; /* The function */ + int iEphCsr; /* Partition buffer or Peer buffer */ + int regAccum; /* Accumulator */ + int regResult; /* Interim result */ + int csrApp; /* Function cursor (used by min/max) */ + int regApp; /* Function register (also used by min/max) */ + int regPart; /* Array of registers for PARTITION BY values */ + Expr *pOwner; /* Expression object this window is attached to */ + int nBufferCol; /* Number of columns in buffer table */ + int iArgCol; /* Offset of first argument for this function */ + int regOne; /* Register containing constant value 1 */ + int regStartRowid; + int regEndRowid; + u8 bExprArgs; /* Defer evaluation of window function arguments + ** due to the SQLITE_SUBTYPE flag */ +}; + +#ifndef SQLITE_OMIT_WINDOWFUNC +SQLITE_PRIVATE void tdsqlite3WindowDelete(tdsqlite3*, Window*); +SQLITE_PRIVATE void tdsqlite3WindowUnlinkFromSelect(Window*); +SQLITE_PRIVATE void tdsqlite3WindowListDelete(tdsqlite3 *db, Window *p); +SQLITE_PRIVATE Window *tdsqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8); +SQLITE_PRIVATE void tdsqlite3WindowAttach(Parse*, Expr*, Window*); +SQLITE_PRIVATE void tdsqlite3WindowLink(Select *pSel, Window *pWin); +SQLITE_PRIVATE int tdsqlite3WindowCompare(Parse*, Window*, Window*, int); +SQLITE_PRIVATE void tdsqlite3WindowCodeInit(Parse*, Select*); +SQLITE_PRIVATE void tdsqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int); +SQLITE_PRIVATE int tdsqlite3WindowRewrite(Parse*, Select*); +SQLITE_PRIVATE int tdsqlite3ExpandSubquery(Parse*, struct SrcList_item*); +SQLITE_PRIVATE void tdsqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*); +SQLITE_PRIVATE Window *tdsqlite3WindowDup(tdsqlite3 *db, Expr *pOwner, Window *p); +SQLITE_PRIVATE Window *tdsqlite3WindowListDup(tdsqlite3 *db, Window *p); +SQLITE_PRIVATE void tdsqlite3WindowFunctions(void); +SQLITE_PRIVATE void tdsqlite3WindowChain(Parse*, Window*, Window*); +SQLITE_PRIVATE Window *tdsqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*); +#else +# define tdsqlite3WindowDelete(a,b) +# define tdsqlite3WindowFunctions() +# define tdsqlite3WindowAttach(a,b,c) +#endif + +/* ** Assuming zIn points to the first byte of a UTF-8 character, ** advance zIn to point to the first byte of the next UTF-8 character. */ @@ -15976,23 +19112,27 @@ struct TreeView { ** The SQLITE_*_BKPT macros are substitutes for the error codes with ** the same name but without the _BKPT suffix. These macros invoke ** routines that report the line-number on which the error originated -** using sqlite3_log(). The routines also provide a convenient place +** using tdsqlite3_log(). The routines also provide a convenient place ** to set a debugger breakpoint. */ -SQLITE_PRIVATE int sqlite3CorruptError(int); -SQLITE_PRIVATE int sqlite3MisuseError(int); -SQLITE_PRIVATE int sqlite3CantopenError(int); -#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__) -#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__) -#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__) +SQLITE_PRIVATE int tdsqlite3ReportError(int iErr, int lineno, const char *zType); +SQLITE_PRIVATE int tdsqlite3CorruptError(int); +SQLITE_PRIVATE int tdsqlite3MisuseError(int); +SQLITE_PRIVATE int tdsqlite3CantopenError(int); +#define SQLITE_CORRUPT_BKPT tdsqlite3CorruptError(__LINE__) +#define SQLITE_MISUSE_BKPT tdsqlite3MisuseError(__LINE__) +#define SQLITE_CANTOPEN_BKPT tdsqlite3CantopenError(__LINE__) #ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3NomemError(int); -SQLITE_PRIVATE int sqlite3IoerrnomemError(int); -# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__) -# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__) +SQLITE_PRIVATE int tdsqlite3NomemError(int); +SQLITE_PRIVATE int tdsqlite3IoerrnomemError(int); +SQLITE_PRIVATE int tdsqlite3CorruptPgnoError(int,Pgno); +# define SQLITE_NOMEM_BKPT tdsqlite3NomemError(__LINE__) +# define SQLITE_IOERR_NOMEM_BKPT tdsqlite3IoerrnomemError(__LINE__) +# define SQLITE_CORRUPT_PGNO(P) tdsqlite3CorruptPgnoError(__LINE__,(P)) #else # define SQLITE_NOMEM_BKPT SQLITE_NOMEM # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM +# define SQLITE_CORRUPT_PGNO(P) tdsqlite3CorruptError(__LINE__) #endif /* @@ -16027,60 +19167,59 @@ SQLITE_PRIVATE int sqlite3IoerrnomemError(int); ** sqlite versions only work for ASCII characters, regardless of locale. */ #ifdef SQLITE_ASCII -# define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) -# define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01) -# define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06) -# define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02) -# define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04) -# define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08) -# define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)]) -# define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80) -#else -# define sqlite3Toupper(x) toupper((unsigned char)(x)) -# define sqlite3Isspace(x) isspace((unsigned char)(x)) -# define sqlite3Isalnum(x) isalnum((unsigned char)(x)) -# define sqlite3Isalpha(x) isalpha((unsigned char)(x)) -# define sqlite3Isdigit(x) isdigit((unsigned char)(x)) -# define sqlite3Isxdigit(x) isxdigit((unsigned char)(x)) -# define sqlite3Tolower(x) tolower((unsigned char)(x)) -# define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`') -#endif -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -SQLITE_PRIVATE int sqlite3IsIdChar(u8); +# define tdsqlite3Toupper(x) ((x)&~(tdsqlite3CtypeMap[(unsigned char)(x)]&0x20)) +# define tdsqlite3Isspace(x) (tdsqlite3CtypeMap[(unsigned char)(x)]&0x01) +# define tdsqlite3Isalnum(x) (tdsqlite3CtypeMap[(unsigned char)(x)]&0x06) +# define tdsqlite3Isalpha(x) (tdsqlite3CtypeMap[(unsigned char)(x)]&0x02) +# define tdsqlite3Isdigit(x) (tdsqlite3CtypeMap[(unsigned char)(x)]&0x04) +# define tdsqlite3Isxdigit(x) (tdsqlite3CtypeMap[(unsigned char)(x)]&0x08) +# define tdsqlite3Tolower(x) (tdsqlite3UpperToLower[(unsigned char)(x)]) +# define tdsqlite3Isquote(x) (tdsqlite3CtypeMap[(unsigned char)(x)]&0x80) +#else +# define tdsqlite3Toupper(x) toupper((unsigned char)(x)) +# define tdsqlite3Isspace(x) isspace((unsigned char)(x)) +# define tdsqlite3Isalnum(x) isalnum((unsigned char)(x)) +# define tdsqlite3Isalpha(x) isalpha((unsigned char)(x)) +# define tdsqlite3Isdigit(x) isdigit((unsigned char)(x)) +# define tdsqlite3Isxdigit(x) isxdigit((unsigned char)(x)) +# define tdsqlite3Tolower(x) tolower((unsigned char)(x)) +# define tdsqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`') #endif +SQLITE_PRIVATE int tdsqlite3IsIdChar(u8); /* ** Internal function prototypes */ -SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*); -SQLITE_PRIVATE int sqlite3Strlen30(const char*); -SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*); -#define sqlite3StrNICmp sqlite3_strnicmp - -SQLITE_PRIVATE int sqlite3MallocInit(void); -SQLITE_PRIVATE void sqlite3MallocEnd(void); -SQLITE_PRIVATE void *sqlite3Malloc(u64); -SQLITE_PRIVATE void *sqlite3MallocZero(u64); -SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64); -SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64); -SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64); -SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*); -SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64); -SQLITE_PRIVATE void *sqlite3Realloc(void*, u64); -SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64); -SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64); -SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*); -SQLITE_PRIVATE int sqlite3MallocSize(void*); -SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*); -SQLITE_PRIVATE void *sqlite3ScratchMalloc(int); -SQLITE_PRIVATE void sqlite3ScratchFree(void*); -SQLITE_PRIVATE void *sqlite3PageMalloc(int); -SQLITE_PRIVATE void sqlite3PageFree(void*); -SQLITE_PRIVATE void sqlite3MemSetDefault(void); -#ifndef SQLITE_OMIT_BUILTIN_TEST -SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void)); -#endif -SQLITE_PRIVATE int sqlite3HeapNearlyFull(void); +SQLITE_PRIVATE int tdsqlite3StrICmp(const char*,const char*); +SQLITE_PRIVATE int tdsqlite3Strlen30(const char*); +#define tdsqlite3Strlen30NN(C) (strlen(C)&0x3fffffff) +SQLITE_PRIVATE char *tdsqlite3ColumnType(Column*,char*); +#define tdsqlite3StrNICmp tdsqlite3_strnicmp + +SQLITE_PRIVATE int tdsqlite3MallocInit(void); +SQLITE_PRIVATE void tdsqlite3MallocEnd(void); +SQLITE_PRIVATE void *tdsqlite3Malloc(u64); +SQLITE_PRIVATE void *tdsqlite3MallocZero(u64); +SQLITE_PRIVATE void *tdsqlite3DbMallocZero(tdsqlite3*, u64); +SQLITE_PRIVATE void *tdsqlite3DbMallocRaw(tdsqlite3*, u64); +SQLITE_PRIVATE void *tdsqlite3DbMallocRawNN(tdsqlite3*, u64); +SQLITE_PRIVATE char *tdsqlite3DbStrDup(tdsqlite3*,const char*); +SQLITE_PRIVATE char *tdsqlite3DbStrNDup(tdsqlite3*,const char*, u64); +SQLITE_PRIVATE char *tdsqlite3DbSpanDup(tdsqlite3*,const char*,const char*); +SQLITE_PRIVATE void *tdsqlite3Realloc(void*, u64); +SQLITE_PRIVATE void *tdsqlite3DbReallocOrFree(tdsqlite3 *, void *, u64); +SQLITE_PRIVATE void *tdsqlite3DbRealloc(tdsqlite3 *, void *, u64); +SQLITE_PRIVATE void tdsqlite3DbFree(tdsqlite3*, void*); +SQLITE_PRIVATE void tdsqlite3DbFreeNN(tdsqlite3*, void*); +SQLITE_PRIVATE int tdsqlite3MallocSize(void*); +SQLITE_PRIVATE int tdsqlite3DbMallocSize(tdsqlite3*, void*); +SQLITE_PRIVATE void *tdsqlite3PageMalloc(int); +SQLITE_PRIVATE void tdsqlite3PageFree(void*); +SQLITE_PRIVATE void tdsqlite3MemSetDefault(void); +#ifndef SQLITE_UNTESTABLE +SQLITE_PRIVATE void tdsqlite3BenignMallocHooks(void (*)(void), void (*)(void)); +#endif +SQLITE_PRIVATE int tdsqlite3HeapNearlyFull(void); /* ** On systems with ample stack space and that support alloca(), make @@ -16088,56 +19227,67 @@ SQLITE_PRIVATE int sqlite3HeapNearlyFull(void); ** obtain space from malloc(). ** ** The alloca() routine never returns NULL. This will cause code paths -** that deal with sqlite3StackAlloc() failures to be unreachable. +** that deal with tdsqlite3StackAlloc() failures to be unreachable. */ #ifdef SQLITE_USE_ALLOCA -# define sqlite3StackAllocRaw(D,N) alloca(N) -# define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N) -# define sqlite3StackFree(D,P) +# define tdsqlite3StackAllocRaw(D,N) alloca(N) +# define tdsqlite3StackAllocZero(D,N) memset(alloca(N), 0, N) +# define tdsqlite3StackFree(D,P) #else -# define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N) -# define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N) -# define sqlite3StackFree(D,P) sqlite3DbFree(D,P) +# define tdsqlite3StackAllocRaw(D,N) tdsqlite3DbMallocRaw(D,N) +# define tdsqlite3StackAllocZero(D,N) tdsqlite3DbMallocZero(D,N) +# define tdsqlite3StackFree(D,P) tdsqlite3DbFree(D,P) #endif /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they ** are, disable MEMSYS3 */ #ifdef SQLITE_ENABLE_MEMSYS5 -SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void); +SQLITE_PRIVATE const tdsqlite3_mem_methods *tdsqlite3MemGetMemsys5(void); #undef SQLITE_ENABLE_MEMSYS3 #endif #ifdef SQLITE_ENABLE_MEMSYS3 -SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void); +SQLITE_PRIVATE const tdsqlite3_mem_methods *tdsqlite3MemGetMemsys3(void); #endif #ifndef SQLITE_MUTEX_OMIT -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void); -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void); -SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int); -SQLITE_PRIVATE int sqlite3MutexInit(void); -SQLITE_PRIVATE int sqlite3MutexEnd(void); +SQLITE_PRIVATE tdsqlite3_mutex_methods const *tdsqlite3DefaultMutex(void); +SQLITE_PRIVATE tdsqlite3_mutex_methods const *tdsqlite3NoopMutex(void); +SQLITE_PRIVATE tdsqlite3_mutex *tdsqlite3MutexAlloc(int); +SQLITE_PRIVATE int tdsqlite3MutexInit(void); +SQLITE_PRIVATE int tdsqlite3MutexEnd(void); #endif #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP) -SQLITE_PRIVATE void sqlite3MemoryBarrier(void); +SQLITE_PRIVATE void tdsqlite3MemoryBarrier(void); #else -# define sqlite3MemoryBarrier() +# define tdsqlite3MemoryBarrier() #endif -SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int); -SQLITE_PRIVATE void sqlite3StatusUp(int, int); -SQLITE_PRIVATE void sqlite3StatusDown(int, int); -SQLITE_PRIVATE void sqlite3StatusHighwater(int, int); +SQLITE_PRIVATE tdsqlite3_int64 tdsqlite3StatusValue(int); +SQLITE_PRIVATE void tdsqlite3StatusUp(int, int); +SQLITE_PRIVATE void tdsqlite3StatusDown(int, int); +SQLITE_PRIVATE void tdsqlite3StatusHighwater(int, int); +SQLITE_PRIVATE int tdsqlite3LookasideUsed(tdsqlite3*,int*); -/* Access to mutexes used by sqlite3_status() */ -SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void); -SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void); +/* Access to mutexes used by tdsqlite3_status() */ +SQLITE_PRIVATE tdsqlite3_mutex *tdsqlite3Pcache1Mutex(void); +SQLITE_PRIVATE tdsqlite3_mutex *tdsqlite3MallocMutex(void); + +#if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT) +SQLITE_PRIVATE void tdsqlite3MutexWarnOnContention(tdsqlite3_mutex*); +#else +# define tdsqlite3MutexWarnOnContention(x) +#endif #ifndef SQLITE_OMIT_FLOATING_POINT -SQLITE_PRIVATE int sqlite3IsNaN(double); +# define EXP754 (((u64)0x7ff)<<52) +# define MAN754 ((((u64)1)<<52)-1) +# define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0) +SQLITE_PRIVATE int tdsqlite3IsNaN(double); #else -# define sqlite3IsNaN(X) 0 +# define IsNaN(X) 0 +# define tdsqlite3IsNaN(X) 0 #endif /* @@ -16147,370 +19297,418 @@ SQLITE_PRIVATE int sqlite3IsNaN(double); struct PrintfArguments { int nArg; /* Total number of arguments */ int nUsed; /* Number of arguments used so far */ - sqlite3_value **apArg; /* The argument values */ + tdsqlite3_value **apArg; /* The argument values */ }; -SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list); -SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...); -SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...); -SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list); +SQLITE_PRIVATE char *tdsqlite3MPrintf(tdsqlite3*,const char*, ...); +SQLITE_PRIVATE char *tdsqlite3VMPrintf(tdsqlite3*,const char*, va_list); #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) -SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...); +SQLITE_PRIVATE void tdsqlite3DebugPrintf(const char*, ...); #endif #if defined(SQLITE_TEST) -SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*); +SQLITE_PRIVATE void *tdsqlite3TestTextToPtr(const char*); #endif #if defined(SQLITE_DEBUG) -SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8); -SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*); -SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*); -SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8); -SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8); -#endif - - -SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*); -SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...); -SQLITE_PRIVATE void sqlite3Dequote(char*); -SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*); -SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int); -SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **); -SQLITE_PRIVATE void sqlite3FinishCoding(Parse*); -SQLITE_PRIVATE int sqlite3GetTempReg(Parse*); -SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int); -SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int); -SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int); -SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*); +SQLITE_PRIVATE void tdsqlite3TreeViewExpr(TreeView*, const Expr*, u8); +SQLITE_PRIVATE void tdsqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*); +SQLITE_PRIVATE void tdsqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*); +SQLITE_PRIVATE void tdsqlite3TreeViewSrcList(TreeView*, const SrcList*); +SQLITE_PRIVATE void tdsqlite3TreeViewSelect(TreeView*, const Select*, u8); +SQLITE_PRIVATE void tdsqlite3TreeViewWith(TreeView*, const With*, u8); +#ifndef SQLITE_OMIT_WINDOWFUNC +SQLITE_PRIVATE void tdsqlite3TreeViewWindow(TreeView*, const Window*, u8); +SQLITE_PRIVATE void tdsqlite3TreeViewWinFunc(TreeView*, const Window*, u8); +#endif +#endif + + +SQLITE_PRIVATE void tdsqlite3SetString(char **, tdsqlite3*, const char*); +SQLITE_PRIVATE void tdsqlite3ErrorMsg(Parse*, const char*, ...); +SQLITE_PRIVATE int tdsqlite3ErrorToParser(tdsqlite3*,int); +SQLITE_PRIVATE void tdsqlite3Dequote(char*); +SQLITE_PRIVATE void tdsqlite3DequoteExpr(Expr*); +SQLITE_PRIVATE void tdsqlite3TokenInit(Token*,char*); +SQLITE_PRIVATE int tdsqlite3KeywordCode(const unsigned char*, int); +SQLITE_PRIVATE int tdsqlite3RunParser(Parse*, const char*, char **); +SQLITE_PRIVATE void tdsqlite3FinishCoding(Parse*); +SQLITE_PRIVATE int tdsqlite3GetTempReg(Parse*); +SQLITE_PRIVATE void tdsqlite3ReleaseTempReg(Parse*,int); +SQLITE_PRIVATE int tdsqlite3GetTempRange(Parse*,int); +SQLITE_PRIVATE void tdsqlite3ReleaseTempRange(Parse*,int,int); +SQLITE_PRIVATE void tdsqlite3ClearTempRegCache(Parse*); #ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int); -#endif -SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int); -SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*); -SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*); -SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*); -SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*); -SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*); -SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*); -SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32); -SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*); -SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*); -SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*); -SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int); -SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int); -SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*); -SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*); -SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*); -SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**); -SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**); -SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int); -SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*); -SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int); -SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*); -SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*); -SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*); -SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**); -SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*); -SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*); -SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int); -SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*); -SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16); -SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int); +SQLITE_PRIVATE int tdsqlite3NoTempsInRange(Parse*,int,int); +#endif +SQLITE_PRIVATE Expr *tdsqlite3ExprAlloc(tdsqlite3*,int,const Token*,int); +SQLITE_PRIVATE Expr *tdsqlite3Expr(tdsqlite3*,int,const char*); +SQLITE_PRIVATE void tdsqlite3ExprAttachSubtrees(tdsqlite3*,Expr*,Expr*,Expr*); +SQLITE_PRIVATE Expr *tdsqlite3PExpr(Parse*, int, Expr*, Expr*); +SQLITE_PRIVATE void tdsqlite3PExprAddSelect(Parse*, Expr*, Select*); +SQLITE_PRIVATE Expr *tdsqlite3ExprAnd(Parse*,Expr*, Expr*); +SQLITE_PRIVATE Expr *tdsqlite3ExprSimplifiedAndOr(Expr*); +SQLITE_PRIVATE Expr *tdsqlite3ExprFunction(Parse*,ExprList*, Token*, int); +SQLITE_PRIVATE void tdsqlite3ExprFunctionUsable(Parse*,Expr*,FuncDef*); +SQLITE_PRIVATE void tdsqlite3ExprAssignVarNumber(Parse*, Expr*, u32); +SQLITE_PRIVATE void tdsqlite3ExprDelete(tdsqlite3*, Expr*); +SQLITE_PRIVATE void tdsqlite3ExprUnmapAndDelete(Parse*, Expr*); +SQLITE_PRIVATE ExprList *tdsqlite3ExprListAppend(Parse*,ExprList*,Expr*); +SQLITE_PRIVATE ExprList *tdsqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*); +SQLITE_PRIVATE void tdsqlite3ExprListSetSortOrder(ExprList*,int,int); +SQLITE_PRIVATE void tdsqlite3ExprListSetName(Parse*,ExprList*,Token*,int); +SQLITE_PRIVATE void tdsqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*); +SQLITE_PRIVATE void tdsqlite3ExprListDelete(tdsqlite3*, ExprList*); +SQLITE_PRIVATE u32 tdsqlite3ExprListFlags(const ExprList*); +SQLITE_PRIVATE int tdsqlite3IndexHasDuplicateRootPage(Index*); +SQLITE_PRIVATE int tdsqlite3Init(tdsqlite3*, char**); +SQLITE_PRIVATE int tdsqlite3InitCallback(void*, int, char**, char**); +SQLITE_PRIVATE int tdsqlite3InitOne(tdsqlite3*, int, char**, u32); +SQLITE_PRIVATE void tdsqlite3Pragma(Parse*,Token*,Token*,Token*,int); +#ifndef SQLITE_OMIT_VIRTUALTABLE +SQLITE_PRIVATE Module *tdsqlite3PragmaVtabRegister(tdsqlite3*,const char *zName); +#endif +SQLITE_PRIVATE void tdsqlite3ResetAllSchemasOfConnection(tdsqlite3*); +SQLITE_PRIVATE void tdsqlite3ResetOneSchema(tdsqlite3*,int); +SQLITE_PRIVATE void tdsqlite3CollapseDatabaseArray(tdsqlite3*); +SQLITE_PRIVATE void tdsqlite3CommitInternalChanges(tdsqlite3*); +SQLITE_PRIVATE void tdsqlite3DeleteColumnNames(tdsqlite3*,Table*); +SQLITE_PRIVATE int tdsqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**); +SQLITE_PRIVATE void tdsqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*,char); +SQLITE_PRIVATE Table *tdsqlite3ResultSetOfSelect(Parse*,Select*,char); +SQLITE_PRIVATE void tdsqlite3OpenMasterTable(Parse *, int); +SQLITE_PRIVATE Index *tdsqlite3PrimaryKeyIndex(Table*); +SQLITE_PRIVATE i16 tdsqlite3TableColumnToIndex(Index*, i16); +#ifdef SQLITE_OMIT_GENERATED_COLUMNS +# define tdsqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */ +# define tdsqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */ +#else +SQLITE_PRIVATE i16 tdsqlite3TableColumnToStorage(Table*, i16); +SQLITE_PRIVATE i16 tdsqlite3StorageColumnToTable(Table*, i16); +#endif +SQLITE_PRIVATE void tdsqlite3StartTable(Parse*,Token*,Token*,int,int,int,int); #if SQLITE_ENABLE_HIDDEN_COLUMNS -SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*); +SQLITE_PRIVATE void tdsqlite3ColumnPropertiesFromName(Table*, Column*); +#else +# define tdsqlite3ColumnPropertiesFromName(T,C) /* no-op */ +#endif +SQLITE_PRIVATE void tdsqlite3AddColumn(Parse*,Token*,Token*); +SQLITE_PRIVATE void tdsqlite3AddNotNull(Parse*, int); +SQLITE_PRIVATE void tdsqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int); +SQLITE_PRIVATE void tdsqlite3AddCheckConstraint(Parse*, Expr*); +SQLITE_PRIVATE void tdsqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*); +SQLITE_PRIVATE void tdsqlite3AddCollateType(Parse*, Token*); +SQLITE_PRIVATE void tdsqlite3AddGenerated(Parse*,Expr*,Token*); +SQLITE_PRIVATE void tdsqlite3EndTable(Parse*,Token*,Token*,u8,Select*); +SQLITE_PRIVATE int tdsqlite3ParseUri(const char*,const char*,unsigned int*, + tdsqlite3_vfs**,char**,char **); +#ifdef SQLITE_HAS_CODEC +SQLITE_PRIVATE int tdsqlite3CodecQueryParameters(tdsqlite3*,const char*,const char*); #else -# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */ +# define tdsqlite3CodecQueryParameters(A,B,C) 0 #endif -SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*); -SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int); -SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int); -SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*); -SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*); -SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*); -SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*); -SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*, - sqlite3_vfs**,char**,char **); -SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*); +SQLITE_PRIVATE Btree *tdsqlite3DbNameToBtree(tdsqlite3*,const char*); -#ifdef SQLITE_OMIT_BUILTIN_TEST -# define sqlite3FaultSim(X) SQLITE_OK +#ifdef SQLITE_UNTESTABLE +# define tdsqlite3FaultSim(X) SQLITE_OK #else -SQLITE_PRIVATE int sqlite3FaultSim(int); +SQLITE_PRIVATE int tdsqlite3FaultSim(int); #endif -SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32); -SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32); -SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32); -SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32); -SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*); -SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*); -SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*); -#ifndef SQLITE_OMIT_BUILTIN_TEST -SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*); +SQLITE_PRIVATE Bitvec *tdsqlite3BitvecCreate(u32); +SQLITE_PRIVATE int tdsqlite3BitvecTest(Bitvec*, u32); +SQLITE_PRIVATE int tdsqlite3BitvecTestNotNull(Bitvec*, u32); +SQLITE_PRIVATE int tdsqlite3BitvecSet(Bitvec*, u32); +SQLITE_PRIVATE void tdsqlite3BitvecClear(Bitvec*, u32, void*); +SQLITE_PRIVATE void tdsqlite3BitvecDestroy(Bitvec*); +SQLITE_PRIVATE u32 tdsqlite3BitvecSize(Bitvec*); +#ifndef SQLITE_UNTESTABLE +SQLITE_PRIVATE int tdsqlite3BitvecBuiltinTest(int,int*); #endif -SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int); -SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*); -SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64); -SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64); -SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*); +SQLITE_PRIVATE RowSet *tdsqlite3RowSetInit(tdsqlite3*); +SQLITE_PRIVATE void tdsqlite3RowSetDelete(void*); +SQLITE_PRIVATE void tdsqlite3RowSetClear(void*); +SQLITE_PRIVATE void tdsqlite3RowSetInsert(RowSet*, i64); +SQLITE_PRIVATE int tdsqlite3RowSetTest(RowSet*, int iBatch, i64); +SQLITE_PRIVATE int tdsqlite3RowSetNext(RowSet*, i64*); -SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int); +SQLITE_PRIVATE void tdsqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int); #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) -SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*); +SQLITE_PRIVATE int tdsqlite3ViewGetColumnNames(Parse*,Table*); #else -# define sqlite3ViewGetColumnNames(A,B) 0 +# define tdsqlite3ViewGetColumnNames(A,B) 0 #endif #if SQLITE_MAX_ATTACHED>30 -SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask); +SQLITE_PRIVATE int tdsqlite3DbMaskAllZero(yDbMask); #endif -SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int); -SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int); -SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*); +SQLITE_PRIVATE void tdsqlite3DropTable(Parse*, SrcList*, int, int); +SQLITE_PRIVATE void tdsqlite3CodeDropTable(Parse*, Table*, int, int); +SQLITE_PRIVATE void tdsqlite3DeleteTable(tdsqlite3*, Table*); +SQLITE_PRIVATE void tdsqlite3FreeIndex(tdsqlite3*, Index*); #ifndef SQLITE_OMIT_AUTOINCREMENT -SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse); -SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse); -#else -# define sqlite3AutoincrementBegin(X) -# define sqlite3AutoincrementEnd(X) -#endif -SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int); -SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*); -SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*); -SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*); -SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int); -SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*); -SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, +SQLITE_PRIVATE void tdsqlite3AutoincrementBegin(Parse *pParse); +SQLITE_PRIVATE void tdsqlite3AutoincrementEnd(Parse *pParse); +#else +# define tdsqlite3AutoincrementBegin(X) +# define tdsqlite3AutoincrementEnd(X) +#endif +SQLITE_PRIVATE void tdsqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*); +#ifndef SQLITE_OMIT_GENERATED_COLUMNS +SQLITE_PRIVATE void tdsqlite3ComputeGeneratedColumns(Parse*, int, Table*); +#endif +SQLITE_PRIVATE void *tdsqlite3ArrayAllocate(tdsqlite3*,void*,int,int*,int*); +SQLITE_PRIVATE IdList *tdsqlite3IdListAppend(Parse*, IdList*, Token*); +SQLITE_PRIVATE int tdsqlite3IdListIndex(IdList*,const char*); +SQLITE_PRIVATE SrcList *tdsqlite3SrcListEnlarge(Parse*, SrcList*, int, int); +SQLITE_PRIVATE SrcList *tdsqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*); +SQLITE_PRIVATE SrcList *tdsqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, Token*, Select*, Expr*, IdList*); -SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *); -SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*); -SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *); -SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*); -SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*); -SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*); -SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*); -SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**); -SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, +SQLITE_PRIVATE void tdsqlite3SrcListIndexedBy(Parse *, SrcList *, Token *); +SQLITE_PRIVATE void tdsqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*); +SQLITE_PRIVATE int tdsqlite3IndexedByLookup(Parse *, struct SrcList_item *); +SQLITE_PRIVATE void tdsqlite3SrcListShiftJoinType(SrcList*); +SQLITE_PRIVATE void tdsqlite3SrcListAssignCursors(Parse*, SrcList*); +SQLITE_PRIVATE void tdsqlite3IdListDelete(tdsqlite3*, IdList*); +SQLITE_PRIVATE void tdsqlite3SrcListDelete(tdsqlite3*, SrcList*); +SQLITE_PRIVATE Index *tdsqlite3AllocateIndexObject(tdsqlite3*,i16,int,char**); +SQLITE_PRIVATE void tdsqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, Expr*, int, int, u8); -SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int); -SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*); -SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*, - Expr*,ExprList*,u32,Expr*,Expr*); -SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*); -SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*); -SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int); -SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int); +SQLITE_PRIVATE void tdsqlite3DropIndex(Parse*, SrcList*, int); +SQLITE_PRIVATE int tdsqlite3Select(Parse*, Select*, SelectDest*); +SQLITE_PRIVATE Select *tdsqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*, + Expr*,ExprList*,u32,Expr*); +SQLITE_PRIVATE void tdsqlite3SelectDelete(tdsqlite3*, Select*); +SQLITE_PRIVATE void tdsqlite3SelectReset(Parse*, Select*); +SQLITE_PRIVATE Table *tdsqlite3SrcListLookup(Parse*, SrcList*); +SQLITE_PRIVATE int tdsqlite3IsReadOnly(Parse*, Table*, int); +SQLITE_PRIVATE void tdsqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int); #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) -SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*); -#endif -SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*); -SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int); -SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int); -SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*); -SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*); +SQLITE_PRIVATE Expr *tdsqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*); +#endif +SQLITE_PRIVATE void tdsqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*); +SQLITE_PRIVATE void tdsqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*, + Upsert*); +SQLITE_PRIVATE WhereInfo *tdsqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int); +SQLITE_PRIVATE void tdsqlite3WhereEnd(WhereInfo*); +SQLITE_PRIVATE LogEst tdsqlite3WhereOutputRowCount(WhereInfo*); +SQLITE_PRIVATE int tdsqlite3WhereIsDistinct(WhereInfo*); +SQLITE_PRIVATE int tdsqlite3WhereIsOrdered(WhereInfo*); +SQLITE_PRIVATE int tdsqlite3WhereOrderByLimitOptLabel(WhereInfo*); +SQLITE_PRIVATE int tdsqlite3WhereIsSorted(WhereInfo*); +SQLITE_PRIVATE int tdsqlite3WhereContinueLabel(WhereInfo*); +SQLITE_PRIVATE int tdsqlite3WhereBreakLabel(WhereInfo*); +SQLITE_PRIVATE int tdsqlite3WhereOkOnePass(WhereInfo*, int*); #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */ #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */ #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */ -SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int); -SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8); -SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int); -SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int); -SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int); -SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int); -SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*); -SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*); -SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int); -SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*); -SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int); -SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int); -SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int); -SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int); -SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8); -SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*); -SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int); -SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int); -SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8); +SQLITE_PRIVATE int tdsqlite3WhereUsesDeferredSeek(WhereInfo*); +SQLITE_PRIVATE void tdsqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int); +SQLITE_PRIVATE int tdsqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8); +SQLITE_PRIVATE void tdsqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int); +SQLITE_PRIVATE void tdsqlite3ExprCodeMove(Parse*, int, int, int); +SQLITE_PRIVATE void tdsqlite3ExprCode(Parse*, Expr*, int); +#ifndef SQLITE_OMIT_GENERATED_COLUMNS +SQLITE_PRIVATE void tdsqlite3ExprCodeGeneratedColumn(Parse*, Column*, int); +#endif +SQLITE_PRIVATE void tdsqlite3ExprCodeCopy(Parse*, Expr*, int); +SQLITE_PRIVATE void tdsqlite3ExprCodeFactorable(Parse*, Expr*, int); +SQLITE_PRIVATE int tdsqlite3ExprCodeAtInit(Parse*, Expr*, int); +SQLITE_PRIVATE int tdsqlite3ExprCodeTemp(Parse*, Expr*, int*); +SQLITE_PRIVATE int tdsqlite3ExprCodeTarget(Parse*, Expr*, int); +SQLITE_PRIVATE int tdsqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8); #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */ #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */ #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */ -SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int); -SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int); -SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int); -SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*); +#define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */ +SQLITE_PRIVATE void tdsqlite3ExprIfTrue(Parse*, Expr*, int, int); +SQLITE_PRIVATE void tdsqlite3ExprIfFalse(Parse*, Expr*, int, int); +SQLITE_PRIVATE void tdsqlite3ExprIfFalseDup(Parse*, Expr*, int, int); +SQLITE_PRIVATE Table *tdsqlite3FindTable(tdsqlite3*,const char*, const char*); #define LOCATE_VIEW 0x01 #define LOCATE_NOERR 0x02 -SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*); -SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *); -SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*); -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*); -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*); -SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*); -SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int); -SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*); -SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int); -SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int); -SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int); -SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*); -SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*); -SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx); -SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*); -SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*); -#ifndef SQLITE_OMIT_BUILTIN_TEST -SQLITE_PRIVATE void sqlite3PrngSaveState(void); -SQLITE_PRIVATE void sqlite3PrngRestoreState(void); -#endif -SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int); -SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int); -SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb); -SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int); -SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*); -SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*); -SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*); -SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *); -SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*); -SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*); -SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*); -SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8); -SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int); +SQLITE_PRIVATE Table *tdsqlite3LocateTable(Parse*,u32 flags,const char*, const char*); +SQLITE_PRIVATE Table *tdsqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *); +SQLITE_PRIVATE Index *tdsqlite3FindIndex(tdsqlite3*,const char*, const char*); +SQLITE_PRIVATE void tdsqlite3UnlinkAndDeleteTable(tdsqlite3*,int,const char*); +SQLITE_PRIVATE void tdsqlite3UnlinkAndDeleteIndex(tdsqlite3*,int,const char*); +SQLITE_PRIVATE void tdsqlite3Vacuum(Parse*,Token*,Expr*); +SQLITE_PRIVATE int tdsqlite3RunVacuum(char**, tdsqlite3*, int, tdsqlite3_value*); +SQLITE_PRIVATE char *tdsqlite3NameFromToken(tdsqlite3*, Token*); +SQLITE_PRIVATE int tdsqlite3ExprCompare(Parse*,Expr*, Expr*, int); +SQLITE_PRIVATE int tdsqlite3ExprCompareSkip(Expr*, Expr*, int); +SQLITE_PRIVATE int tdsqlite3ExprListCompare(ExprList*, ExprList*, int); +SQLITE_PRIVATE int tdsqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int); +SQLITE_PRIVATE int tdsqlite3ExprImpliesNonNullRow(Expr*,int); +SQLITE_PRIVATE void tdsqlite3ExprAnalyzeAggregates(NameContext*, Expr*); +SQLITE_PRIVATE void tdsqlite3ExprAnalyzeAggList(NameContext*,ExprList*); +SQLITE_PRIVATE int tdsqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx); +SQLITE_PRIVATE int tdsqlite3FunctionUsesThisSrc(Expr*, SrcList*); +SQLITE_PRIVATE Vdbe *tdsqlite3GetVdbe(Parse*); +#ifndef SQLITE_UNTESTABLE +SQLITE_PRIVATE void tdsqlite3PrngSaveState(void); +SQLITE_PRIVATE void tdsqlite3PrngRestoreState(void); +#endif +SQLITE_PRIVATE void tdsqlite3RollbackAll(tdsqlite3*,int); +SQLITE_PRIVATE void tdsqlite3CodeVerifySchema(Parse*, int); +SQLITE_PRIVATE void tdsqlite3CodeVerifyNamedSchema(Parse*, const char *zDb); +SQLITE_PRIVATE void tdsqlite3BeginTransaction(Parse*, int); +SQLITE_PRIVATE void tdsqlite3EndTransaction(Parse*,int); +SQLITE_PRIVATE void tdsqlite3Savepoint(Parse*, int, Token*); +SQLITE_PRIVATE void tdsqlite3CloseSavepoints(tdsqlite3 *); +SQLITE_PRIVATE void tdsqlite3LeaveMutexAndCloseZombie(tdsqlite3*); +SQLITE_PRIVATE u32 tdsqlite3IsTrueOrFalse(const char*); +SQLITE_PRIVATE int tdsqlite3ExprIdToTrueFalse(Expr*); +SQLITE_PRIVATE int tdsqlite3ExprTruthValue(const Expr*); +SQLITE_PRIVATE int tdsqlite3ExprIsConstant(Expr*); +SQLITE_PRIVATE int tdsqlite3ExprIsConstantNotJoin(Expr*); +SQLITE_PRIVATE int tdsqlite3ExprIsConstantOrFunction(Expr*, u8); +SQLITE_PRIVATE int tdsqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*); +SQLITE_PRIVATE int tdsqlite3ExprIsTableConstant(Expr*,int); #ifdef SQLITE_ENABLE_CURSOR_HINTS -SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*); +SQLITE_PRIVATE int tdsqlite3ExprContainsSubquery(Expr*); #endif -SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*); -SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*); -SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char); -SQLITE_PRIVATE int sqlite3IsRowid(const char*); -SQLITE_PRIVATE void sqlite3GenerateRowDelete( +SQLITE_PRIVATE int tdsqlite3ExprIsInteger(Expr*, int*); +SQLITE_PRIVATE int tdsqlite3ExprCanBeNull(const Expr*); +SQLITE_PRIVATE int tdsqlite3ExprNeedsNoAffinityChange(const Expr*, char); +SQLITE_PRIVATE int tdsqlite3IsRowid(const char*); +SQLITE_PRIVATE void tdsqlite3GenerateRowDelete( Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int); -SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int); -SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int); -SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int); -SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int, - u8,u8,int,int*,int*); -SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int); -SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*); -SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int); -SQLITE_PRIVATE void sqlite3MultiWrite(Parse*); -SQLITE_PRIVATE void sqlite3MayAbort(Parse*); -SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8); -SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*); -SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*); -SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int); -SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int); -SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int); -SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*); -SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int); -#if SELECTTRACE_ENABLED -SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*); +SQLITE_PRIVATE void tdsqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int); +SQLITE_PRIVATE int tdsqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int); +SQLITE_PRIVATE void tdsqlite3ResolvePartIdxLabel(Parse*,int); +SQLITE_PRIVATE int tdsqlite3ExprReferencesUpdatedColumn(Expr*,int*,int); +SQLITE_PRIVATE void tdsqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int, + u8,u8,int,int*,int*,Upsert*); +#ifdef SQLITE_ENABLE_NULL_TRIM +SQLITE_PRIVATE void tdsqlite3SetMakeRecordP5(Vdbe*,Table*); #else -# define sqlite3SelectSetName(A,B) -#endif -SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int); -SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8); -SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void); -SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void); -SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*); -SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*); -SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*); -SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int); +# define tdsqlite3SetMakeRecordP5(A,B) +#endif +SQLITE_PRIVATE void tdsqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int); +SQLITE_PRIVATE int tdsqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*); +SQLITE_PRIVATE void tdsqlite3BeginWriteOperation(Parse*, int, int); +SQLITE_PRIVATE void tdsqlite3MultiWrite(Parse*); +SQLITE_PRIVATE void tdsqlite3MayAbort(Parse*); +SQLITE_PRIVATE void tdsqlite3HaltConstraint(Parse*, int, int, char*, i8, u8); +SQLITE_PRIVATE void tdsqlite3UniqueConstraint(Parse*, int, Index*); +SQLITE_PRIVATE void tdsqlite3RowidConstraint(Parse*, int, Table*); +SQLITE_PRIVATE Expr *tdsqlite3ExprDup(tdsqlite3*,Expr*,int); +SQLITE_PRIVATE ExprList *tdsqlite3ExprListDup(tdsqlite3*,ExprList*,int); +SQLITE_PRIVATE SrcList *tdsqlite3SrcListDup(tdsqlite3*,SrcList*,int); +SQLITE_PRIVATE IdList *tdsqlite3IdListDup(tdsqlite3*,IdList*); +SQLITE_PRIVATE Select *tdsqlite3SelectDup(tdsqlite3*,Select*,int); +SQLITE_PRIVATE FuncDef *tdsqlite3FunctionSearch(int,const char*); +SQLITE_PRIVATE void tdsqlite3InsertBuiltinFuncs(FuncDef*,int); +SQLITE_PRIVATE FuncDef *tdsqlite3FindFunction(tdsqlite3*,const char*,int,u8,u8); +SQLITE_PRIVATE void tdsqlite3RegisterBuiltinFunctions(void); +SQLITE_PRIVATE void tdsqlite3RegisterDateTimeFunctions(void); +SQLITE_PRIVATE void tdsqlite3RegisterPerConnectionBuiltinFunctions(tdsqlite3*); +SQLITE_PRIVATE int tdsqlite3SafetyCheckOk(tdsqlite3*); +SQLITE_PRIVATE int tdsqlite3SafetyCheckSickOrOk(tdsqlite3*); +SQLITE_PRIVATE void tdsqlite3ChangeCookie(Parse*, int); #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) -SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int); +SQLITE_PRIVATE void tdsqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int); #endif #ifndef SQLITE_OMIT_TRIGGER -SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*, +SQLITE_PRIVATE void tdsqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*, Expr*,int, int); -SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*); -SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int); -SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*); -SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask); -SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *); -SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *, +SQLITE_PRIVATE void tdsqlite3FinishTrigger(Parse*, TriggerStep*, Token*); +SQLITE_PRIVATE void tdsqlite3DropTrigger(Parse*, SrcList*, int); +SQLITE_PRIVATE void tdsqlite3DropTriggerPtr(Parse*, Trigger*); +SQLITE_PRIVATE Trigger *tdsqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask); +SQLITE_PRIVATE Trigger *tdsqlite3TriggerList(Parse *, Table *); +SQLITE_PRIVATE void tdsqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *, int, int, int); -SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int); +SQLITE_PRIVATE void tdsqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int); void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*); -SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*, - Select*,u8); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*); -SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*); -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*); -SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int); -# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p)) -# define sqlite3IsToplevel(p) ((p)->pToplevel==0) -#else -# define sqlite3TriggersExist(B,C,D,E,F) 0 -# define sqlite3DeleteTrigger(A,B) -# define sqlite3DropTriggerPtr(A,B) -# define sqlite3UnlinkAndDeleteTrigger(A,B,C) -# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) -# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F) -# define sqlite3TriggerList(X, Y) 0 -# define sqlite3ParseToplevel(p) p -# define sqlite3IsToplevel(p) 1 -# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0 -#endif - -SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*); -SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int); -SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int); +SQLITE_PRIVATE void tdsqlite3DeleteTriggerStep(tdsqlite3*, TriggerStep*); +SQLITE_PRIVATE TriggerStep *tdsqlite3TriggerSelectStep(tdsqlite3*,Select*, + const char*,const char*); +SQLITE_PRIVATE TriggerStep *tdsqlite3TriggerInsertStep(Parse*,Token*, IdList*, + Select*,u8,Upsert*, + const char*,const char*); +SQLITE_PRIVATE TriggerStep *tdsqlite3TriggerUpdateStep(Parse*,Token*,ExprList*, Expr*, u8, + const char*,const char*); +SQLITE_PRIVATE TriggerStep *tdsqlite3TriggerDeleteStep(Parse*,Token*, Expr*, + const char*,const char*); +SQLITE_PRIVATE void tdsqlite3DeleteTrigger(tdsqlite3*, Trigger*); +SQLITE_PRIVATE void tdsqlite3UnlinkAndDeleteTrigger(tdsqlite3*,int,const char*); +SQLITE_PRIVATE u32 tdsqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int); +# define tdsqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p)) +# define tdsqlite3IsToplevel(p) ((p)->pToplevel==0) +#else +# define tdsqlite3TriggersExist(B,C,D,E,F) 0 +# define tdsqlite3DeleteTrigger(A,B) +# define tdsqlite3DropTriggerPtr(A,B) +# define tdsqlite3UnlinkAndDeleteTrigger(A,B,C) +# define tdsqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) +# define tdsqlite3CodeRowTriggerDirect(A,B,C,D,E,F) +# define tdsqlite3TriggerList(X, Y) 0 +# define tdsqlite3ParseToplevel(p) p +# define tdsqlite3IsToplevel(p) 1 +# define tdsqlite3TriggerColmask(A,B,C,D,E,F,G) 0 +#endif + +SQLITE_PRIVATE int tdsqlite3JoinType(Parse*, Token*, Token*, Token*); +SQLITE_PRIVATE void tdsqlite3SetJoinExpr(Expr*,int); +SQLITE_PRIVATE void tdsqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int); +SQLITE_PRIVATE void tdsqlite3DeferForeignKey(Parse*, int); #ifndef SQLITE_OMIT_AUTHORIZATION -SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*); -SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*); -SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*); -SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*); -SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int); -#else -# define sqlite3AuthRead(a,b,c,d) -# define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK -# define sqlite3AuthContextPush(a,b,c) -# define sqlite3AuthContextPop(a) ((void)(a)) -#endif -SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*); -SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*); -SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*); -SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*); -SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*); -SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*); -SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*); -SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*); -SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8); -SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*); -SQLITE_PRIVATE int sqlite3Atoi(const char*); -SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar); -SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte); -SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**); -SQLITE_PRIVATE LogEst sqlite3LogEst(u64); -SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst); +SQLITE_PRIVATE void tdsqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*); +SQLITE_PRIVATE int tdsqlite3AuthCheck(Parse*,int, const char*, const char*, const char*); +SQLITE_PRIVATE void tdsqlite3AuthContextPush(Parse*, AuthContext*, const char*); +SQLITE_PRIVATE void tdsqlite3AuthContextPop(AuthContext*); +SQLITE_PRIVATE int tdsqlite3AuthReadCol(Parse*, const char *, const char *, int); +#else +# define tdsqlite3AuthRead(a,b,c,d) +# define tdsqlite3AuthCheck(a,b,c,d,e) SQLITE_OK +# define tdsqlite3AuthContextPush(a,b,c) +# define tdsqlite3AuthContextPop(a) ((void)(a)) +#endif +SQLITE_PRIVATE void tdsqlite3Attach(Parse*, Expr*, Expr*, Expr*); +SQLITE_PRIVATE void tdsqlite3Detach(Parse*, Expr*); +SQLITE_PRIVATE void tdsqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*); +SQLITE_PRIVATE int tdsqlite3FixSrcList(DbFixer*, SrcList*); +SQLITE_PRIVATE int tdsqlite3FixSelect(DbFixer*, Select*); +SQLITE_PRIVATE int tdsqlite3FixExpr(DbFixer*, Expr*); +SQLITE_PRIVATE int tdsqlite3FixExprList(DbFixer*, ExprList*); +SQLITE_PRIVATE int tdsqlite3FixTriggerStep(DbFixer*, TriggerStep*); +SQLITE_PRIVATE int tdsqlite3RealSameAsInt(double,tdsqlite3_int64); +SQLITE_PRIVATE int tdsqlite3AtoF(const char *z, double*, int, u8); +SQLITE_PRIVATE int tdsqlite3GetInt32(const char *, int*); +SQLITE_PRIVATE int tdsqlite3Atoi(const char*); +#ifndef SQLITE_OMIT_UTF16 +SQLITE_PRIVATE int tdsqlite3Utf16ByteLen(const void *pData, int nChar); +#endif +SQLITE_PRIVATE int tdsqlite3Utf8CharLen(const char *pData, int nByte); +SQLITE_PRIVATE u32 tdsqlite3Utf8Read(const u8**); +SQLITE_PRIVATE LogEst tdsqlite3LogEst(u64); +SQLITE_PRIVATE LogEst tdsqlite3LogEstAdd(LogEst,LogEst); #ifndef SQLITE_OMIT_VIRTUALTABLE -SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double); +SQLITE_PRIVATE LogEst tdsqlite3LogEstFromDouble(double); #endif #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ - defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \ + defined(SQLITE_ENABLE_STAT4) || \ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) -SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst); +SQLITE_PRIVATE u64 tdsqlite3LogEstToInt(LogEst); #endif +SQLITE_PRIVATE VList *tdsqlite3VListAdd(tdsqlite3*,VList*,const char*,int,int); +SQLITE_PRIVATE const char *tdsqlite3VListNumToName(VList*,int); +SQLITE_PRIVATE int tdsqlite3VListNameToNum(VList*,const char*,int); /* ** Routines to read and write variable-length integers. These used to ** be defined locally, but now we use the varint routines in the util.c ** file. */ -SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64); -SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *); -SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *); -SQLITE_PRIVATE int sqlite3VarintLen(u64 v); +SQLITE_PRIVATE int tdsqlite3PutVarint(unsigned char*, u64); +SQLITE_PRIVATE u8 tdsqlite3GetVarint(const unsigned char *, u64 *); +SQLITE_PRIVATE u8 tdsqlite3GetVarint32(const unsigned char *, u32 *); +SQLITE_PRIVATE int tdsqlite3VarintLen(u64 v); /* ** The common case is for a varint to be a single byte. They following @@ -16518,242 +19716,304 @@ SQLITE_PRIVATE int sqlite3VarintLen(u64 v); ** the procedure for larger varints. */ #define getVarint32(A,B) \ - (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B))) + (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:tdsqlite3GetVarint32((A),(u32 *)&(B))) #define putVarint32(A,B) \ (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\ - sqlite3PutVarint((A),(B))) -#define getVarint sqlite3GetVarint -#define putVarint sqlite3PutVarint - - -SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*); -SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int); -SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2); -SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity); -SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int); -SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr); -SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8); -SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*); -SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...); -SQLITE_PRIVATE void sqlite3Error(sqlite3*,int); -SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int); -SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n); -SQLITE_PRIVATE u8 sqlite3HexToInt(int h); -SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **); + tdsqlite3PutVarint((A),(B))) +#define getVarint tdsqlite3GetVarint +#define putVarint tdsqlite3PutVarint + + +SQLITE_PRIVATE const char *tdsqlite3IndexAffinityStr(tdsqlite3*, Index*); +SQLITE_PRIVATE void tdsqlite3TableAffinity(Vdbe*, Table*, int); +SQLITE_PRIVATE char tdsqlite3CompareAffinity(Expr *pExpr, char aff2); +SQLITE_PRIVATE int tdsqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity); +SQLITE_PRIVATE char tdsqlite3TableColumnAffinity(Table*,int); +SQLITE_PRIVATE char tdsqlite3ExprAffinity(Expr *pExpr); +SQLITE_PRIVATE int tdsqlite3Atoi64(const char*, i64*, int, u8); +SQLITE_PRIVATE int tdsqlite3DecOrHexToI64(const char*, i64*); +SQLITE_PRIVATE void tdsqlite3ErrorWithMsg(tdsqlite3*, int, const char*,...); +SQLITE_PRIVATE void tdsqlite3Error(tdsqlite3*,int); +SQLITE_PRIVATE void tdsqlite3SystemError(tdsqlite3*,int); +SQLITE_PRIVATE void *tdsqlite3HexToBlob(tdsqlite3*, const char *z, int n); +SQLITE_PRIVATE u8 tdsqlite3HexToInt(int h); +SQLITE_PRIVATE int tdsqlite3TwoPartName(Parse *, Token *, Token *, Token **); #if defined(SQLITE_NEED_ERR_NAME) -SQLITE_PRIVATE const char *sqlite3ErrName(int); -#endif - -SQLITE_PRIVATE const char *sqlite3ErrStr(int); -SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse); -SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int); -SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName); -SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr); -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int); -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*); -SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*); -SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *); -SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *); -SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int); -SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64); -SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64); -SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64); -SQLITE_PRIVATE int sqlite3AbsInt32(int); +SQLITE_PRIVATE const char *tdsqlite3ErrName(int); +#endif + +#ifdef SQLITE_ENABLE_DESERIALIZE +SQLITE_PRIVATE int tdsqlite3MemdbInit(void); +#endif + +SQLITE_PRIVATE const char *tdsqlite3ErrStr(int); +SQLITE_PRIVATE int tdsqlite3ReadSchema(Parse *pParse); +SQLITE_PRIVATE CollSeq *tdsqlite3FindCollSeq(tdsqlite3*,u8 enc, const char*,int); +SQLITE_PRIVATE int tdsqlite3IsBinary(const CollSeq*); +SQLITE_PRIVATE CollSeq *tdsqlite3LocateCollSeq(Parse *pParse, const char*zName); +SQLITE_PRIVATE CollSeq *tdsqlite3ExprCollSeq(Parse *pParse, Expr *pExpr); +SQLITE_PRIVATE CollSeq *tdsqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr); +SQLITE_PRIVATE int tdsqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*); +SQLITE_PRIVATE Expr *tdsqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int); +SQLITE_PRIVATE Expr *tdsqlite3ExprAddCollateString(Parse*,Expr*,const char*); +SQLITE_PRIVATE Expr *tdsqlite3ExprSkipCollate(Expr*); +SQLITE_PRIVATE Expr *tdsqlite3ExprSkipCollateAndLikely(Expr*); +SQLITE_PRIVATE int tdsqlite3CheckCollSeq(Parse *, CollSeq *); +SQLITE_PRIVATE int tdsqlite3WritableSchema(tdsqlite3*); +SQLITE_PRIVATE int tdsqlite3CheckObjectName(Parse*, const char*,const char*,const char*); +SQLITE_PRIVATE void tdsqlite3VdbeSetChanges(tdsqlite3 *, int); +SQLITE_PRIVATE int tdsqlite3AddInt64(i64*,i64); +SQLITE_PRIVATE int tdsqlite3SubInt64(i64*,i64); +SQLITE_PRIVATE int tdsqlite3MulInt64(i64*,i64); +SQLITE_PRIVATE int tdsqlite3AbsInt32(int); #ifdef SQLITE_ENABLE_8_3_NAMES -SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*); +SQLITE_PRIVATE void tdsqlite3FileSuffix3(const char*, char*); #else -# define sqlite3FileSuffix3(X,Y) +# define tdsqlite3FileSuffix3(X,Y) #endif -SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8); +SQLITE_PRIVATE u8 tdsqlite3GetBoolean(const char *z,u8); -SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8); -SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8); -SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, +SQLITE_PRIVATE const void *tdsqlite3ValueText(tdsqlite3_value*, u8); +SQLITE_PRIVATE int tdsqlite3ValueBytes(tdsqlite3_value*, u8); +SQLITE_PRIVATE void tdsqlite3ValueSetStr(tdsqlite3_value*, int, const void *,u8, void(*)(void*)); -SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*); -SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*); -SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *); -SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8); -SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **); -SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8); +SQLITE_PRIVATE void tdsqlite3ValueSetNull(tdsqlite3_value*); +SQLITE_PRIVATE void tdsqlite3ValueFree(tdsqlite3_value*); +#ifndef SQLITE_UNTESTABLE +SQLITE_PRIVATE void tdsqlite3ResultIntReal(tdsqlite3_context*); +#endif +SQLITE_PRIVATE tdsqlite3_value *tdsqlite3ValueNew(tdsqlite3 *); +#ifndef SQLITE_OMIT_UTF16 +SQLITE_PRIVATE char *tdsqlite3Utf16to8(tdsqlite3 *, const void*, int, u8); +#endif +SQLITE_PRIVATE int tdsqlite3ValueFromExpr(tdsqlite3 *, Expr *, u8, u8, tdsqlite3_value **); +SQLITE_PRIVATE void tdsqlite3ValueApplyAffinity(tdsqlite3_value *, u8, u8); #ifndef SQLITE_AMALGAMATION -SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[]; -SQLITE_PRIVATE const char sqlite3StrBINARY[]; -SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[]; -SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[]; -SQLITE_PRIVATE const Token sqlite3IntTokens[]; -SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config; -SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; +SQLITE_PRIVATE const unsigned char tdsqlite3OpcodeProperty[]; +SQLITE_PRIVATE const char tdsqlite3StrBINARY[]; +SQLITE_PRIVATE const unsigned char tdsqlite3UpperToLower[]; +SQLITE_PRIVATE const unsigned char tdsqlite3CtypeMap[]; +SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config tdsqlite3Config; +SQLITE_PRIVATE FuncDefHash tdsqlite3BuiltinFunctions; #ifndef SQLITE_OMIT_WSD -SQLITE_PRIVATE int sqlite3PendingByte; -#endif -#endif -SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int); -SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*); -SQLITE_PRIVATE void sqlite3AlterFunctions(void); -SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*); -SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *); -SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...); -SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*); -SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int); -SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*); -SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p); -SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*); -SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*); -SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*); -SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*); -SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*); -SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*); -SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int); -SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *); -SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *); -SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*); -SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*); -SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*); -SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*); -SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*); -SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *); -SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB); -SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*); -SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*); -SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int); -SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*); -SQLITE_PRIVATE void sqlite3SchemaClear(void *); -SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *); -SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *); -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int); -SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*); -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*); -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*); -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*); +SQLITE_PRIVATE int tdsqlite3PendingByte; +#endif #endif -SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, - void (*)(sqlite3_context*,int,sqlite3_value **), - void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*), +#ifdef VDBE_PROFILE +SQLITE_PRIVATE tdsqlite3_uint64 tdsqlite3NProfileCnt; +#endif +SQLITE_PRIVATE void tdsqlite3RootPageMoved(tdsqlite3*, int, int, int); +SQLITE_PRIVATE void tdsqlite3Reindex(Parse*, Token*, Token*); +SQLITE_PRIVATE void tdsqlite3AlterFunctions(void); +SQLITE_PRIVATE void tdsqlite3AlterRenameTable(Parse*, SrcList*, Token*); +SQLITE_PRIVATE void tdsqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*); +SQLITE_PRIVATE int tdsqlite3GetToken(const unsigned char *, int *); +SQLITE_PRIVATE void tdsqlite3NestedParse(Parse*, const char*, ...); +SQLITE_PRIVATE void tdsqlite3ExpirePreparedStatements(tdsqlite3*, int); +SQLITE_PRIVATE void tdsqlite3CodeRhsOfIN(Parse*, Expr*, int); +SQLITE_PRIVATE int tdsqlite3CodeSubselect(Parse*, Expr*); +SQLITE_PRIVATE void tdsqlite3SelectPrep(Parse*, Select*, NameContext*); +SQLITE_PRIVATE void tdsqlite3SelectWrongNumTermsError(Parse *pParse, Select *p); +SQLITE_PRIVATE int tdsqlite3MatchEName( + const struct ExprList_item*, + const char*, + const char*, + const char* +); +SQLITE_PRIVATE int tdsqlite3ResolveExprNames(NameContext*, Expr*); +SQLITE_PRIVATE int tdsqlite3ResolveExprListNames(NameContext*, ExprList*); +SQLITE_PRIVATE void tdsqlite3ResolveSelectNames(Parse*, Select*, NameContext*); +SQLITE_PRIVATE int tdsqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*); +SQLITE_PRIVATE int tdsqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*); +SQLITE_PRIVATE void tdsqlite3ColumnDefault(Vdbe *, Table *, int, int); +SQLITE_PRIVATE void tdsqlite3AlterFinishAddColumn(Parse *, Token *); +SQLITE_PRIVATE void tdsqlite3AlterBeginAddColumn(Parse *, SrcList *); +SQLITE_PRIVATE void *tdsqlite3RenameTokenMap(Parse*, void*, Token*); +SQLITE_PRIVATE void tdsqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom); +SQLITE_PRIVATE void tdsqlite3RenameExprUnmap(Parse*, Expr*); +SQLITE_PRIVATE void tdsqlite3RenameExprlistUnmap(Parse*, ExprList*); +SQLITE_PRIVATE CollSeq *tdsqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*); +SQLITE_PRIVATE char tdsqlite3AffinityType(const char*, Column*); +SQLITE_PRIVATE void tdsqlite3Analyze(Parse*, Token*, Token*); +SQLITE_PRIVATE int tdsqlite3InvokeBusyHandler(BusyHandler*, tdsqlite3_file*); +SQLITE_PRIVATE int tdsqlite3FindDb(tdsqlite3*, Token*); +SQLITE_PRIVATE int tdsqlite3FindDbName(tdsqlite3 *, const char *); +SQLITE_PRIVATE int tdsqlite3AnalysisLoad(tdsqlite3*,int iDB); +SQLITE_PRIVATE void tdsqlite3DeleteIndexSamples(tdsqlite3*,Index*); +SQLITE_PRIVATE void tdsqlite3DefaultRowEst(Index*); +SQLITE_PRIVATE void tdsqlite3RegisterLikeFunctions(tdsqlite3*, int); +SQLITE_PRIVATE int tdsqlite3IsLikeFunction(tdsqlite3*,Expr*,int*,char*); +SQLITE_PRIVATE void tdsqlite3SchemaClear(void *); +SQLITE_PRIVATE Schema *tdsqlite3SchemaGet(tdsqlite3 *, Btree *); +SQLITE_PRIVATE int tdsqlite3SchemaToIndex(tdsqlite3 *db, Schema *); +SQLITE_PRIVATE KeyInfo *tdsqlite3KeyInfoAlloc(tdsqlite3*,int,int); +SQLITE_PRIVATE void tdsqlite3KeyInfoUnref(KeyInfo*); +SQLITE_PRIVATE KeyInfo *tdsqlite3KeyInfoRef(KeyInfo*); +SQLITE_PRIVATE KeyInfo *tdsqlite3KeyInfoOfIndex(Parse*, Index*); +SQLITE_PRIVATE KeyInfo *tdsqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int); +SQLITE_PRIVATE int tdsqlite3HasExplicitNulls(Parse*, ExprList*); + +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int tdsqlite3KeyInfoIsWriteable(KeyInfo*); +#endif +SQLITE_PRIVATE int tdsqlite3CreateFunc(tdsqlite3 *, const char *, int, int, void *, + void (*)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*)(tdsqlite3_context*), + void (*)(tdsqlite3_context*), + void (*)(tdsqlite3_context*,int,tdsqlite3_value **), FuncDestructor *pDestructor ); -SQLITE_PRIVATE void sqlite3OomFault(sqlite3*); -SQLITE_PRIVATE void sqlite3OomClear(sqlite3*); -SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int); -SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *); - -SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int); -SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int); -SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*); -SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char); -SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*); -SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*); -SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int); -SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int); - -SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *); -SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *); +SQLITE_PRIVATE void tdsqlite3NoopDestructor(void*); +SQLITE_PRIVATE void tdsqlite3OomFault(tdsqlite3*); +SQLITE_PRIVATE void tdsqlite3OomClear(tdsqlite3*); +SQLITE_PRIVATE int tdsqlite3ApiExit(tdsqlite3 *db, int); +SQLITE_PRIVATE int tdsqlite3OpenTempDatabase(Parse *); + +SQLITE_PRIVATE void tdsqlite3StrAccumInit(StrAccum*, tdsqlite3*, char*, int, int); +SQLITE_PRIVATE char *tdsqlite3StrAccumFinish(StrAccum*); +SQLITE_PRIVATE void tdsqlite3SelectDestInit(SelectDest*,int,int); +SQLITE_PRIVATE Expr *tdsqlite3CreateColumnExpr(tdsqlite3 *, SrcList *, int, int); + +SQLITE_PRIVATE void tdsqlite3BackupRestart(tdsqlite3_backup *); +SQLITE_PRIVATE void tdsqlite3BackupUpdate(tdsqlite3_backup *, Pgno, const u8 *); #ifndef SQLITE_OMIT_SUBQUERY -SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*); +SQLITE_PRIVATE int tdsqlite3ExprCheckIN(Parse*, Expr*); #else -# define sqlite3ExprCheckIN(x,y) SQLITE_OK +# define tdsqlite3ExprCheckIN(x,y) SQLITE_OK #endif -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 -SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void); -SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( +#ifdef SQLITE_ENABLE_STAT4 +SQLITE_PRIVATE int tdsqlite3Stat4ProbeSetValue( Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*); -SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**); -SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*); -SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**); -SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int); +SQLITE_PRIVATE int tdsqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, tdsqlite3_value**); +SQLITE_PRIVATE void tdsqlite3Stat4ProbeFree(UnpackedRecord*); +SQLITE_PRIVATE int tdsqlite3Stat4Column(tdsqlite3*, const void*, int, int, tdsqlite3_value**); +SQLITE_PRIVATE char tdsqlite3IndexColumnAffinity(tdsqlite3*, Index*, int); #endif /* ** The interface to the LEMON-generated parser */ -SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64)); -SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*)); -SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*); +#ifndef SQLITE_AMALGAMATION +SQLITE_PRIVATE void *tdsqlite3ParserAlloc(void*(*)(u64), Parse*); +SQLITE_PRIVATE void tdsqlite3ParserFree(void*, void(*)(void*)); +#endif +SQLITE_PRIVATE void tdsqlite3Parser(void*, int, Token); +SQLITE_PRIVATE int tdsqlite3ParserFallback(int); #ifdef YYTRACKMAXSTACKDEPTH -SQLITE_PRIVATE int sqlite3ParserStackPeak(void*); +SQLITE_PRIVATE int tdsqlite3ParserStackPeak(void*); #endif -SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*); +SQLITE_PRIVATE void tdsqlite3AutoLoadExtensions(tdsqlite3*); #ifndef SQLITE_OMIT_LOAD_EXTENSION -SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*); +SQLITE_PRIVATE void tdsqlite3CloseExtensions(tdsqlite3*); #else -# define sqlite3CloseExtensions(X) +# define tdsqlite3CloseExtensions(X) #endif #ifndef SQLITE_OMIT_SHARED_CACHE -SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *); +SQLITE_PRIVATE void tdsqlite3TableLock(Parse *, int, int, u8, const char *); #else - #define sqlite3TableLock(v,w,x,y,z) + #define tdsqlite3TableLock(v,w,x,y,z) #endif #ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*); +SQLITE_PRIVATE int tdsqlite3Utf8To8(unsigned char*); #endif #ifdef SQLITE_OMIT_VIRTUALTABLE -# define sqlite3VtabClear(Y) -# define sqlite3VtabSync(X,Y) SQLITE_OK -# define sqlite3VtabRollback(X) -# define sqlite3VtabCommit(X) -# define sqlite3VtabInSync(db) 0 -# define sqlite3VtabLock(X) -# define sqlite3VtabUnlock(X) -# define sqlite3VtabUnlockList(X) -# define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK -# define sqlite3GetVTable(X,Y) ((VTable*)0) -#else -SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*); -SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p); -SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*); -SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db); -SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db); -SQLITE_PRIVATE void sqlite3VtabLock(VTable *); -SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *); -SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*); -SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int); -SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*); -SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*); -# define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0) -#endif -SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*); -SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*); -SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*); -SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int); -SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*); -SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*); -SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*); -SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **); -SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*); -SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *); -SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *); -SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*); -SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**); -SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*); -SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int); -SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *); -SQLITE_PRIVATE void sqlite3ParserReset(Parse*); -SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*); -SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*); -SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *); -SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*); -SQLITE_PRIVATE const char *sqlite3JournalModename(int); +# define tdsqlite3VtabClear(Y) +# define tdsqlite3VtabSync(X,Y) SQLITE_OK +# define tdsqlite3VtabRollback(X) +# define tdsqlite3VtabCommit(X) +# define tdsqlite3VtabInSync(db) 0 +# define tdsqlite3VtabLock(X) +# define tdsqlite3VtabUnlock(X) +# define tdsqlite3VtabModuleUnref(D,X) +# define tdsqlite3VtabUnlockList(X) +# define tdsqlite3VtabSavepoint(X, Y, Z) SQLITE_OK +# define tdsqlite3GetVTable(X,Y) ((VTable*)0) +#else +SQLITE_PRIVATE void tdsqlite3VtabClear(tdsqlite3 *db, Table*); +SQLITE_PRIVATE void tdsqlite3VtabDisconnect(tdsqlite3 *db, Table *p); +SQLITE_PRIVATE int tdsqlite3VtabSync(tdsqlite3 *db, Vdbe*); +SQLITE_PRIVATE int tdsqlite3VtabRollback(tdsqlite3 *db); +SQLITE_PRIVATE int tdsqlite3VtabCommit(tdsqlite3 *db); +SQLITE_PRIVATE void tdsqlite3VtabLock(VTable *); +SQLITE_PRIVATE void tdsqlite3VtabUnlock(VTable *); +SQLITE_PRIVATE void tdsqlite3VtabModuleUnref(tdsqlite3*,Module*); +SQLITE_PRIVATE void tdsqlite3VtabUnlockList(tdsqlite3*); +SQLITE_PRIVATE int tdsqlite3VtabSavepoint(tdsqlite3 *, int, int); +SQLITE_PRIVATE void tdsqlite3VtabImportErrmsg(Vdbe*, tdsqlite3_vtab*); +SQLITE_PRIVATE VTable *tdsqlite3GetVTable(tdsqlite3*, Table*); +SQLITE_PRIVATE Module *tdsqlite3VtabCreateModule( + tdsqlite3*, + const char*, + const tdsqlite3_module*, + void*, + void(*)(void*) + ); +# define tdsqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0) +#endif +SQLITE_PRIVATE int tdsqlite3ReadOnlyShadowTables(tdsqlite3 *db); +#ifndef SQLITE_OMIT_VIRTUALTABLE +SQLITE_PRIVATE int tdsqlite3ShadowTableName(tdsqlite3 *db, const char *zName); +#else +# define tdsqlite3ShadowTableName(A,B) 0 +#endif +SQLITE_PRIVATE int tdsqlite3VtabEponymousTableInit(Parse*,Module*); +SQLITE_PRIVATE void tdsqlite3VtabEponymousTableClear(tdsqlite3*,Module*); +SQLITE_PRIVATE void tdsqlite3VtabMakeWritable(Parse*,Table*); +SQLITE_PRIVATE void tdsqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int); +SQLITE_PRIVATE void tdsqlite3VtabFinishParse(Parse*, Token*); +SQLITE_PRIVATE void tdsqlite3VtabArgInit(Parse*); +SQLITE_PRIVATE void tdsqlite3VtabArgExtend(Parse*, Token*); +SQLITE_PRIVATE int tdsqlite3VtabCallCreate(tdsqlite3*, int, const char *, char **); +SQLITE_PRIVATE int tdsqlite3VtabCallConnect(Parse*, Table*); +SQLITE_PRIVATE int tdsqlite3VtabCallDestroy(tdsqlite3*, int, const char *); +SQLITE_PRIVATE int tdsqlite3VtabBegin(tdsqlite3 *, VTable *); +SQLITE_PRIVATE FuncDef *tdsqlite3VtabOverloadFunction(tdsqlite3 *,FuncDef*, int nArg, Expr*); +SQLITE_PRIVATE tdsqlite3_int64 tdsqlite3StmtCurrentTime(tdsqlite3_context*); +SQLITE_PRIVATE int tdsqlite3VdbeParameterIndex(Vdbe*, const char*, int); +SQLITE_PRIVATE int tdsqlite3TransferBindings(tdsqlite3_stmt *, tdsqlite3_stmt *); +SQLITE_PRIVATE void tdsqlite3ParserReset(Parse*); +#ifdef SQLITE_ENABLE_NORMALIZE +SQLITE_PRIVATE char *tdsqlite3Normalize(Vdbe*, const char*); +#endif +SQLITE_PRIVATE int tdsqlite3Reprepare(Vdbe*); +SQLITE_PRIVATE void tdsqlite3ExprListCheckLength(Parse*, ExprList*, const char*); +SQLITE_PRIVATE CollSeq *tdsqlite3ExprCompareCollSeq(Parse*,Expr*); +SQLITE_PRIVATE CollSeq *tdsqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *); +SQLITE_PRIVATE int tdsqlite3TempInMemory(const tdsqlite3*); +SQLITE_PRIVATE const char *tdsqlite3JournalModename(int); #ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*); -SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int); +SQLITE_PRIVATE int tdsqlite3Checkpoint(tdsqlite3*, int, int, int*, int*); +SQLITE_PRIVATE int tdsqlite3WalDefaultHook(void*,tdsqlite3*,const char*,int); #endif #ifndef SQLITE_OMIT_CTE -SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*); -SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*); -SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8); +SQLITE_PRIVATE With *tdsqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*); +SQLITE_PRIVATE void tdsqlite3WithDelete(tdsqlite3*,With*); +SQLITE_PRIVATE void tdsqlite3WithPush(Parse*, With*, u8); +#else +#define tdsqlite3WithPush(x,y,z) +#define tdsqlite3WithDelete(x,y) +#endif +#ifndef SQLITE_OMIT_UPSERT +SQLITE_PRIVATE Upsert *tdsqlite3UpsertNew(tdsqlite3*,ExprList*,Expr*,ExprList*,Expr*); +SQLITE_PRIVATE void tdsqlite3UpsertDelete(tdsqlite3*,Upsert*); +SQLITE_PRIVATE Upsert *tdsqlite3UpsertDup(tdsqlite3*,Upsert*); +SQLITE_PRIVATE int tdsqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*); +SQLITE_PRIVATE void tdsqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int); #else -#define sqlite3WithPush(x,y,z) -#define sqlite3WithDelete(x,y) +#define tdsqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0) +#define tdsqlite3UpsertDelete(x,y) +#define tdsqlite3UpsertDup(x,y) ((Upsert*)0) #endif + /* Declarations for functions in fkey.c. All of these are replaced by ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign ** key functionality is available. If OMIT_TRIGGER is defined but @@ -16762,25 +20022,26 @@ SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8); ** provided (enforcement of FK constraints requires the triggers sub-system). */ #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) -SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int); -SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*); -SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int); -SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int); -SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*); -SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *); -#else - #define sqlite3FkActions(a,b,c,d,e,f) - #define sqlite3FkCheck(a,b,c,d,e,f) - #define sqlite3FkDropTable(a,b,c) - #define sqlite3FkOldmask(a,b) 0 - #define sqlite3FkRequired(a,b,c,d) 0 +SQLITE_PRIVATE void tdsqlite3FkCheck(Parse*, Table*, int, int, int*, int); +SQLITE_PRIVATE void tdsqlite3FkDropTable(Parse*, SrcList *, Table*); +SQLITE_PRIVATE void tdsqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int); +SQLITE_PRIVATE int tdsqlite3FkRequired(Parse*, Table*, int*, int); +SQLITE_PRIVATE u32 tdsqlite3FkOldmask(Parse*, Table*); +SQLITE_PRIVATE FKey *tdsqlite3FkReferences(Table *); +#else + #define tdsqlite3FkActions(a,b,c,d,e,f) + #define tdsqlite3FkCheck(a,b,c,d,e,f) + #define tdsqlite3FkDropTable(a,b,c) + #define tdsqlite3FkOldmask(a,b) 0 + #define tdsqlite3FkRequired(a,b,c,d) 0 + #define tdsqlite3FkReferences(a) 0 #endif #ifndef SQLITE_OMIT_FOREIGN_KEY -SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*); -SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**); +SQLITE_PRIVATE void tdsqlite3FkDelete(tdsqlite3 *, Table*); +SQLITE_PRIVATE int tdsqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**); #else - #define sqlite3FkDelete(a,b) - #define sqlite3FkLocateIndex(a,b,c,d,e) + #define tdsqlite3FkDelete(a,b) + #define tdsqlite3FkLocateIndex(a,b,c,d,e) #endif @@ -16792,19 +20053,19 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**); /* ** The interface to the code in fault.c used for identifying "benign" -** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST +** malloc failures. This is only present if SQLITE_UNTESTABLE ** is not defined. */ -#ifndef SQLITE_OMIT_BUILTIN_TEST -SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void); -SQLITE_PRIVATE void sqlite3EndBenignMalloc(void); +#ifndef SQLITE_UNTESTABLE +SQLITE_PRIVATE void tdsqlite3BeginBenignMalloc(void); +SQLITE_PRIVATE void tdsqlite3EndBenignMalloc(void); #else - #define sqlite3BeginBenignMalloc() - #define sqlite3EndBenignMalloc() + #define tdsqlite3BeginBenignMalloc() + #define tdsqlite3EndBenignMalloc() #endif /* -** Allowed return values from sqlite3FindInIndex() +** Allowed return values from tdsqlite3FindInIndex() */ #define IN_INDEX_ROWID 1 /* Search the rowid of the table */ #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */ @@ -16812,60 +20073,64 @@ SQLITE_PRIVATE void sqlite3EndBenignMalloc(void); #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */ #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */ /* -** Allowed flags for the 3rd parameter to sqlite3FindInIndex(). +** Allowed flags for the 3rd parameter to tdsqlite3FindInIndex(). */ #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */ #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */ #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */ -SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*); +SQLITE_PRIVATE int tdsqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*); -SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int); -SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *); -#ifdef SQLITE_ENABLE_ATOMIC_WRITE -SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *); +SQLITE_PRIVATE int tdsqlite3JournalOpen(tdsqlite3_vfs *, const char *, tdsqlite3_file *, int, int); +SQLITE_PRIVATE int tdsqlite3JournalSize(tdsqlite3_vfs *); +#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \ + || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) +SQLITE_PRIVATE int tdsqlite3JournalCreate(tdsqlite3_file *); #endif -SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p); -SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *); +SQLITE_PRIVATE int tdsqlite3JournalIsInMemory(tdsqlite3_file *p); +SQLITE_PRIVATE void tdsqlite3MemJournalOpen(tdsqlite3_file *); -SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p); +SQLITE_PRIVATE void tdsqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p); #if SQLITE_MAX_EXPR_DEPTH>0 -SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *); -SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int); +SQLITE_PRIVATE int tdsqlite3SelectExprHeight(Select *); +SQLITE_PRIVATE int tdsqlite3ExprCheckHeight(Parse*, int); #else - #define sqlite3SelectExprHeight(x) 0 - #define sqlite3ExprCheckHeight(x,y) + #define tdsqlite3SelectExprHeight(x) 0 + #define tdsqlite3ExprCheckHeight(x,y) #endif -SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*); -SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32); +SQLITE_PRIVATE u32 tdsqlite3Get4byte(const u8*); +SQLITE_PRIVATE void tdsqlite3Put4byte(u8*, u32); #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY -SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *); -SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db); -SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db); +SQLITE_PRIVATE void tdsqlite3ConnectionBlocked(tdsqlite3 *, tdsqlite3 *); +SQLITE_PRIVATE void tdsqlite3ConnectionUnlocked(tdsqlite3 *db); +SQLITE_PRIVATE void tdsqlite3ConnectionClosed(tdsqlite3 *db); #else - #define sqlite3ConnectionBlocked(x,y) - #define sqlite3ConnectionUnlocked(x) - #define sqlite3ConnectionClosed(x) + #define tdsqlite3ConnectionBlocked(x,y) + #define tdsqlite3ConnectionUnlocked(x) + #define tdsqlite3ConnectionClosed(x) #endif #ifdef SQLITE_DEBUG -SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *); +SQLITE_PRIVATE void tdsqlite3ParserTrace(FILE*, char *); +#endif +#if defined(YYCOVERAGE) +SQLITE_PRIVATE int tdsqlite3ParserCoverage(FILE*); #endif /* ** If the SQLITE_ENABLE IOTRACE exists then the global variable -** sqlite3IoTrace is a pointer to a printf-like routine used to +** tdsqlite3IoTrace is a pointer to a printf-like routine used to ** print I/O tracing messages. */ #ifdef SQLITE_ENABLE_IOTRACE -# define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; } -SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*); -SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...); +# define IOTRACE(A) if( tdsqlite3IoTrace ){ tdsqlite3IoTrace A; } +SQLITE_PRIVATE void tdsqlite3VdbeIOTraceSql(Vdbe*); +SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *tdsqlite3IoTrace)(const char*,...); #else # define IOTRACE(A) -# define sqlite3VdbeIOTraceSql(X) +# define tdsqlite3VdbeIOTraceSql(X) #endif /* @@ -16873,16 +20138,16 @@ SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...); ** only. They are used to verify that different "types" of memory ** allocations are properly tracked by the system. ** -** sqlite3MemdebugSetType() sets the "type" of an allocation to one of +** tdsqlite3MemdebugSetType() sets the "type" of an allocation to one of ** the MEMTYPE_* macros defined below. The type must be a bitmask with ** a single bit set. ** -** sqlite3MemdebugHasType() returns true if any of the bits in its second -** argument match the type set by the previous sqlite3MemdebugSetType(). -** sqlite3MemdebugHasType() is intended for use inside assert() statements. +** tdsqlite3MemdebugHasType() returns true if any of the bits in its second +** argument match the type set by the previous tdsqlite3MemdebugSetType(). +** tdsqlite3MemdebugHasType() is intended for use inside assert() statements. ** -** sqlite3MemdebugNoType() returns true if none of the bits in its second -** argument match the type set by the previous sqlite3MemdebugSetType(). +** tdsqlite3MemdebugNoType() returns true if none of the bits in its second +** argument match the type set by the previous tdsqlite3MemdebugSetType(). ** ** Perhaps the most important point is the difference between MEMTYPE_HEAP ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means @@ -16897,35 +20162,42 @@ SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...); ** play when the SQLITE_MEMDEBUG compile-time option is used. */ #ifdef SQLITE_MEMDEBUG -SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8); -SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8); -SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8); +SQLITE_PRIVATE void tdsqlite3MemdebugSetType(void*,u8); +SQLITE_PRIVATE int tdsqlite3MemdebugHasType(void*,u8); +SQLITE_PRIVATE int tdsqlite3MemdebugNoType(void*,u8); #else -# define sqlite3MemdebugSetType(X,Y) /* no-op */ -# define sqlite3MemdebugHasType(X,Y) 1 -# define sqlite3MemdebugNoType(X,Y) 1 +# define tdsqlite3MemdebugSetType(X,Y) /* no-op */ +# define tdsqlite3MemdebugHasType(X,Y) 1 +# define tdsqlite3MemdebugNoType(X,Y) 1 #endif #define MEMTYPE_HEAP 0x01 /* General heap allocations */ #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */ -#define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */ -#define MEMTYPE_PCACHE 0x08 /* Page cache allocations */ +#define MEMTYPE_PCACHE 0x04 /* Page cache allocations */ /* ** Threading interface */ #if SQLITE_MAX_WORKER_THREADS>0 -SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*); -SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**); +SQLITE_PRIVATE int tdsqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*); +SQLITE_PRIVATE int tdsqlite3ThreadJoin(SQLiteThread*, void**); #endif +#if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST) +SQLITE_PRIVATE int tdsqlite3DbpageRegister(tdsqlite3*); +#endif #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST) -SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*); +SQLITE_PRIVATE int tdsqlite3DbstatRegister(tdsqlite3*); #endif -SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr); -SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr); -SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int); -SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int); +SQLITE_PRIVATE int tdsqlite3ExprVectorSize(Expr *pExpr); +SQLITE_PRIVATE int tdsqlite3ExprIsVector(Expr *pExpr); +SQLITE_PRIVATE Expr *tdsqlite3VectorFieldSubexpr(Expr*, int); +SQLITE_PRIVATE Expr *tdsqlite3ExprForVectorField(Parse*,Expr*,int); +SQLITE_PRIVATE void tdsqlite3VectorErrorMsg(Parse*, Expr*); + +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +SQLITE_PRIVATE const char **tdsqlite3CompileOptions(int *pnOpt); +#endif #endif /* SQLITEINT_H */ @@ -16965,8 +20237,153 @@ SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int); #ifdef SQLITE_HAS_CODEC /* #include <assert.h> */ +/************** Include sqlcipher.h in the middle of crypto.c ****************/ +/************** Begin file sqlcipher.h ***************************************/ +/* +** SQLCipher +** sqlcipher.h developed by Stephen Lombardo (Zetetic LLC) +** sjlombardo at zetetic dot net +** http://zetetic.net +** +** Copyright (c) 2008, ZETETIC LLC +** All rights reserved. +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in the +** documentation and/or other materials provided with the distribution. +** * Neither the name of the ZETETIC LLC nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY +** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY +** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +** +*/ +/* BEGIN SQLCIPHER */ +#ifdef SQLITE_HAS_CODEC +#ifndef SQLCIPHER_H +#define SQLCIPHER_H + +#define SQLCIPHER_HMAC_SHA1 0 +#define SQLCIPHER_HMAC_SHA1_LABEL "HMAC_SHA1" +#define SQLCIPHER_HMAC_SHA256 1 +#define SQLCIPHER_HMAC_SHA256_LABEL "HMAC_SHA256" +#define SQLCIPHER_HMAC_SHA512 2 +#define SQLCIPHER_HMAC_SHA512_LABEL "HMAC_SHA512" + + +#define SQLCIPHER_PBKDF2_HMAC_SHA1 0 +#define SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL "PBKDF2_HMAC_SHA1" +#define SQLCIPHER_PBKDF2_HMAC_SHA256 1 +#define SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL "PBKDF2_HMAC_SHA256" +#define SQLCIPHER_PBKDF2_HMAC_SHA512 2 +#define SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL "PBKDF2_HMAC_SHA512" + + +typedef struct { + int (*activate)(void *ctx); + int (*deactivate)(void *ctx); + const char* (*get_provider_name)(void *ctx); + int (*add_random)(void *ctx, void *buffer, int length); + int (*random)(void *ctx, void *buffer, int length); + int (*hmac)(void *ctx, int algorithm, unsigned char *hmac_key, int key_sz, unsigned char *in, int in_sz, unsigned char *in2, int in2_sz, unsigned char *out); + int (*kdf)(void *ctx, int algorithm, const unsigned char *pass, int pass_sz, unsigned char* salt, int salt_sz, int workfactor, int key_sz, unsigned char *key); + int (*cipher)(void *ctx, int mode, unsigned char *key, int key_sz, unsigned char *iv, unsigned char *in, int in_sz, unsigned char *out); + const char* (*get_cipher)(void *ctx); + int (*get_key_sz)(void *ctx); + int (*get_iv_sz)(void *ctx); + int (*get_block_sz)(void *ctx); + int (*get_hmac_sz)(void *ctx, int algorithm); + int (*ctx_init)(void **ctx); + int (*ctx_free)(void **ctx); + int (*fips_status)(void *ctx); + const char* (*get_provider_version)(void *ctx); +} sqlcipher_provider; + +/* utility functions */ +SQLITE_PRIVATE void* sqlcipher_malloc(u64); +SQLITE_PRIVATE void sqlcipher_mlock(void *, u64); +SQLITE_PRIVATE void sqlcipher_munlock(void *, u64); +SQLITE_PRIVATE void* sqlcipher_memset(void *, unsigned char, u64); +SQLITE_PRIVATE int sqlcipher_ismemset(const void *, unsigned char, u64); +SQLITE_PRIVATE int sqlcipher_memcmp(const void *, const void *, int); +SQLITE_PRIVATE void sqlcipher_free(void *, u64); +SQLITE_PRIVATE char* sqlcipher_version(); + +/* provider interfaces */ +SQLITE_PRIVATE int sqlcipher_register_provider(sqlcipher_provider *); +SQLITE_PRIVATE sqlcipher_provider* sqlcipher_get_provider(void); + +#define SQLCIPHER_MUTEX_PROVIDER 0 +#define SQLCIPHER_MUTEX_PROVIDER_ACTIVATE 1 +#define SQLCIPHER_MUTEX_PROVIDER_RAND 2 +#define SQLCIPHER_MUTEX_RESERVED1 3 +#define SQLCIPHER_MUTEX_RESERVED2 4 +#define SQLCIPHER_MUTEX_RESERVED3 5 +#define SQLCIPHER_MUTEX_COUNT 6 + +SQLITE_PRIVATE tdsqlite3_mutex* sqlcipher_mutex(int); + +#endif +#endif +/* END SQLCIPHER */ + + +/************** End of sqlcipher.h *******************************************/ +/************** Continuing where we left off in crypto.c *********************/ +/************** Include crypto.h in the middle of crypto.c *******************/ +/************** Begin file crypto.h ******************************************/ +/* +** SQLCipher +** crypto.h developed by Stephen Lombardo (Zetetic LLC) +** sjlombardo at zetetic dot net +** http://zetetic.net +** +** Copyright (c) 2008, ZETETIC LLC +** All rights reserved. +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in the +** documentation and/or other materials provided with the distribution. +** * Neither the name of the ZETETIC LLC nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY +** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY +** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +** +*/ +/* BEGIN SQLCIPHER */ +#ifdef SQLITE_HAS_CODEC +#ifndef CRYPTO_H +#define CRYPTO_H + /* #include "sqliteInt.h" */ -/************** Include btreeInt.h in the middle of crypto.c *****************/ +/************** Include btreeInt.h in the middle of crypto.h *****************/ /************** Begin file btreeInt.h ****************************************/ /* ** 2004 April 6 @@ -17229,37 +20646,39 @@ typedef struct CellInfo CellInfo; #define PTF_LEAF 0x08 /* -** As each page of the file is loaded into memory, an instance of the following -** structure is appended and initialized to zero. This structure stores -** information about the page that is decoded from the raw file page. +** An instance of this object stores information about each a single database +** page that has been loaded into memory. The information in this object +** is derived from the raw on-disk page content. ** -** The pParent field points back to the parent page. This allows us to -** walk up the BTree from any leaf to the root. Care must be taken to -** unref() the parent page pointer when this page is no longer referenced. -** The pageDestructor() routine handles that chore. +** As each database page is loaded into memory, the pager allocats an +** instance of this object and zeros the first 8 bytes. (This is the +** "extra" information associated with each page of the pager.) ** ** Access to all fields of this structure is controlled by the mutex ** stored in MemPage.pBt->mutex. */ struct MemPage { u8 isInit; /* True if previously initialized. MUST BE FIRST! */ - u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ + u8 bBusy; /* Prevent endless loops on corrupt database files */ u8 intKey; /* True if table b-trees. False for index b-trees */ u8 intKeyLeaf; /* True if the leaf of an intKey table */ + Pgno pgno; /* Page number for this page */ + /* Only the first 8 bytes (above) are zeroed by pager.c when a new page + ** is allocated. All fields that follow must be initialized before use */ u8 leaf; /* True if a leaf page */ u8 hdrOffset; /* 100 for page 1. 0 otherwise */ u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ u8 max1bytePayload; /* min(maxLocal,127) */ - u8 bBusy; /* Prevent endless loops on corrupt database files */ + u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ u16 cellOffset; /* Index in aData of first cell pointer */ - u16 nFree; /* Number of free bytes on the page */ + int nFree; /* Number of free bytes on the page. -1 for unknown */ u16 nCell; /* Number of cells on this page, local and ovfl */ u16 maskPage; /* Mask for page offset */ - u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th + u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th ** non-overflow cell */ - u8 *apOvfl[5]; /* Pointers to the body of overflow cells */ + u8 *apOvfl[4]; /* Pointers to the body of overflow cells */ BtShared *pBt; /* Pointer to BtShared that this page is part of */ u8 *aData; /* Pointer to disk image of the page data */ u8 *aDataEnd; /* One byte past the end of usable data */ @@ -17268,17 +20687,9 @@ struct MemPage { DbPage *pDbPage; /* Pager page handle */ u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */ void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */ - Pgno pgno; /* Page number for this page */ }; /* -** The in-memory image of a disk page has the auxiliary information appended -** to the end. EXTRA_SIZE is the number of bytes of space needed to hold -** that extra information. -*/ -#define EXTRA_SIZE sizeof(MemPage) - -/* ** A linked list of the following structures is stored at BtShared.pLock. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor ** is opened on the table with root page BtShared.iTable. Locks are removed @@ -17318,13 +20729,13 @@ struct BtLock { ** they often do so without holding sqlite3.mutex. */ struct Btree { - sqlite3 *db; /* The database connection holding this btree */ + tdsqlite3 *db; /* The database connection holding this btree */ BtShared *pBt; /* Sharable content of this btree */ u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ u8 sharable; /* True if we can share pBt with another db */ u8 locked; /* True if db currently has pBt locked */ u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */ - int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ + int wantToLock; /* Number of nested calls to tdsqlite3BtreeEnter() */ int nBackup; /* Number of backup operations reading this btree */ u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */ Btree *pNext; /* List of other sharable Btrees from the same db */ @@ -17382,10 +20793,10 @@ struct Btree { */ struct BtShared { Pager *pPager; /* The page cache */ - sqlite3 *db; /* Database connection currently using this Btree */ + tdsqlite3 *db; /* Database connection currently using this Btree */ BtCursor *pCursor; /* A list of all open cursors */ MemPage *pPage1; /* First page of the database */ - u8 openFlags; /* Flags to sqlite3BtreeOpen() */ + u8 openFlags; /* Flags to tdsqlite3BtreeOpen() */ #ifndef SQLITE_OMIT_AUTOVACUUM u8 autoVacuum; /* True if auto-vacuum is enabled */ u8 incrVacuum; /* True if incr-vacuum is enabled */ @@ -17405,9 +20816,9 @@ struct BtShared { u32 usableSize; /* Number of usable bytes on each page */ int nTransaction; /* Number of open transactions (read + write) */ u32 nPage; /* Number of pages in the database */ - void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ + void *pSchema; /* Pointer to space allocated by tdsqlite3BtreeSchema() */ void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */ - sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */ + tdsqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */ Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */ #ifndef SQLITE_OMIT_SHARED_CACHE int nRef; /* Number of references to this structure */ @@ -17424,10 +20835,12 @@ struct BtShared { #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */ #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */ #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */ -#define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */ -#define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */ -#define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */ -#define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */ +#define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */ +#define BTS_FAST_SECURE 0x000c /* Combination of the previous two */ +#define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */ +#define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */ +#define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */ +#define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */ /* ** An instance of the following structure is used to hold information @@ -17468,35 +20881,43 @@ struct CellInfo { ** found at self->pBt->mutex. ** ** skipNext meaning: -** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op. -** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op. -** eState==FAULT: Cursor fault with skipNext as error code. +** The meaning of skipNext depends on the value of eState: +** +** eState Meaning of skipNext +** VALID skipNext is meaningless and is ignored +** INVALID skipNext is meaningless and is ignored +** SKIPNEXT tdsqlite3BtreeNext() is a no-op if skipNext>0 and +** tdsqlite3BtreePrevious() is no-op if skipNext<0. +** REQUIRESEEK restoreCursorPosition() restores the cursor to +** eState=SKIPNEXT if skipNext!=0 +** FAULT skipNext holds the cursor fault error code. */ struct BtCursor { + u8 eState; /* One of the CURSOR_XXX constants (see below) */ + u8 curFlags; /* zero or more BTCF_* flags defined below */ + u8 curPagerFlags; /* Flags to send to tdsqlite3PagerGet() */ + u8 hints; /* As configured by CursorSetHints() */ + int skipNext; /* Prev() is noop if negative. Next() is noop if positive. + ** Error code if eState==CURSOR_FAULT */ Btree *pBtree; /* The Btree to which this cursor belongs */ + Pgno *aOverflow; /* Cache of overflow page locations */ + void *pKey; /* Saved key that was cursor last known position */ + /* All fields above are zeroed when the cursor is allocated. See + ** tdsqlite3BtreeCursorZero(). Fields that follow must be manually + ** initialized. */ +#define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */ BtShared *pBt; /* The BtShared this cursor points to */ BtCursor *pNext; /* Forms a linked list of all cursors */ - Pgno *aOverflow; /* Cache of overflow page locations */ CellInfo info; /* A parse of the cell we are pointing at */ i64 nKey; /* Size of pKey, or last integer key */ - void *pKey; /* Saved key that was cursor last known position */ Pgno pgnoRoot; /* The root page of this tree */ - int nOvflAlloc; /* Allocated size of aOverflow[] array */ - int skipNext; /* Prev() is noop if negative. Next() is noop if positive. - ** Error code if eState==CURSOR_FAULT */ - u8 curFlags; /* zero or more BTCF_* flags defined below */ - u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */ - u8 eState; /* One of the CURSOR_XXX constants (see below) */ - u8 hints; /* As configured by CursorSetHints() */ - /* All fields above are zeroed when the cursor is allocated. See - ** sqlite3BtreeCursorZero(). Fields that follow must be manually - ** initialized. */ i8 iPage; /* Index of current page in apPage */ u8 curIntKey; /* Value of apPage[0]->intKey */ - struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */ - void *padding1; /* Make object size a multiple of 16 */ - u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */ - MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */ + u16 ix; /* Current index for apPage[iPage] */ + u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */ + struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */ + MemPage *pPage; /* Current page */ + MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */ }; /* @@ -17508,6 +20929,7 @@ struct BtCursor { #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */ #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */ #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */ +#define BTCF_Pinned 0x40 /* Cursor is busy and cannot be moved */ /* ** Potential values for BtCursor.eState. @@ -17522,7 +20944,7 @@ struct BtCursor { ** ** CURSOR_SKIPNEXT: ** Cursor is valid except that the Cursor.skipNext field is non-zero -** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious() +** indicating that the next tdsqlite3BtreeNext() or tdsqlite3BtreePrevious() ** operation should be a no-op. ** ** CURSOR_REQUIRESEEK: @@ -17539,8 +20961,8 @@ struct BtCursor { ** Do nothing else with this cursor. Any attempt to use the cursor ** should return the error code stored in BtCursor.skipNext */ -#define CURSOR_INVALID 0 -#define CURSOR_VALID 1 +#define CURSOR_VALID 0 +#define CURSOR_INVALID 1 #define CURSOR_SKIPNEXT 2 #define CURSOR_REQUIRESEEK 3 #define CURSOR_FAULT 4 @@ -17651,6 +21073,7 @@ struct IntegrityCk { int v1, v2; /* Values for up to two %d fields in zPfx */ StrAccum errMsg; /* Accumulate the error message text here */ u32 *heap; /* Min-heap used for analyzing cell coverage */ + tdsqlite3 *db; /* Database connection running the check */ }; /* @@ -17658,8 +21081,8 @@ struct IntegrityCk { */ #define get2byte(x) ((x)[0]<<8 | (x)[1]) #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) -#define get4byte sqlite3Get4byte -#define put4byte sqlite3Put4byte +#define get4byte tdsqlite3Get4byte +#define put4byte tdsqlite3Put4byte /* ** get2byteAligned(), unlike get2byte(), requires that its argument point to a @@ -17668,75 +21091,36 @@ struct IntegrityCk { */ #if SQLITE_BYTEORDER==4321 # define get2byteAligned(x) (*(u16*)(x)) -#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ - && GCC_VERSION>=4008000 +#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000 # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x)) -#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ - && defined(_MSC_VER) && _MSC_VER>=1300 +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x)) #else # define get2byteAligned(x) ((x)[0]<<8 | (x)[1]) #endif /************** End of btreeInt.h ********************************************/ -/************** Continuing where we left off in crypto.c *********************/ -/************** Include crypto.h in the middle of crypto.c *******************/ -/************** Begin file crypto.h ******************************************/ -/* -** SQLCipher -** crypto.h developed by Stephen Lombardo (Zetetic LLC) -** sjlombardo at zetetic dot net -** http://zetetic.net -** -** Copyright (c) 2008, ZETETIC LLC -** All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of the ZETETIC LLC nor the -** names of its contributors may be used to endorse or promote products -** derived from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY -** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY -** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -*/ -/* BEGIN SQLCIPHER */ -#ifdef SQLITE_HAS_CODEC -#ifndef CRYPTO_H -#define CRYPTO_H +/************** Continuing where we left off in crypto.h *********************/ +/* #include "pager.h" */ -#if !defined (SQLCIPHER_CRYPTO_CC) \ - && !defined (SQLCIPHER_CRYPTO_LIBTOMCRYPT) \ - && !defined (SQLCIPHER_CRYPTO_OPENSSL) -#define SQLCIPHER_CRYPTO_OPENSSL -#endif +/* extensions defined in pager.c */ +SQLITE_PRIVATE void *tdsqlite3PagerGetCodec(Pager*); +SQLITE_PRIVATE void tdsqlite3PagerSetCodec(Pager*, void *(*)(void*,void*,Pgno,int), void (*)(void*,int,int), void (*)(void*), void *); +SQLITE_API int tdsqlite3pager_is_mj_pgno(Pager*, Pgno); +SQLITE_API void tdsqlite3pager_error(Pager*, int); +SQLITE_API void tdsqlite3pager_reset(Pager *pPager); #define FILE_HEADER_SZ 16 -#ifndef CIPHER_VERSION -#ifdef SQLCIPHER_FIPS -#define CIPHER_VERSION "3.4.1 FIPS" -#else -#define CIPHER_VERSION "3.4.1" -#endif +#define CIPHER_XSTR(s) CIPHER_STR(s) +#define CIPHER_STR(s) #s + +#ifndef CIPHER_VERSION_NUMBER +#define CIPHER_VERSION_NUMBER 4.4.0 #endif -#ifndef CIPHER -#define CIPHER "aes-256-cbc" +#ifndef CIPHER_VERSION_BUILD +#define CIPHER_VERSION_BUILD community #endif #define CIPHER_DECRYPT 0 @@ -17747,7 +21131,7 @@ struct IntegrityCk { #define CIPHER_READWRITE_CTX 2 #ifndef PBKDF2_ITER -#define PBKDF2_ITER 64000 +#define PBKDF2_ITER 256000 #endif /* possible flags for cipher_ctx->flags */ @@ -17784,11 +21168,30 @@ struct IntegrityCk { #define CIPHER_MAX_KEY_SZ 64 #endif +#ifdef __ANDROID__ +#include <android/log.h> +#endif #ifdef CODEC_DEBUG -#define CODEC_TRACE(X) {printf X;fflush(stdout);} +#ifdef __ANDROID__ +#define CODEC_TRACE(...) {__android_log_print(ANDROID_LOG_DEBUG, "sqlcipher", __VA_ARGS__);} +#else +#define CODEC_TRACE(...) {fprintf(stderr, __VA_ARGS__);fflush(stderr);} +#endif #else -#define CODEC_TRACE(X) +#define CODEC_TRACE(...) +#endif + +#ifdef CODEC_DEBUG_MUTEX +#define CODEC_TRACE_MUTEX(...) CODEC_TRACE(__VA_ARGS__) +#else +#define CODEC_TRACE_MUTEX(...) +#endif + +#ifdef CODEC_DEBUG_MEMORY +#define CODEC_TRACE_MEMORY(...) CODEC_TRACE(__VA_ARGS__) +#else +#define CODEC_TRACE_MEMORY(...) #endif #ifdef CODEC_DEBUG_PAGEDATA @@ -17807,18 +21210,6 @@ struct IntegrityCk { #define CODEC_HEXDUMP(DESC,BUFFER,LEN) #endif -/* extensions defined in pager.c */ -SQLITE_API void sqlite3pager_get_codec(Pager *pPager, void **ctx); -SQLITE_API int sqlite3pager_is_mj_pgno(Pager *pPager, Pgno pgno); -SQLITE_PRIVATE sqlite3_file *sqlite3Pager_get_fd(Pager *pPager); -SQLITE_API void sqlite3pager_sqlite3PagerSetCodec( - Pager *pPager, - void *(*xCodec)(void*,void*,Pgno,int), - void (*xCodecSizeChng)(void*,int,int), - void (*xCodecFree)(void*), - void *pCodec -); -SQLITE_API void sqlite3pager_sqlite3PagerSetError(Pager *pPager, int error); /* end extensions defined in pager.c */ /* @@ -17840,7 +21231,7 @@ static void cipher_hex2bin(const unsigned char *hex, int sz, unsigned char *out) static void cipher_bin2hex(const unsigned char* in, int sz, char *out) { int i; for(i=0; i < sz; i++) { - sqlite3_snprintf(3, out + (i*2), "%02x ", in[i]); + tdsqlite3_snprintf(3, out + (i*2), "%02x ", in[i]); } } @@ -17858,73 +21249,143 @@ static int cipher_isHex(const unsigned char *hex, int sz){ } /* extensions defined in crypto_impl.c */ -typedef struct codec_ctx codec_ctx; +/* the default implementation of SQLCipher uses a cipher_ctx + to keep track of read / write state separately. The following + struct and associated functions are defined here */ +typedef struct { + int derive_key; + int pass_sz; + unsigned char *key; + unsigned char *hmac_key; + unsigned char *pass; + char *keyspec; +} cipher_ctx; + + +typedef struct { + int store_pass; + int kdf_iter; + int fast_kdf_iter; + int kdf_salt_sz; + int key_sz; + int iv_sz; + int block_sz; + int page_sz; + int keyspec_sz; + int reserve_sz; + int hmac_sz; + int plaintext_header_sz; + int hmac_algorithm; + int kdf_algorithm; + unsigned int skip_read_hmac; + unsigned int need_kdf_salt; + unsigned int flags; + unsigned char *kdf_salt; + unsigned char *hmac_kdf_salt; + unsigned char *buffer; + Btree *pBt; + cipher_ctx *read_ctx; + cipher_ctx *write_ctx; + sqlcipher_provider *provider; + void *provider_ctx; +} codec_ctx ; + +/* crypto.c functions */ +SQLITE_PRIVATE int sqlcipher_codec_pragma(tdsqlite3*, int, Parse*, const char *, const char*); +SQLITE_PRIVATE int tdsqlite3CodecAttach(tdsqlite3*, int, const void *, int); +SQLITE_PRIVATE void tdsqlite3CodecGetKey(tdsqlite3*, int, void**, int*); +SQLITE_PRIVATE void sqlcipher_exportFunc(tdsqlite3_context *, int, tdsqlite3_value **); + +/* crypto_impl.c functions */ + +SQLITE_PRIVATE void sqlcipher_init_memmethods(void); /* activation and initialization */ -void sqlcipher_activate(); -void sqlcipher_deactivate(); -int sqlcipher_codec_ctx_init(codec_ctx **, Db *, Pager *, sqlite3_file *, const void *, int); -void sqlcipher_codec_ctx_free(codec_ctx **); -int sqlcipher_codec_key_derive(codec_ctx *); -int sqlcipher_codec_key_copy(codec_ctx *, int); +SQLITE_PRIVATE void sqlcipher_activate(void); +SQLITE_PRIVATE void sqlcipher_deactivate(void); + +SQLITE_PRIVATE int sqlcipher_codec_ctx_init(codec_ctx **, Db *, Pager *, const void *, int); +SQLITE_PRIVATE void sqlcipher_codec_ctx_free(codec_ctx **); +SQLITE_PRIVATE int sqlcipher_codec_key_derive(codec_ctx *); +SQLITE_PRIVATE int sqlcipher_codec_key_copy(codec_ctx *, int); /* page cipher implementation */ -int sqlcipher_page_cipher(codec_ctx *, int, Pgno, int, int, unsigned char *, unsigned char *); +SQLITE_PRIVATE int sqlcipher_page_cipher(codec_ctx *, int, Pgno, int, int, unsigned char *, unsigned char *); /* context setters & getters */ -void sqlcipher_codec_ctx_set_error(codec_ctx *, int); +SQLITE_PRIVATE void sqlcipher_codec_ctx_set_error(codec_ctx *, int); + +SQLITE_PRIVATE void sqlcipher_codec_get_pass(codec_ctx *, void **, int *); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_pass(codec_ctx *, const void *, int, int); +SQLITE_PRIVATE void sqlcipher_codec_get_keyspec(codec_ctx *, void **zKey, int *nKey); -int sqlcipher_codec_ctx_set_pass(codec_ctx *, const void *, int, int); -void sqlcipher_codec_get_keyspec(codec_ctx *, void **zKey, int *nKey); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_pagesize(codec_ctx *, int); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_pagesize(codec_ctx *); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_reservesize(codec_ctx *); -int sqlcipher_codec_ctx_set_pagesize(codec_ctx *, int); -int sqlcipher_codec_ctx_get_pagesize(codec_ctx *); -int sqlcipher_codec_ctx_get_reservesize(codec_ctx *); +SQLITE_PRIVATE void sqlcipher_set_default_pagesize(int page_size); +SQLITE_PRIVATE int sqlcipher_get_default_pagesize(void); -void sqlcipher_set_default_pagesize(int page_size); -int sqlcipher_get_default_pagesize(); +SQLITE_PRIVATE void sqlcipher_set_default_kdf_iter(int iter); +SQLITE_PRIVATE int sqlcipher_get_default_kdf_iter(void); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *, int); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_kdf_iter(codec_ctx *ctx); -void sqlcipher_set_default_kdf_iter(int iter); -int sqlcipher_get_default_kdf_iter(); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_kdf_salt(codec_ctx *ctx, unsigned char *salt, int sz); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx, void **salt); -int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *, int, int); -int sqlcipher_codec_ctx_get_kdf_iter(codec_ctx *ctx, int); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *, int); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx *); -void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx); +SQLITE_PRIVATE const char* sqlcipher_codec_ctx_get_cipher(codec_ctx *ctx); -int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *, int, int); -int sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx *, int); +SQLITE_PRIVATE void* sqlcipher_codec_ctx_get_data(codec_ctx *); -int sqlcipher_codec_ctx_set_cipher(codec_ctx *, const char *, int); -const char* sqlcipher_codec_ctx_get_cipher(codec_ctx *ctx, int for_ctx); +SQLITE_PRIVATE void sqlcipher_set_default_use_hmac(int use); +SQLITE_PRIVATE int sqlcipher_get_default_use_hmac(void); -void* sqlcipher_codec_ctx_get_data(codec_ctx *); +SQLITE_PRIVATE void sqlcipher_set_hmac_salt_mask(unsigned char mask); +SQLITE_PRIVATE unsigned char sqlcipher_get_hmac_salt_mask(void); -void sqlcipher_exportFunc(sqlite3_context *, int, sqlite3_value **); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_use_hmac(codec_ctx *ctx); -void sqlcipher_set_default_use_hmac(int use); -int sqlcipher_get_default_use_hmac(); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_flag(codec_ctx *ctx, unsigned int flag); +SQLITE_PRIVATE int sqlcipher_codec_ctx_unset_flag(codec_ctx *ctx, unsigned int flag); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_flag(codec_ctx *ctx, unsigned int flag); -void sqlcipher_set_hmac_salt_mask(unsigned char mask); -unsigned char sqlcipher_get_hmac_salt_mask(); +SQLITE_PRIVATE const char* sqlcipher_codec_get_cipher_provider(codec_ctx *ctx); +SQLITE_PRIVATE int sqlcipher_codec_ctx_migrate(codec_ctx *ctx); +SQLITE_PRIVATE int sqlcipher_codec_add_random(codec_ctx *ctx, const char *data, int random_sz); +SQLITE_PRIVATE int sqlcipher_cipher_profile(tdsqlite3 *db, const char *destination); +SQLITE_PRIVATE int sqlcipher_codec_get_store_pass(codec_ctx *ctx); +SQLITE_PRIVATE void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey); +SQLITE_PRIVATE void sqlcipher_codec_set_store_pass(codec_ctx *ctx, int value); +SQLITE_PRIVATE int sqlcipher_codec_fips_status(codec_ctx *ctx); +SQLITE_PRIVATE const char* sqlcipher_codec_get_provider_version(codec_ctx *ctx); -int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use); -int sqlcipher_codec_ctx_get_use_hmac(codec_ctx *ctx, int for_ctx); +SQLITE_PRIVATE int sqlcipher_set_default_plaintext_header_size(int size); +SQLITE_PRIVATE int sqlcipher_get_default_plaintext_header_size(void); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_plaintext_header_size(codec_ctx *ctx, int size); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_plaintext_header_size(codec_ctx *ctx); -int sqlcipher_codec_ctx_set_flag(codec_ctx *ctx, unsigned int flag); -int sqlcipher_codec_ctx_unset_flag(codec_ctx *ctx, unsigned int flag); -int sqlcipher_codec_ctx_get_flag(codec_ctx *ctx, unsigned int flag, int for_ctx); +SQLITE_PRIVATE int sqlcipher_set_default_hmac_algorithm(int algorithm); +SQLITE_PRIVATE int sqlcipher_get_default_hmac_algorithm(void); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_hmac_algorithm(codec_ctx *ctx, int algorithm); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_hmac_algorithm(codec_ctx *ctx); + +SQLITE_PRIVATE int sqlcipher_set_default_kdf_algorithm(int algorithm); +SQLITE_PRIVATE int sqlcipher_get_default_kdf_algorithm(void); +SQLITE_PRIVATE int sqlcipher_codec_ctx_set_kdf_algorithm(codec_ctx *ctx, int algorithm); +SQLITE_PRIVATE int sqlcipher_codec_ctx_get_kdf_algorithm(codec_ctx *ctx); + +SQLITE_PRIVATE void sqlcipher_set_mem_security(int); +SQLITE_PRIVATE int sqlcipher_get_mem_security(void); + +SQLITE_PRIVATE int sqlcipher_find_db_index(tdsqlite3 *db, const char *zDb); + +SQLITE_PRIVATE int sqlcipher_codec_ctx_integrity_check(codec_ctx *, Parse *, char *); -const char* sqlcipher_codec_get_cipher_provider(codec_ctx *ctx); -int sqlcipher_codec_ctx_migrate(codec_ctx *ctx); -int sqlcipher_codec_add_random(codec_ctx *ctx, const char *data, int random_sz); -int sqlcipher_cipher_profile(sqlite3 *db, const char *destination); -static void sqlcipher_profile_callback(void *file, const char *sql, sqlite3_uint64 run_time); -static int sqlcipher_codec_get_store_pass(codec_ctx *ctx); -static void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey); -static void sqlcipher_codec_set_store_pass(codec_ctx *ctx, int value); -int sqlcipher_codec_fips_status(codec_ctx *ctx); -const char* sqlcipher_codec_get_provider_version(codec_ctx *ctx); #endif #endif /* END SQLCIPHER */ @@ -17932,162 +21393,181 @@ const char* sqlcipher_codec_get_provider_version(codec_ctx *ctx); /************** End of crypto.h **********************************************/ /************** Continuing where we left off in crypto.c *********************/ -static const char* codec_get_cipher_version() { - return CIPHER_VERSION; -} +#ifdef SQLCIPHER_EXT +#include "sqlcipher_ext.h" +#endif /* Generate code to return a string value */ -static void codec_vdbe_return_static_string(Parse *pParse, const char *zLabel, const char *value){ - Vdbe *v = sqlite3GetVdbe(pParse); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC); - sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, value, 0); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); +static void codec_vdbe_return_string(Parse *pParse, const char *zLabel, const char *value, int value_type){ + Vdbe *v = tdsqlite3GetVdbe(pParse); + tdsqlite3VdbeSetNumCols(v, 1); + tdsqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, value, value_type); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } -static int codec_set_btree_to_codec_pagesize(sqlite3 *db, Db *pDb, codec_ctx *ctx) { +static int codec_set_btree_to_codec_pagesize(tdsqlite3 *db, Db *pDb, codec_ctx *ctx) { int rc, page_sz, reserve_sz; page_sz = sqlcipher_codec_ctx_get_pagesize(ctx); reserve_sz = sqlcipher_codec_ctx_get_reservesize(ctx); - sqlite3_mutex_enter(db->mutex); + CODEC_TRACE("codec_set_btree_to_codec_pagesize: tdsqlite3BtreeSetPageSize() size=%d reserve=%d\n", page_sz, reserve_sz); + + CODEC_TRACE_MUTEX("codec_set_btree_to_codec_pagesize: entering database mutex %p\n", db->mutex); + tdsqlite3_mutex_enter(db->mutex); + CODEC_TRACE_MUTEX("codec_set_btree_to_codec_pagesize: entered database mutex %p\n", db->mutex); db->nextPagesize = page_sz; /* before forcing the page size we need to unset the BTS_PAGESIZE_FIXED flag, else sqliteBtreeSetPageSize will block the change */ pDb->pBt->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; - CODEC_TRACE(("codec_set_btree_to_codec_pagesize: sqlite3BtreeSetPageSize() size=%d reserve=%d\n", page_sz, reserve_sz)); - rc = sqlite3BtreeSetPageSize(pDb->pBt, page_sz, reserve_sz, 0); - sqlite3_mutex_leave(db->mutex); + rc = tdsqlite3BtreeSetPageSize(pDb->pBt, page_sz, reserve_sz, 0); + + CODEC_TRACE("codec_set_btree_to_codec_pagesize: tdsqlite3BtreeSetPageSize returned %d\n", rc); + + CODEC_TRACE_MUTEX("codec_set_btree_to_codec_pagesize: leaving database mutex %p\n", db->mutex); + tdsqlite3_mutex_leave(db->mutex); + CODEC_TRACE_MUTEX("codec_set_btree_to_codec_pagesize: left database mutex %p\n", db->mutex); + return rc; } -static int codec_set_pass_key(sqlite3* db, int nDb, const void *zKey, int nKey, int for_ctx) { +static int codec_set_pass_key(tdsqlite3* db, int nDb, const void *zKey, int nKey, int for_ctx) { struct Db *pDb = &db->aDb[nDb]; - CODEC_TRACE(("codec_set_pass_key: entered db=%p nDb=%d zKey=%s nKey=%d for_ctx=%d\n", db, nDb, (char *)zKey, nKey, for_ctx)); + CODEC_TRACE("codec_set_pass_key: entered db=%p nDb=%d zKey=%s nKey=%d for_ctx=%d\n", db, nDb, (char *)zKey, nKey, for_ctx); if(pDb->pBt) { - codec_ctx *ctx; - sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx); + codec_ctx *ctx = (codec_ctx*) tdsqlite3PagerGetCodec(pDb->pBt->pBt->pPager); + if(ctx) return sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, for_ctx); } return SQLITE_ERROR; } -int sqlcipher_codec_pragma(sqlite3* db, int iDb, Parse *pParse, const char *zLeft, const char *zRight) { - char *pragma_cipher_deprecated_msg = "PRAGMA cipher command is deprecated, please remove from usage."; +int sqlcipher_codec_pragma(tdsqlite3* db, int iDb, Parse *pParse, const char *zLeft, const char *zRight) { struct Db *pDb = &db->aDb[iDb]; codec_ctx *ctx = NULL; int rc; if(pDb->pBt) { - sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx); + ctx = (codec_ctx*) tdsqlite3PagerGetCodec(pDb->pBt->pBt->pPager); } - CODEC_TRACE(("sqlcipher_codec_pragma: entered db=%p iDb=%d pParse=%p zLeft=%s zRight=%s ctx=%p\n", db, iDb, pParse, zLeft, zRight, ctx)); + CODEC_TRACE("sqlcipher_codec_pragma: entered db=%p iDb=%d pParse=%p zLeft=%s zRight=%s ctx=%p\n", db, iDb, pParse, zLeft, zRight, ctx); - if( sqlite3StrICmp(zLeft, "cipher_fips_status")== 0 && !zRight ){ +#ifdef SQLCIPHER_EXT + if( tdsqlite3StrICmp(zLeft, "cipher_license")==0 && zRight ){ + char *license_result = tdsqlite3_mprintf("%d", sqlcipher_license_key(zRight)); + codec_vdbe_return_string(pParse, "cipher_license", license_result, P4_DYNAMIC); + } else + if( tdsqlite3StrICmp(zLeft, "cipher_license")==0 && !zRight ){ + if(ctx) { + char *license_result = tdsqlite3_mprintf("%d", ctx + ? sqlcipher_license_key_status(ctx->provider) + : SQLITE_ERROR); + codec_vdbe_return_string(pParse, "cipher_license", license_result, P4_DYNAMIC); + } + } else +#endif + if( tdsqlite3StrICmp(zLeft, "cipher_fips_status")== 0 && !zRight ){ if(ctx) { - char *fips_mode_status = sqlite3_mprintf("%d", sqlcipher_codec_fips_status(ctx)); - codec_vdbe_return_static_string(pParse, "cipher_fips_status", fips_mode_status); - sqlite3_free(fips_mode_status); + char *fips_mode_status = tdsqlite3_mprintf("%d", sqlcipher_codec_fips_status(ctx)); + codec_vdbe_return_string(pParse, "cipher_fips_status", fips_mode_status, P4_DYNAMIC); } } else - if( sqlite3StrICmp(zLeft, "cipher_store_pass")==0 && zRight ) { + if( tdsqlite3StrICmp(zLeft, "cipher_store_pass")==0 && zRight ) { if(ctx) { - sqlcipher_codec_set_store_pass(ctx, sqlite3GetBoolean(zRight, 1)); + sqlcipher_codec_set_store_pass(ctx, tdsqlite3GetBoolean(zRight, 1)); } } else - if( sqlite3StrICmp(zLeft, "cipher_store_pass")==0 && !zRight ) { + if( tdsqlite3StrICmp(zLeft, "cipher_store_pass")==0 && !zRight ) { if(ctx){ - char *store_pass_value = sqlite3_mprintf("%d", sqlcipher_codec_get_store_pass(ctx)); - codec_vdbe_return_static_string(pParse, "cipher_store_pass", store_pass_value); - sqlite3_free(store_pass_value); + char *store_pass_value = tdsqlite3_mprintf("%d", sqlcipher_codec_get_store_pass(ctx)); + codec_vdbe_return_string(pParse, "cipher_store_pass", store_pass_value, P4_DYNAMIC); } } - if( sqlite3StrICmp(zLeft, "cipher_profile")== 0 && zRight ){ - char *profile_status = sqlite3_mprintf("%d", sqlcipher_cipher_profile(db, zRight)); - codec_vdbe_return_static_string(pParse, "cipher_profile", profile_status); - sqlite3_free(profile_status); + if( tdsqlite3StrICmp(zLeft, "cipher_profile")== 0 && zRight ){ + char *profile_status = tdsqlite3_mprintf("%d", sqlcipher_cipher_profile(db, zRight)); + codec_vdbe_return_string(pParse, "cipher_profile", profile_status, P4_DYNAMIC); } else - if( sqlite3StrICmp(zLeft, "cipher_add_random")==0 && zRight ){ + if( tdsqlite3StrICmp(zLeft, "cipher_add_random")==0 && zRight ){ if(ctx) { - char *add_random_status = sqlite3_mprintf("%d", sqlcipher_codec_add_random(ctx, zRight, sqlite3Strlen30(zRight))); - codec_vdbe_return_static_string(pParse, "cipher_add_random", add_random_status); - sqlite3_free(add_random_status); + char *add_random_status = tdsqlite3_mprintf("%d", sqlcipher_codec_add_random(ctx, zRight, tdsqlite3Strlen30(zRight))); + codec_vdbe_return_string(pParse, "cipher_add_random", add_random_status, P4_DYNAMIC); } } else - if( sqlite3StrICmp(zLeft, "cipher_migrate")==0 && !zRight ){ + if( tdsqlite3StrICmp(zLeft, "cipher_migrate")==0 && !zRight ){ if(ctx){ - char *migrate_status = sqlite3_mprintf("%d", sqlcipher_codec_ctx_migrate(ctx)); - codec_vdbe_return_static_string(pParse, "cipher_migrate", migrate_status); - sqlite3_free(migrate_status); + char *migrate_status = tdsqlite3_mprintf("%d", sqlcipher_codec_ctx_migrate(ctx)); + codec_vdbe_return_string(pParse, "cipher_migrate", migrate_status, P4_DYNAMIC); } } else - if( sqlite3StrICmp(zLeft, "cipher_provider")==0 && !zRight ){ - if(ctx) { codec_vdbe_return_static_string(pParse, "cipher_provider", - sqlcipher_codec_get_cipher_provider(ctx)); + if( tdsqlite3StrICmp(zLeft, "cipher_provider")==0 && !zRight ){ + if(ctx) { codec_vdbe_return_string(pParse, "cipher_provider", + sqlcipher_codec_get_cipher_provider(ctx), P4_TRANSIENT); } } else - if( sqlite3StrICmp(zLeft, "cipher_provider_version")==0 && !zRight){ - if(ctx) { codec_vdbe_return_static_string(pParse, "cipher_provider_version", - sqlcipher_codec_get_provider_version(ctx)); + if( tdsqlite3StrICmp(zLeft, "cipher_provider_version")==0 && !zRight){ + if(ctx) { codec_vdbe_return_string(pParse, "cipher_provider_version", + sqlcipher_codec_get_provider_version(ctx), P4_TRANSIENT); } } else - if( sqlite3StrICmp(zLeft, "cipher_version")==0 && !zRight ){ - codec_vdbe_return_static_string(pParse, "cipher_version", codec_get_cipher_version()); + if( tdsqlite3StrICmp(zLeft, "cipher_version")==0 && !zRight ){ + codec_vdbe_return_string(pParse, "cipher_version", sqlcipher_version(), P4_DYNAMIC); }else - if( sqlite3StrICmp(zLeft, "cipher")==0 ){ + if( tdsqlite3StrICmp(zLeft, "cipher")==0 ){ if(ctx) { if( zRight ) { - rc = sqlcipher_codec_ctx_set_cipher(ctx, zRight, 2); // change cipher for both - codec_vdbe_return_static_string(pParse, "cipher", pragma_cipher_deprecated_msg); - sqlite3_log(SQLITE_WARNING, pragma_cipher_deprecated_msg); - return rc; + const char* message = "PRAGMA cipher is no longer supported."; + codec_vdbe_return_string(pParse, "cipher", message, P4_TRANSIENT); + tdsqlite3_log(SQLITE_WARNING, message); }else { - codec_vdbe_return_static_string(pParse, "cipher", - sqlcipher_codec_ctx_get_cipher(ctx, 2)); + codec_vdbe_return_string(pParse, "cipher", sqlcipher_codec_ctx_get_cipher(ctx), P4_TRANSIENT); } } }else - if( sqlite3StrICmp(zLeft, "rekey_cipher")==0 && zRight ){ - if(ctx) sqlcipher_codec_ctx_set_cipher(ctx, zRight, 1); // change write cipher only + if( tdsqlite3StrICmp(zLeft, "rekey_cipher")==0 && zRight ){ + const char* message = "PRAGMA rekey_cipher is no longer supported."; + codec_vdbe_return_string(pParse, "rekey_cipher", message, P4_TRANSIENT); + tdsqlite3_log(SQLITE_WARNING, message); }else - if( sqlite3StrICmp(zLeft,"cipher_default_kdf_iter")==0 ){ + if( tdsqlite3StrICmp(zLeft,"cipher_default_kdf_iter")==0 ){ if( zRight ) { - sqlcipher_set_default_kdf_iter(atoi(zRight)); // change default KDF iterations + sqlcipher_set_default_kdf_iter(atoi(zRight)); /* change default KDF iterations */ } else { - char *kdf_iter = sqlite3_mprintf("%d", sqlcipher_get_default_kdf_iter()); - codec_vdbe_return_static_string(pParse, "cipher_default_kdf_iter", kdf_iter); - sqlite3_free(kdf_iter); + char *kdf_iter = tdsqlite3_mprintf("%d", sqlcipher_get_default_kdf_iter()); + codec_vdbe_return_string(pParse, "cipher_default_kdf_iter", kdf_iter, P4_DYNAMIC); } }else - if( sqlite3StrICmp(zLeft, "kdf_iter")==0 ){ + if( tdsqlite3StrICmp(zLeft, "kdf_iter")==0 ){ if(ctx) { if( zRight ) { - sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight), 2); // change of RW PBKDF2 iteration + sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight)); /* change of RW PBKDF2 iteration */ } else { - char *kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_kdf_iter(ctx, 2)); - codec_vdbe_return_static_string(pParse, "kdf_iter", kdf_iter); - sqlite3_free(kdf_iter); + char *kdf_iter = tdsqlite3_mprintf("%d", sqlcipher_codec_ctx_get_kdf_iter(ctx)); + codec_vdbe_return_string(pParse, "kdf_iter", kdf_iter, P4_DYNAMIC); } } }else - if( sqlite3StrICmp(zLeft, "fast_kdf_iter")==0){ + if( tdsqlite3StrICmp(zLeft, "fast_kdf_iter")==0){ if(ctx) { if( zRight ) { - sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, atoi(zRight), 2); // change of RW PBKDF2 iteration + char *deprecation = "PRAGMA fast_kdf_iter is deprecated, please remove from use"; + sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, atoi(zRight)); /* change of RW PBKDF2 iteration */ + codec_vdbe_return_string(pParse, "fast_kdf_iter", deprecation, P4_TRANSIENT); + tdsqlite3_log(SQLITE_WARNING, deprecation); } else { - char *fast_kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_fast_kdf_iter(ctx, 2)); - codec_vdbe_return_static_string(pParse, "fast_kdf_iter", fast_kdf_iter); - sqlite3_free(fast_kdf_iter); + char *fast_kdf_iter = tdsqlite3_mprintf("%d", sqlcipher_codec_ctx_get_fast_kdf_iter(ctx)); + codec_vdbe_return_string(pParse, "fast_kdf_iter", fast_kdf_iter, P4_DYNAMIC); } } }else - if( sqlite3StrICmp(zLeft, "rekey_kdf_iter")==0 && zRight ){ - if(ctx) sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight), 1); // write iterations only + if( tdsqlite3StrICmp(zLeft, "rekey_kdf_iter")==0 && zRight ){ + const char* message = "PRAGMA rekey_kdf_iter is no longer supported."; + codec_vdbe_return_string(pParse, "rekey_kdf_iter", message, P4_TRANSIENT); + tdsqlite3_log(SQLITE_WARNING, message); }else - if( sqlite3StrICmp(zLeft,"cipher_page_size")==0 ){ + if( tdsqlite3StrICmp(zLeft,"cipher_page_size")==0 ){ if(ctx) { if( zRight ) { int size = atoi(zRight); @@ -18096,84 +21576,416 @@ int sqlcipher_codec_pragma(sqlite3* db, int iDb, Parse *pParse, const char *zLef rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); } else { - char * page_size = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_pagesize(ctx)); - codec_vdbe_return_static_string(pParse, "cipher_page_size", page_size); - sqlite3_free(page_size); + char * page_size = tdsqlite3_mprintf("%d", sqlcipher_codec_ctx_get_pagesize(ctx)); + codec_vdbe_return_string(pParse, "cipher_page_size", page_size, P4_DYNAMIC); } } }else - if( sqlite3StrICmp(zLeft,"cipher_default_page_size")==0 ){ + if( tdsqlite3StrICmp(zLeft,"cipher_default_page_size")==0 ){ if( zRight ) { sqlcipher_set_default_pagesize(atoi(zRight)); } else { - char *default_page_size = sqlite3_mprintf("%d", sqlcipher_get_default_pagesize()); - codec_vdbe_return_static_string(pParse, "cipher_default_page_size", default_page_size); - sqlite3_free(default_page_size); + char *default_page_size = tdsqlite3_mprintf("%d", sqlcipher_get_default_pagesize()); + codec_vdbe_return_string(pParse, "cipher_default_page_size", default_page_size, P4_DYNAMIC); } }else - if( sqlite3StrICmp(zLeft,"cipher_default_use_hmac")==0 ){ + if( tdsqlite3StrICmp(zLeft,"cipher_default_use_hmac")==0 ){ if( zRight ) { - sqlcipher_set_default_use_hmac(sqlite3GetBoolean(zRight,1)); + sqlcipher_set_default_use_hmac(tdsqlite3GetBoolean(zRight,1)); } else { - char *default_use_hmac = sqlite3_mprintf("%d", sqlcipher_get_default_use_hmac()); - codec_vdbe_return_static_string(pParse, "cipher_default_use_hmac", default_use_hmac); - sqlite3_free(default_use_hmac); + char *default_use_hmac = tdsqlite3_mprintf("%d", sqlcipher_get_default_use_hmac()); + codec_vdbe_return_string(pParse, "cipher_default_use_hmac", default_use_hmac, P4_DYNAMIC); } }else - if( sqlite3StrICmp(zLeft,"cipher_use_hmac")==0 ){ + if( tdsqlite3StrICmp(zLeft,"cipher_use_hmac")==0 ){ if(ctx) { if( zRight ) { - rc = sqlcipher_codec_ctx_set_use_hmac(ctx, sqlite3GetBoolean(zRight,1)); + rc = sqlcipher_codec_ctx_set_use_hmac(ctx, tdsqlite3GetBoolean(zRight,1)); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); /* since the use of hmac has changed, the page size may also change */ rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx); if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); } else { - char *hmac_flag = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_use_hmac(ctx, 2)); - codec_vdbe_return_static_string(pParse, "cipher_use_hmac", hmac_flag); - sqlite3_free(hmac_flag); + char *hmac_flag = tdsqlite3_mprintf("%d", sqlcipher_codec_ctx_get_use_hmac(ctx)); + codec_vdbe_return_string(pParse, "cipher_use_hmac", hmac_flag, P4_DYNAMIC); } } }else - if( sqlite3StrICmp(zLeft,"cipher_hmac_pgno")==0 ){ + if( tdsqlite3StrICmp(zLeft,"cipher_hmac_pgno")==0 ){ if(ctx) { if(zRight) { - // clear both pgno endian flags - if(sqlite3StrICmp(zRight, "le") == 0) { + char *deprecation = "PRAGMA cipher_hmac_pgno is deprecated, please remove from use"; + /* clear both pgno endian flags */ + if(tdsqlite3StrICmp(zRight, "le") == 0) { sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO); sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_LE_PGNO); - } else if(sqlite3StrICmp(zRight, "be") == 0) { + } else if(tdsqlite3StrICmp(zRight, "be") == 0) { sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO); sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_BE_PGNO); - } else if(sqlite3StrICmp(zRight, "native") == 0) { + } else if(tdsqlite3StrICmp(zRight, "native") == 0) { sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO); sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO); } + codec_vdbe_return_string(pParse, "cipher_hmac_pgno", deprecation, P4_TRANSIENT); + tdsqlite3_log(SQLITE_WARNING, deprecation); + } else { - if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_LE_PGNO, 2)) { - codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "le"); - } else if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_BE_PGNO, 2)) { - codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "be"); + if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_LE_PGNO)) { + codec_vdbe_return_string(pParse, "cipher_hmac_pgno", "le", P4_TRANSIENT); + } else if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_BE_PGNO)) { + codec_vdbe_return_string(pParse, "cipher_hmac_pgno", "be", P4_TRANSIENT); } else { - codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "native"); + codec_vdbe_return_string(pParse, "cipher_hmac_pgno", "native", P4_TRANSIENT); } } } }else - if( sqlite3StrICmp(zLeft,"cipher_hmac_salt_mask")==0 ){ + if( tdsqlite3StrICmp(zLeft,"cipher_hmac_salt_mask")==0 ){ if(ctx) { if(zRight) { - if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == 5) { + char *deprecation = "PRAGMA cipher_hmac_salt_mask is deprecated, please remove from use"; + if (tdsqlite3StrNICmp(zRight ,"x'", 2) == 0 && tdsqlite3Strlen30(zRight) == 5) { unsigned char mask = 0; const unsigned char *hex = (const unsigned char *)zRight+2; cipher_hex2bin(hex,2,&mask); sqlcipher_set_hmac_salt_mask(mask); } + codec_vdbe_return_string(pParse, "cipher_hmac_salt_mask", deprecation, P4_TRANSIENT); + tdsqlite3_log(SQLITE_WARNING, deprecation); + } else { + char *hmac_salt_mask = tdsqlite3_mprintf("%02x", sqlcipher_get_hmac_salt_mask()); + codec_vdbe_return_string(pParse, "cipher_hmac_salt_mask", hmac_salt_mask, P4_DYNAMIC); + } + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_plaintext_header_size")==0 ){ + if(ctx) { + if( zRight ) { + int size = atoi(zRight); + if((rc = sqlcipher_codec_ctx_set_plaintext_header_size(ctx, size)) != SQLITE_OK) + sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + } else { + char *size = tdsqlite3_mprintf("%d", sqlcipher_codec_ctx_get_plaintext_header_size(ctx)); + codec_vdbe_return_string(pParse, "cipher_plaintext_header_size", size, P4_DYNAMIC); + } + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_default_plaintext_header_size")==0 ){ + if( zRight ) { + sqlcipher_set_default_plaintext_header_size(atoi(zRight)); + } else { + char *size = tdsqlite3_mprintf("%d", sqlcipher_get_default_plaintext_header_size()); + codec_vdbe_return_string(pParse, "cipher_default_plaintext_header_size", size, P4_DYNAMIC); + tdsqlite3_free(size); + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_salt")==0 ){ + if(ctx) { + if(zRight) { + if (tdsqlite3StrNICmp(zRight ,"x'", 2) == 0 && tdsqlite3Strlen30(zRight) == (FILE_HEADER_SZ*2)+3) { + unsigned char *salt = (unsigned char*) tdsqlite3_malloc(FILE_HEADER_SZ); + const unsigned char *hex = (const unsigned char *)zRight+2; + cipher_hex2bin(hex,FILE_HEADER_SZ*2,salt); + sqlcipher_codec_ctx_set_kdf_salt(ctx, salt, FILE_HEADER_SZ); + tdsqlite3_free(salt); + } + } else { + void *salt; + char *hexsalt = (char*) tdsqlite3_malloc((FILE_HEADER_SZ*2)+1); + if((rc = sqlcipher_codec_ctx_get_kdf_salt(ctx, &salt)) == SQLITE_OK) { + cipher_bin2hex(salt, FILE_HEADER_SZ, hexsalt); + codec_vdbe_return_string(pParse, "cipher_salt", hexsalt, P4_DYNAMIC); + } else { + tdsqlite3_free(hexsalt); + sqlcipher_codec_ctx_set_error(ctx, rc); + } + } + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_hmac_algorithm")==0 ){ + if(ctx) { + if(zRight) { + rc = SQLITE_ERROR; + if(tdsqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA1_LABEL) == 0) { + rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1); + } else if(tdsqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA256_LABEL) == 0) { + rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA256); + } else if(tdsqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA512_LABEL) == 0) { + rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA512); + } + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + } else { + int algorithm = sqlcipher_codec_ctx_get_hmac_algorithm(ctx); + if(algorithm == SQLCIPHER_HMAC_SHA1) { + codec_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA1_LABEL, P4_TRANSIENT); + } else if(algorithm == SQLCIPHER_HMAC_SHA256) { + codec_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA256_LABEL, P4_TRANSIENT); + } else if(algorithm == SQLCIPHER_HMAC_SHA512) { + codec_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA512_LABEL, P4_TRANSIENT); + } + } + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_default_hmac_algorithm")==0 ){ + if(zRight) { + rc = SQLITE_ERROR; + if(tdsqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA1_LABEL) == 0) { + rc = sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA1); + } else if(tdsqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA256_LABEL) == 0) { + rc = sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA256); + } else if(tdsqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA512_LABEL) == 0) { + rc = sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA512); + } + } else { + int algorithm = sqlcipher_get_default_hmac_algorithm(); + if(algorithm == SQLCIPHER_HMAC_SHA1) { + codec_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA1_LABEL, P4_TRANSIENT); + } else if(algorithm == SQLCIPHER_HMAC_SHA256) { + codec_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA256_LABEL, P4_TRANSIENT); + } else if(algorithm == SQLCIPHER_HMAC_SHA512) { + codec_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA512_LABEL, P4_TRANSIENT); + } + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_kdf_algorithm")==0 ){ + if(ctx) { + if(zRight) { + rc = SQLITE_ERROR; + if(tdsqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL) == 0) { + rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1); + } else if(tdsqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL) == 0) { + rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA256); + } else if(tdsqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL) == 0) { + rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA512); + } + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); } else { - char *hmac_salt_mask = sqlite3_mprintf("%02x", sqlcipher_get_hmac_salt_mask()); - codec_vdbe_return_static_string(pParse, "cipher_hmac_salt_mask", hmac_salt_mask); - sqlite3_free(hmac_salt_mask); + int algorithm = sqlcipher_codec_ctx_get_kdf_algorithm(ctx); + if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) { + codec_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL, P4_TRANSIENT); + } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) { + codec_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL, P4_TRANSIENT); + } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) { + codec_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL, P4_TRANSIENT); + } + } + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_default_kdf_algorithm")==0 ){ + if(zRight) { + rc = SQLITE_ERROR; + if(tdsqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL) == 0) { + rc = sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA1); + } else if(tdsqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL) == 0) { + rc = sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA256); + } else if(tdsqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL) == 0) { + rc = sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA512); + } + } else { + int algorithm = sqlcipher_get_default_kdf_algorithm(); + if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) { + codec_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL, P4_TRANSIENT); + } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) { + codec_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL, P4_TRANSIENT); + } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) { + codec_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL, P4_TRANSIENT); + } + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_compatibility")==0 ){ + if(ctx) { + if(zRight) { + int version = atoi(zRight); + + switch(version) { + case 1: + rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 4000); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 0); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + break; + + case 2: + rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 4000); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + break; + + case 3: + rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 64000); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + break; + + default: + rc = sqlcipher_codec_ctx_set_pagesize(ctx, 4096); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA512); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA512); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 256000); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + break; + } + + rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx); + if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); + } + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_default_compatibility")==0 ){ + if(zRight) { + int version = atoi(zRight); + switch(version) { + case 1: + sqlcipher_set_default_pagesize(1024); + sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA1); + sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA1); + sqlcipher_set_default_kdf_iter(4000); + sqlcipher_set_default_use_hmac(0); + break; + + case 2: + sqlcipher_set_default_pagesize(1024); + sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA1); + sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA1); + sqlcipher_set_default_kdf_iter(4000); + sqlcipher_set_default_use_hmac(1); + break; + + case 3: + sqlcipher_set_default_pagesize(1024); + sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA1); + sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA1); + sqlcipher_set_default_kdf_iter(64000); + sqlcipher_set_default_use_hmac(1); + break; + + default: + sqlcipher_set_default_pagesize(4096); + sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA512); + sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA512); + sqlcipher_set_default_kdf_iter(256000); + sqlcipher_set_default_use_hmac(1); + break; + } + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_memory_security")==0 ){ + if( zRight ) { + sqlcipher_set_mem_security(tdsqlite3GetBoolean(zRight,1)); + } else { + char *on = tdsqlite3_mprintf("%d", sqlcipher_get_mem_security()); + codec_vdbe_return_string(pParse, "cipher_memory_security", on, P4_DYNAMIC); + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_settings")==0 ){ + if(ctx) { + int algorithm; + char *pragma; + + pragma = tdsqlite3_mprintf("PRAGMA kdf_iter = %d;", sqlcipher_codec_ctx_get_kdf_iter(ctx)); + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + pragma = tdsqlite3_mprintf("PRAGMA cipher_page_size = %d;", sqlcipher_codec_ctx_get_pagesize(ctx)); + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + pragma = tdsqlite3_mprintf("PRAGMA cipher_use_hmac = %d;", sqlcipher_codec_ctx_get_use_hmac(ctx)); + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + pragma = tdsqlite3_mprintf("PRAGMA cipher_plaintext_header_size = %d;", sqlcipher_codec_ctx_get_plaintext_header_size(ctx)); + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + algorithm = sqlcipher_codec_ctx_get_hmac_algorithm(ctx); + pragma = NULL; + if(algorithm == SQLCIPHER_HMAC_SHA1) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA1_LABEL); + } else if(algorithm == SQLCIPHER_HMAC_SHA256) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA256_LABEL); + } else if(algorithm == SQLCIPHER_HMAC_SHA512) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA512_LABEL); } + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + algorithm = sqlcipher_codec_ctx_get_kdf_algorithm(ctx); + pragma = NULL; + if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL); + } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL); + } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL); + } + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + } + }else + if( tdsqlite3StrICmp(zLeft,"cipher_default_settings")==0 ){ + int algorithm; + char *pragma; + + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_kdf_iter = %d;", sqlcipher_get_default_kdf_iter()); + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_page_size = %d;", sqlcipher_get_default_pagesize()); + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_use_hmac = %d;", sqlcipher_get_default_use_hmac()); + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_plaintext_header_size = %d;", sqlcipher_get_default_plaintext_header_size()); + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + algorithm = sqlcipher_get_default_hmac_algorithm(); + pragma = NULL; + if(algorithm == SQLCIPHER_HMAC_SHA1) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA1_LABEL); + } else if(algorithm == SQLCIPHER_HMAC_SHA256) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA256_LABEL); + } else if(algorithm == SQLCIPHER_HMAC_SHA512) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA512_LABEL); + } + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + + algorithm = sqlcipher_get_default_kdf_algorithm(); + pragma = NULL; + if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL); + } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL); + } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) { + pragma = tdsqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL); + } + codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC); + }else + if( tdsqlite3StrICmp(zLeft,"cipher_integrity_check")==0 ){ + if(ctx) { + sqlcipher_codec_ctx_integrity_check(ctx, pParse, "cipher_integrity_check"); } }else { return 0; @@ -18181,22 +21993,36 @@ int sqlcipher_codec_pragma(sqlite3* db, int iDb, Parse *pParse, const char *zLef return 1; } +/* these constants are used internally within SQLite's pager.c to differentiate between + operations on the main database or journal pages. This is important in the context + of a rekey operations, where the journal must be written using the original key + material (to allow a transactional rollback), while the new database pages are being + written with the new key material*/ +#define CODEC_READ_OP 3 +#define CODEC_WRITE_OP 6 +#define CODEC_JOURNAL_OP 7 /* - * sqlite3Codec can be called in multiple modes. + * tdsqlite3Codec can be called in multiple modes. * encrypt mode - expected to return a pointer to the * encrypted data without altering pData. * decrypt mode - expected to return a pointer to pData, with * the data decrypted in the input buffer */ -void* sqlite3Codec(void *iCtx, void *data, Pgno pgno, int mode) { +static void* tdsqlite3Codec(void *iCtx, void *data, Pgno pgno, int mode) { codec_ctx *ctx = (codec_ctx *) iCtx; int offset = 0, rc = 0; int page_sz = sqlcipher_codec_ctx_get_pagesize(ctx); unsigned char *pData = (unsigned char *) data; void *buffer = sqlcipher_codec_ctx_get_data(ctx); - void *kdf_salt = sqlcipher_codec_ctx_get_kdf_salt(ctx); - CODEC_TRACE(("sqlite3Codec: entered pgno=%d, mode=%d, page_sz=%d\n", pgno, mode, page_sz)); + int plaintext_header_sz = sqlcipher_codec_ctx_get_plaintext_header_size(ctx); + int cctx = CIPHER_READ_CTX; + + CODEC_TRACE("tdsqlite3Codec: entered pgno=%d, mode=%d, page_sz=%d\n", pgno, mode, page_sz); + +#ifdef SQLCIPHER_EXT + if(sqlcipher_license_check(ctx) != SQLITE_OK) return NULL; +#endif /* call to derive keys if not present yet */ if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) { @@ -18204,94 +22030,133 @@ void* sqlite3Codec(void *iCtx, void *data, Pgno pgno, int mode) { return NULL; } - if(pgno == 1) offset = FILE_HEADER_SZ; /* adjust starting pointers in data page for header offset on first page*/ + if(pgno == 1) /* adjust starting pointers in data page for header offset on first page*/ + offset = plaintext_header_sz ? plaintext_header_sz : FILE_HEADER_SZ; + - CODEC_TRACE(("sqlite3Codec: switch mode=%d offset=%d\n", mode, offset)); + CODEC_TRACE("tdsqlite3Codec: switch mode=%d offset=%d\n", mode, offset); switch(mode) { - case 0: /* decrypt */ - case 2: - case 3: - if(pgno == 1) memcpy(buffer, SQLITE_FILE_HEADER, FILE_HEADER_SZ); /* copy file header to the first 16 bytes of the page */ - rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_DECRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset); - if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); + case CODEC_READ_OP: /* decrypt */ + if(pgno == 1) /* copy initial part of file header or SQLite magic to buffer */ + memcpy(buffer, plaintext_header_sz ? pData : (void *) SQLITE_FILE_HEADER, offset); + + rc = sqlcipher_page_cipher(ctx, cctx, pgno, CIPHER_DECRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset); + if(rc != SQLITE_OK) { /* clear results of failed cipher operation and set error */ + sqlcipher_memset((unsigned char*) buffer+offset, 0, page_sz-offset); + sqlcipher_codec_ctx_set_error(ctx, rc); + } memcpy(pData, buffer, page_sz); /* copy buffer data back to pData and return */ return pData; break; - case 6: /* encrypt */ - if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */ - rc = sqlcipher_page_cipher(ctx, CIPHER_WRITE_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset); - if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); - return buffer; /* return persistent buffer data, pData remains intact */ - break; - case 7: - if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */ - rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset); - if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc); + + case CODEC_WRITE_OP: /* encrypt database page, operate on write context and fall through to case 7, so the write context is used*/ + cctx = CIPHER_WRITE_CTX; + + case CODEC_JOURNAL_OP: /* encrypt journal page, operate on read context use to get the original page data from the database */ + if(pgno == 1) { /* copy initial part of file header or salt to buffer */ + void *kdf_salt = NULL; + /* retrieve the kdf salt */ + if((rc = sqlcipher_codec_ctx_get_kdf_salt(ctx, &kdf_salt)) != SQLITE_OK) { + sqlcipher_codec_ctx_set_error(ctx, rc); + return NULL; + } + memcpy(buffer, plaintext_header_sz ? pData : kdf_salt, offset); + } + rc = sqlcipher_page_cipher(ctx, cctx, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset); + if(rc != SQLITE_OK) { /* clear results of failed cipher operation and set error */ + sqlcipher_memset((unsigned char*)buffer+offset, 0, page_sz-offset); + sqlcipher_codec_ctx_set_error(ctx, rc); + } return buffer; /* return persistent buffer data, pData remains intact */ break; + default: + sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); /* unsupported mode, set error */ return pData; break; } } -SQLITE_PRIVATE void sqlite3FreeCodecArg(void *pCodecArg) { +static void tdsqlite3FreeCodecArg(void *pCodecArg) { codec_ctx *ctx = (codec_ctx *) pCodecArg; if(pCodecArg == NULL) return; - sqlcipher_codec_ctx_free(&ctx); // wipe and free allocated memory for the context + sqlcipher_codec_ctx_free(&ctx); /* wipe and free allocated memory for the context */ sqlcipher_deactivate(); /* cleanup related structures, OpenSSL etc, when codec is detatched */ } -SQLITE_PRIVATE int sqlite3CodecAttach(sqlite3* db, int nDb, const void *zKey, int nKey) { +SQLITE_PRIVATE int tdsqlite3CodecAttach(tdsqlite3* db, int nDb, const void *zKey, int nKey) { struct Db *pDb = &db->aDb[nDb]; - CODEC_TRACE(("sqlite3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, (char *)zKey, nKey)); + CODEC_TRACE("tdsqlite3CodecAttach: entered db=%p, nDb=%d zKey=%s, nKey=%d\n", db, nDb, (char *)zKey, nKey); if(nKey && zKey && pDb->pBt) { int rc; Pager *pPager = pDb->pBt->pBt->pPager; - sqlite3_file *fd = sqlite3Pager_get_fd(pPager); + tdsqlite3_file *fd; codec_ctx *ctx; + /* check if the tdsqlite3_file is open, and if not force handle to NULL */ + if((fd = tdsqlite3PagerFile(pPager))->pMethods == 0) fd = NULL; + + CODEC_TRACE("tdsqlite3CodecAttach: calling sqlcipher_activate()\n"); sqlcipher_activate(); /* perform internal initialization for sqlcipher */ - sqlite3_mutex_enter(db->mutex); + CODEC_TRACE_MUTEX("tdsqlite3CodecAttach: entering database mutex %p\n", db->mutex); + tdsqlite3_mutex_enter(db->mutex); + CODEC_TRACE_MUTEX("tdsqlite3CodecAttach: entered database mutex %p\n", db->mutex); + +#ifdef SQLCIPHER_EXT + if((rc = tdsqlite3_set_authorizer(db, sqlcipher_license_authorizer, db)) != SQLITE_OK) { + tdsqlite3_mutex_leave(db->mutex); + return rc; + } +#endif /* point the internal codec argument against the contet to be prepared */ - rc = sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, fd, zKey, nKey); + CODEC_TRACE("tdsqlite3CodecAttach: calling sqlcipher_codec_ctx_init()\n"); + rc = sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, zKey, nKey); if(rc != SQLITE_OK) { /* initialization failed, do not attach potentially corrupted context */ - sqlite3_mutex_leave(db->mutex); + CODEC_TRACE("tdsqlite3CodecAttach: context initialization failed with rc=%d\n", rc); + /* force an error at the pager level, such that even the upstream caller ignores the return code + the pager will be in an error state and will process no further operations */ + tdsqlite3pager_error(pPager, rc); + pDb->pBt->pBt->db->errCode = rc; + CODEC_TRACE_MUTEX("tdsqlite3CodecAttach: leaving database mutex %p (early return on rc=%d)\n", db->mutex, rc); + tdsqlite3_mutex_leave(db->mutex); + CODEC_TRACE_MUTEX("tdsqlite3CodecAttach: left database mutex %p (early return on rc=%d)\n", db->mutex, rc); return rc; } - sqlite3pager_sqlite3PagerSetCodec(sqlite3BtreePager(pDb->pBt), sqlite3Codec, NULL, sqlite3FreeCodecArg, (void *) ctx); + CODEC_TRACE("tdsqlite3CodecAttach: calling tdsqlite3PagerSetCodec()\n"); + tdsqlite3PagerSetCodec(tdsqlite3BtreePager(pDb->pBt), tdsqlite3Codec, NULL, tdsqlite3FreeCodecArg, (void *) ctx); + CODEC_TRACE("tdsqlite3CodecAttach: calling codec_set_btree_to_codec_pagesize()\n"); codec_set_btree_to_codec_pagesize(db, pDb, ctx); /* force secure delete. This has the benefit of wiping internal data when deleted and also ensures that all pages are written to disk (i.e. not skipped by - sqlite3PagerDontWrite optimizations) */ - sqlite3BtreeSecureDelete(pDb->pBt, 1); + tdsqlite3PagerDontWrite optimizations) */ + CODEC_TRACE("tdsqlite3CodecAttach: calling tdsqlite3BtreeSecureDelete()\n"); + tdsqlite3BtreeSecureDelete(pDb->pBt, 1); /* if fd is null, then this is an in-memory database and we dont' want to overwrite the AutoVacuum settings if not null, then set to the default */ if(fd != NULL) { - sqlite3BtreeSetAutoVacuum(pDb->pBt, SQLITE_DEFAULT_AUTOVACUUM); + CODEC_TRACE("tdsqlite3CodecAttach: calling tdsqlite3BtreeSetAutoVacuum()\n"); + tdsqlite3BtreeSetAutoVacuum(pDb->pBt, SQLITE_DEFAULT_AUTOVACUUM); } - sqlite3_mutex_leave(db->mutex); + CODEC_TRACE_MUTEX("tdsqlite3CodecAttach: leaving database mutex %p\n", db->mutex); + tdsqlite3_mutex_leave(db->mutex); + CODEC_TRACE_MUTEX("tdsqlite3CodecAttach: left database mutex %p\n", db->mutex); } return SQLITE_OK; } -SQLITE_API void sqlite3_activate_see(const char* in) { - /* do nothing, security enhancements are always active */ -} - -static int sqlcipher_find_db_index(sqlite3 *db, const char *zDb) { +int sqlcipher_find_db_index(tdsqlite3 *db, const char *zDb) { int db_index; if(zDb == NULL){ return 0; @@ -18305,27 +22170,31 @@ static int sqlcipher_find_db_index(sqlite3 *db, const char *zDb) { return 0; } -SQLITE_API int sqlite3_key(sqlite3 *db, const void *pKey, int nKey) { - CODEC_TRACE(("sqlite3_key entered: db=%p pKey=%s nKey=%d\n", db, (char *)pKey, nKey)); - return sqlite3_key_v2(db, "main", pKey, nKey); +SQLITE_API void tdsqlite3_activate_see(const char* in) { + /* do nothing, security enhancements are always active */ } -SQLITE_API int sqlite3_key_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) { - CODEC_TRACE(("sqlite3_key_v2: entered db=%p zDb=%s pKey=%s nKey=%d\n", db, zDb, (char *)pKey, nKey)); +SQLITE_API int tdsqlite3_key(tdsqlite3 *db, const void *pKey, int nKey) { + CODEC_TRACE("tdsqlite3_key entered: db=%p pKey=%s nKey=%d\n", db, (char *)pKey, nKey); + return tdsqlite3_key_v2(db, "main", pKey, nKey); +} + +SQLITE_API int tdsqlite3_key_v2(tdsqlite3 *db, const char *zDb, const void *pKey, int nKey) { + CODEC_TRACE("tdsqlite3_key_v2: entered db=%p zDb=%s pKey=%s nKey=%d\n", db, zDb, (char *)pKey, nKey); /* attach key if db and pKey are not null and nKey is > 0 */ if(db && pKey && nKey) { int db_index = sqlcipher_find_db_index(db, zDb); - return sqlite3CodecAttach(db, db_index, pKey, nKey); + return tdsqlite3CodecAttach(db, db_index, pKey, nKey); } return SQLITE_ERROR; } -SQLITE_API int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) { - CODEC_TRACE(("sqlite3_rekey entered: db=%p pKey=%s nKey=%d\n", db, (char *)pKey, nKey)); - return sqlite3_rekey_v2(db, "main", pKey, nKey); +SQLITE_API int tdsqlite3_rekey(tdsqlite3 *db, const void *pKey, int nKey) { + CODEC_TRACE("tdsqlite3_rekey entered: db=%p pKey=%s nKey=%d\n", db, (char *)pKey, nKey); + return tdsqlite3_rekey_v2(db, "main", pKey, nKey); } -/* sqlite3_rekey_v2 +/* tdsqlite3_rekey_v2 ** Given a database, this will reencrypt the database using a new key. ** There is only one possible modes of operation - to encrypt a database ** that is already encrpyted. If the database is not already encrypted @@ -18335,12 +22204,12 @@ SQLITE_API int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) { ** 2. If there is NOT already a key present do nothing ** 3. If there is a key present, re-encrypt the database with the new key */ -SQLITE_API int sqlite3_rekey_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) { - CODEC_TRACE(("sqlite3_rekey_v2: entered db=%p zDb=%s pKey=%s, nKey=%d\n", db, zDb, (char *)pKey, nKey)); +SQLITE_API int tdsqlite3_rekey_v2(tdsqlite3 *db, const char *zDb, const void *pKey, int nKey) { + CODEC_TRACE("tdsqlite3_rekey_v2: entered db=%p zDb=%s pKey=%s, nKey=%d\n", db, zDb, (char *)pKey, nKey); if(db && pKey && nKey) { int db_index = sqlcipher_find_db_index(db, zDb); struct Db *pDb = &db->aDb[db_index]; - CODEC_TRACE(("sqlite3_rekey_v2: database pDb=%p db_index:%d\n", pDb, db_index)); + CODEC_TRACE("tdsqlite3_rekey_v2: database pDb=%p db_index:%d\n", pDb, db_index); if(pDb->pBt) { codec_ctx *ctx; int rc, page_count; @@ -18348,15 +22217,17 @@ SQLITE_API int sqlite3_rekey_v2(sqlite3 *db, const char *zDb, const void *pKey, PgHdr *page; Pager *pPager = pDb->pBt->pBt->pPager; - sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx); + ctx = (codec_ctx*) tdsqlite3PagerGetCodec(pDb->pBt->pBt->pPager); if(ctx == NULL) { /* there was no codec attached to this database, so this should do nothing! */ - CODEC_TRACE(("sqlite3_rekey_v2: no codec attached to db, exiting\n")); + CODEC_TRACE("tdsqlite3_rekey_v2: no codec attached to db, exiting\n"); return SQLITE_OK; } - sqlite3_mutex_enter(db->mutex); + CODEC_TRACE_MUTEX("tdsqlite3_rekey_v2: entering database mutex %p\n", db->mutex); + tdsqlite3_mutex_enter(db->mutex); + CODEC_TRACE_MUTEX("tdsqlite3_rekey_v2: entered database mutex %p\n", db->mutex); codec_set_pass_key(db, db_index, pKey, nKey, CIPHER_WRITE_CTX); @@ -18366,52 +22237,56 @@ SQLITE_API int sqlite3_rekey_v2(sqlite3 *db, const char *zDb, const void *pKey, ** 3. If that goes ok then commit and put ctx->rekey into ctx->key ** note: don't deallocate rekey since it may be used in a subsequent iteration */ - rc = sqlite3BtreeBeginTrans(pDb->pBt, 1); /* begin write transaction */ - sqlite3PagerPagecount(pPager, &page_count); + rc = tdsqlite3BtreeBeginTrans(pDb->pBt, 1, 0); /* begin write transaction */ + tdsqlite3PagerPagecount(pPager, &page_count); for(pgno = 1; rc == SQLITE_OK && pgno <= (unsigned int)page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */ - if(!sqlite3pager_is_mj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */ - rc = sqlite3PagerGet(pPager, pgno, &page, 0); + if(!tdsqlite3pager_is_mj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */ + rc = tdsqlite3PagerGet(pPager, pgno, &page, 0); if(rc == SQLITE_OK) { /* write page see pager_incr_changecounter for example */ - rc = sqlite3PagerWrite(page); + rc = tdsqlite3PagerWrite(page); if(rc == SQLITE_OK) { - sqlite3PagerUnref(page); + tdsqlite3PagerUnref(page); } else { - CODEC_TRACE(("sqlite3_rekey_v2: error %d occurred writing page %d\n", rc, pgno)); + CODEC_TRACE("tdsqlite3_rekey_v2: error %d occurred writing page %d\n", rc, pgno); } } else { - CODEC_TRACE(("sqlite3_rekey_v2: error %d occurred getting page %d\n", rc, pgno)); + CODEC_TRACE("tdsqlite3_rekey_v2: error %d occurred getting page %d\n", rc, pgno); } } } /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */ if(rc == SQLITE_OK) { - CODEC_TRACE(("sqlite3_rekey_v2: committing\n")); - rc = sqlite3BtreeCommit(pDb->pBt); + CODEC_TRACE("tdsqlite3_rekey_v2: committing\n"); + rc = tdsqlite3BtreeCommit(pDb->pBt); sqlcipher_codec_key_copy(ctx, CIPHER_WRITE_CTX); } else { - CODEC_TRACE(("sqlite3_rekey_v2: rollback\n")); - sqlite3BtreeRollback(pDb->pBt, SQLITE_ABORT_ROLLBACK, 0); + CODEC_TRACE("tdsqlite3_rekey_v2: rollback\n"); + tdsqlite3BtreeRollback(pDb->pBt, SQLITE_ABORT_ROLLBACK, 0); } - sqlite3_mutex_leave(db->mutex); + CODEC_TRACE_MUTEX("tdsqlite3_rekey_v2: leaving database mutex %p\n", db->mutex); + tdsqlite3_mutex_leave(db->mutex); + CODEC_TRACE_MUTEX("tdsqlite3_rekey_v2: left database mutex %p\n", db->mutex); } return SQLITE_OK; } return SQLITE_ERROR; } -SQLITE_PRIVATE void sqlite3CodecGetKey(sqlite3* db, int nDb, void **zKey, int *nKey) { +SQLITE_PRIVATE void tdsqlite3CodecGetKey(tdsqlite3* db, int nDb, void **zKey, int *nKey) { struct Db *pDb = &db->aDb[nDb]; - CODEC_TRACE(("sqlite3CodecGetKey: entered db=%p, nDb=%d\n", db, nDb)); + CODEC_TRACE("tdsqlite3CodecGetKey: entered db=%p, nDb=%d\n", db, nDb); if( pDb->pBt ) { - codec_ctx *ctx; - sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx); + codec_ctx *ctx = (codec_ctx*) tdsqlite3PagerGetCodec(pDb->pBt->pBt->pPager); + if(ctx) { - if(sqlcipher_codec_get_store_pass(ctx) == 1) { + /* pass back the keyspec from the codec, unless PRAGMA cipher_store_pass + is set or keyspec has not yet been derived, in which case pass + back the password key material */ + sqlcipher_codec_get_keyspec(ctx, zKey, nKey); + if(sqlcipher_codec_get_store_pass(ctx) == 1 || *zKey == NULL) { sqlcipher_codec_get_pass(ctx, zKey, nKey); - } else { - sqlcipher_codec_get_keyspec(ctx, zKey, nKey); } } else { *zKey = NULL; @@ -18442,11 +22317,11 @@ SQLITE_PRIVATE void sqlite3CodecGetKey(sqlite3* db, int nDb, void **zKey, int *n ** ** Based on vacuumFinalize from vacuum.c */ -static int sqlcipher_finalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){ +static int sqlcipher_finalize(tdsqlite3 *db, tdsqlite3_stmt *pStmt, char **pzErrMsg){ int rc; - rc = sqlite3VdbeFinalize((Vdbe*)pStmt); + rc = tdsqlite3VdbeFinalize((Vdbe*)pStmt); if( rc ){ - sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); + tdsqlite3SetString(pzErrMsg, db, tdsqlite3_errmsg(db)); } return rc; } @@ -18456,17 +22331,17 @@ static int sqlcipher_finalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg) ** ** Based on execSql from vacuum.c */ -static int sqlcipher_execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ - sqlite3_stmt *pStmt; +static int sqlcipher_execSql(tdsqlite3 *db, char **pzErrMsg, const char *zSql){ + tdsqlite3_stmt *pStmt; VVA_ONLY( int rc; ) if( !zSql ){ return SQLITE_NOMEM; } - if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ - sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); - return sqlite3_errcode(db); + if( SQLITE_OK!=tdsqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ + tdsqlite3SetString(pzErrMsg, db, tdsqlite3_errmsg(db)); + return tdsqlite3_errcode(db); } - VVA_ONLY( rc = ) sqlite3_step(pStmt); + VVA_ONLY( rc = ) tdsqlite3_step(pStmt); assert( rc!=SQLITE_ROW ); return sqlcipher_finalize(db, pStmt, pzErrMsg); } @@ -18477,15 +22352,15 @@ static int sqlcipher_execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ ** ** Based on execExecSql from vacuum.c */ -static int sqlcipher_execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ - sqlite3_stmt *pStmt; +static int sqlcipher_execExecSql(tdsqlite3 *db, char **pzErrMsg, const char *zSql){ + tdsqlite3_stmt *pStmt; int rc; - rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + rc = tdsqlite3_prepare(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ - rc = sqlcipher_execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0)); + while( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + rc = sqlcipher_execSql(db, pzErrMsg, (char*)tdsqlite3_column_text(pStmt, 0)); if( rc!=SQLITE_OK ){ sqlcipher_finalize(db, pStmt, pzErrMsg); return rc; @@ -18498,120 +22373,135 @@ static int sqlcipher_execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql) /* * copy database and schema from the main database to an attached database * - * Based on sqlite3RunVacuum from vacuum.c -*/ -void sqlcipher_exportFunc(sqlite3_context *context, int argc, sqlite3_value **argv) { - sqlite3 *db = sqlite3_context_db_handle(context); - const char* attachedDb = (const char*) sqlite3_value_text(argv[0]); - int saved_flags; /* Saved value of the db->flags */ - int saved_nChange; /* Saved value of db->nChange */ - int saved_nTotalChange; /* Saved value of db->nTotalChange */ - int (*saved_xTrace)(u32,void*,void*,void*); /* Saved db->xTrace */ + * Based on tdsqlite3RunVacuum from vacuum.c +*/ +void sqlcipher_exportFunc(tdsqlite3_context *context, int argc, tdsqlite3_value **argv) { + tdsqlite3 *db = tdsqlite3_context_db_handle(context); + const char* targetDb, *sourceDb; + int targetDb_idx = 0; + u64 saved_flags = db->flags; /* Saved value of the db->flags */ + u32 saved_mDbFlags = db->mDbFlags; /* Saved value of the db->mDbFlags */ + int saved_nChange = db->nChange; /* Saved value of db->nChange */ + int saved_nTotalChange = db->nTotalChange; /* Saved value of db->nTotalChange */ + u8 saved_mTrace = db->mTrace; /* Saved value of db->mTrace */ + int (*saved_xTrace)(u32,void*,void*,void*) = db->xTrace; /* Saved db->xTrace */ int rc = SQLITE_OK; /* Return code from service routines */ char *zSql = NULL; /* SQL statements */ char *pzErrMsg = NULL; - - saved_flags = db->flags; - saved_nChange = db->nChange; - saved_nTotalChange = db->nTotalChange; - saved_xTrace = db->xTrace; - db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin; - db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder); + + if(argc != 1 && argc != 2) { + rc = SQLITE_ERROR; + pzErrMsg = tdsqlite3_mprintf("invalid number of arguments (%d) passed to sqlcipher_export", argc); + goto end_of_export; + } + + targetDb = (const char*) tdsqlite3_value_text(argv[0]); + sourceDb = (argc == 2) ? (char *) tdsqlite3_value_text(argv[1]) : "main"; + + /* if the name of the target is not main, but the index returned is zero + there is a mismatch and we should not proceed */ + targetDb_idx = sqlcipher_find_db_index(db, targetDb); + if(targetDb_idx == 0 && tdsqlite3StrICmp("main", targetDb) != 0) { + rc = SQLITE_ERROR; + pzErrMsg = tdsqlite3_mprintf("unknown database %s", targetDb); + goto end_of_export; + } + db->init.iDb = targetDb_idx; + + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks; + db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum; + db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_Defensive | SQLITE_CountRows); db->xTrace = 0; + db->mTrace = 0; /* Query the schema of the main database. Create a mirror schema ** in the temporary database. */ - zSql = sqlite3_mprintf( - "SELECT 'CREATE TABLE %s.' || substr(sql,14) " - " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" + zSql = tdsqlite3_mprintf( + "SELECT sql " + " FROM %s.sqlite_master WHERE type='table' AND name!='sqlite_sequence'" " AND rootpage>0" - , attachedDb); + , sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; - sqlite3_free(zSql); + tdsqlite3_free(zSql); - zSql = sqlite3_mprintf( - "SELECT 'CREATE INDEX %s.' || substr(sql,14)" - " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %%' " - , attachedDb); + zSql = tdsqlite3_mprintf( + "SELECT sql " + " FROM %s.sqlite_master WHERE sql LIKE 'CREATE INDEX %%' " + , sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; - sqlite3_free(zSql); + tdsqlite3_free(zSql); - zSql = sqlite3_mprintf( - "SELECT 'CREATE UNIQUE INDEX %s.' || substr(sql,21) " - " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %%'" - , attachedDb); + zSql = tdsqlite3_mprintf( + "SELECT sql " + " FROM %s.sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %%'" + , sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; - sqlite3_free(zSql); + tdsqlite3_free(zSql); /* Loop through the tables in the main database. For each, do ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy ** the contents to the temporary database. */ - zSql = sqlite3_mprintf( + zSql = tdsqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " - "|| ' SELECT * FROM main.' || quote(name) || ';'" - "FROM main.sqlite_master " + "|| ' SELECT * FROM %s.' || quote(name) || ';'" + "FROM %s.sqlite_master " "WHERE type = 'table' AND name!='sqlite_sequence' " " AND rootpage>0" - , attachedDb); + , targetDb, sourceDb, sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; - sqlite3_free(zSql); + tdsqlite3_free(zSql); - /* Copy over the sequence table + /* Copy over the contents of the sequence table */ - zSql = sqlite3_mprintf( - "SELECT 'DELETE FROM %s.' || quote(name) || ';' " - "FROM %s.sqlite_master WHERE name='sqlite_sequence' " - , attachedDb, attachedDb); - rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); - if( rc!=SQLITE_OK ) goto end_of_export; - sqlite3_free(zSql); - - zSql = sqlite3_mprintf( + zSql = tdsqlite3_mprintf( "SELECT 'INSERT INTO %s.' || quote(name) " - "|| ' SELECT * FROM main.' || quote(name) || ';' " + "|| ' SELECT * FROM %s.' || quote(name) || ';' " "FROM %s.sqlite_master WHERE name=='sqlite_sequence';" - , attachedDb, attachedDb); + , targetDb, sourceDb, targetDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; - sqlite3_free(zSql); + tdsqlite3_free(zSql); /* Copy the triggers, views, and virtual tables from the main database ** over to the temporary database. None of these objects has any ** associated storage, so all we have to do is copy their entries ** from the SQLITE_MASTER table. */ - zSql = sqlite3_mprintf( + zSql = tdsqlite3_mprintf( "INSERT INTO %s.sqlite_master " " SELECT type, name, tbl_name, rootpage, sql" - " FROM main.sqlite_master" + " FROM %s.sqlite_master" " WHERE type='view' OR type='trigger'" " OR (type='table' AND rootpage=0)" - , attachedDb); + , targetDb, sourceDb); rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql); if( rc!=SQLITE_OK ) goto end_of_export; - sqlite3_free(zSql); + tdsqlite3_free(zSql); zSql = NULL; end_of_export: + db->init.iDb = 0; db->flags = saved_flags; + db->mDbFlags = saved_mDbFlags; db->nChange = saved_nChange; db->nTotalChange = saved_nTotalChange; db->xTrace = saved_xTrace; + db->mTrace = saved_mTrace; - sqlite3_free(zSql); + if(zSql) tdsqlite3_free(zSql); if(rc) { if(pzErrMsg != NULL) { - sqlite3_result_error(context, pzErrMsg, -1); - sqlite3DbFree(db, pzErrMsg); + tdsqlite3_result_error(context, pzErrMsg, -1); + tdsqlite3DbFree(db, pzErrMsg); } else { - sqlite3_result_error(context, sqlite3ErrStr(rc), -1); + tdsqlite3_result_error(context, tdsqlite3ErrStr(rc), -1); } } } @@ -18656,146 +22546,112 @@ end_of_export: /* BEGIN SQLCIPHER */ #ifdef SQLITE_HAS_CODEC -/* #include "sqliteInt.h" */ -/* #include "btreeInt.h" */ -/************** Include sqlcipher.h in the middle of crypto_impl.c ***********/ -/************** Begin file sqlcipher.h ***************************************/ -/* -** SQLCipher -** sqlcipher.h developed by Stephen Lombardo (Zetetic LLC) -** sjlombardo at zetetic dot net -** http://zetetic.net -** -** Copyright (c) 2008, ZETETIC LLC -** All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of the ZETETIC LLC nor the -** names of its contributors may be used to endorse or promote products -** derived from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY -** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY -** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -*/ -/* BEGIN SQLCIPHER */ -#ifdef SQLITE_HAS_CODEC -#ifndef SQLCIPHER_H -#define SQLCIPHER_H - - -typedef struct { - int (*activate)(void *ctx); - int (*deactivate)(void *ctx); - const char* (*get_provider_name)(void *ctx); - int (*add_random)(void *ctx, void *buffer, int length); - int (*random)(void *ctx, void *buffer, int length); - int (*hmac)(void *ctx, unsigned char *hmac_key, int key_sz, unsigned char *in, int in_sz, unsigned char *in2, int in2_sz, unsigned char *out); - int (*kdf)(void *ctx, const unsigned char *pass, int pass_sz, unsigned char* salt, int salt_sz, int workfactor, int key_sz, unsigned char *key); - int (*cipher)(void *ctx, int mode, unsigned char *key, int key_sz, unsigned char *iv, unsigned char *in, int in_sz, unsigned char *out); - int (*set_cipher)(void *ctx, const char *cipher_name); - const char* (*get_cipher)(void *ctx); - int (*get_key_sz)(void *ctx); - int (*get_iv_sz)(void *ctx); - int (*get_block_sz)(void *ctx); - int (*get_hmac_sz)(void *ctx); - int (*ctx_copy)(void *target_ctx, void *source_ctx); - int (*ctx_cmp)(void *c1, void *c2); - int (*ctx_init)(void **ctx); - int (*ctx_free)(void **ctx); - int (*fips_status)(void *ctx); - const char* (*get_provider_version)(void *ctx); -} sqlcipher_provider; - -/* utility functions */ -void sqlcipher_free(void *ptr, int sz); -void* sqlcipher_malloc(int sz); -void* sqlcipher_memset(void *v, unsigned char value, int len); -int sqlcipher_ismemset(const void *v, unsigned char value, int len); -int sqlcipher_memcmp(const void *v0, const void *v1, int len); -void sqlcipher_free(void *, int); - -/* provider interfaces */ -int sqlcipher_register_provider(sqlcipher_provider *p); -sqlcipher_provider* sqlcipher_get_provider(); - -#endif -#endif -/* END SQLCIPHER */ - - -/************** End of sqlcipher.h *******************************************/ -/************** Continuing where we left off in crypto_impl.c ****************/ +/* #include "sqlcipher.h" */ /* #include "crypto.h" */ -#ifndef OMIT_MEMLOCK +// #ifndef OMIT_MEMLOCK #if defined(__unix__) || defined(__APPLE__) || defined(_AIX) +#include <errno.h> +#include <unistd.h> +#include <sys/resource.h> #include <sys/mman.h> #elif defined(_WIN32) -# include <windows.h> -#endif +#include <windows.h> #endif +// #endif -/* the default implementation of SQLCipher uses a cipher_ctx - to keep track of read / write state separately. The following - struct and associated functions are defined here */ -typedef struct { - int store_pass; - int derive_key; - int kdf_iter; - int fast_kdf_iter; - int key_sz; - int iv_sz; - int block_sz; - int pass_sz; - int reserve_sz; - int hmac_sz; - int keyspec_sz; - unsigned int flags; - unsigned char *key; - unsigned char *hmac_key; - unsigned char *pass; - char *keyspec; - sqlcipher_provider *provider; - void *provider_ctx; -} cipher_ctx; +static volatile unsigned int default_flags = DEFAULT_CIPHER_FLAGS; +static volatile unsigned char hmac_salt_mask = HMAC_SALT_MASK; -static unsigned int default_flags = DEFAULT_CIPHER_FLAGS; -static unsigned char hmac_salt_mask = HMAC_SALT_MASK; -static int default_kdf_iter = PBKDF2_ITER; -static int default_page_size = 1024; -static unsigned int sqlcipher_activate_count = 0; -static sqlite3_mutex* sqlcipher_provider_mutex = NULL; +#include <openssl/opensslv.h> + +#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10000000L +static volatile int default_kdf_iter = 64000; +static volatile int default_page_size = 1024; +static volatile int default_plaintext_header_sz = 0; +static volatile int default_hmac_algorithm = SQLCIPHER_HMAC_SHA1; +static volatile int default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA1; +#else +static volatile int default_kdf_iter = PBKDF2_ITER; +static volatile int default_page_size = 4096; +static volatile int default_plaintext_header_sz = 0; +static volatile int default_hmac_algorithm = SQLCIPHER_HMAC_SHA512; +static volatile int default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA512; +#endif +static volatile int mem_security_on = 1; +static volatile int mem_security_initialized = 0; +static volatile int mem_security_activated = 0; +static volatile unsigned int sqlcipher_activate_count = 0; +static volatile tdsqlite3_mem_methods default_mem_methods; static sqlcipher_provider *default_provider = NULL; -struct codec_ctx { - int kdf_salt_sz; - int page_sz; - unsigned char *kdf_salt; - unsigned char *hmac_kdf_salt; - unsigned char *buffer; - Btree *pBt; - cipher_ctx *read_ctx; - cipher_ctx *write_ctx; - unsigned int skip_read_hmac; - unsigned int need_kdf_salt; +static tdsqlite3_mutex* sqlcipher_static_mutex[SQLCIPHER_MUTEX_COUNT]; + +tdsqlite3_mutex* sqlcipher_mutex(int mutex) { + if(mutex < 0 || mutex >= SQLCIPHER_MUTEX_COUNT) return NULL; + return sqlcipher_static_mutex[mutex]; +} + +static int sqlcipher_mem_init(void *pAppData) { + return default_mem_methods.xInit(pAppData); +} +static void sqlcipher_mem_shutdown(void *pAppData) { + default_mem_methods.xShutdown(pAppData); +} +static void *sqlcipher_mem_malloc(int n) { + void *ptr = default_mem_methods.xMalloc(n); + if(mem_security_on) { + CODEC_TRACE_MEMORY("sqlcipher_mem_malloc: calling sqlcipher_mlock(%p,%d)\n", ptr, n); + sqlcipher_mlock(ptr, n); + if(!mem_security_activated) mem_security_activated = 1; + } + return ptr; +} +static int sqlcipher_mem_size(void *p) { + return default_mem_methods.xSize(p); +} +static void sqlcipher_mem_free(void *p) { + int sz; + if(mem_security_on) { + sz = sqlcipher_mem_size(p); + CODEC_TRACE_MEMORY("sqlcipher_mem_free: calling sqlcipher_memset(%p,0,%d) and sqlcipher_munlock(%p, %d) \n", p, sz, p, sz); + sqlcipher_memset(p, 0, sz); + sqlcipher_munlock(p, sz); + if(!mem_security_activated) mem_security_activated = 1; + } + default_mem_methods.xFree(p); +} +static void *sqlcipher_mem_realloc(void *p, int n) { + return default_mem_methods.xRealloc(p, n); +} +static int sqlcipher_mem_roundup(int n) { + return default_mem_methods.xRoundup(n); +} + +static tdsqlite3_mem_methods sqlcipher_mem_methods = { + sqlcipher_mem_malloc, + sqlcipher_mem_free, + sqlcipher_mem_realloc, + sqlcipher_mem_size, + sqlcipher_mem_roundup, + sqlcipher_mem_init, + sqlcipher_mem_shutdown, + 0 }; +void sqlcipher_init_memmethods() { + if(mem_security_initialized) return; + if(tdsqlite3_config(SQLITE_CONFIG_GETMALLOC, &default_mem_methods) != SQLITE_OK || + tdsqlite3_config(SQLITE_CONFIG_MALLOC, &sqlcipher_mem_methods) != SQLITE_OK) { + mem_security_on = mem_security_activated = 0; + } + mem_security_initialized = 1; +} + int sqlcipher_register_provider(sqlcipher_provider *p) { - sqlite3_mutex_enter(sqlcipher_provider_mutex); + CODEC_TRACE_MUTEX("sqlcipher_register_provider: entering SQLCIPHER_MUTEX_PROVIDER\n"); + tdsqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); + CODEC_TRACE_MUTEX("sqlcipher_register_provider: entered SQLCIPHER_MUTEX_PROVIDER\n"); + if(default_provider != NULL && default_provider != p) { /* only free the current registerd provider if it has been initialized and it isn't a pointer to the same provider passed to the function @@ -18803,7 +22659,10 @@ int sqlcipher_register_provider(sqlcipher_provider *p) { sqlcipher_free(default_provider, sizeof(sqlcipher_provider)); } default_provider = p; - sqlite3_mutex_leave(sqlcipher_provider_mutex); + CODEC_TRACE_MUTEX("sqlcipher_register_provider: leaving SQLCIPHER_MUTEX_PROVIDER\n"); + tdsqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); + CODEC_TRACE_MUTEX("sqlcipher_register_provider: left SQLCIPHER_MUTEX_PROVIDER\n"); + return SQLITE_OK; } @@ -18814,70 +22673,58 @@ sqlcipher_provider* sqlcipher_get_provider() { return default_provider; } -void sqlcipher_activate() { - sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); - - if(sqlcipher_provider_mutex == NULL) { - /* allocate a new mutex to guard access to the provider */ - sqlcipher_provider_mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); - } - - /* check to see if there is a provider registered at this point - if there no provider registered at this point, register the - default provider */ - if(sqlcipher_get_provider() == NULL) { - sqlcipher_provider *p = sqlcipher_malloc(sizeof(sqlcipher_provider)); -#if defined (SQLCIPHER_CRYPTO_CC) - extern int sqlcipher_cc_setup(sqlcipher_provider *p); - sqlcipher_cc_setup(p); -#elif defined (SQLCIPHER_CRYPTO_LIBTOMCRYPT) - extern int sqlcipher_ltc_setup(sqlcipher_provider *p); - sqlcipher_ltc_setup(p); -#elif defined (SQLCIPHER_CRYPTO_OPENSSL) - extern int sqlcipher_openssl_setup(sqlcipher_provider *p); - sqlcipher_openssl_setup(p); -#else -#error "NO DEFAULT SQLCIPHER CRYPTO PROVIDER DEFINED" -#endif - sqlcipher_register_provider(p); - } - - sqlcipher_activate_count++; /* increment activation count */ - - sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); -} - void sqlcipher_deactivate() { - sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + CODEC_TRACE_MUTEX("sqlcipher_deactivate: entering static master mutex\n"); + tdsqlite3_mutex_enter(tdsqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + CODEC_TRACE_MUTEX("sqlcipher_deactivate: entered static master mutex\n"); + sqlcipher_activate_count--; /* if no connections are using sqlcipher, cleanup globals */ if(sqlcipher_activate_count < 1) { - sqlite3_mutex_enter(sqlcipher_provider_mutex); + + CODEC_TRACE_MUTEX("sqlcipher_deactivate: entering SQLCIPHER_MUTEX_PROVIDER\n"); + tdsqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); + CODEC_TRACE_MUTEX("sqlcipher_deactivate: entered SQLCIPHER_MUTEX_PROVIDER\n"); + if(default_provider != NULL) { sqlcipher_free(default_provider, sizeof(sqlcipher_provider)); default_provider = NULL; } - sqlite3_mutex_leave(sqlcipher_provider_mutex); - - /* last connection closed, free provider mutex*/ - sqlite3_mutex_free(sqlcipher_provider_mutex); - sqlcipher_provider_mutex = NULL; + CODEC_TRACE_MUTEX("sqlcipher_deactivate: leaving SQLCIPHER_MUTEX_PROVIDER\n"); + tdsqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); + CODEC_TRACE_MUTEX("sqlcipher_deactivate: left SQLCIPHER_MUTEX_PROVIDER\n"); + +#ifdef SQLCIPHER_EXT + sqlcipher_ext_provider_destroy(); +#endif + + /* last connection closed, free mutexes */ + if(sqlcipher_activate_count == 0) { + int i; + for(i = 0; i < SQLCIPHER_MUTEX_COUNT; i++) { + tdsqlite3_mutex_free(sqlcipher_static_mutex[i]); + } + } sqlcipher_activate_count = 0; /* reset activation count */ } - sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + + CODEC_TRACE_MUTEX("sqlcipher_deactivate: leaving static master mutex\n"); + tdsqlite3_mutex_leave(tdsqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + CODEC_TRACE_MUTEX("sqlcipher_deactivate: left static master mutex\n"); } /* constant time memset using volitile to avoid having the memset optimized out by the compiler. Note: As suggested by Joachim Schipper (joachim.schipper@fox-it.com) */ -void* sqlcipher_memset(void *v, unsigned char value, int len) { - int i = 0; +void* sqlcipher_memset(void *v, unsigned char value, u64 len) { + u64 i = 0; volatile unsigned char *a = v; if (v == NULL) return v; + CODEC_TRACE_MEMORY("sqlcipher_memset: setting %p[0-%llu]=%d)\n", a, len, value); for(i = 0; i < len; i++) { a[i] = value; } @@ -18888,9 +22735,9 @@ void* sqlcipher_memset(void *v, unsigned char value, int len) { /* constant time memory check tests every position of a memory segement matches a single value (i.e. the memory is all zeros) returns 0 if match, 1 of no match */ -int sqlcipher_ismemset(const void *v, unsigned char value, int len) { +int sqlcipher_ismemset(const void *v, unsigned char value, u64 len) { const unsigned char *a = v; - int i = 0, result = 0; + u64 i = 0, result = 0; for(i = 0; i < len; i++) { result |= a[i] ^ value; @@ -18912,54 +22759,98 @@ int sqlcipher_memcmp(const void *v0, const void *v1, int len) { return (result != 0); } -/** - * Free and wipe memory. Uses SQLites internal sqlite3_free so that memory - * can be countend and memory leak detection works in the test suite. - * If ptr is not null memory will be freed. - * If sz is greater than zero, the memory will be overwritten with zero before it is freed - * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the - * memory segment so it can be paged - */ -void sqlcipher_free(void *ptr, int sz) { - if(ptr) { - if(sz > 0) { - sqlcipher_memset(ptr, 0, sz); +void sqlcipher_mlock(void *ptr, u64 sz) { #ifndef OMIT_MEMLOCK #if defined(__unix__) || defined(__APPLE__) - munlock(ptr, sz); + int rc; + unsigned long pagesize = sysconf(_SC_PAGESIZE); + unsigned long offset = (unsigned long) ptr % pagesize; + + if(ptr == NULL || sz == 0) return; + + CODEC_TRACE_MEMORY("sqlcipher_mem_lock: calling mlock(%p,%lu); _SC_PAGESIZE=%lu\n", ptr - offset, sz + offset, pagesize); + rc = mlock(ptr - offset, sz + offset); + if(rc!=0) { + CODEC_TRACE_MEMORY("sqlcipher_mem_lock: mlock(%p,%lu) returned %d errno=%d\n", ptr - offset, sz + offset, rc, errno); + } #elif defined(_WIN32) #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP)) -VirtualUnlock(ptr, sz); + int rc; + CODEC_TRACE("sqlcipher_mem_lock: calling VirtualLock(%p,%d)\n", ptr, sz); + rc = VirtualLock(ptr, sz); + if(rc==0) { + CODEC_TRACE("sqlcipher_mem_lock: VirtualLock(%p,%d) returned %d LastError=%d\n", ptr, sz, rc, GetLastError()); + } #endif #endif #endif - } - sqlite3_free(ptr); - } } -/** - * allocate memory. Uses sqlite's internall malloc wrapper so memory can be - * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK - * attempts to lock the memory pages so sensitive information won't be swapped - */ -void* sqlcipher_malloc(int sz) { - void *ptr = sqlite3Malloc(sz); - sqlcipher_memset(ptr, 0, sz); +void sqlcipher_munlock(void *ptr, u64 sz) { #ifndef OMIT_MEMLOCK - if(ptr) { #if defined(__unix__) || defined(__APPLE__) - mlock(ptr, sz); + int rc; + unsigned long pagesize = sysconf(_SC_PAGESIZE); + unsigned long offset = (unsigned long) ptr % pagesize; + + if(ptr == NULL || sz == 0) return; + + CODEC_TRACE_MEMORY("sqlcipher_mem_unlock: calling munlock(%p,%lu)\n", ptr - offset, sz + offset); + rc = munlock(ptr - offset, sz + offset); + if(rc!=0) { + CODEC_TRACE_MEMORY("sqlcipher_mem_unlock: munlock(%p,%lu) returned %d errno=%d\n", ptr - offset, sz + offset, rc, errno); + } #elif defined(_WIN32) #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP)) - VirtualLock(ptr, sz); + int rc; + CODEC_TRACE("sqlcipher_mem_lock: calling VirtualUnlock(%p,%d)\n", ptr, sz); + rc = VirtualUnlock(ptr, sz); + if(!rc) { + CODEC_TRACE("sqlcipher_mem_unlock: VirtualUnlock(%p,%d) returned %d LastError=%d\n", ptr, sz, rc, GetLastError()); + } #endif #endif - } #endif +} + +/** + * Free and wipe memory. Uses SQLites internal tdsqlite3_free so that memory + * can be countend and memory leak detection works in the test suite. + * If ptr is not null memory will be freed. + * If sz is greater than zero, the memory will be overwritten with zero before it is freed + * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the + * memory segment so it can be paged + */ +void sqlcipher_free(void *ptr, u64 sz) { + CODEC_TRACE_MEMORY("sqlcipher_free: calling sqlcipher_memset(%p,0,%llu)\n", ptr, sz); + sqlcipher_memset(ptr, 0, sz); + sqlcipher_munlock(ptr, sz); + tdsqlite3_free(ptr); +} + +/** + * allocate memory. Uses sqlite's internall malloc wrapper so memory can be + * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK + * attempts to lock the memory pages so sensitive information won't be swapped + */ +void* sqlcipher_malloc(u64 sz) { + void *ptr; + CODEC_TRACE_MEMORY("sqlcipher_malloc: calling tdsqlite3Malloc(%llu)\n", sz); + ptr = tdsqlite3Malloc(sz); + CODEC_TRACE_MEMORY("sqlcipher_malloc: calling sqlcipher_memset(%p,0,%llu)\n", ptr, sz); + sqlcipher_memset(ptr, 0, sz); + sqlcipher_mlock(ptr, sz); return ptr; } +char* sqlcipher_version() { +#ifdef CIPHER_VERSION_QUALIFIER + char *version = tdsqlite3_mprintf("%s %s %s", CIPHER_XSTR(CIPHER_VERSION_NUMBER), CIPHER_XSTR(CIPHER_VERSION_QUALIFIER), CIPHER_XSTR(CIPHER_VERSION_BUILD)); +#else + char *version = tdsqlite3_mprintf("%s %s", CIPHER_XSTR(CIPHER_VERSION_NUMBER), CIPHER_XSTR(CIPHER_VERSION_BUILD)); +#endif + return version; +} /** * Initialize new cipher_ctx struct. This function will allocate memory @@ -18968,29 +22859,21 @@ void* sqlcipher_malloc(int sz) { * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ -static int sqlcipher_cipher_ctx_init(cipher_ctx **iCtx) { - int rc; - cipher_ctx *ctx; +static int sqlcipher_cipher_ctx_init(codec_ctx *ctx, cipher_ctx **iCtx) { + cipher_ctx *c_ctx; + CODEC_TRACE("sqlcipher_cipher_ctx_init: allocating context\n"); *iCtx = (cipher_ctx *) sqlcipher_malloc(sizeof(cipher_ctx)); - ctx = *iCtx; - if(ctx == NULL) return SQLITE_NOMEM; + c_ctx = *iCtx; + if(c_ctx == NULL) return SQLITE_NOMEM; - ctx->provider = (sqlcipher_provider *) sqlcipher_malloc(sizeof(sqlcipher_provider)); - if(ctx->provider == NULL) return SQLITE_NOMEM; + CODEC_TRACE("sqlcipher_cipher_ctx_init: allocating key\n"); + c_ctx->key = (unsigned char *) sqlcipher_malloc(ctx->key_sz); - /* make a copy of the provider to be used for the duration of the context */ - sqlite3_mutex_enter(sqlcipher_provider_mutex); - memcpy(ctx->provider, default_provider, sizeof(sqlcipher_provider)); - sqlite3_mutex_leave(sqlcipher_provider_mutex); - - if((rc = ctx->provider->ctx_init(&ctx->provider_ctx)) != SQLITE_OK) return rc; - ctx->key = (unsigned char *) sqlcipher_malloc(CIPHER_MAX_KEY_SZ); - ctx->hmac_key = (unsigned char *) sqlcipher_malloc(CIPHER_MAX_KEY_SZ); - if(ctx->key == NULL) return SQLITE_NOMEM; - if(ctx->hmac_key == NULL) return SQLITE_NOMEM; + CODEC_TRACE("sqlcipher_cipher_ctx_init: allocating hmac_key\n"); + c_ctx->hmac_key = (unsigned char *) sqlcipher_malloc(ctx->key_sz); - /* setup default flags */ - ctx->flags = default_flags; + if(c_ctx->key == NULL) return SQLITE_NOMEM; + if(c_ctx->hmac_key == NULL) return SQLITE_NOMEM; return SQLITE_OK; } @@ -18998,16 +22881,35 @@ static int sqlcipher_cipher_ctx_init(cipher_ctx **iCtx) { /** * Free and wipe memory associated with a cipher_ctx */ -static void sqlcipher_cipher_ctx_free(cipher_ctx **iCtx) { - cipher_ctx *ctx = *iCtx; - CODEC_TRACE(("cipher_ctx_free: entered iCtx=%p\n", iCtx)); - ctx->provider->ctx_free(&ctx->provider_ctx); - sqlcipher_free(ctx->provider, sizeof(sqlcipher_provider)); - sqlcipher_free(ctx->key, ctx->key_sz); - sqlcipher_free(ctx->hmac_key, ctx->key_sz); - sqlcipher_free(ctx->pass, ctx->pass_sz); - sqlcipher_free(ctx->keyspec, ctx->keyspec_sz); - sqlcipher_free(ctx, sizeof(cipher_ctx)); +static void sqlcipher_cipher_ctx_free(codec_ctx* ctx, cipher_ctx **iCtx) { + cipher_ctx *c_ctx = *iCtx; + CODEC_TRACE("cipher_ctx_free: entered iCtx=%p\n", iCtx); + sqlcipher_free(c_ctx->key, ctx->key_sz); + sqlcipher_free(c_ctx->hmac_key, ctx->key_sz); + sqlcipher_free(c_ctx->pass, c_ctx->pass_sz); + sqlcipher_free(c_ctx->keyspec, ctx->keyspec_sz); + sqlcipher_free(c_ctx, sizeof(cipher_ctx)); +} + +static int sqlcipher_codec_ctx_reserve_setup(codec_ctx *ctx) { + int base_reserve = ctx->iv_sz; /* base reserve size will be IV only */ + int reserve = base_reserve; + + ctx->hmac_sz = ctx->provider->get_hmac_sz(ctx->provider_ctx, ctx->hmac_algorithm); + + if(sqlcipher_codec_ctx_get_use_hmac(ctx)) + reserve += ctx->hmac_sz; /* if reserve will include hmac, update that size */ + + /* calculate the amount of reserve needed in even increments of the cipher block size */ + reserve = ((reserve % ctx->block_sz) == 0) ? reserve : + ((reserve / ctx->block_sz) + 1) * ctx->block_sz; + + CODEC_TRACE("sqlcipher_codec_ctx_reserve_setup: base_reserve=%d block_sz=%d md_size=%d reserve=%d\n", + base_reserve, ctx->block_sz, ctx->hmac_sz, reserve); + + ctx->reserve_sz = reserve; + + return SQLITE_OK; } /** @@ -19018,14 +22920,7 @@ static void sqlcipher_cipher_ctx_free(cipher_ctx **iCtx) { */ static int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) { int are_equal = ( - c1->iv_sz == c2->iv_sz - && c1->kdf_iter == c2->kdf_iter - && c1->fast_kdf_iter == c2->fast_kdf_iter - && c1->key_sz == c2->key_sz - && c1->pass_sz == c2->pass_sz - && c1->flags == c2->flags - && c1->hmac_sz == c2->hmac_sz - && c1->provider->ctx_cmp(c1->provider_ctx, c2->provider_ctx) + c1->pass_sz == c2->pass_sz && ( c1->pass == c2->pass || !sqlcipher_memcmp((const unsigned char*)c1->pass, @@ -19033,39 +22928,25 @@ static int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) { c1->pass_sz) )); - CODEC_TRACE(("sqlcipher_cipher_ctx_cmp: entered \ + CODEC_TRACE("sqlcipher_cipher_ctx_cmp: entered \ c1=%p c2=%p \ - c1->iv_sz=%d c2->iv_sz=%d \ - c1->kdf_iter=%d c2->kdf_iter=%d \ - c1->fast_kdf_iter=%d c2->fast_kdf_iter=%d \ - c1->key_sz=%d c2->key_sz=%d \ c1->pass_sz=%d c2->pass_sz=%d \ - c1->flags=%d c2->flags=%d \ - c1->hmac_sz=%d c2->hmac_sz=%d \ - c1->provider_ctx=%p c2->provider_ctx=%p \ c1->pass=%p c2->pass=%p \ c1->pass=%s c2->pass=%s \ - provider->ctx_cmp=%d \ sqlcipher_memcmp=%d \ are_equal=%d \ \n", c1, c2, - c1->iv_sz, c2->iv_sz, - c1->kdf_iter, c2->kdf_iter, - c1->fast_kdf_iter, c2->fast_kdf_iter, - c1->key_sz, c2->key_sz, c1->pass_sz, c2->pass_sz, - c1->flags, c2->flags, - c1->hmac_sz, c2->hmac_sz, - c1->provider_ctx, c2->provider_ctx, c1->pass, c2->pass, c1->pass, c2->pass, - c1->provider->ctx_cmp(c1->provider_ctx, c2->provider_ctx), - sqlcipher_memcmp((const unsigned char*)c1->pass, - (const unsigned char*)c2->pass, - c1->pass_sz), + (c1->pass == NULL || c2->pass == NULL) + ? -1 : sqlcipher_memcmp( + (const unsigned char*)c1->pass, + (const unsigned char*)c2->pass, + c1->pass_sz), are_equal - )); + ); return !are_equal; /* return 0 if they are the same, 1 otherwise */ } @@ -19078,38 +22959,30 @@ static int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) { * returns SQLITE_OK if initialization was successful * returns SQLITE_NOMEM if an error occured allocating memory */ -static int sqlcipher_cipher_ctx_copy(cipher_ctx *target, cipher_ctx *source) { +static int sqlcipher_cipher_ctx_copy(codec_ctx *ctx, cipher_ctx *target, cipher_ctx *source) { void *key = target->key; void *hmac_key = target->hmac_key; - void *provider = target->provider; - void *provider_ctx = target->provider_ctx; - CODEC_TRACE(("sqlcipher_cipher_ctx_copy: entered target=%p, source=%p\n", target, source)); + CODEC_TRACE("sqlcipher_cipher_ctx_copy: entered target=%p, source=%p\n", target, source); sqlcipher_free(target->pass, target->pass_sz); - sqlcipher_free(target->keyspec, target->keyspec_sz); + sqlcipher_free(target->keyspec, ctx->keyspec_sz); memcpy(target, source, sizeof(cipher_ctx)); - target->key = key; //restore pointer to previously allocated key data - memcpy(target->key, source->key, CIPHER_MAX_KEY_SZ); - - target->hmac_key = hmac_key; //restore pointer to previously allocated hmac key data - memcpy(target->hmac_key, source->hmac_key, CIPHER_MAX_KEY_SZ); - - target->provider = provider; // restore pointer to previouly allocated provider; - memcpy(target->provider, source->provider, sizeof(sqlcipher_provider)); + target->key = key; /* restore pointer to previously allocated key data */ + memcpy(target->key, source->key, ctx->key_sz); - target->provider_ctx = provider_ctx; // restore pointer to previouly allocated provider context; - target->provider->ctx_copy(target->provider_ctx, source->provider_ctx); + target->hmac_key = hmac_key; /* restore pointer to previously allocated hmac key data */ + memcpy(target->hmac_key, source->hmac_key, ctx->key_sz); if(source->pass && source->pass_sz) { target->pass = sqlcipher_malloc(source->pass_sz); if(target->pass == NULL) return SQLITE_NOMEM; memcpy(target->pass, source->pass, source->pass_sz); } - if(source->keyspec && source->keyspec_sz) { - target->keyspec = sqlcipher_malloc(source->keyspec_sz); + if(source->keyspec) { + target->keyspec = sqlcipher_malloc(ctx->keyspec_sz); if(target->keyspec == NULL) return SQLITE_NOMEM; - memcpy(target->keyspec, source->keyspec, source->keyspec_sz); + memcpy(target->keyspec, source->keyspec, ctx->keyspec_sz); } return SQLITE_OK; } @@ -19120,33 +22993,28 @@ static int sqlcipher_cipher_ctx_copy(cipher_ctx *target, cipher_ctx *source) { * returns SQLITE_OK if assignment was successfull * returns SQLITE_NOMEM if an error occured allocating memory */ -static int sqlcipher_cipher_ctx_set_keyspec(cipher_ctx *ctx, const unsigned char *key, int key_sz, const unsigned char *salt, int salt_sz) { - - /* free, zero existing pointers and size */ - sqlcipher_free(ctx->keyspec, ctx->keyspec_sz); - ctx->keyspec = NULL; - ctx->keyspec_sz = 0; +static int sqlcipher_cipher_ctx_set_keyspec(codec_ctx *ctx, cipher_ctx *c_ctx, const unsigned char *key) { + /* free, zero existing pointers and size */ + sqlcipher_free(c_ctx->keyspec, ctx->keyspec_sz); + c_ctx->keyspec = NULL; - /* establic a hex-formated key specification, containing the raw encryption key and - the salt used to generate it */ - ctx->keyspec_sz = ((key_sz + salt_sz) * 2) + 3; - ctx->keyspec = sqlcipher_malloc(ctx->keyspec_sz); - if(ctx->keyspec == NULL) return SQLITE_NOMEM; + c_ctx->keyspec = sqlcipher_malloc(ctx->keyspec_sz); + if(c_ctx->keyspec == NULL) return SQLITE_NOMEM; - ctx->keyspec[0] = 'x'; - ctx->keyspec[1] = '\''; - cipher_bin2hex(key, key_sz, ctx->keyspec + 2); - cipher_bin2hex(salt, salt_sz, ctx->keyspec + (key_sz * 2) + 2); - ctx->keyspec[ctx->keyspec_sz - 1] = '\''; + c_ctx->keyspec[0] = 'x'; + c_ctx->keyspec[1] = '\''; + cipher_bin2hex(key, ctx->key_sz, c_ctx->keyspec + 2); + cipher_bin2hex(ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->keyspec + (ctx->key_sz * 2) + 2); + c_ctx->keyspec[ctx->keyspec_sz - 1] = '\''; return SQLITE_OK; } int sqlcipher_codec_get_store_pass(codec_ctx *ctx) { - return ctx->read_ctx->store_pass; + return ctx->store_pass; } void sqlcipher_codec_set_store_pass(codec_ctx *ctx, int value) { - ctx->read_ctx->store_pass = value; + ctx->store_pass = value; } void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey) { @@ -19154,6 +23022,11 @@ void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey) { *nKey = ctx->read_ctx->pass_sz; } +static void sqlcipher_set_derive_key(codec_ctx *ctx, int derive) { + if(ctx->read_ctx != NULL) ctx->read_ctx->derive_key = 1; + if(ctx->write_ctx != NULL) ctx->write_ctx->derive_key = 1; +} + /** * Set the passphrase for the cipher_ctx * @@ -19161,7 +23034,6 @@ void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey) { * returns SQLITE_NOMEM if an error occured allocating memory */ static int sqlcipher_cipher_ctx_set_pass(cipher_ctx *ctx, const void *zKey, int nKey) { - /* free, zero existing pointers and size */ sqlcipher_free(ctx->pass, ctx->pass_sz); ctx->pass = NULL; @@ -19184,37 +23056,14 @@ int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int c_ctx->derive_key = 1; if(for_ctx == 2) - if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) + if((rc = sqlcipher_cipher_ctx_copy(ctx, for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) return rc; return SQLITE_OK; } -int sqlcipher_codec_ctx_set_cipher(codec_ctx *ctx, const char *cipher_name, int for_ctx) { - cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; - int rc; - - rc = c_ctx->provider->set_cipher(c_ctx->provider_ctx, cipher_name); - if(rc != SQLITE_OK){ - sqlcipher_codec_ctx_set_error(ctx, rc); - return rc; - } - c_ctx->key_sz = c_ctx->provider->get_key_sz(c_ctx->provider_ctx); - c_ctx->iv_sz = c_ctx->provider->get_iv_sz(c_ctx->provider_ctx); - c_ctx->block_sz = c_ctx->provider->get_block_sz(c_ctx->provider_ctx); - c_ctx->hmac_sz = c_ctx->provider->get_hmac_sz(c_ctx->provider_ctx); - c_ctx->derive_key = 1; - - if(for_ctx == 2) - if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) - return rc; - - return SQLITE_OK; -} - -const char* sqlcipher_codec_ctx_get_cipher(codec_ctx *ctx, int for_ctx) { - cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; - return c_ctx->provider->get_cipher(c_ctx->provider_ctx); +const char* sqlcipher_codec_ctx_get_cipher(codec_ctx *ctx) { + return ctx->provider->get_cipher(ctx->provider_ctx); } /* set the global default KDF iteration */ @@ -19226,42 +23075,24 @@ int sqlcipher_get_default_kdf_iter() { return default_kdf_iter; } -int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter, int for_ctx) { - cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; - int rc; - - c_ctx->kdf_iter = kdf_iter; - c_ctx->derive_key = 1; - - if(for_ctx == 2) - if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) - return rc; - +int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter) { + ctx->kdf_iter = kdf_iter; + sqlcipher_set_derive_key(ctx, 1); return SQLITE_OK; } -int sqlcipher_codec_ctx_get_kdf_iter(codec_ctx *ctx, int for_ctx) { - cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; - return c_ctx->kdf_iter; +int sqlcipher_codec_ctx_get_kdf_iter(codec_ctx *ctx) { + return ctx->kdf_iter; } -int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter, int for_ctx) { - cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; - int rc; - - c_ctx->fast_kdf_iter = fast_kdf_iter; - c_ctx->derive_key = 1; - - if(for_ctx == 2) - if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) - return rc; - +int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter) { + ctx->fast_kdf_iter = fast_kdf_iter; + sqlcipher_set_derive_key(ctx, 1); return SQLITE_OK; } -int sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx *ctx, int for_ctx) { - cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; - return c_ctx->fast_kdf_iter; +int sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx *ctx) { + return ctx->fast_kdf_iter; } /* set the global default flag for HMAC */ @@ -19284,76 +23115,156 @@ unsigned char sqlcipher_get_hmac_salt_mask() { /* set the codec flag for whether this individual database should be using hmac */ int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use) { - int reserve = CIPHER_MAX_IV_SZ; /* base reserve size will be IV only */ - - if(use) reserve += ctx->read_ctx->hmac_sz; /* if reserve will include hmac, update that size */ - - /* calculate the amount of reserve needed in even increments of the cipher block size */ - - reserve = ((reserve % ctx->read_ctx->block_sz) == 0) ? reserve : - ((reserve / ctx->read_ctx->block_sz) + 1) * ctx->read_ctx->block_sz; - - CODEC_TRACE(("sqlcipher_codec_ctx_set_use_hmac: use=%d block_sz=%d md_size=%d reserve=%d\n", - use, ctx->read_ctx->block_sz, ctx->read_ctx->hmac_sz, reserve)); - - if(use) { sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_HMAC); } else { sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_HMAC); } - - ctx->write_ctx->reserve_sz = ctx->read_ctx->reserve_sz = reserve; + return sqlcipher_codec_ctx_reserve_setup(ctx); +} + +int sqlcipher_codec_ctx_get_use_hmac(codec_ctx *ctx) { + return (ctx->flags & CIPHER_FLAG_HMAC) != 0; +} + +/* the length of plaintext header size must be: + * 1. greater than or equal to zero + * 2. a multiple of the cipher block size + * 3. less than the usable size of the first database page + */ +int sqlcipher_set_default_plaintext_header_size(int size) { + default_plaintext_header_sz = size; + return SQLITE_OK; +} + +int sqlcipher_codec_ctx_set_plaintext_header_size(codec_ctx *ctx, int size) { + if(size >= 0 && (size % ctx->block_sz) == 0 && size < (ctx->page_sz - ctx->reserve_sz)) { + ctx->plaintext_header_sz = size; + return SQLITE_OK; + } + return SQLITE_ERROR; +} + +int sqlcipher_get_default_plaintext_header_size() { + return default_plaintext_header_sz; +} + +int sqlcipher_codec_ctx_get_plaintext_header_size(codec_ctx *ctx) { + return ctx->plaintext_header_sz; +} + +/* manipulate HMAC algorithm */ +int sqlcipher_set_default_hmac_algorithm(int algorithm) { + default_hmac_algorithm = algorithm; + return SQLITE_OK; +} + +int sqlcipher_codec_ctx_set_hmac_algorithm(codec_ctx *ctx, int algorithm) { + ctx->hmac_algorithm = algorithm; + return sqlcipher_codec_ctx_reserve_setup(ctx); +} + +int sqlcipher_get_default_hmac_algorithm() { + return default_hmac_algorithm; +} + +int sqlcipher_codec_ctx_get_hmac_algorithm(codec_ctx *ctx) { + return ctx->hmac_algorithm; +} + +/* manipulate KDF algorithm */ +int sqlcipher_set_default_kdf_algorithm(int algorithm) { + default_kdf_algorithm = algorithm; return SQLITE_OK; } -int sqlcipher_codec_ctx_get_use_hmac(codec_ctx *ctx, int for_ctx) { - cipher_ctx * c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; - return (c_ctx->flags & CIPHER_FLAG_HMAC) != 0; +int sqlcipher_codec_ctx_set_kdf_algorithm(codec_ctx *ctx, int algorithm) { + ctx->kdf_algorithm = algorithm; + return SQLITE_OK; +} + +int sqlcipher_get_default_kdf_algorithm() { + return default_kdf_algorithm; +} + +int sqlcipher_codec_ctx_get_kdf_algorithm(codec_ctx *ctx) { + return ctx->kdf_algorithm; } int sqlcipher_codec_ctx_set_flag(codec_ctx *ctx, unsigned int flag) { - ctx->write_ctx->flags |= flag; - ctx->read_ctx->flags |= flag; + ctx->flags |= flag; return SQLITE_OK; } int sqlcipher_codec_ctx_unset_flag(codec_ctx *ctx, unsigned int flag) { - ctx->write_ctx->flags &= ~flag; - ctx->read_ctx->flags &= ~flag; + ctx->flags &= ~flag; return SQLITE_OK; } -int sqlcipher_codec_ctx_get_flag(codec_ctx *ctx, unsigned int flag, int for_ctx) { - cipher_ctx * c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx; - return (c_ctx->flags & flag) != 0; +int sqlcipher_codec_ctx_get_flag(codec_ctx *ctx, unsigned int flag) { + return (ctx->flags & flag) != 0; } void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) { - CODEC_TRACE(("sqlcipher_codec_ctx_set_error: ctx=%p, error=%d\n", ctx, error)); - sqlite3pager_sqlite3PagerSetError(ctx->pBt->pBt->pPager, error); + CODEC_TRACE("sqlcipher_codec_ctx_set_error: ctx=%p, error=%d\n", ctx, error); + tdsqlite3pager_error(ctx->pBt->pBt->pPager, error); ctx->pBt->pBt->db->errCode = error; } int sqlcipher_codec_ctx_get_reservesize(codec_ctx *ctx) { - return ctx->read_ctx->reserve_sz; + return ctx->reserve_sz; } void* sqlcipher_codec_ctx_get_data(codec_ctx *ctx) { return ctx->buffer; } -void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx) { - return ctx->kdf_salt; +static int sqlcipher_codec_ctx_init_kdf_salt(codec_ctx *ctx) { + tdsqlite3_file *fd = tdsqlite3PagerFile(ctx->pBt->pBt->pPager); + + if(!ctx->need_kdf_salt) { + return SQLITE_OK; /* don't reload salt when not needed */ + } + + /* read salt from header, if present, otherwise generate a new random salt */ + CODEC_TRACE("sqlcipher_codec_ctx_init_kdf_salt: obtaining salt\n"); + if(fd == NULL || fd->pMethods == 0 || tdsqlite3OsRead(fd, ctx->kdf_salt, ctx->kdf_salt_sz, 0) != SQLITE_OK) { + CODEC_TRACE("sqlcipher_codec_ctx_init_kdf_salt: unable to read salt from file header, generating random\n"); + if(ctx->provider->random(ctx->provider_ctx, ctx->kdf_salt, ctx->kdf_salt_sz) != SQLITE_OK) return SQLITE_ERROR; + } + ctx->need_kdf_salt = 0; + return SQLITE_OK; +} + +int sqlcipher_codec_ctx_set_kdf_salt(codec_ctx *ctx, unsigned char *salt, int size) { + if(size >= ctx->kdf_salt_sz) { + memcpy(ctx->kdf_salt, salt, ctx->kdf_salt_sz); + ctx->need_kdf_salt = 0; + return SQLITE_OK; + } + return SQLITE_ERROR; +} + +int sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx, void** salt) { + int rc = SQLITE_OK; + if(ctx->need_kdf_salt) { + rc = sqlcipher_codec_ctx_init_kdf_salt(ctx); + } + *salt = ctx->kdf_salt; + return rc; } void sqlcipher_codec_get_keyspec(codec_ctx *ctx, void **zKey, int *nKey) { *zKey = ctx->read_ctx->keyspec; - *nKey = ctx->read_ctx->keyspec_sz; + *nKey = ctx->keyspec_sz; } int sqlcipher_codec_ctx_set_pagesize(codec_ctx *ctx, int size) { + if(!((size != 0) && ((size & (size - 1)) == 0)) || size < 512 || size > 65536) { + CODEC_TRACE(("cipher_page_size not a power of 2 and between 512 and 65536 inclusive\n")); + return SQLITE_ERROR; + } /* attempt to free the existing page buffer */ sqlcipher_free(ctx->buffer,ctx->page_sz); ctx->page_sz = size; @@ -19379,9 +23290,22 @@ int sqlcipher_get_default_pagesize() { return default_page_size; } -int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlite3_file *fd, const void *zKey, int nKey) { +void sqlcipher_set_mem_security(int on) { + mem_security_on = on; + mem_security_activated = 0; +} + +int sqlcipher_get_mem_security() { + return mem_security_on && mem_security_activated; +} + + +int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, const void *zKey, int nKey) { int rc; codec_ctx *ctx; + + CODEC_TRACE("sqlcipher_codec_ctx_init: allocating context\n"); + *iCtx = sqlcipher_malloc(sizeof(codec_ctx)); ctx = *iCtx; @@ -19393,6 +23317,7 @@ int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlite3_f directly off the database file. This is the salt for the key derivation function. If we get a short read allocate a new random salt value */ + CODEC_TRACE("sqlcipher_codec_ctx_init: allocating kdf_salt\n"); ctx->kdf_salt_sz = FILE_HEADER_SZ; ctx->kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz); if(ctx->kdf_salt == NULL) return SQLITE_NOMEM; @@ -19400,34 +23325,88 @@ int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlite3_f /* allocate space for separate hmac salt data. We want the HMAC derivation salt to be different than the encryption key derivation salt */ + CODEC_TRACE("sqlcipher_codec_ctx_init: allocating hmac_kdf_salt\n"); ctx->hmac_kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz); if(ctx->hmac_kdf_salt == NULL) return SQLITE_NOMEM; + /* setup default flags */ + ctx->flags = default_flags; + + /* defer attempt to read KDF salt until first use */ + ctx->need_kdf_salt = 1; + + /* setup the crypto provider */ + CODEC_TRACE("sqlcipher_codec_ctx_init: allocating provider\n"); + ctx->provider = (sqlcipher_provider *) sqlcipher_malloc(sizeof(sqlcipher_provider)); + if(ctx->provider == NULL) return SQLITE_NOMEM; + + /* make a copy of the provider to be used for the duration of the context */ + CODEC_TRACE_MUTEX("sqlcipher_codec_ctx_init: entering SQLCIPHER_MUTEX_PROVIDER\n"); + tdsqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); + CODEC_TRACE_MUTEX("sqlcipher_codec_ctx_init: entered SQLCIPHER_MUTEX_PROVIDER\n"); + + memcpy(ctx->provider, default_provider, sizeof(sqlcipher_provider)); + + CODEC_TRACE_MUTEX("sqlcipher_codec_ctx_init: leaving SQLCIPHER_MUTEX_PROVIDER\n"); + tdsqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER)); + CODEC_TRACE_MUTEX("sqlcipher_codec_ctx_init: left SQLCIPHER_MUTEX_PROVIDER\n"); + + CODEC_TRACE("sqlcipher_codec_ctx_init: calling provider ctx_init\n"); + if((rc = ctx->provider->ctx_init(&ctx->provider_ctx)) != SQLITE_OK) return rc; + + ctx->key_sz = ctx->provider->get_key_sz(ctx->provider_ctx); + ctx->iv_sz = ctx->provider->get_iv_sz(ctx->provider_ctx); + ctx->block_sz = ctx->provider->get_block_sz(ctx->provider_ctx); + + /* establic the size for a hex-formated key specification, containing the + raw encryption key and the salt used to generate it format. will be x'hexkey...hexsalt' + so oversize by 3 bytes */ + ctx->keyspec_sz = ((ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3; /* Always overwrite page size and set to the default because the first page of the database in encrypted and thus sqlite can't effectively determine the pagesize. this causes an issue in cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman */ + CODEC_TRACE("sqlcipher_codec_ctx_init: calling sqlcipher_codec_ctx_set_pagesize with %d\n", default_page_size); if((rc = sqlcipher_codec_ctx_set_pagesize(ctx, default_page_size)) != SQLITE_OK) return rc; - if((rc = sqlcipher_cipher_ctx_init(&ctx->read_ctx)) != SQLITE_OK) return rc; - if((rc = sqlcipher_cipher_ctx_init(&ctx->write_ctx)) != SQLITE_OK) return rc; + /* establish settings for the KDF iterations and fast (HMAC) KDF iterations */ + CODEC_TRACE("sqlcipher_codec_ctx_init: setting default_kdf_iter\n"); + if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, default_kdf_iter)) != SQLITE_OK) return rc; - if(fd == NULL || sqlite3OsRead(fd, ctx->kdf_salt, FILE_HEADER_SZ, 0) != SQLITE_OK) { - ctx->need_kdf_salt = 1; - } + CODEC_TRACE("sqlcipher_codec_ctx_init: setting fast_kdf_iter\n"); + if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER)) != SQLITE_OK) return rc; - if((rc = sqlcipher_codec_ctx_set_cipher(ctx, CIPHER, 0)) != SQLITE_OK) return rc; - if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, default_kdf_iter, 0)) != SQLITE_OK) return rc; - if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER, 0)) != SQLITE_OK) return rc; - if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLITE_OK) return rc; + /* set the default HMAC and KDF algorithms which will determine the reserve size */ + CODEC_TRACE("sqlcipher_codec_ctx_init: calling sqlcipher_codec_ctx_set_hmac_algorithm with %d\n", default_hmac_algorithm); + if((rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, default_hmac_algorithm)) != SQLITE_OK) return rc; /* Note that use_hmac is a special case that requires recalculation of page size so we call set_use_hmac to perform setup */ + CODEC_TRACE("sqlcipher_codec_ctx_init: setting use_hmac\n"); if((rc = sqlcipher_codec_ctx_set_use_hmac(ctx, default_flags & CIPHER_FLAG_HMAC)) != SQLITE_OK) return rc; - if((rc = sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx)) != SQLITE_OK) return rc; + CODEC_TRACE("sqlcipher_codec_ctx_init: calling sqlcipher_codec_ctx_set_kdf_algorithm with %d\n", default_kdf_algorithm); + if((rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, default_kdf_algorithm)) != SQLITE_OK) return rc; + + /* setup the default plaintext header size */ + CODEC_TRACE("sqlcipher_codec_ctx_init: calling sqlcipher_codec_ctx_set_plaintext_header_size with %d\n", default_plaintext_header_sz); + if((rc = sqlcipher_codec_ctx_set_plaintext_header_size(ctx, default_plaintext_header_sz)) != SQLITE_OK) return rc; + + /* initialize the read and write sub-contexts. this must happen after key_sz is established */ + CODEC_TRACE("sqlcipher_codec_ctx_init: initializing read_ctx\n"); + if((rc = sqlcipher_cipher_ctx_init(ctx, &ctx->read_ctx)) != SQLITE_OK) return rc; + + CODEC_TRACE("sqlcipher_codec_ctx_init: initializing write_ctx\n"); + if((rc = sqlcipher_cipher_ctx_init(ctx, &ctx->write_ctx)) != SQLITE_OK) return rc; + + /* set the key material on one of the sub cipher contexts and sync them up */ + CODEC_TRACE("sqlcipher_codec_ctx_init: setting pass key\n"); + if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLITE_OK) return rc; + + CODEC_TRACE("sqlcipher_codec_ctx_init: copying write_ctx to read_ctx\n"); + if((rc = sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx)) != SQLITE_OK) return rc; return SQLITE_OK; } @@ -19438,12 +23417,16 @@ int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlite3_f */ void sqlcipher_codec_ctx_free(codec_ctx **iCtx) { codec_ctx *ctx = *iCtx; - CODEC_TRACE(("codec_ctx_free: entered iCtx=%p\n", iCtx)); + CODEC_TRACE("codec_ctx_free: entered iCtx=%p\n", iCtx); sqlcipher_free(ctx->kdf_salt, ctx->kdf_salt_sz); sqlcipher_free(ctx->hmac_kdf_salt, ctx->kdf_salt_sz); sqlcipher_free(ctx->buffer, 0); - sqlcipher_cipher_ctx_free(&ctx->read_ctx); - sqlcipher_cipher_ctx_free(&ctx->write_ctx); + + ctx->provider->ctx_free(&ctx->provider_ctx); + sqlcipher_free(ctx->provider, sizeof(sqlcipher_provider)); + + sqlcipher_cipher_ctx_free(ctx, &ctx->read_ctx); + sqlcipher_cipher_ctx_free(ctx, &ctx->write_ctx); sqlcipher_free(ctx, sizeof(codec_ctx)); } @@ -19455,7 +23438,7 @@ static void sqlcipher_put4byte_le(unsigned char *p, u32 v) { p[3] = (u8)(v>>24); } -static int sqlcipher_page_hmac(cipher_ctx *ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) { +static int sqlcipher_page_hmac(codec_ctx *ctx, cipher_ctx *c_ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) { unsigned char pgno_raw[sizeof(pgno)]; /* we may convert page number to consistent representation before calculating MAC for compatibility across big-endian and little-endian platforms. @@ -19468,7 +23451,7 @@ static int sqlcipher_page_hmac(cipher_ctx *ctx, Pgno pgno, unsigned char *in, in if(ctx->flags & CIPHER_FLAG_LE_PGNO) { /* compute hmac using little endian pgno*/ sqlcipher_put4byte_le(pgno_raw, pgno); } else if(ctx->flags & CIPHER_FLAG_BE_PGNO) { /* compute hmac using big endian pgno */ - sqlite3Put4byte(pgno_raw, pgno); /* sqlite3Put4byte converts 32bit uint to big endian */ + tdsqlite3Put4byte(pgno_raw, pgno); /* tdsqlite3Put4byte converts 32bit uint to big endian */ } else { /* use native byte ordering */ memcpy(pgno_raw, &pgno, sizeof(pgno)); } @@ -19476,12 +23459,11 @@ static int sqlcipher_page_hmac(cipher_ctx *ctx, Pgno pgno, unsigned char *in, in /* include the encrypted page data, initialization vector, and page number in HMAC. This will prevent both tampering with the ciphertext, manipulation of the IV, or resequencing otherwise valid pages out of order in a database */ - ctx->provider->hmac( - ctx->provider_ctx, ctx->hmac_key, + return ctx->provider->hmac( + ctx->provider_ctx, ctx->hmac_algorithm, c_ctx->hmac_key, ctx->key_sz, in, in_sz, (unsigned char*) &pgno_raw, sizeof(pgno), out); - return SQLITE_OK; } /* @@ -19498,70 +23480,76 @@ int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int int size; /* calculate some required positions into various buffers */ - size = page_sz - c_ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */ + size = page_sz - ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */ iv_out = out + size; iv_in = in + size; /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain random bytes. note, these pointers are only valid when using hmac */ - hmac_in = in + size + c_ctx->iv_sz; - hmac_out = out + size + c_ctx->iv_sz; + hmac_in = in + size + ctx->iv_sz; + hmac_out = out + size + ctx->iv_sz; out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */ - CODEC_TRACE(("codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size)); + CODEC_TRACE("codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size); CODEC_HEXDUMP("codec_cipher: input page data", in, page_sz); /* the key size should never be zero. If it is, error out. */ - if(c_ctx->key_sz == 0) { - CODEC_TRACE(("codec_cipher: error possible context corruption, key_sz is zero for pgno=%d\n", pgno)); - sqlcipher_memset(out, 0, page_sz); - return SQLITE_ERROR; + if(ctx->key_sz == 0) { + CODEC_TRACE("codec_cipher: error possible context corruption, key_sz is zero for pgno=%d\n", pgno); + goto error; } if(mode == CIPHER_ENCRYPT) { /* start at front of the reserve block, write random data to the end */ - if(c_ctx->provider->random(c_ctx->provider_ctx, iv_out, c_ctx->reserve_sz) != SQLITE_OK) return SQLITE_ERROR; + if(ctx->provider->random(ctx->provider_ctx, iv_out, ctx->reserve_sz) != SQLITE_OK) goto error; } else { /* CIPHER_DECRYPT */ - memcpy(iv_out, iv_in, c_ctx->iv_sz); /* copy the iv from the input to output buffer */ + memcpy(iv_out, iv_in, ctx->iv_sz); /* copy the iv from the input to output buffer */ } - if((c_ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_DECRYPT) && !ctx->skip_read_hmac) { - if(sqlcipher_page_hmac(c_ctx, pgno, in, size + c_ctx->iv_sz, hmac_out) != SQLITE_OK) { - sqlcipher_memset(out, 0, page_sz); - CODEC_TRACE(("codec_cipher: hmac operations failed for pgno=%d\n", pgno)); - return SQLITE_ERROR; + if((ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_DECRYPT) && !ctx->skip_read_hmac) { + if(sqlcipher_page_hmac(ctx, c_ctx, pgno, in, size + ctx->iv_sz, hmac_out) != SQLITE_OK) { + CODEC_TRACE("codec_cipher: hmac operation on decrypt failed for pgno=%d\n", pgno); + goto error; } - CODEC_TRACE(("codec_cipher: comparing hmac on in=%p out=%p hmac_sz=%d\n", hmac_in, hmac_out, c_ctx->hmac_sz)); - if(sqlcipher_memcmp(hmac_in, hmac_out, c_ctx->hmac_sz) != 0) { /* the hmac check failed */ + CODEC_TRACE("codec_cipher: comparing hmac on in=%p out=%p hmac_sz=%d\n", hmac_in, hmac_out, ctx->hmac_sz); + if(sqlcipher_memcmp(hmac_in, hmac_out, ctx->hmac_sz) != 0) { /* the hmac check failed */ if(sqlcipher_ismemset(in, 0, page_sz) == 0) { /* first check if the entire contents of the page is zeros. If so, this page resulted from a short read (i.e. sqlite attempted to pull a page after the end of the file. these short read failures must be ignored for autovaccum mode to work so wipe the output buffer and return SQLITE_OK to skip the decryption step. */ - CODEC_TRACE(("codec_cipher: zeroed page (short read) for pgno %d, encryption but returning SQLITE_OK\n", pgno)); + CODEC_TRACE("codec_cipher: zeroed page (short read) for pgno %d, encryption but returning SQLITE_OK\n", pgno); sqlcipher_memset(out, 0, page_sz); - return SQLITE_OK; + return SQLITE_OK; } else { - /* if the page memory is not all zeros, it means the there was data and a hmac on the page. + /* if the page memory is not all zeros, it means the there was data and a hmac on the page. since the check failed, the page was either tampered with or corrupted. wipe the output buffer, and return SQLITE_ERROR to the caller */ - CODEC_TRACE(("codec_cipher: hmac check failed for pgno=%d returning SQLITE_ERROR\n", pgno)); - sqlcipher_memset(out, 0, page_sz); - return SQLITE_ERROR; + CODEC_TRACE("codec_cipher: hmac check failed for pgno=%d returning SQLITE_ERROR\n", pgno); + goto error; } } } - c_ctx->provider->cipher(c_ctx->provider_ctx, mode, c_ctx->key, c_ctx->key_sz, iv_out, in, size, out); + if(ctx->provider->cipher(ctx->provider_ctx, mode, c_ctx->key, ctx->key_sz, iv_out, in, size, out) != SQLITE_OK) { + CODEC_TRACE("codec_cipher: cipher operation mode=%d failed for pgno=%d returning SQLITE_ERROR\n", mode, pgno); + goto error; + }; - if((c_ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_ENCRYPT)) { - sqlcipher_page_hmac(c_ctx, pgno, out_start, size + c_ctx->iv_sz, hmac_out); + if((ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_ENCRYPT)) { + if(sqlcipher_page_hmac(ctx, c_ctx, pgno, out_start, size + ctx->iv_sz, hmac_out) != SQLITE_OK) { + CODEC_TRACE("codec_cipher: hmac operation on encrypt failed for pgno=%d\n", pgno); + goto error; + }; } CODEC_HEXDUMP("codec_cipher: output page data", out_start, page_sz); return SQLITE_OK; +error: + sqlcipher_memset(out, 0, page_sz); + return SQLITE_ERROR; } /** @@ -19581,43 +23569,44 @@ int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int */ static int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) { int rc; - CODEC_TRACE(("cipher_ctx_key_derive: entered c_ctx->pass=%s, c_ctx->pass_sz=%d \ - ctx->kdf_salt=%p ctx->kdf_salt_sz=%d c_ctx->kdf_iter=%d \ - ctx->hmac_kdf_salt=%p, c_ctx->fast_kdf_iter=%d c_ctx->key_sz=%d\n", - c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter, - ctx->hmac_kdf_salt, c_ctx->fast_kdf_iter, c_ctx->key_sz)); + CODEC_TRACE("cipher_ctx_key_derive: entered c_ctx->pass=%s, c_ctx->pass_sz=%d \ + ctx->kdf_salt=%p ctx->kdf_salt_sz=%d ctx->kdf_iter=%d \ + ctx->hmac_kdf_salt=%p, ctx->fast_kdf_iter=%d ctx->key_sz=%d\n", + c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, ctx->kdf_iter, + ctx->hmac_kdf_salt, ctx->fast_kdf_iter, ctx->key_sz); - if(c_ctx->pass && c_ctx->pass_sz) { // if pass is not null - + if(c_ctx->pass && c_ctx->pass_sz) { /* if key material is present on the context for derivation */ + + /* if necessary, initialize the salt from the header or random source */ if(ctx->need_kdf_salt) { - if(ctx->read_ctx->provider->random(ctx->read_ctx->provider_ctx, ctx->kdf_salt, FILE_HEADER_SZ) != SQLITE_OK) return SQLITE_ERROR; - ctx->need_kdf_salt = 0; + if((rc = sqlcipher_codec_ctx_init_kdf_salt(ctx)) != SQLITE_OK) return rc; } - if (c_ctx->pass_sz == ((c_ctx->key_sz * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, c_ctx->key_sz * 2)) { + + if (c_ctx->pass_sz == ((ctx->key_sz * 2) + 3) && tdsqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, ctx->key_sz * 2)) { int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */ const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */ - CODEC_TRACE(("cipher_ctx_key_derive: using raw key from hex\n")); + CODEC_TRACE("cipher_ctx_key_derive: using raw key from hex\n"); cipher_hex2bin(z, n, c_ctx->key); - } else if (c_ctx->pass_sz == (((c_ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, (c_ctx->key_sz + ctx->kdf_salt_sz) * 2)) { + } else if (c_ctx->pass_sz == (((ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3) && tdsqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, (ctx->key_sz + ctx->kdf_salt_sz) * 2)) { const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */ - CODEC_TRACE(("cipher_ctx_key_derive: using raw key from hex\n")); - cipher_hex2bin(z, (c_ctx->key_sz * 2), c_ctx->key); - cipher_hex2bin(z + (c_ctx->key_sz * 2), (ctx->kdf_salt_sz * 2), ctx->kdf_salt); + CODEC_TRACE("cipher_ctx_key_derive: using raw key from hex\n"); + cipher_hex2bin(z, (ctx->key_sz * 2), c_ctx->key); + cipher_hex2bin(z + (ctx->key_sz * 2), (ctx->kdf_salt_sz * 2), ctx->kdf_salt); } else { - CODEC_TRACE(("cipher_ctx_key_derive: deriving key using full PBKDF2 with %d iterations\n", c_ctx->kdf_iter)); - c_ctx->provider->kdf(c_ctx->provider_ctx, c_ctx->pass, c_ctx->pass_sz, - ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter, - c_ctx->key_sz, c_ctx->key); + CODEC_TRACE("cipher_ctx_key_derive: deriving key using full PBKDF2 with %d iterations\n", ctx->kdf_iter); + if(ctx->provider->kdf(ctx->provider_ctx, ctx->kdf_algorithm, c_ctx->pass, c_ctx->pass_sz, + ctx->kdf_salt, ctx->kdf_salt_sz, ctx->kdf_iter, + ctx->key_sz, c_ctx->key) != SQLITE_OK) return SQLITE_ERROR; } /* set the context "keyspec" containing the hex-formatted key and salt to be used when attaching databases */ - if((rc = sqlcipher_cipher_ctx_set_keyspec(c_ctx, c_ctx->key, c_ctx->key_sz, ctx->kdf_salt, ctx->kdf_salt_sz)) != SQLITE_OK) return rc; + if((rc = sqlcipher_cipher_ctx_set_keyspec(ctx, c_ctx, c_ctx->key)) != SQLITE_OK) return rc; /* if this context is setup to use hmac checks, generate a seperate and different key for HMAC. In this case, we use the output of the previous KDF as the input to this KDF run. This ensures a distinct but predictable HMAC key. */ - if(c_ctx->flags & CIPHER_FLAG_HMAC) { + if(ctx->flags & CIPHER_FLAG_HMAC) { int i; /* start by copying the kdf key into the hmac salt slot @@ -19630,13 +23619,13 @@ static int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) { ctx->hmac_kdf_salt[i] ^= hmac_salt_mask; } - CODEC_TRACE(("cipher_ctx_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations\n", - c_ctx->fast_kdf_iter)); + CODEC_TRACE("cipher_ctx_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations\n", + ctx->fast_kdf_iter); - c_ctx->provider->kdf(c_ctx->provider_ctx, c_ctx->key, c_ctx->key_sz, - ctx->hmac_kdf_salt, ctx->kdf_salt_sz, c_ctx->fast_kdf_iter, - c_ctx->key_sz, c_ctx->hmac_key); + if(ctx->provider->kdf(ctx->provider_ctx, ctx->kdf_algorithm, c_ctx->key, ctx->key_sz, + ctx->hmac_kdf_salt, ctx->kdf_salt_sz, ctx->fast_kdf_iter, + ctx->key_sz, c_ctx->hmac_key) != SQLITE_OK) return SQLITE_ERROR; } c_ctx->derive_key = 0; @@ -19654,14 +23643,14 @@ int sqlcipher_codec_key_derive(codec_ctx *ctx) { if(ctx->write_ctx->derive_key) { if(sqlcipher_cipher_ctx_cmp(ctx->write_ctx, ctx->read_ctx) == 0) { /* the relevant parameters are the same, just copy read key */ - if(sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx) != SQLITE_OK) return SQLITE_ERROR; + if(sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx) != SQLITE_OK) return SQLITE_ERROR; } else { if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->write_ctx) != SQLITE_OK) return SQLITE_ERROR; } } /* TODO: wipe and free passphrase after key derivation */ - if(ctx->read_ctx->store_pass != 1) { + if(ctx->store_pass != 1) { sqlcipher_cipher_ctx_set_pass(ctx->read_ctx, NULL, 0); sqlcipher_cipher_ctx_set_pass(ctx->write_ctx, NULL, 0); } @@ -19671,553 +23660,396 @@ int sqlcipher_codec_key_derive(codec_ctx *ctx) { int sqlcipher_codec_key_copy(codec_ctx *ctx, int source) { if(source == CIPHER_READ_CTX) { - return sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx); + return sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx); } else { - return sqlcipher_cipher_ctx_copy(ctx->read_ctx, ctx->write_ctx); + return sqlcipher_cipher_ctx_copy(ctx, ctx->read_ctx, ctx->write_ctx); } } const char* sqlcipher_codec_get_cipher_provider(codec_ctx *ctx) { - return ctx->read_ctx->provider->get_provider_name(ctx->read_ctx); + return ctx->provider->get_provider_name(ctx->provider_ctx); } -static int sqlcipher_check_connection(const char *filename, char *key, int key_sz, char *sql, int *user_version) { +static int sqlcipher_check_connection(const char *filename, char *key, int key_sz, char *sql, int *user_version, char** journal_mode) { int rc; - sqlite3 *db = NULL; - sqlite3_stmt *statement = NULL; + tdsqlite3 *db = NULL; + tdsqlite3_stmt *statement = NULL; + char *query_journal_mode = "PRAGMA journal_mode;"; char *query_user_version = "PRAGMA user_version;"; - - rc = sqlite3_open(filename, &db); - if(rc != SQLITE_OK){ - goto cleanup; - } - rc = sqlite3_key(db, key, key_sz); - if(rc != SQLITE_OK){ - goto cleanup; - } - rc = sqlite3_exec(db, sql, NULL, NULL, NULL); - if(rc != SQLITE_OK){ - goto cleanup; - } - rc = sqlite3_prepare(db, query_user_version, -1, &statement, NULL); - if(rc != SQLITE_OK){ + + rc = tdsqlite3_open(filename, &db); + if(rc != SQLITE_OK) goto cleanup; + + rc = tdsqlite3_key(db, key, key_sz); + if(rc != SQLITE_OK) goto cleanup; + + rc = tdsqlite3_exec(db, sql, NULL, NULL, NULL); + if(rc != SQLITE_OK) goto cleanup; + + /* start by querying the user version. + this will fail if the key is incorrect */ + rc = tdsqlite3_prepare(db, query_user_version, -1, &statement, NULL); + if(rc != SQLITE_OK) goto cleanup; + + rc = tdsqlite3_step(statement); + if(rc == SQLITE_ROW) { + *user_version = tdsqlite3_column_int(statement, 0); + } else { goto cleanup; } - rc = sqlite3_step(statement); - if(rc == SQLITE_ROW){ - *user_version = sqlite3_column_int(statement, 0); - rc = SQLITE_OK; + tdsqlite3_finalize(statement); + + rc = tdsqlite3_prepare(db, query_journal_mode, -1, &statement, NULL); + if(rc != SQLITE_OK) goto cleanup; + + rc = tdsqlite3_step(statement); + if(rc == SQLITE_ROW) { + *journal_mode = tdsqlite3_mprintf("%s", tdsqlite3_column_text(statement, 0)); + } else { + goto cleanup; } + rc = SQLITE_OK; + /* cleanup will finalize open statement */ cleanup: - if(statement){ - sqlite3_finalize(statement); - } - if(db){ - sqlite3_close(db); - } + if(statement) tdsqlite3_finalize(statement); + if(db) tdsqlite3_close(db); return rc; } -int sqlcipher_codec_ctx_migrate(codec_ctx *ctx) { - u32 meta; +int sqlcipher_codec_ctx_integrity_check(codec_ctx *ctx, Parse *pParse, char *column) { + Pgno page = 1; int rc = 0; - int command_idx = 0; - int password_sz; - int saved_flags; - int saved_nChange; - int saved_nTotalChange; - int (*saved_xTrace)(u32,void*,void*,void*); /* Saved db->xTrace */ - Db *pDb = 0; - sqlite3 *db = ctx->pBt->db; - const char *db_filename = sqlite3_db_filename(db, "main"); - char *migrated_db_filename = sqlite3_mprintf("%s-migrated", db_filename); - char *pragma_hmac_off = "PRAGMA cipher_use_hmac = OFF;"; - char *pragma_4k_kdf_iter = "PRAGMA kdf_iter = 4000;"; - char *pragma_1x_and_4k; - char *set_user_version; - char *key; - int key_sz; - int user_version = 0; - int upgrade_1x_format = 0; - int upgrade_4k_format = 0; - static const unsigned char aCopy[] = { - BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */ - BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */ - BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */ - BTREE_USER_VERSION, 0, /* Preserve the user version */ - BTREE_APPLICATION_ID, 0, /* Preserve the application id */ - }; - + char *result; + unsigned char *hmac_out = NULL; + tdsqlite3_file *fd = tdsqlite3PagerFile(ctx->pBt->pBt->pPager); + i64 file_sz; + + Vdbe *v = tdsqlite3GetVdbe(pParse); + tdsqlite3VdbeSetNumCols(v, 1); + tdsqlite3VdbeSetColName(v, 0, COLNAME_NAME, column, SQLITE_STATIC); + + if(fd == NULL || fd->pMethods == 0) { + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "database file is undefined", P4_TRANSIENT); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + goto cleanup; + } - key_sz = ctx->read_ctx->pass_sz + 1; - key = sqlcipher_malloc(key_sz); - memset(key, 0, key_sz); - memcpy(key, ctx->read_ctx->pass, ctx->read_ctx->pass_sz); + if(!(ctx->flags & CIPHER_FLAG_HMAC)) { + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "HMAC is not enabled, unable to integrity check", P4_TRANSIENT); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + goto cleanup; + } - if(db_filename){ - const char* commands[5]; - char *attach_command = sqlite3_mprintf("ATTACH DATABASE '%s-migrated' as migrate KEY '%q';", - db_filename, key); + if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) { + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "unable to derive keys", P4_TRANSIENT); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + goto cleanup; + } - int rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, "", &user_version); - if(rc == SQLITE_OK){ - CODEC_TRACE(("No upgrade required - exiting\n")); - goto exit; - } - - // Version 2 - check for 4k with hmac format - rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, pragma_4k_kdf_iter, &user_version); - if(rc == SQLITE_OK) { - CODEC_TRACE(("Version 2 format found\n")); - upgrade_4k_format = 1; - } + tdsqlite3OsFileSize(fd, &file_sz); + hmac_out = sqlcipher_malloc(ctx->hmac_sz); - // Version 1 - check both no hmac and 4k together - pragma_1x_and_4k = sqlite3_mprintf("%s%s", pragma_hmac_off, - pragma_4k_kdf_iter); - rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, pragma_1x_and_4k, &user_version); - sqlite3_free(pragma_1x_and_4k); - if(rc == SQLITE_OK) { - CODEC_TRACE(("Version 1 format found\n")); - upgrade_1x_format = 1; - upgrade_4k_format = 1; - } + for(page = 1; page <= file_sz / ctx->page_sz; page++) { + int offset = (page - 1) * ctx->page_sz; + int payload_sz = ctx->page_sz - ctx->reserve_sz + ctx->iv_sz; + int read_sz = ctx->page_sz; - if(upgrade_1x_format == 0 && upgrade_4k_format == 0) { - CODEC_TRACE(("Upgrade format not determined\n")); - goto handle_error; + if(page==1) { + int page1_offset = ctx->plaintext_header_sz ? ctx->plaintext_header_sz : FILE_HEADER_SZ; + read_sz = read_sz - page1_offset; + payload_sz = payload_sz - page1_offset; + offset += page1_offset; } - set_user_version = sqlite3_mprintf("PRAGMA migrate.user_version = %d;", user_version); - commands[0] = upgrade_4k_format == 1 ? pragma_4k_kdf_iter : ""; - commands[1] = upgrade_1x_format == 1 ? pragma_hmac_off : ""; - commands[2] = attach_command; - commands[3] = "SELECT sqlcipher_export('migrate');"; - commands[4] = set_user_version; - - for(command_idx = 0; command_idx < ArraySize(commands); command_idx++){ - const char *command = commands[command_idx]; - if(strcmp(command, "") == 0){ - continue; - } - rc = sqlite3_exec(db, command, NULL, NULL, NULL); - if(rc != SQLITE_OK){ - break; - } + sqlcipher_memset(ctx->buffer, 0, ctx->page_sz); + sqlcipher_memset(hmac_out, 0, ctx->hmac_sz); + if(tdsqlite3OsRead(fd, ctx->buffer, read_sz, offset) != SQLITE_OK) { + result = tdsqlite3_mprintf("error reading %d bytes from file page %d at offset %d\n", read_sz, page, offset); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } else if(sqlcipher_page_hmac(ctx, ctx->read_ctx, page, ctx->buffer, payload_sz, hmac_out) != SQLITE_OK) { + result = tdsqlite3_mprintf("HMAC operation failed for page %d", page); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } else if(sqlcipher_memcmp(ctx->buffer + payload_sz, hmac_out, ctx->hmac_sz) != 0) { + result = tdsqlite3_mprintf("HMAC verification failed for page %d", page); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } - sqlite3_free(attach_command); - sqlite3_free(set_user_version); - sqlcipher_free(key, key_sz); - - if(rc == SQLITE_OK){ - Btree *pDest; - Btree *pSrc; - int i = 0; - - if( !db->autoCommit ){ - CODEC_TRACE(("cannot migrate from within a transaction")); - goto handle_error; - } - if( db->nVdbeActive>1 ){ - CODEC_TRACE(("cannot migrate - SQL statements in progress")); - goto handle_error; - } - - /* Save the current value of the database flags so that it can be - ** restored before returning. Then set the writable-schema flag, and - ** disable CHECK and foreign key constraints. */ - saved_flags = db->flags; - saved_nChange = db->nChange; - saved_nTotalChange = db->nTotalChange; - saved_xTrace = db->xTrace; - db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin; - db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder); - db->xTrace = 0; - - pDest = db->aDb[0].pBt; - pDb = &(db->aDb[db->nDb-1]); - pSrc = pDb->pBt; - - rc = sqlite3_exec(db, "BEGIN;", NULL, NULL, NULL); - rc = sqlite3BtreeBeginTrans(pSrc, 2); - rc = sqlite3BtreeBeginTrans(pDest, 2); - - assert( 1==sqlite3BtreeIsInTrans(pDest) ); - assert( 1==sqlite3BtreeIsInTrans(pSrc) ); - - sqlite3CodecGetKey(db, db->nDb - 1, (void**)&key, &password_sz); - sqlite3CodecAttach(db, 0, key, password_sz); - sqlite3pager_get_codec(pDest->pBt->pPager, (void**)&ctx); - - ctx->skip_read_hmac = 1; - for(i=0; i<ArraySize(aCopy); i+=2){ - sqlite3BtreeGetMeta(pSrc, aCopy[i], &meta); - rc = sqlite3BtreeUpdateMeta(pDest, aCopy[i], meta+aCopy[i+1]); - if( NEVER(rc!=SQLITE_OK) ) goto handle_error; - } - rc = sqlite3BtreeCopyFile(pDest, pSrc); - ctx->skip_read_hmac = 0; - if( rc!=SQLITE_OK ) goto handle_error; - rc = sqlite3BtreeCommit(pDest); - - db->flags = saved_flags; - db->nChange = saved_nChange; - db->nTotalChange = saved_nTotalChange; - db->xTrace = saved_xTrace; - db->autoCommit = 1; - sqlite3BtreeClose(pDb->pBt); - pDb->pBt = 0; - pDb->pSchema = 0; - sqlite3ResetAllSchemasOfConnection(db); - remove(migrated_db_filename); - sqlite3_free(migrated_db_filename); - } else { - CODEC_TRACE(("*** migration failure** \n\n")); - } - } - goto exit; - handle_error: - CODEC_TRACE(("An error occurred attempting to migrate the database\n")); - rc = SQLITE_ERROR; + if(file_sz % ctx->page_sz != 0) { + result = tdsqlite3_mprintf("page %d has an invalid size of %lld bytes", page, file_sz - ((file_sz / ctx->page_sz) * ctx->page_sz)); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + } - exit: - return rc; +cleanup: + if(hmac_out != NULL) sqlcipher_free(hmac_out, ctx->hmac_sz); + return SQLITE_OK; } -int sqlcipher_codec_add_random(codec_ctx *ctx, const char *zRight, int random_sz){ - const char *suffix = &zRight[random_sz-1]; - int n = random_sz - 3; /* adjust for leading x' and tailing ' */ - if (n > 0 && - sqlite3StrNICmp((const char *)zRight ,"x'", 2) == 0 && - sqlite3StrNICmp(suffix, "'", 1) == 0 && - n % 2 == 0) { - int rc = 0; - int buffer_sz = n / 2; - unsigned char *random; - const unsigned char *z = (const unsigned char *)zRight + 2; /* adjust lead offset of x' */ - CODEC_TRACE(("sqlcipher_codec_add_random: using raw random blob from hex\n")); - random = sqlcipher_malloc(buffer_sz); - memset(random, 0, buffer_sz); - cipher_hex2bin(z, n, random); - rc = ctx->read_ctx->provider->add_random(ctx->read_ctx->provider_ctx, random, buffer_sz); - sqlcipher_free(random, buffer_sz); - return rc; +int sqlcipher_codec_ctx_migrate(codec_ctx *ctx) { + int i, pass_sz, keyspec_sz, nRes, user_version, rc, oflags; + Db *pDb = 0; + tdsqlite3 *db = ctx->pBt->db; + const char *db_filename = tdsqlite3_db_filename(db, "main"); + char *set_user_version = NULL, *pass = NULL, *attach_command = NULL, *migrated_db_filename = NULL, *keyspec = NULL, *temp = NULL, *journal_mode = NULL, *set_journal_mode = NULL, *pragma_compat = NULL; + Btree *pDest = NULL, *pSrc = NULL; + tdsqlite3_file *srcfile, *destfile; +#if defined(_WIN32) || defined(SQLITE_OS_WINRT) + LPWSTR w_db_filename = NULL, w_migrated_db_filename = NULL; + int w_db_filename_sz = 0, w_migrated_db_filename_sz = 0; +#endif + pass_sz = keyspec_sz = rc = user_version = 0; + + if(!db_filename || tdsqlite3Strlen30(db_filename) < 1) + goto cleanup; /* exit immediately if this is an in memory database */ + + /* pull the provided password / key material off the current codec context */ + pass_sz = ctx->read_ctx->pass_sz; + pass = sqlcipher_malloc(pass_sz+1); + memset(pass, 0, pass_sz+1); + memcpy(pass, ctx->read_ctx->pass, pass_sz); + + /* Version 4 - current, no upgrade required, so exit immediately */ + rc = sqlcipher_check_connection(db_filename, pass, pass_sz, "", &user_version, &journal_mode); + if(rc == SQLITE_OK){ + CODEC_TRACE("No upgrade required - exiting\n"); + goto cleanup; } - return SQLITE_ERROR; -} - -int sqlcipher_cipher_profile(sqlite3 *db, const char *destination){ - FILE *f; - if(sqlite3StrICmp(destination, "stdout") == 0){ - f = stdout; - }else if(sqlite3StrICmp(destination, "stderr") == 0){ - f = stderr; - }else if(sqlite3StrICmp(destination, "off") == 0){ - f = 0; - }else{ -#if defined(_WIN32) && (__STDC_VERSION__ > 199901L) || defined(SQLITE_OS_WINRT) - if(fopen_s(&f, destination, "a") != 0){ -#else - f = fopen(destination, "a"); - if(f == 0){ -#endif - return SQLITE_ERROR; - } + for(i = 3; i > 0; i--) { + pragma_compat = tdsqlite3_mprintf("PRAGMA cipher_compatibility = %d;", i); + rc = sqlcipher_check_connection(db_filename, pass, pass_sz, pragma_compat, &user_version, &journal_mode); + if(rc == SQLITE_OK) { + CODEC_TRACE("Version %d format found\n", i); + goto migrate; + } + if(pragma_compat) sqlcipher_free(pragma_compat, tdsqlite3Strlen30(pragma_compat)); + pragma_compat = NULL; } - sqlite3_profile(db, sqlcipher_profile_callback, f); - return SQLITE_OK; -} - -static void sqlcipher_profile_callback(void *file, const char *sql, sqlite3_uint64 run_time){ - FILE *f = (FILE*)file; - double elapsed = run_time/1000000.0; - if(f) fprintf(f, "Elapsed time:%.3f ms - %s\n", elapsed, sql); -} + /* if we exit the loop normally we failed to determine the version, this is an error */ + CODEC_TRACE("Upgrade format not determined\n"); + goto handle_error; -int sqlcipher_codec_fips_status(codec_ctx *ctx) { - return ctx->read_ctx->provider->fips_status(ctx->read_ctx); -} +migrate: -const char* sqlcipher_codec_get_provider_version(codec_ctx *ctx) { - return ctx->read_ctx->provider->get_provider_version(ctx->read_ctx); -} + temp = tdsqlite3_mprintf("%s-migrated", db_filename); + /* overallocate migrated_db_filename, because tdsqlite3OsOpen will read past the null terminator + * to determine whether the filename was URI formatted */ + migrated_db_filename = sqlcipher_malloc(tdsqlite3Strlen30(temp)+2); + memcpy(migrated_db_filename, temp, tdsqlite3Strlen30(temp)); + sqlcipher_free(temp, tdsqlite3Strlen30(temp)); -#endif -/* END SQLCIPHER */ + attach_command = tdsqlite3_mprintf("ATTACH DATABASE '%s' as migrate;", migrated_db_filename, pass); + set_user_version = tdsqlite3_mprintf("PRAGMA migrate.user_version = %d;", user_version); -/************** End of crypto_impl.c *****************************************/ -/************** Begin file crypto_libtomcrypt.c ******************************/ -/* -** SQLCipher -** http://sqlcipher.net -** -** Copyright (c) 2008 - 2013, ZETETIC LLC -** All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of the ZETETIC LLC nor the -** names of its contributors may be used to endorse or promote products -** derived from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY -** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY -** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -*/ -/* BEGIN SQLCIPHER */ -#ifdef SQLITE_HAS_CODEC -#ifdef SQLCIPHER_CRYPTO_LIBTOMCRYPT -/* #include "sqliteInt.h" */ -/* #include "sqlcipher.h" */ -#include <tomcrypt.h> + rc = tdsqlite3_exec(db, pragma_compat, NULL, NULL, NULL); + if(rc != SQLITE_OK){ + CODEC_TRACE("set compatibility mode failed, error code %d\n", rc); + goto handle_error; + } -#define FORTUNA_MAX_SZ 32 -static prng_state prng; -static unsigned int ltc_init = 0; -static unsigned int ltc_ref_count = 0; -static sqlite3_mutex* ltc_rand_mutex = NULL; + /* force journal mode to DELETE, we will set it back later if different */ + rc = tdsqlite3_exec(db, "PRAGMA journal_mode = delete;", NULL, NULL, NULL); + if(rc != SQLITE_OK){ + CODEC_TRACE("force journal mode DELETE failed, error code %d\n", rc); + goto handle_error; + } -static int sqlcipher_ltc_add_random(void *ctx, void *buffer, int length) { - int rc = 0; - int data_to_read = length; - int block_sz = data_to_read < FORTUNA_MAX_SZ ? data_to_read : FORTUNA_MAX_SZ; - const unsigned char * data = (const unsigned char *)buffer; -#ifndef SQLCIPHER_LTC_NO_MUTEX_RAND - sqlite3_mutex_enter(ltc_rand_mutex); -#endif - while(data_to_read > 0){ - rc = fortuna_add_entropy(data, block_sz, &prng); - rc = rc != CRYPT_OK ? SQLITE_ERROR : SQLITE_OK; - if(rc != SQLITE_OK){ - break; - } - data_to_read -= block_sz; - data += block_sz; - block_sz = data_to_read < FORTUNA_MAX_SZ ? data_to_read : FORTUNA_MAX_SZ; - } - fortuna_ready(&prng); -#ifndef SQLCIPHER_LTC_NO_MUTEX_RAND - sqlite3_mutex_leave(ltc_rand_mutex); -#endif - return rc; -} + rc = tdsqlite3_exec(db, attach_command, NULL, NULL, NULL); + if(rc != SQLITE_OK){ + CODEC_TRACE("attach failed, error code %d\n", rc); + goto handle_error; + } -static int sqlcipher_ltc_activate(void *ctx) { - unsigned char random_buffer[FORTUNA_MAX_SZ]; -#ifndef SQLCIPHER_LTC_NO_MUTEX_RAND - if(ltc_rand_mutex == NULL){ - ltc_rand_mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + rc = tdsqlite3_key_v2(db, "migrate", pass, pass_sz); + if(rc != SQLITE_OK){ + CODEC_TRACE("keying attached database failed, error code %d\n", rc); + goto handle_error; } - sqlite3_mutex_enter(ltc_rand_mutex); -#endif - sqlcipher_memset(random_buffer, 0, FORTUNA_MAX_SZ); - if(ltc_init == 0) { - if(register_prng(&fortuna_desc) != CRYPT_OK) return SQLITE_ERROR; - if(register_cipher(&rijndael_desc) != CRYPT_OK) return SQLITE_ERROR; - if(register_hash(&sha1_desc) != CRYPT_OK) return SQLITE_ERROR; - if(fortuna_start(&prng) != CRYPT_OK) { - return SQLITE_ERROR; - } - ltc_init = 1; + + rc = tdsqlite3_exec(db, "SELECT sqlcipher_export('migrate');", NULL, NULL, NULL); + if(rc != SQLITE_OK){ + CODEC_TRACE("sqlcipher_export failed, error code %d\n", rc); + goto handle_error; } - ltc_ref_count++; -#ifndef SQLCIPHER_TEST - sqlite3_randomness(FORTUNA_MAX_SZ, random_buffer); -#endif -#ifndef SQLCIPHER_LTC_NO_MUTEX_RAND - sqlite3_mutex_leave(ltc_rand_mutex); -#endif - if(sqlcipher_ltc_add_random(ctx, random_buffer, FORTUNA_MAX_SZ) != SQLITE_OK) { - return SQLITE_ERROR; + + rc = tdsqlite3_exec(db, set_user_version, NULL, NULL, NULL); + if(rc != SQLITE_OK){ + CODEC_TRACE("set user version failed, error code %d\n", rc); + goto handle_error; } - sqlcipher_memset(random_buffer, 0, FORTUNA_MAX_SZ); - return SQLITE_OK; -} -static int sqlcipher_ltc_deactivate(void *ctx) { -#ifndef SQLCIPHER_LTC_NO_MUTEX_RAND - sqlite3_mutex_enter(ltc_rand_mutex); -#endif - ltc_ref_count--; - if(ltc_ref_count == 0){ - fortuna_done(&prng); - sqlcipher_memset((void *)&prng, 0, sizeof(prng)); -#ifndef SQLCIPHER_LTC_NO_MUTEX_RAND - sqlite3_mutex_leave(ltc_rand_mutex); - sqlite3_mutex_free(ltc_rand_mutex); - ltc_rand_mutex = NULL; -#endif + if( !db->autoCommit ){ + CODEC_TRACE("cannot migrate from within a transaction"); + goto handle_error; } -#ifndef SQLCIPHER_LTC_NO_MUTEX_RAND - else { - sqlite3_mutex_leave(ltc_rand_mutex); + if( db->nVdbeActive>1 ){ + CODEC_TRACE("cannot migrate - SQL statements in progress"); + goto handle_error; } -#endif - return SQLITE_OK; -} -static const char* sqlcipher_ltc_get_provider_name(void *ctx) { - return "libtomcrypt"; -} + pDest = db->aDb[0].pBt; + pDb = &(db->aDb[db->nDb-1]); + pSrc = pDb->pBt; -static const char* sqlcipher_ltc_get_provider_version(void *ctx) { - return SCRYPT; -} + nRes = tdsqlite3BtreeGetOptimalReserve(pSrc); + /* unset the BTS_PAGESIZE_FIXED flag to avoid SQLITE_READONLY */ + pDest->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; + rc = tdsqlite3BtreeSetPageSize(pDest, default_page_size, nRes, 0); + CODEC_TRACE("set btree page size to %d res %d rc %d\n", default_page_size, nRes, rc); + if( rc!=SQLITE_OK ) goto handle_error; -static int sqlcipher_ltc_random(void *ctx, void *buffer, int length) { -#ifndef SQLCIPHER_LTC_NO_MUTEX_RAND - sqlite3_mutex_enter(ltc_rand_mutex); -#endif - fortuna_read(buffer, length, &prng); -#ifndef SQLCIPHER_LTC_NO_MUTEX_RAND - sqlite3_mutex_leave(ltc_rand_mutex); -#endif - return SQLITE_OK; -} + tdsqlite3CodecGetKey(db, db->nDb - 1, (void**)&keyspec, &keyspec_sz); + tdsqlite3CodecAttach(db, 0, keyspec, keyspec_sz); + + srcfile = tdsqlite3PagerFile(pSrc->pBt->pPager); + destfile = tdsqlite3PagerFile(pDest->pBt->pPager); -static int sqlcipher_ltc_hmac(void *ctx, unsigned char *hmac_key, int key_sz, unsigned char *in, int in_sz, unsigned char *in2, int in2_sz, unsigned char *out) { - int rc, hash_idx; - hmac_state hmac; - unsigned long outlen = key_sz; + tdsqlite3OsClose(srcfile); + tdsqlite3OsClose(destfile); - hash_idx = find_hash("sha1"); - if((rc = hmac_init(&hmac, hash_idx, hmac_key, key_sz)) != CRYPT_OK) return SQLITE_ERROR; - if((rc = hmac_process(&hmac, in, in_sz)) != CRYPT_OK) return SQLITE_ERROR; - if((rc = hmac_process(&hmac, in2, in2_sz)) != CRYPT_OK) return SQLITE_ERROR; - if((rc = hmac_done(&hmac, out, &outlen)) != CRYPT_OK) return SQLITE_ERROR; - return SQLITE_OK; -} +#if defined(_WIN32) || defined(SQLITE_OS_WINRT) + CODEC_TRACE("performing windows MoveFileExA\n"); -static int sqlcipher_ltc_kdf(void *ctx, const unsigned char *pass, int pass_sz, unsigned char* salt, int salt_sz, int workfactor, int key_sz, unsigned char *key) { - int rc, hash_idx; - unsigned long outlen = key_sz; - unsigned long random_buffer_sz = sizeof(char) * 256; - unsigned char *random_buffer = sqlcipher_malloc(random_buffer_sz); - sqlcipher_memset(random_buffer, 0, random_buffer_sz); + w_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) db_filename, -1, NULL, 0); + w_db_filename = sqlcipher_malloc(w_db_filename_sz * sizeof(wchar_t)); + w_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) db_filename, -1, (const LPWSTR) w_db_filename, w_db_filename_sz); - hash_idx = find_hash("sha1"); - if((rc = pkcs_5_alg2(pass, pass_sz, salt, salt_sz, - workfactor, hash_idx, key, &outlen)) != CRYPT_OK) { - return SQLITE_ERROR; + w_migrated_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) migrated_db_filename, -1, NULL, 0); + w_migrated_db_filename = sqlcipher_malloc(w_migrated_db_filename_sz * sizeof(wchar_t)); + w_migrated_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) migrated_db_filename, -1, (const LPWSTR) w_migrated_db_filename, w_migrated_db_filename_sz); + + if(!MoveFileExW(w_migrated_db_filename, w_db_filename, MOVEFILE_REPLACE_EXISTING)) { + CODEC_TRACE("move error"); + rc = SQLITE_ERROR; + CODEC_TRACE("error occurred while renaming %d\n", rc); + goto handle_error; } - if((rc = pkcs_5_alg2(key, key_sz, salt, salt_sz, - 1, hash_idx, random_buffer, &random_buffer_sz)) != CRYPT_OK) { - return SQLITE_ERROR; +#else + CODEC_TRACE("performing POSIX rename\n"); + if ((rc = rename(migrated_db_filename, db_filename)) != 0) { + CODEC_TRACE("error occurred while renaming %d\n", rc); + goto handle_error; } - sqlcipher_ltc_add_random(ctx, random_buffer, random_buffer_sz); - sqlcipher_free(random_buffer, random_buffer_sz); - return SQLITE_OK; -} +#endif + CODEC_TRACE("renamed migration database %s to main database %s: %d\n", migrated_db_filename, db_filename, rc); -static const char* sqlcipher_ltc_get_cipher(void *ctx) { - return "rijndael"; -} + rc = tdsqlite3OsOpen(db->pVfs, migrated_db_filename, srcfile, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_DB, &oflags); + CODEC_TRACE("reopened migration database: %d\n", rc); + if( rc!=SQLITE_OK ) goto handle_error; -static int sqlcipher_ltc_cipher(void *ctx, int mode, unsigned char *key, int key_sz, unsigned char *iv, unsigned char *in, int in_sz, unsigned char *out) { - int rc, cipher_idx; - symmetric_CBC cbc; + rc = tdsqlite3OsOpen(db->pVfs, db_filename, destfile, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_DB, &oflags); + CODEC_TRACE("reopened main database: %d\n", rc); + if( rc!=SQLITE_OK ) goto handle_error; - if((cipher_idx = find_cipher(sqlcipher_ltc_get_cipher(ctx))) == -1) return SQLITE_ERROR; - if((rc = cbc_start(cipher_idx, iv, key, key_sz, 0, &cbc)) != CRYPT_OK) return SQLITE_ERROR; - rc = mode == 1 ? cbc_encrypt(in, out, in_sz, &cbc) : cbc_decrypt(in, out, in_sz, &cbc); - if(rc != CRYPT_OK) return SQLITE_ERROR; - cbc_done(&cbc); - return SQLITE_OK; -} + tdsqlite3pager_reset(pDest->pBt->pPager); + CODEC_TRACE("reset pager\n"); -static int sqlcipher_ltc_set_cipher(void *ctx, const char *cipher_name) { - return SQLITE_OK; -} + rc = tdsqlite3_exec(db, "DETACH DATABASE migrate;", NULL, NULL, NULL); + CODEC_TRACE("DETACH DATABASE called %d\n", rc); + if(rc != SQLITE_OK) goto cleanup; -static int sqlcipher_ltc_get_key_sz(void *ctx) { - int cipher_idx = find_cipher(sqlcipher_ltc_get_cipher(ctx)); - return cipher_descriptor[cipher_idx].max_key_length; -} + rc = tdsqlite3OsDelete(db->pVfs, migrated_db_filename, 0); + CODEC_TRACE("deleted migration database: %d\n", rc); + if( rc!=SQLITE_OK ) goto handle_error; -static int sqlcipher_ltc_get_iv_sz(void *ctx) { - int cipher_idx = find_cipher(sqlcipher_ltc_get_cipher(ctx)); - return cipher_descriptor[cipher_idx].block_length; -} + tdsqlite3ResetAllSchemasOfConnection(db); + CODEC_TRACE("reset all schemas\n"); -static int sqlcipher_ltc_get_block_sz(void *ctx) { - int cipher_idx = find_cipher(sqlcipher_ltc_get_cipher(ctx)); - return cipher_descriptor[cipher_idx].block_length; -} + set_journal_mode = tdsqlite3_mprintf("PRAGMA journal_mode = %s;", journal_mode); + rc = tdsqlite3_exec(db, set_journal_mode, NULL, NULL, NULL); + CODEC_TRACE("%s: %d\n", set_journal_mode, rc); + if( rc!=SQLITE_OK ) goto handle_error; -static int sqlcipher_ltc_get_hmac_sz(void *ctx) { - int hash_idx = find_hash("sha1"); - return hash_descriptor[hash_idx].hashsize; -} + goto cleanup; -static int sqlcipher_ltc_ctx_copy(void *target_ctx, void *source_ctx) { - return SQLITE_OK; +handle_error: + CODEC_TRACE("An error occurred attempting to migrate the database - last error %d\n", rc); + rc = SQLITE_ERROR; + +cleanup: + if(pass) sqlcipher_free(pass, pass_sz); + if(attach_command) sqlcipher_free(attach_command, tdsqlite3Strlen30(attach_command)); + if(migrated_db_filename) sqlcipher_free(migrated_db_filename, tdsqlite3Strlen30(migrated_db_filename)); + if(set_user_version) sqlcipher_free(set_user_version, tdsqlite3Strlen30(set_user_version)); + if(set_journal_mode) sqlcipher_free(set_journal_mode, tdsqlite3Strlen30(set_journal_mode)); + if(journal_mode) sqlcipher_free(journal_mode, tdsqlite3Strlen30(journal_mode)); + if(pragma_compat) sqlcipher_free(pragma_compat, tdsqlite3Strlen30(pragma_compat)); +#if defined(_WIN32) || defined(SQLITE_OS_WINRT) + if(w_db_filename) sqlcipher_free(w_db_filename, w_db_filename_sz); + if(w_migrated_db_filename) sqlcipher_free(w_migrated_db_filename, w_migrated_db_filename_sz); +#endif + return rc; } -static int sqlcipher_ltc_ctx_cmp(void *c1, void *c2) { - return 1; +int sqlcipher_codec_add_random(codec_ctx *ctx, const char *zRight, int random_sz){ + const char *suffix = &zRight[random_sz-1]; + int n = random_sz - 3; /* adjust for leading x' and tailing ' */ + if (n > 0 && + tdsqlite3StrNICmp((const char *)zRight ,"x'", 2) == 0 && + tdsqlite3StrNICmp(suffix, "'", 1) == 0 && + n % 2 == 0) { + int rc = 0; + int buffer_sz = n / 2; + unsigned char *random; + const unsigned char *z = (const unsigned char *)zRight + 2; /* adjust lead offset of x' */ + CODEC_TRACE("sqlcipher_codec_add_random: using raw random blob from hex\n"); + random = sqlcipher_malloc(buffer_sz); + memset(random, 0, buffer_sz); + cipher_hex2bin(z, n, random); + rc = ctx->provider->add_random(ctx->provider_ctx, random, buffer_sz); + sqlcipher_free(random, buffer_sz); + return rc; + } + return SQLITE_ERROR; } -static int sqlcipher_ltc_ctx_init(void **ctx) { - sqlcipher_ltc_activate(NULL); - return SQLITE_OK; +static void sqlcipher_profile_callback(void *file, const char *sql, tdsqlite3_uint64 run_time){ + FILE *f = (FILE*)file; + double elapsed = run_time/1000000.0; + if(f) fprintf(f, "Elapsed time:%.3f ms - %s\n", elapsed, sql); } -static int sqlcipher_ltc_ctx_free(void **ctx) { - sqlcipher_ltc_deactivate(&ctx); +int sqlcipher_cipher_profile(tdsqlite3 *db, const char *destination){ +#if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED) + return SQLITE_ERROR; +#else + FILE *f; + if(tdsqlite3StrICmp(destination, "stdout") == 0){ + f = stdout; + }else if(tdsqlite3StrICmp(destination, "stderr") == 0){ + f = stderr; + }else if(tdsqlite3StrICmp(destination, "off") == 0){ + f = 0; + }else{ +#if !defined(SQLCIPHER_PROFILE_USE_FOPEN) && (defined(_WIN32) && (__STDC_VERSION__ > 199901L) || defined(SQLITE_OS_WINRT)) + if(fopen_s(&f, destination, "a") != 0) return SQLITE_ERROR; +#else + if((f = fopen(destination, "a")) == 0) return SQLITE_ERROR; +#endif + } + tdsqlite3_profile(db, sqlcipher_profile_callback, f); return SQLITE_OK; +#endif } -static int sqlcipher_ltc_fips_status(void *ctx) { - return 0; +int sqlcipher_codec_fips_status(codec_ctx *ctx) { + return ctx->provider->fips_status(ctx->provider_ctx); } -int sqlcipher_ltc_setup(sqlcipher_provider *p) { - p->activate = sqlcipher_ltc_activate; - p->deactivate = sqlcipher_ltc_deactivate; - p->get_provider_name = sqlcipher_ltc_get_provider_name; - p->random = sqlcipher_ltc_random; - p->hmac = sqlcipher_ltc_hmac; - p->kdf = sqlcipher_ltc_kdf; - p->cipher = sqlcipher_ltc_cipher; - p->set_cipher = sqlcipher_ltc_set_cipher; - p->get_cipher = sqlcipher_ltc_get_cipher; - p->get_key_sz = sqlcipher_ltc_get_key_sz; - p->get_iv_sz = sqlcipher_ltc_get_iv_sz; - p->get_block_sz = sqlcipher_ltc_get_block_sz; - p->get_hmac_sz = sqlcipher_ltc_get_hmac_sz; - p->ctx_copy = sqlcipher_ltc_ctx_copy; - p->ctx_cmp = sqlcipher_ltc_ctx_cmp; - p->ctx_init = sqlcipher_ltc_ctx_init; - p->ctx_free = sqlcipher_ltc_ctx_free; - p->add_random = sqlcipher_ltc_add_random; - p->fips_status = sqlcipher_ltc_fips_status; - p->get_provider_version = sqlcipher_ltc_get_provider_version; - return SQLITE_OK; +const char* sqlcipher_codec_get_provider_version(codec_ctx *ctx) { + return ctx->provider->get_provider_version(ctx->provider_ctx); } #endif -#endif /* END SQLCIPHER */ -/************** End of crypto_libtomcrypt.c **********************************/ +/************** End of crypto_impl.c *****************************************/ /************** Begin file crypto_openssl.c **********************************/ /* ** SQLCipher @@ -20251,13 +24083,25 @@ int sqlcipher_ltc_setup(sqlcipher_provider *p) { */ /* BEGIN SQLCIPHER */ #ifdef SQLITE_HAS_CODEC -#ifdef SQLCIPHER_CRYPTO_OPENSSL /* #include "sqliteInt.h" */ /* #include "crypto.h" */ /* #include "sqlcipher.h" */ #include <openssl/rand.h> #include <openssl/evp.h> +#include <openssl/objects.h> #include <openssl/hmac.h> +#include <openssl/err.h> + +#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10000000L +// HMAC_* functions returned void before 87d52468aa600e02326e13f01331e1f3b8602ed0 +#define HMAC_Init_ex_(...) (HMAC_Init_ex(__VA_ARGS__), 1) +#define HMAC_Update_(...) (HMAC_Update(__VA_ARGS__), 1) +#define HMAC_Final_(...) (HMAC_Final(__VA_ARGS__), 1) +#else +#define HMAC_Init_ex_(...) HMAC_Init_ex(__VA_ARGS__) +#define HMAC_Update_(...) HMAC_Update(__VA_ARGS__) +#define HMAC_Final_(...) HMAC_Final(__VA_ARGS__) +#endif typedef struct { EVP_CIPHER *evp_cipher; @@ -20265,9 +24109,8 @@ typedef struct { static unsigned int openssl_external_init = 0; static unsigned int openssl_init_count = 0; -static sqlite3_mutex* openssl_rand_mutex = NULL; -#if OPENSSL_VERSION_NUMBER < 0x10100000L +#if (defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10100000L) || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) static HMAC_CTX *HMAC_CTX_new(void) { HMAC_CTX *ctx = OPENSSL_malloc(sizeof(*ctx)); @@ -20277,10 +24120,10 @@ static HMAC_CTX *HMAC_CTX_new(void) return ctx; } -// Per 1.1.0 (https://wiki.openssl.org/index.php/1.1_API_Changes) -// HMAC_CTX_free should call HMAC_CTX_cleanup, then EVP_MD_CTX_Cleanup. -// HMAC_CTX_cleanup internally calls EVP_MD_CTX_cleanup so these -// calls are not needed. +/* Per 1.1.0 (https://wiki.openssl.org/index.php/1.1_API_Changes) + HMAC_CTX_free should call HMAC_CTX_cleanup, then EVP_MD_CTX_Cleanup. + HMAC_CTX_cleanup internally calls EVP_MD_CTX_cleanup so these + calls are not needed. */ static void HMAC_CTX_free(HMAC_CTX *ctx) { if (ctx != NULL) { @@ -20292,15 +24135,22 @@ static void HMAC_CTX_free(HMAC_CTX *ctx) static int sqlcipher_openssl_add_random(void *ctx, void *buffer, int length) { #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND - sqlite3_mutex_enter(openssl_rand_mutex); + CODEC_TRACE_MUTEX("sqlcipher_openssl_add_random: entering SQLCIPHER_MUTEX_PROVIDER_RAND\n"); + tdsqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER_RAND)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_add_random: entered SQLCIPHER_MUTEX_PROVIDER_RAND\n"); #endif RAND_add(buffer, length, 0); #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND - sqlite3_mutex_leave(openssl_rand_mutex); + CODEC_TRACE_MUTEX("sqlcipher_openssl_add_random: leaving SQLCIPHER_MUTEX_PROVIDER_RAND\n"); + tdsqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER_RAND)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_add_random: left SQLCIPHER_MUTEX_PROVIDER_RAND\n"); #endif return SQLITE_OK; } +#define OPENSSL_CIPHER "aes-256-cbc" + + /* activate and initialize sqlcipher. Most importantly, this will automatically intialize OpenSSL's EVP system if it hasn't already be externally. Note that this function may be called multiple times as new codecs are intiialized. @@ -20311,9 +24161,12 @@ static int sqlcipher_openssl_activate(void *ctx) { /* initialize openssl and increment the internal init counter but only if it hasn't been initalized outside of SQLCipher by this program e.g. on startup */ - sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + + CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: entering SQLCIPHER_MUTEX_PROVIDER_ACTIVATE\n"); + tdsqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER_ACTIVATE)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: entered SQLCIPHER_MUTEX_PROVIDER_ACTIVATE\n"); - if(openssl_init_count == 0 && EVP_get_cipherbyname(CIPHER) != NULL) { + if(openssl_init_count == 0 && EVP_get_cipherbyname(OPENSSL_CIPHER) != NULL) { /* if openssl has not yet been initialized by this library, but a call to get_cipherbyname works, then the openssl library has been initialized externally already. */ @@ -20323,26 +24176,30 @@ static int sqlcipher_openssl_activate(void *ctx) { #ifdef SQLCIPHER_FIPS if(!FIPS_mode()){ if(!FIPS_mode_set(1)){ + unsigned long err = 0; ERR_load_crypto_strings(); +#ifdef __ANDROID__ + while((err = ERR_get_error()) != 0) { + __android_log_print(ANDROID_LOG_ERROR, "sqlcipher","error: %lx. %s.", err, ERR_error_string(err, NULL)); + } +#else ERR_print_errors_fp(stderr); +#endif } } #endif if(openssl_init_count == 0 && openssl_external_init == 0) { /* if the library was not externally initialized, then should be now */ +#if (defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10100000L) || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) OpenSSL_add_all_algorithms(); - } - -#ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND - if(openssl_rand_mutex == NULL) { - /* allocate a mutex to guard against concurrent calls to RAND_bytes() */ - openssl_rand_mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); - } #endif + } openssl_init_count++; - sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: leaving SQLCIPHER_MUTEX_PROVIDER_ACTIVATE\n"); + tdsqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER_ACTIVATE)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: left SQLCIPHER_MUTEX_PROVIDER_ACTIVATE\n"); return SQLITE_OK; } @@ -20350,7 +24207,9 @@ static int sqlcipher_openssl_activate(void *ctx) { freeing the EVP structures on the final deactivation to ensure that OpenSSL memory is cleaned up */ static int sqlcipher_openssl_deactivate(void *ctx) { - sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: entering SQLCIPHER_MUTEX_PROVIDER_ACTIVATE\n"); + tdsqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER_ACTIVATE)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: entered SQLCIPHER_MUTEX_PROVIDER_ACTIVATE\n"); openssl_init_count--; if(openssl_init_count == 0) { @@ -20360,16 +24219,17 @@ static int sqlcipher_openssl_deactivate(void *ctx) { Note: this code will only be reached if OpensSSL_add_all_algorithms() is called by SQLCipher internally. This should prevent SQLCipher from "cleaning up" openssl when it was initialized externally by the program */ +#if (defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10100000L) || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) EVP_cleanup(); +#endif } else { openssl_external_init = 0; } -#ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND - sqlite3_mutex_free(openssl_rand_mutex); - openssl_rand_mutex = NULL; -#endif - } - sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + } + + CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: leaving SQLCIPHER_MUTEX_PROVIDER_ACTIVATE\n"); + tdsqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER_ACTIVATE)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: left SQLCIPHER_MUTEX_PROVIDER_ACTIVATE\n"); return SQLITE_OK; } @@ -20391,60 +24251,111 @@ static int sqlcipher_openssl_random (void *ctx, void *buffer, int length) { but a more proper solution is that applications setup platform-appropriate thread saftey in openssl externally */ #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND - sqlite3_mutex_enter(openssl_rand_mutex); + CODEC_TRACE_MUTEX("sqlcipher_openssl_random: entering SQLCIPHER_MUTEX_PROVIDER_RAND\n"); + tdsqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER_RAND)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_random: entered SQLCIPHER_MUTEX_PROVIDER_RAND\n"); #endif rc = RAND_bytes((unsigned char *)buffer, length); #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND - sqlite3_mutex_leave(openssl_rand_mutex); + CODEC_TRACE_MUTEX("sqlcipher_openssl_random: leaving SQLCIPHER_MUTEX_PROVIDER_RAND\n"); + tdsqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER_RAND)); + CODEC_TRACE_MUTEX("sqlcipher_openssl_random: left SQLCIPHER_MUTEX_PROVIDER_RAND\n"); #endif return (rc == 1) ? SQLITE_OK : SQLITE_ERROR; } -static int sqlcipher_openssl_hmac(void *ctx, unsigned char *hmac_key, int key_sz, unsigned char *in, int in_sz, unsigned char *in2, int in2_sz, unsigned char *out) { +static int sqlcipher_openssl_hmac(void *ctx, int algorithm, unsigned char *hmac_key, int key_sz, unsigned char *in, int in_sz, unsigned char *in2, int in2_sz, unsigned char *out) { unsigned int outlen; - HMAC_CTX* hctx = HMAC_CTX_new(); - if(hctx == NULL) return SQLITE_ERROR; - HMAC_Init_ex(hctx, hmac_key, key_sz, EVP_sha1(), NULL); - HMAC_Update(hctx, in, in_sz); - HMAC_Update(hctx, in2, in2_sz); - HMAC_Final(hctx, out, &outlen); - HMAC_CTX_free(hctx); - return SQLITE_OK; + int rc = SQLITE_OK; + HMAC_CTX* hctx = NULL; + + if(in == NULL) goto error; + + hctx = HMAC_CTX_new(); + if(hctx == NULL) goto error; + + switch(algorithm) { + case SQLCIPHER_HMAC_SHA1: + if(!HMAC_Init_ex_(hctx, hmac_key, key_sz, EVP_sha1(), NULL)) goto error; + break; + case SQLCIPHER_HMAC_SHA256: + if(!HMAC_Init_ex_(hctx, hmac_key, key_sz, EVP_sha256(), NULL)) goto error; + break; + case SQLCIPHER_HMAC_SHA512: + if(!HMAC_Init_ex_(hctx, hmac_key, key_sz, EVP_sha512(), NULL)) goto error; + break; + default: + goto error; + } + + if(!HMAC_Update_(hctx, in, in_sz)) goto error; + if(in2 != NULL) { + if(!HMAC_Update_(hctx, in2, in2_sz)) goto error; + } + if(!HMAC_Final_(hctx, out, &outlen)) goto error; + + goto cleanup; +error: + rc = SQLITE_ERROR; +cleanup: + if(hctx) HMAC_CTX_free(hctx); + return rc; } -static int sqlcipher_openssl_kdf(void *ctx, const unsigned char *pass, int pass_sz, unsigned char* salt, int salt_sz, int workfactor, int key_sz, unsigned char *key) { - PKCS5_PBKDF2_HMAC_SHA1((const char *)pass, pass_sz, salt, salt_sz, workfactor, key_sz, key); - return SQLITE_OK; +static int sqlcipher_openssl_kdf(void *ctx, int algorithm, const unsigned char *pass, int pass_sz, unsigned char* salt, int salt_sz, int workfactor, int key_sz, unsigned char *key) { + int rc = SQLITE_OK; + +#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10000000L +// PKCS5_PBKDF2_HMAC was added in 856640b54f3d22a34d6565e9c78c441a15222577 and added to the header only in 777c47acbeecf9602cc465864c9f5f2c609c989d, +// so use PKCS5_PBKDF2_HMAC_SHA1 unconditionally if OpenSSL < 1.0.0 + if(!PKCS5_PBKDF2_HMAC_SHA1((const char *)pass, pass_sz, salt, salt_sz, workfactor, key_sz, key)) goto error; +#else + switch(algorithm) { + case SQLCIPHER_HMAC_SHA1: + if(!PKCS5_PBKDF2_HMAC((const char *)pass, pass_sz, salt, salt_sz, workfactor, EVP_sha1(), key_sz, key)) goto error; + break; + case SQLCIPHER_HMAC_SHA256: + if(!PKCS5_PBKDF2_HMAC((const char *)pass, pass_sz, salt, salt_sz, workfactor, EVP_sha256(), key_sz, key)) goto error; + break; + case SQLCIPHER_HMAC_SHA512: + if(!PKCS5_PBKDF2_HMAC((const char *)pass, pass_sz, salt, salt_sz, workfactor, EVP_sha512(), key_sz, key)) goto error; + break; + default: + return SQLITE_ERROR; + } +#endif + + goto cleanup; +error: + rc = SQLITE_ERROR; +cleanup: + return rc; } static int sqlcipher_openssl_cipher(void *ctx, int mode, unsigned char *key, int key_sz, unsigned char *iv, unsigned char *in, int in_sz, unsigned char *out) { - int tmp_csz, csz; + int tmp_csz, csz, rc = SQLITE_OK; EVP_CIPHER_CTX* ectx = EVP_CIPHER_CTX_new(); - if(ectx == NULL) return SQLITE_ERROR; - EVP_CipherInit_ex(ectx, ((openssl_ctx *)ctx)->evp_cipher, NULL, NULL, NULL, mode); - EVP_CIPHER_CTX_set_padding(ectx, 0); // no padding - EVP_CipherInit_ex(ectx, NULL, NULL, key, iv, mode); - EVP_CipherUpdate(ectx, out, &tmp_csz, in, in_sz); + if(ectx == NULL) goto error; + if(!EVP_CipherInit_ex(ectx, ((openssl_ctx *)ctx)->evp_cipher, NULL, NULL, NULL, mode)) goto error; + if(!EVP_CIPHER_CTX_set_padding(ectx, 0)) goto error; /* no padding */ + if(!EVP_CipherInit_ex(ectx, NULL, NULL, key, iv, mode)) goto error; + if(!EVP_CipherUpdate(ectx, out, &tmp_csz, in, in_sz)) goto error; csz = tmp_csz; out += tmp_csz; - EVP_CipherFinal_ex(ectx, out, &tmp_csz); + if(!EVP_CipherFinal_ex(ectx, out, &tmp_csz)) goto error; csz += tmp_csz; - EVP_CIPHER_CTX_free(ectx); assert(in_sz == csz); - return SQLITE_OK; -} -static int sqlcipher_openssl_set_cipher(void *ctx, const char *cipher_name) { - openssl_ctx *o_ctx = (openssl_ctx *)ctx; - EVP_CIPHER* cipher = (EVP_CIPHER *) EVP_get_cipherbyname(cipher_name); - if(cipher != NULL) { - o_ctx->evp_cipher = cipher; - } - return cipher != NULL ? SQLITE_OK : SQLITE_ERROR; + goto cleanup; +error: + rc = SQLITE_ERROR; +cleanup: + if(ectx) EVP_CIPHER_CTX_free(ectx); + return rc; } static const char* sqlcipher_openssl_get_cipher(void *ctx) { - return EVP_CIPHER_name(((openssl_ctx *)ctx)->evp_cipher); + return OBJ_nid2sn(EVP_CIPHER_nid(((openssl_ctx *)ctx)->evp_cipher)); } static int sqlcipher_openssl_get_key_sz(void *ctx) { @@ -20459,24 +24370,32 @@ static int sqlcipher_openssl_get_block_sz(void *ctx) { return EVP_CIPHER_block_size(((openssl_ctx *)ctx)->evp_cipher); } -static int sqlcipher_openssl_get_hmac_sz(void *ctx) { - return EVP_MD_size(EVP_sha1()); -} - -static int sqlcipher_openssl_ctx_copy(void *target_ctx, void *source_ctx) { - memcpy(target_ctx, source_ctx, sizeof(openssl_ctx)); - return SQLITE_OK; -} - -static int sqlcipher_openssl_ctx_cmp(void *c1, void *c2) { - return ((openssl_ctx *)c1)->evp_cipher == ((openssl_ctx *)c2)->evp_cipher; +static int sqlcipher_openssl_get_hmac_sz(void *ctx, int algorithm) { + switch(algorithm) { + case SQLCIPHER_HMAC_SHA1: + return EVP_MD_size(EVP_sha1()); + break; + case SQLCIPHER_HMAC_SHA256: + return EVP_MD_size(EVP_sha256()); + break; + case SQLCIPHER_HMAC_SHA512: + return EVP_MD_size(EVP_sha512()); + break; + default: + return 0; + } } static int sqlcipher_openssl_ctx_init(void **ctx) { + openssl_ctx *o_ctx; + *ctx = sqlcipher_malloc(sizeof(openssl_ctx)); if(*ctx == NULL) return SQLITE_NOMEM; sqlcipher_openssl_activate(*ctx); - return SQLITE_OK; + + o_ctx = (openssl_ctx *)*ctx; + o_ctx->evp_cipher = (EVP_CIPHER *) EVP_get_cipherbyname(OPENSSL_CIPHER); + return o_ctx->evp_cipher != NULL ? SQLITE_OK : SQLITE_ERROR; } static int sqlcipher_openssl_ctx_free(void **ctx) { @@ -20493,7 +24412,7 @@ static int sqlcipher_openssl_fips_status(void *ctx) { #endif } -int sqlcipher_openssl_setup(sqlcipher_provider *p) { +SQLITE_PRIVATE int sqlcipher_openssl_setup(sqlcipher_provider *p) { p->activate = sqlcipher_openssl_activate; p->deactivate = sqlcipher_openssl_deactivate; p->get_provider_name = sqlcipher_openssl_get_provider_name; @@ -20501,14 +24420,11 @@ int sqlcipher_openssl_setup(sqlcipher_provider *p) { p->hmac = sqlcipher_openssl_hmac; p->kdf = sqlcipher_openssl_kdf; p->cipher = sqlcipher_openssl_cipher; - p->set_cipher = sqlcipher_openssl_set_cipher; p->get_cipher = sqlcipher_openssl_get_cipher; p->get_key_sz = sqlcipher_openssl_get_key_sz; p->get_iv_sz = sqlcipher_openssl_get_iv_sz; p->get_block_sz = sqlcipher_openssl_get_block_sz; p->get_hmac_sz = sqlcipher_openssl_get_hmac_sz; - p->ctx_copy = sqlcipher_openssl_ctx_copy; - p->ctx_cmp = sqlcipher_openssl_ctx_cmp; p->ctx_init = sqlcipher_openssl_ctx_init; p->ctx_free = sqlcipher_openssl_ctx_free; p->add_random = sqlcipher_openssl_add_random; @@ -20517,180 +24433,44 @@ int sqlcipher_openssl_setup(sqlcipher_provider *p) { return SQLITE_OK; } -#endif -#endif -/* END SQLCIPHER */ - -/************** End of crypto_openssl.c **************************************/ -/************** Begin file crypto_cc.c ***************************************/ -/* -** SQLCipher -** http://sqlcipher.net -** -** Copyright (c) 2008 - 2013, ZETETIC LLC -** All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of the ZETETIC LLC nor the -** names of its contributors may be used to endorse or promote products -** derived from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY -** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY -** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -** -*/ -/* BEGIN SQLCIPHER */ -#ifdef SQLITE_HAS_CODEC -#ifdef SQLCIPHER_CRYPTO_CC -/* #include "crypto.h" */ -/* #include "sqlcipher.h" */ -#include <CommonCrypto/CommonCrypto.h> -#include <Security/SecRandom.h> -#include <CoreFoundation/CoreFoundation.h> - -static int sqlcipher_cc_add_random(void *ctx, void *buffer, int length) { - return SQLITE_OK; -} - -/* generate a defined number of random bytes */ -static int sqlcipher_cc_random (void *ctx, void *buffer, int length) { - return (SecRandomCopyBytes(kSecRandomDefault, length, (uint8_t *)buffer) == 0) ? SQLITE_OK : SQLITE_ERROR; -} - -static const char* sqlcipher_cc_get_provider_name(void *ctx) { - return "commoncrypto"; -} +void sqlcipher_activate() { + CODEC_TRACE_MUTEX("sqlcipher_activate: entering static master mutex\n"); + tdsqlite3_mutex_enter(tdsqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + CODEC_TRACE_MUTEX("sqlcipher_activate: entered static master mutex\n"); -static const char* sqlcipher_cc_get_provider_version(void *ctx) { -#if TARGET_OS_MAC - CFTypeRef version; - CFBundleRef bundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security")); - if(bundle == NULL) { - return "unknown"; + /* allocate new mutexes */ + if(sqlcipher_activate_count == 0) { + int i; + for(i = 0; i < SQLCIPHER_MUTEX_COUNT; i++) { + sqlcipher_static_mutex[i] = tdsqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + } } - version = CFBundleGetValueForInfoDictionaryKey(bundle, CFSTR("CFBundleShortVersionString")); - return CFStringGetCStringPtr(version, kCFStringEncodingUTF8); -#else - return "unknown"; -#endif -} - -static int sqlcipher_cc_hmac(void *ctx, unsigned char *hmac_key, int key_sz, unsigned char *in, int in_sz, unsigned char *in2, int in2_sz, unsigned char *out) { - CCHmacContext hmac_context; - CCHmacInit(&hmac_context, kCCHmacAlgSHA1, hmac_key, key_sz); - CCHmacUpdate(&hmac_context, in, in_sz); - CCHmacUpdate(&hmac_context, in2, in2_sz); - CCHmacFinal(&hmac_context, out); - return SQLITE_OK; -} - -static int sqlcipher_cc_kdf(void *ctx, const unsigned char *pass, int pass_sz, unsigned char* salt, int salt_sz, int workfactor, int key_sz, unsigned char *key) { - CCKeyDerivationPBKDF(kCCPBKDF2, (const char *)pass, pass_sz, salt, salt_sz, kCCPRFHmacAlgSHA1, workfactor, key, key_sz); - return SQLITE_OK; -} - -static int sqlcipher_cc_cipher(void *ctx, int mode, unsigned char *key, int key_sz, unsigned char *iv, unsigned char *in, int in_sz, unsigned char *out) { - CCCryptorRef cryptor; - size_t tmp_csz, csz; - CCOperation op = mode == CIPHER_ENCRYPT ? kCCEncrypt : kCCDecrypt; - - CCCryptorCreate(op, kCCAlgorithmAES128, 0, key, kCCKeySizeAES256, iv, &cryptor); - CCCryptorUpdate(cryptor, in, in_sz, out, in_sz, &tmp_csz); - csz = tmp_csz; - out += tmp_csz; - CCCryptorFinal(cryptor, out, in_sz - csz, &tmp_csz); - csz += tmp_csz; - CCCryptorRelease(cryptor); - assert(in_sz == csz); - - return SQLITE_OK; -} - -static int sqlcipher_cc_set_cipher(void *ctx, const char *cipher_name) { - return SQLITE_OK; -} - -static const char* sqlcipher_cc_get_cipher(void *ctx) { - return "aes-256-cbc"; -} -static int sqlcipher_cc_get_key_sz(void *ctx) { - return kCCKeySizeAES256; -} - -static int sqlcipher_cc_get_iv_sz(void *ctx) { - return kCCBlockSizeAES128; -} - -static int sqlcipher_cc_get_block_sz(void *ctx) { - return kCCBlockSizeAES128; -} - -static int sqlcipher_cc_get_hmac_sz(void *ctx) { - return CC_SHA1_DIGEST_LENGTH; -} - -static int sqlcipher_cc_ctx_copy(void *target_ctx, void *source_ctx) { - return SQLITE_OK; -} - -static int sqlcipher_cc_ctx_cmp(void *c1, void *c2) { - return 1; /* always indicate contexts are the same */ -} - -static int sqlcipher_cc_ctx_init(void **ctx) { - return SQLITE_OK; -} - -static int sqlcipher_cc_ctx_free(void **ctx) { - return SQLITE_OK; -} + /* check to see if there is a provider registered at this point + if there no provider registered at this point, register the + default provider */ + if(sqlcipher_get_provider() == NULL) { + sqlcipher_provider *p = sqlcipher_malloc(sizeof(sqlcipher_provider)); + sqlcipher_openssl_setup(p); + CODEC_TRACE("sqlcipher_activate: calling sqlcipher_register_provider(%p)\n", p); +#ifdef SQLCIPHER_EXT + sqlcipher_ext_provider_setup(p); +#endif + sqlcipher_register_provider(p); + CODEC_TRACE("sqlcipher_activate: called sqlcipher_register_provider(%p)\n",p); + } -static int sqlcipher_cc_fips_status(void *ctx) { - return 0; -} + sqlcipher_activate_count++; /* increment activation count */ -int sqlcipher_cc_setup(sqlcipher_provider *p) { - p->random = sqlcipher_cc_random; - p->get_provider_name = sqlcipher_cc_get_provider_name; - p->hmac = sqlcipher_cc_hmac; - p->kdf = sqlcipher_cc_kdf; - p->cipher = sqlcipher_cc_cipher; - p->set_cipher = sqlcipher_cc_set_cipher; - p->get_cipher = sqlcipher_cc_get_cipher; - p->get_key_sz = sqlcipher_cc_get_key_sz; - p->get_iv_sz = sqlcipher_cc_get_iv_sz; - p->get_block_sz = sqlcipher_cc_get_block_sz; - p->get_hmac_sz = sqlcipher_cc_get_hmac_sz; - p->ctx_copy = sqlcipher_cc_ctx_copy; - p->ctx_cmp = sqlcipher_cc_ctx_cmp; - p->ctx_init = sqlcipher_cc_ctx_init; - p->ctx_free = sqlcipher_cc_ctx_free; - p->add_random = sqlcipher_cc_add_random; - p->fips_status = sqlcipher_cc_fips_status; - p->get_provider_version = sqlcipher_cc_get_provider_version; - return SQLITE_OK; + CODEC_TRACE_MUTEX("sqlcipher_activate: leaving static master mutex\n"); + tdsqlite3_mutex_leave(tdsqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER)); + CODEC_TRACE_MUTEX("sqlcipher_activate: left static master mutex\n"); } #endif -#endif /* END SQLCIPHER */ -/************** End of crypto_cc.c *******************************************/ +/************** End of crypto_openssl.c **************************************/ /************** Begin file global.c ******************************************/ /* ** 2008 June 13 @@ -20715,7 +24495,7 @@ int sqlcipher_cc_setup(sqlcipher_provider *p) { ** handle case conversions for the UTF character set since the tables ** involved are nearly as big or bigger than SQLite itself. */ -SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = { +SQLITE_PRIVATE const unsigned char tdsqlite3UpperToLower[] = { #ifdef SQLITE_ASCII 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, @@ -20773,7 +24553,7 @@ SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = { ** ** (x & ~(map[x]&0x20)) ** -** The equivalent of tolower() is implemented using the sqlite3UpperToLower[] +** The equivalent of tolower() is implemented using the tdsqlite3UpperToLower[] ** array. tolower() is used more often than toupper() by SQLite. ** ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an @@ -20781,8 +24561,7 @@ SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = { ** non-ASCII UTF character. Hence the test for whether or not a character is ** part of an identifier is 0x46. */ -#ifdef SQLITE_ASCII -SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = { +SQLITE_PRIVATE const unsigned char tdsqlite3CtypeMap[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */ @@ -20819,7 +24598,6 @@ SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = { 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */ 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */ }; -#endif /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards ** compatibility for legacy applications, the URI filename capability is @@ -20831,17 +24609,31 @@ SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = { ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally ** disabled. The default value may be changed by compiling with the ** SQLITE_USE_URI symbol defined. +** +** URI filenames are enabled by default if SQLITE_HAS_CODEC is +** enabled. */ #ifndef SQLITE_USE_URI -# define SQLITE_USE_URI 0 +# ifdef SQLITE_HAS_CODEC +# define SQLITE_USE_URI 1 +# else +# define SQLITE_USE_URI 0 +# endif #endif /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if ** that compile-time option is omitted. */ -#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN +#if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN) # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1 +#else +# if !SQLITE_ALLOW_COVERING_INDEX_SCAN +# error "Compile-time disabling of covering index scan using the\ + -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\ + Contact SQLite developers if this is a problem for you, and\ + delete this #error macro to continue with your build." +# endif #endif /* The minimum PMA size is set to this value multiplied by the database @@ -20864,19 +24656,49 @@ SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = { #endif /* +** The default lookaside-configuration, the format "SZ,N". SZ is the +** number of bytes in each lookaside slot (should be a multiple of 8) +** and N is the number of slots. The lookaside-configuration can be +** changed as start-time using tdsqlite3_config(SQLITE_CONFIG_LOOKASIDE) +** or at run-time for an individual database connection using +** tdsqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE); +** +** With the two-size-lookaside enhancement, less lookaside is required. +** The default configuration of 1200,40 actually provides 30 1200-byte slots +** and 93 128-byte slots, which is more lookaside than is available +** using the older 1200,100 configuration without two-size-lookaside. +*/ +#ifndef SQLITE_DEFAULT_LOOKASIDE +# ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE +# define SQLITE_DEFAULT_LOOKASIDE 1200,100 /* 120KB of memory */ +# else +# define SQLITE_DEFAULT_LOOKASIDE 1200,40 /* 48KB of memory */ +# endif +#endif + + +/* The default maximum size of an in-memory database created using +** tdsqlite3_deserialize() +*/ +#ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE +# define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824 +#endif + +/* ** The following singleton contains the global configuration for ** the SQLite library. */ -SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = { +SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config tdsqlite3Config = { SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */ 1, /* bCoreMutex */ SQLITE_THREADSAFE==1, /* bFullMutex */ SQLITE_USE_URI, /* bOpenUri */ SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */ + 0, /* bSmallMalloc */ + 1, /* bExtraSchemaChecks */ 0x7ffffffe, /* mxStrlen */ 0, /* neverCorrupt */ - 128, /* szLookaside */ - 500, /* nLookaside */ + SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */ SQLITE_STMTJRNL_SPILL, /* nStmtSpill */ {0,0,0,0,0,0,0,0}, /* m */ {0,0,0,0,0,0,0,0,0}, /* mutex */ @@ -20886,9 +24708,6 @@ SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = { 0, 0, /* mnHeap, mxHeap */ SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */ SQLITE_MAX_MMAP_SIZE, /* mxMmap */ - (void*)0, /* pScratch */ - 0, /* szScratch */ - 0, /* nScratch */ (void*)0, /* pPage */ 0, /* szPage */ SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */ @@ -20913,11 +24732,16 @@ SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = { 0, /* xVdbeBranch */ 0, /* pVbeBranchArg */ #endif -#ifndef SQLITE_OMIT_BUILTIN_TEST +#ifdef SQLITE_ENABLE_DESERIALIZE + SQLITE_MEMDB_DEFAULT_MAXSIZE, /* mxMemdbSize */ +#endif +#ifndef SQLITE_UNTESTABLE 0, /* xTestCallback */ #endif 0, /* bLocaltimeFault */ - 0x7ffffffe /* iOnceResetThreshold */ + 0x7ffffffe, /* iOnceResetThreshold */ + SQLITE_DEFAULT_SORTERREF_SIZE, /* szSorterRef */ + 0, /* iPrngSeed */ }; /* @@ -20925,16 +24749,15 @@ SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = { ** database connections. After initialization, this table is ** read-only. */ -SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; +SQLITE_PRIVATE FuncDefHash tdsqlite3BuiltinFunctions; +#ifdef VDBE_PROFILE /* -** Constant tokens for values 0 and 1. +** The following performance counter can be used in place of +** tdsqlite3Hwtime() for profiling. This is a no-op on standard builds. */ -SQLITE_PRIVATE const Token sqlite3IntTokens[] = { - { "0", 1 }, - { "1", 1 } -}; - +SQLITE_PRIVATE tdsqlite3_uint64 tdsqlite3NProfileCnt = 0; +#endif /* ** The value of the "pending" byte must be 0x40000000 (1 byte past the @@ -20946,7 +24769,7 @@ SQLITE_PRIVATE const Token sqlite3IntTokens[] = { ** During testing, it is often desirable to move the pending byte to ** a different position in the file. This allows code that has to ** deal with the pending byte to run on files that are much smaller -** than 1 GiB. The sqlite3_test_control() interface can be used to +** than 1 GiB. The tdsqlite3_test_control() interface can be used to ** move the pending byte. ** ** IMPORTANT: Changing the pending byte to any value other than @@ -20955,7 +24778,7 @@ SQLITE_PRIVATE const Token sqlite3IntTokens[] = { ** and incorrect behavior. */ #ifndef SQLITE_OMIT_WSD -SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000; +SQLITE_PRIVATE int tdsqlite3PendingByte = 0x40000000; #endif /* #include "opcodes.h" */ @@ -20965,468 +24788,14 @@ SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000; ** from the comments following the "case OP_xxxx:" statements in ** the vdbe.c file. */ -SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER; +SQLITE_PRIVATE const unsigned char tdsqlite3OpcodeProperty[] = OPFLG_INITIALIZER; /* ** Name of the default collating sequence */ -SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY"; +SQLITE_PRIVATE const char tdsqlite3StrBINARY[] = "BINARY"; /************** End of global.c **********************************************/ -/************** Begin file ctime.c *******************************************/ -/* -** 2010 February 23 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file implements routines used to report what compile-time options -** SQLite was built with. -*/ - -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS - -/* #include "sqliteInt.h" */ - -/* -** An array of names of all compile-time options. This array should -** be sorted A-Z. -** -** This array looks large, but in a typical installation actually uses -** only a handful of compile-time options, so most times this array is usually -** rather short and uses little memory space. -*/ -static const char * const azCompileOpt[] = { - -/* These macros are provided to "stringify" the value of the define -** for those options in which the value is meaningful. */ -#define CTIMEOPT_VAL_(opt) #opt -#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) - -#if SQLITE_32BIT_ROWID - "32BIT_ROWID", -#endif -#if SQLITE_4_BYTE_ALIGNED_MALLOC - "4_BYTE_ALIGNED_MALLOC", -#endif -#if SQLITE_CASE_SENSITIVE_LIKE - "CASE_SENSITIVE_LIKE", -#endif -#if SQLITE_CHECK_PAGES - "CHECK_PAGES", -#endif -#if defined(__clang__) && defined(__clang_major__) - "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "." - CTIMEOPT_VAL(__clang_minor__) "." - CTIMEOPT_VAL(__clang_patchlevel__), -#elif defined(_MSC_VER) - "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER), -#elif defined(__GNUC__) && defined(__VERSION__) - "COMPILER=gcc-" __VERSION__, -#endif -#if SQLITE_COVERAGE_TEST - "COVERAGE_TEST", -#endif -#if SQLITE_DEBUG - "DEBUG", -#endif -#if SQLITE_DEFAULT_LOCKING_MODE - "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), -#endif -#if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc) - "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE), -#endif -#if SQLITE_DISABLE_DIRSYNC - "DISABLE_DIRSYNC", -#endif -#if SQLITE_DISABLE_LFS - "DISABLE_LFS", -#endif -#if SQLITE_ENABLE_8_3_NAMES - "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES), -#endif -#if SQLITE_ENABLE_API_ARMOR - "ENABLE_API_ARMOR", -#endif -#if SQLITE_ENABLE_ATOMIC_WRITE - "ENABLE_ATOMIC_WRITE", -#endif -#if SQLITE_ENABLE_CEROD - "ENABLE_CEROD", -#endif -#if SQLITE_ENABLE_COLUMN_METADATA - "ENABLE_COLUMN_METADATA", -#endif -#if SQLITE_ENABLE_DBSTAT_VTAB - "ENABLE_DBSTAT_VTAB", -#endif -#if SQLITE_ENABLE_EXPENSIVE_ASSERT - "ENABLE_EXPENSIVE_ASSERT", -#endif -#if SQLITE_ENABLE_FTS1 - "ENABLE_FTS1", -#endif -#if SQLITE_ENABLE_FTS2 - "ENABLE_FTS2", -#endif -#if SQLITE_ENABLE_FTS3 - "ENABLE_FTS3", -#endif -#if SQLITE_ENABLE_FTS3_PARENTHESIS - "ENABLE_FTS3_PARENTHESIS", -#endif -#if SQLITE_ENABLE_FTS4 - "ENABLE_FTS4", -#endif -#if SQLITE_ENABLE_FTS5 - "ENABLE_FTS5", -#endif -#if SQLITE_ENABLE_ICU - "ENABLE_ICU", -#endif -#if SQLITE_ENABLE_IOTRACE - "ENABLE_IOTRACE", -#endif -#if SQLITE_ENABLE_JSON1 - "ENABLE_JSON1", -#endif -#if SQLITE_ENABLE_LOAD_EXTENSION - "ENABLE_LOAD_EXTENSION", -#endif -#if SQLITE_ENABLE_LOCKING_STYLE - "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), -#endif -#if SQLITE_ENABLE_MEMORY_MANAGEMENT - "ENABLE_MEMORY_MANAGEMENT", -#endif -#if SQLITE_ENABLE_MEMSYS3 - "ENABLE_MEMSYS3", -#endif -#if SQLITE_ENABLE_MEMSYS5 - "ENABLE_MEMSYS5", -#endif -#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK - "ENABLE_OVERSIZE_CELL_CHECK", -#endif -#if SQLITE_ENABLE_RTREE - "ENABLE_RTREE", -#endif -#if defined(SQLITE_ENABLE_STAT4) - "ENABLE_STAT4", -#elif defined(SQLITE_ENABLE_STAT3) - "ENABLE_STAT3", -#endif -#if SQLITE_ENABLE_UNLOCK_NOTIFY - "ENABLE_UNLOCK_NOTIFY", -#endif -#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT - "ENABLE_UPDATE_DELETE_LIMIT", -#endif -#if SQLITE_HAS_CODEC - "HAS_CODEC", -#endif -#if HAVE_ISNAN || SQLITE_HAVE_ISNAN - "HAVE_ISNAN", -#endif -#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX - "HOMEGROWN_RECURSIVE_MUTEX", -#endif -#if SQLITE_IGNORE_AFP_LOCK_ERRORS - "IGNORE_AFP_LOCK_ERRORS", -#endif -#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS - "IGNORE_FLOCK_LOCK_ERRORS", -#endif -#ifdef SQLITE_INT64_TYPE - "INT64_TYPE", -#endif -#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS - "LIKE_DOESNT_MATCH_BLOBS", -#endif -#if SQLITE_LOCK_TRACE - "LOCK_TRACE", -#endif -#if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc) - "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE), -#endif -#ifdef SQLITE_MAX_SCHEMA_RETRY - "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY), -#endif -#if SQLITE_MEMDEBUG - "MEMDEBUG", -#endif -#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT - "MIXED_ENDIAN_64BIT_FLOAT", -#endif -#if SQLITE_NO_SYNC - "NO_SYNC", -#endif -#if SQLITE_OMIT_ALTERTABLE - "OMIT_ALTERTABLE", -#endif -#if SQLITE_OMIT_ANALYZE - "OMIT_ANALYZE", -#endif -#if SQLITE_OMIT_ATTACH - "OMIT_ATTACH", -#endif -#if SQLITE_OMIT_AUTHORIZATION - "OMIT_AUTHORIZATION", -#endif -#if SQLITE_OMIT_AUTOINCREMENT - "OMIT_AUTOINCREMENT", -#endif -#if SQLITE_OMIT_AUTOINIT - "OMIT_AUTOINIT", -#endif -#if SQLITE_OMIT_AUTOMATIC_INDEX - "OMIT_AUTOMATIC_INDEX", -#endif -#if SQLITE_OMIT_AUTORESET - "OMIT_AUTORESET", -#endif -#if SQLITE_OMIT_AUTOVACUUM - "OMIT_AUTOVACUUM", -#endif -#if SQLITE_OMIT_BETWEEN_OPTIMIZATION - "OMIT_BETWEEN_OPTIMIZATION", -#endif -#if SQLITE_OMIT_BLOB_LITERAL - "OMIT_BLOB_LITERAL", -#endif -#if SQLITE_OMIT_BTREECOUNT - "OMIT_BTREECOUNT", -#endif -#if SQLITE_OMIT_BUILTIN_TEST - "OMIT_BUILTIN_TEST", -#endif -#if SQLITE_OMIT_CAST - "OMIT_CAST", -#endif -#if SQLITE_OMIT_CHECK - "OMIT_CHECK", -#endif -#if SQLITE_OMIT_COMPLETE - "OMIT_COMPLETE", -#endif -#if SQLITE_OMIT_COMPOUND_SELECT - "OMIT_COMPOUND_SELECT", -#endif -#if SQLITE_OMIT_CTE - "OMIT_CTE", -#endif -#if SQLITE_OMIT_DATETIME_FUNCS - "OMIT_DATETIME_FUNCS", -#endif -#if SQLITE_OMIT_DECLTYPE - "OMIT_DECLTYPE", -#endif -#if SQLITE_OMIT_DEPRECATED - "OMIT_DEPRECATED", -#endif -#if SQLITE_OMIT_DISKIO - "OMIT_DISKIO", -#endif -#if SQLITE_OMIT_EXPLAIN - "OMIT_EXPLAIN", -#endif -#if SQLITE_OMIT_FLAG_PRAGMAS - "OMIT_FLAG_PRAGMAS", -#endif -#if SQLITE_OMIT_FLOATING_POINT - "OMIT_FLOATING_POINT", -#endif -#if SQLITE_OMIT_FOREIGN_KEY - "OMIT_FOREIGN_KEY", -#endif -#if SQLITE_OMIT_GET_TABLE - "OMIT_GET_TABLE", -#endif -#if SQLITE_OMIT_INCRBLOB - "OMIT_INCRBLOB", -#endif -#if SQLITE_OMIT_INTEGRITY_CHECK - "OMIT_INTEGRITY_CHECK", -#endif -#if SQLITE_OMIT_LIKE_OPTIMIZATION - "OMIT_LIKE_OPTIMIZATION", -#endif -#if SQLITE_OMIT_LOAD_EXTENSION - "OMIT_LOAD_EXTENSION", -#endif -#if SQLITE_OMIT_LOCALTIME - "OMIT_LOCALTIME", -#endif -#if SQLITE_OMIT_LOOKASIDE - "OMIT_LOOKASIDE", -#endif -#if SQLITE_OMIT_MEMORYDB - "OMIT_MEMORYDB", -#endif -#if SQLITE_OMIT_OR_OPTIMIZATION - "OMIT_OR_OPTIMIZATION", -#endif -#if SQLITE_OMIT_PAGER_PRAGMAS - "OMIT_PAGER_PRAGMAS", -#endif -#if SQLITE_OMIT_PRAGMA - "OMIT_PRAGMA", -#endif -#if SQLITE_OMIT_PROGRESS_CALLBACK - "OMIT_PROGRESS_CALLBACK", -#endif -#if SQLITE_OMIT_QUICKBALANCE - "OMIT_QUICKBALANCE", -#endif -#if SQLITE_OMIT_REINDEX - "OMIT_REINDEX", -#endif -#if SQLITE_OMIT_SCHEMA_PRAGMAS - "OMIT_SCHEMA_PRAGMAS", -#endif -#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS - "OMIT_SCHEMA_VERSION_PRAGMAS", -#endif -#if SQLITE_OMIT_SHARED_CACHE - "OMIT_SHARED_CACHE", -#endif -#if SQLITE_OMIT_SUBQUERY - "OMIT_SUBQUERY", -#endif -#if SQLITE_OMIT_TCL_VARIABLE - "OMIT_TCL_VARIABLE", -#endif -#if SQLITE_OMIT_TEMPDB - "OMIT_TEMPDB", -#endif -#if SQLITE_OMIT_TRACE - "OMIT_TRACE", -#endif -#if SQLITE_OMIT_TRIGGER - "OMIT_TRIGGER", -#endif -#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION - "OMIT_TRUNCATE_OPTIMIZATION", -#endif -#if SQLITE_OMIT_UTF16 - "OMIT_UTF16", -#endif -#if SQLITE_OMIT_VACUUM - "OMIT_VACUUM", -#endif -#if SQLITE_OMIT_VIEW - "OMIT_VIEW", -#endif -#if SQLITE_OMIT_VIRTUALTABLE - "OMIT_VIRTUALTABLE", -#endif -#if SQLITE_OMIT_WAL - "OMIT_WAL", -#endif -#if SQLITE_OMIT_WSD - "OMIT_WSD", -#endif -#if SQLITE_OMIT_XFER_OPT - "OMIT_XFER_OPT", -#endif -#if SQLITE_PERFORMANCE_TRACE - "PERFORMANCE_TRACE", -#endif -#if SQLITE_PROXY_DEBUG - "PROXY_DEBUG", -#endif -#if SQLITE_RTREE_INT_ONLY - "RTREE_INT_ONLY", -#endif -#if SQLITE_SECURE_DELETE - "SECURE_DELETE", -#endif -#if SQLITE_SMALL_STACK - "SMALL_STACK", -#endif -#if SQLITE_SOUNDEX - "SOUNDEX", -#endif -#if SQLITE_SYSTEM_MALLOC - "SYSTEM_MALLOC", -#endif -#if SQLITE_TCL - "TCL", -#endif -#if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc) - "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE), -#endif -#if SQLITE_TEST - "TEST", -#endif -#if defined(SQLITE_THREADSAFE) - "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE), -#endif -#if SQLITE_USE_ALLOCA - "USE_ALLOCA", -#endif -#if SQLITE_USER_AUTHENTICATION - "USER_AUTHENTICATION", -#endif -#if SQLITE_WIN32_MALLOC - "WIN32_MALLOC", -#endif -#if SQLITE_ZERO_MALLOC - "ZERO_MALLOC" -#endif -}; - -/* -** Given the name of a compile-time option, return true if that option -** was used and false if not. -** -** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix -** is not required for a match. -*/ -SQLITE_API int sqlite3_compileoption_used(const char *zOptName){ - int i, n; - -#if SQLITE_ENABLE_API_ARMOR - if( zOptName==0 ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7; - n = sqlite3Strlen30(zOptName); - - /* Since ArraySize(azCompileOpt) is normally in single digits, a - ** linear search is adequate. No need for a binary search. */ - for(i=0; i<ArraySize(azCompileOpt); i++){ - if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0 - && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0 - ){ - return 1; - } - } - return 0; -} - -/* -** Return the N-th compile-time option string. If N is out of range, -** return a NULL pointer. -*/ -SQLITE_API const char *sqlite3_compileoption_get(int N){ - if( N>=0 && N<ArraySize(azCompileOpt) ){ - return azCompileOpt[N]; - } - return 0; -} - -#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ - -/************** End of ctime.c ***********************************************/ /************** Begin file status.c ******************************************/ /* ** 2008 June 18 @@ -21440,7 +24809,7 @@ SQLITE_API const char *sqlite3_compileoption_get(int N){ ** ************************************************************************* ** -** This module implements the sqlite3_status() interface and related +** This module implements the tdsqlite3_status() interface and related ** functionality. */ /* #include "sqliteInt.h" */ @@ -21521,57 +24890,61 @@ typedef struct AuxData AuxData; */ typedef struct VdbeCursor VdbeCursor; struct VdbeCursor { - u8 eCurType; /* One of the CURTYPE_* values above */ - i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */ - u8 nullRow; /* True if pointing to a row with no data */ - u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ - u8 isTable; /* True for rowid tables. False for indexes */ + u8 eCurType; /* One of the CURTYPE_* values above */ + i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */ + u8 nullRow; /* True if pointing to a row with no data */ + u8 deferredMoveto; /* A call to tdsqlite3BtreeMoveto() is needed */ + u8 isTable; /* True for rowid tables. False for indexes */ #ifdef SQLITE_DEBUG - u8 seekOp; /* Most recent seek operation on this cursor */ - u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */ -#endif - Bool isEphemeral:1; /* True for an ephemeral table */ - Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */ - Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */ - Pgno pgnoRoot; /* Root page of the open btree cursor */ - i16 nField; /* Number of fields in the header */ - u16 nHdrParsed; /* Number of header fields parsed so far */ + u8 seekOp; /* Most recent seek operation on this cursor */ + u8 wrFlag; /* The wrFlag argument to tdsqlite3BtreeCursor() */ +#endif + Bool isEphemeral:1; /* True for an ephemeral table */ + Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */ + Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */ + Bool seekHit:1; /* See the OP_SeekHit and OP_IfNoHope opcodes */ + Btree *pBtx; /* Separate file holding temporary table */ + i64 seqCount; /* Sequence counter */ + int *aAltMap; /* Mapping from table to index column numbers */ + + /* Cached OP_Column parse information is only valid if cacheStatus matches + ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of + ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that + ** the cache is out of date. */ + u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ + int seekResult; /* Result of previous tdsqlite3BtreeMoveto() or 0 + ** if there have been no prior seeks on the cursor. */ + /* seekResult does not distinguish between "no seeks have ever occurred + ** on this cursor" and "the most recent seek was an exact match". + ** For CURTYPE_PSEUDO, seekResult is the register holding the record */ + + /* When a new VdbeCursor is allocated, only the fields above are zeroed. + ** The fields that follow are uninitialized, and must be individually + ** initialized prior to first use. */ + VdbeCursor *pAltCursor; /* Associated index cursor from which to read */ union { - BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */ - sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */ - int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */ - VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */ + BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */ + tdsqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */ + VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */ } uc; - Btree *pBt; /* Separate file holding temporary table */ - KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */ - int seekResult; /* Result of previous sqlite3BtreeMoveto() */ - i64 seqCount; /* Sequence counter */ - i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ - VdbeCursor *pAltCursor; /* Associated index cursor from which to read */ - int *aAltMap; /* Mapping from table to index column numbers */ + KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */ + u32 iHdrOffset; /* Offset to next unparsed byte of the header */ + Pgno pgnoRoot; /* Root page of the open btree cursor */ + i16 nField; /* Number of fields in the header */ + u16 nHdrParsed; /* Number of header fields parsed so far */ + i64 movetoTarget; /* Argument to the deferred tdsqlite3BtreeMoveto() */ + u32 *aOffset; /* Pointer to aType[nField] */ + const u8 *aRow; /* Data for the current row, if all on one page */ + u32 payloadSize; /* Total number of bytes in the record */ + u32 szRow; /* Byte available in aRow */ #ifdef SQLITE_ENABLE_COLUMN_USED_MASK - u64 maskUsed; /* Mask of columns used by this cursor */ + u64 maskUsed; /* Mask of columns used by this cursor */ #endif - /* Cached information about the header for the data record that the - ** cursor is currently pointing to. Only valid if cacheStatus matches - ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of - ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that - ** the cache is out of date. - ** - ** aRow might point to (ephemeral) data for the current row, or it might - ** be NULL. - */ - u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ - u32 payloadSize; /* Total number of bytes in the record */ - u32 szRow; /* Byte available in aRow */ - u32 iHdrOffset; /* Offset to next unparsed byte of the header */ - const u8 *aRow; /* Data for the current row, if all on one page */ - u32 *aOffset; /* Pointer to aType[nField] */ - u32 aType[1]; /* Type values for all entries in the record */ /* 2*nField extra array elements allocated for aType[], beyond the one ** static element declared in the structure. nField total array slots for ** aType[] and nField+1 array slots for aOffset[] */ + u32 aType[1]; /* Type values record decode. MUST BE LAST */ }; @@ -21595,7 +24968,7 @@ struct VdbeCursor { ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing ** this instead of deleting the VdbeFrame immediately is to avoid recursive -** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the +** calls to tdsqlite3VdbeMemRelease() when the memory cells belonging to the ** child frame are released. ** ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is @@ -21609,9 +24982,13 @@ struct VdbeFrame { i64 *anExec; /* Event counters from parent frame */ Mem *aMem; /* Array of memory cells for parent frame */ VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */ + u8 *aOnce; /* Bitmask used by OP_Once */ void *token; /* Copy of SubProgram.token */ i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ AuxData *pAuxData; /* Linked list of auxdata allocations */ +#if SQLITE_DEBUG + u32 iFrameMagic; /* magic number for sanity checking */ +#endif int nCursor; /* Number of entries in apCsr */ int pc; /* Program Counter in parent (calling) frame */ int nOp; /* Size of aOp array */ @@ -21622,6 +24999,13 @@ struct VdbeFrame { int nDbChange; /* Value of db->nChange */ }; +/* Magic number for sanity checking on VdbeFrame objects */ +#define SQLITE_FRAME_MAGIC 0x879fb71e + +/* +** Return a pointer to the array of registers allocated for use +** by a VdbeFrame. +*/ #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))]) /* @@ -21629,14 +25013,13 @@ struct VdbeFrame { ** structures. Each Mem struct may cache multiple representations (string, ** integer etc.) of the same value. */ -struct Mem { +struct tdsqlite3_value { union MemValue { double r; /* Real value used when MEM_Real is set in flags */ i64 i; /* Integer value used when MEM_Int is set in flags */ - int nZero; /* Used when bit MEM_Zero is set in flags */ + int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */ + const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */ FuncDef *pDef; /* Used only when flags==MEM_Agg */ - RowSet *pRowSet; /* Used only when flags==MEM_RowSet */ - VdbeFrame *pFrame; /* Used when flags==MEM_Frame */ } u; u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ @@ -21647,11 +25030,11 @@ struct Mem { char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */ int szMalloc; /* Size of the zMalloc allocation */ u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */ - sqlite3 *db; /* The associated database connection */ + tdsqlite3 *db; /* The associated database connection */ void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */ #ifdef SQLITE_DEBUG Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */ - void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */ + u16 mScopyFlags; /* flags value immediately after the shallow copy */ #endif }; @@ -21665,7 +25048,8 @@ struct Mem { ** representations of the value stored in the Mem struct. ** ** If the MEM_Null flag is set, then the value is an SQL NULL value. -** No other flags may be set in this case. +** For a pointer type created using tdsqlite3_bind_pointer() or +** tdsqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set. ** ** If the MEM_Str flag is set then Mem.z points at a string representation. ** Usually this is encoded in the same unicode encoding as the main @@ -21673,17 +25057,17 @@ struct Mem { ** set, then the string is nul terminated. The MEM_Int and MEM_Real ** flags may coexist with the MEM_Str flag. */ -#define MEM_Null 0x0001 /* Value is NULL */ +#define MEM_Null 0x0001 /* Value is NULL (or a pointer) */ #define MEM_Str 0x0002 /* Value is a string */ #define MEM_Int 0x0004 /* Value is an integer */ #define MEM_Real 0x0008 /* Value is a real number */ #define MEM_Blob 0x0010 /* Value is a BLOB */ -#define MEM_AffMask 0x001f /* Mask of affinity bits */ -#define MEM_RowSet 0x0020 /* Value is a RowSet object */ -#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */ +#define MEM_IntReal 0x0020 /* MEM_Int that stringifies like MEM_Real */ +#define MEM_AffMask 0x003f /* Mask of affinity bits */ +#define MEM_FromBind 0x0040 /* Value originates from tdsqlite3_bind() */ #define MEM_Undefined 0x0080 /* Value is undefined */ #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */ -#define MEM_TypeMask 0x81ff /* Mask of type bits */ +#define MEM_TypeMask 0xc1bf /* Mask of type bits */ /* Whenever Mem contains a valid string or blob representation, one of @@ -21691,7 +25075,7 @@ struct Mem { ** policy for Mem.z. The MEM_Term flag tells us whether or not the ** string is \000 or \u0000 terminated */ -#define MEM_Term 0x0200 /* String rep is nul terminated */ +#define MEM_Term 0x0200 /* String in Mem.z is zero terminated */ #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */ #define MEM_Static 0x0800 /* Mem.z points to a static string */ #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */ @@ -21707,7 +25091,7 @@ struct Mem { ** that needs to be deallocated to avoid a leak. */ #define VdbeMemDynamic(X) \ - (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0) + (((X)->flags&(MEM_Agg|MEM_Dyn))!=0) /* ** Clear any existing type flags from a Mem and replace them with f @@ -21716,6 +25100,13 @@ struct Mem { ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f) /* +** True if Mem X is a NULL-nochng type. +*/ +#define MemNullNochng(X) \ + (((X)->flags&MEM_TypeMask)==(MEM_Null|MEM_Zero) \ + && (X)->n==0 && (X)->u.nZero==0) + +/* ** Return true if a memory cell is not marked as invalid. This macro ** is for use inside assert() statements only. */ @@ -21725,17 +25116,17 @@ struct Mem { /* ** Each auxiliary data pointer stored by a user defined function -** implementation calling sqlite3_set_auxdata() is stored in an instance +** implementation calling tdsqlite3_set_auxdata() is stored in an instance ** of this structure. All such structures associated with a single VM ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed ** when the VM is halted (if not before). */ struct AuxData { - int iOp; /* Instruction number of OP_Function opcode */ - int iArg; /* Index of function argument. */ + int iAuxOp; /* Instruction number of OP_Function opcode */ + int iAuxArg; /* Index of function argument. */ void *pAux; /* Aux data pointer */ - void (*xDelete)(void *); /* Destructor for the aux data */ - AuxData *pNext; /* Next element in list */ + void (*xDeleteAux)(void*); /* Destructor for the aux data */ + AuxData *pNextAux; /* Next element in list */ }; /* @@ -21751,7 +25142,7 @@ struct AuxData { ** This structure is defined inside of vdbeInt.h because it uses substructures ** (Mem) which are only defined there. */ -struct sqlite3_context { +struct tdsqlite3_context { Mem *pOut; /* The return value is stored here */ FuncDef *pFunc; /* Pointer to function information */ Mem *pMem; /* Memory cell used to store aggregate context */ @@ -21759,9 +25150,8 @@ struct sqlite3_context { int iOp; /* Instruction number of OP_Function */ int isError; /* Error code returned by the function. */ u8 skipFlag; /* Skip accumulator loading if true */ - u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */ u8 argc; /* Number of arguments */ - sqlite3_value *argv[1]; /* Argument set */ + tdsqlite3_value *argv[1]; /* Argument set */ }; /* A bitfield type for use inside of structures. Always follow with :N where @@ -21769,6 +25159,9 @@ struct sqlite3_context { */ typedef unsigned bft; /* Bit Field Type */ +/* The ScanStatus object holds a single value for the +** tdsqlite3_stmt_scanstatus() interface. +*/ typedef struct ScanStatus ScanStatus; struct ScanStatus { int addrExplain; /* OP_Explain for loop */ @@ -21779,19 +25172,31 @@ struct ScanStatus { char *zName; /* Name of table or index */ }; +/* The DblquoteStr object holds the text of a double-quoted +** string for a prepared statement. A linked list of these objects +** is constructed during statement parsing and is held on Vdbe.pDblStr. +** When computing a normalized SQL statement for an SQL statement, that +** list is consulted for each double-quoted identifier to see if the +** identifier should really be a string literal. +*/ +typedef struct DblquoteStr DblquoteStr; +struct DblquoteStr { + DblquoteStr *pNextStr; /* Next string literal in the list */ + char z[8]; /* Dequoted value for the string */ +}; + /* ** An instance of the virtual machine. This structure contains the complete ** state of the virtual machine. ** -** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare() +** The "tdsqlite3_stmt" structure pointer that is returned by tdsqlite3_prepare() ** is really a pointer to an instance of this structure. */ struct Vdbe { - sqlite3 *db; /* The database connection that owns this statement */ + tdsqlite3 *db; /* The database connection that owns this statement */ Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */ Parse *pParse; /* Parsing context used to create this Vdbe */ ynVar nVar; /* Number of entries in aVar[] */ - ynVar nzVar; /* Number of entries in azVar[] */ u32 magic; /* Magic number for sanity checking */ int nMem; /* Number of memory locations currently allocated */ int nCursor; /* Number of slots in apCsr[] */ @@ -21799,47 +25204,53 @@ struct Vdbe { int pc; /* The program counter */ int rc; /* Value to return */ int nChange; /* Number of db changes made since last reset */ - int iStatement; /* Statement number (or 0 if has not opened stmt) */ + int iStatement; /* Statement number (or 0 if has no opened stmt) */ i64 iCurrentTime; /* Value of julianday('now') for this statement */ i64 nFkConstraint; /* Number of imm. FK constraints this VM */ i64 nStmtDefCons; /* Number of def. constraints when stmt started */ i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */ + Mem *aMem; /* The memory locations */ + Mem **apArg; /* Arguments to currently executing user function */ + VdbeCursor **apCsr; /* One element of this array for each open cursor */ + Mem *aVar; /* Values for the OP_Variable opcode. */ /* When allocating a new Vdbe object, all of the fields below should be ** initialized to zero or NULL */ Op *aOp; /* Space to hold the virtual machine's program */ - Mem *aMem; /* The memory locations */ - Mem **apArg; /* Arguments to currently executing user function */ + int nOp; /* Number of instructions in the program */ + int nOpAlloc; /* Slots allocated for aOp[] */ Mem *aColName; /* Column names to return */ Mem *pResultSet; /* Pointer to an array of results */ char *zErrMsg; /* Error message written here */ - VdbeCursor **apCsr; /* One element of this array for each open cursor */ - Mem *aVar; /* Values for the OP_Variable opcode. */ - char **azVar; /* Name of variables */ + VList *pVList; /* Name of variables */ #ifndef SQLITE_OMIT_TRACE i64 startTime; /* Time when query started - used for profiling */ #endif - int nOp; /* Number of instructions in the program */ #ifdef SQLITE_DEBUG - int rcApp; /* errcode set by sqlite3_result_error_code() */ + int rcApp; /* errcode set by tdsqlite3_result_error_code() */ + u32 nWrite; /* Number of write operations that have occurred */ #endif u16 nResColumn; /* Number of columns in one row of the result set */ u8 errorAction; /* Recovery action to do in case of an error */ u8 minWriteFileFormat; /* Minimum file format for writable database files */ - bft expired:1; /* True if the VM needs to be recompiled */ - bft doingRerun:1; /* True if rerunning after an auto-reprepare */ + u8 prepFlags; /* SQLITE_PREPARE_* flags */ + bft expired:2; /* 1: recompile VM immediately 2: when convenient */ bft explain:2; /* True if EXPLAIN present on SQL command */ + bft doingRerun:1; /* True if rerunning after an auto-reprepare */ bft changeCntOn:1; /* True to update the change-counter */ bft runOnlyOnce:1; /* Automatically expire on reset */ bft usesStmtJournal:1; /* True if uses a statement journal */ bft readOnly:1; /* True for statements that do not write */ bft bIsReader:1; /* True for statements that read */ - bft isPrepareV2:1; /* True if prepared with prepare_v2() */ yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */ yDbMask lockMask; /* Subset of btreeMask that requires a lock */ - u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */ + u32 aCounter[7]; /* Counters used by tdsqlite3_stmt_status() */ char *zSql; /* Text of the SQL statement that generated this */ +#ifdef SQLITE_ENABLE_NORMALIZE + char *zNormSql; /* Normalization of the associated SQL statement */ + DblquoteStr *pDblStr; /* List of double-quoted string literals */ +#endif void *pFree; /* Free this when deleting the vdbe */ VdbeFrame *pFrame; /* Parent frame */ VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */ @@ -21850,7 +25261,7 @@ struct Vdbe { #ifdef SQLITE_ENABLE_STMT_SCANSTATUS i64 *anExec; /* Number of times each op has been executed */ int nScan; /* Entries in aScan[] */ - ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */ + ScanStatus *aScan; /* Scan definitions for tdsqlite3_stmt_scanstatus() */ #endif }; @@ -21865,7 +25276,7 @@ struct Vdbe { /* ** Structure used to store the context required by the -** sqlite3_preupdate_*() API functions. +** tdsqlite3_preupdate_*() API functions. */ struct PreUpdate { Vdbe *v; @@ -21880,116 +25291,140 @@ struct PreUpdate { i64 iKey2; /* Second key value passed to hook */ Mem *aNew; /* Array of new.* values */ Table *pTab; /* Schema object being upated */ + Index *pPk; /* PK index if pTab is WITHOUT ROWID */ }; /* ** Function prototypes */ -SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...); -SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); +SQLITE_PRIVATE void tdsqlite3VdbeError(Vdbe*, const char *, ...); +SQLITE_PRIVATE void tdsqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); void sqliteVdbePopStack(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*); -SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*); -#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) -SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*); -#endif -SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32); -SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8); -SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*); -SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32); -SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); -SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int); +SQLITE_PRIVATE int SQLITE_NOINLINE tdsqlite3VdbeFinishMoveto(VdbeCursor*); +SQLITE_PRIVATE int tdsqlite3VdbeCursorMoveto(VdbeCursor**, int*); +SQLITE_PRIVATE int tdsqlite3VdbeCursorRestore(VdbeCursor*); +SQLITE_PRIVATE u32 tdsqlite3VdbeSerialTypeLen(u32); +SQLITE_PRIVATE u8 tdsqlite3VdbeOneByteSerialTypeLen(u8); +SQLITE_PRIVATE u32 tdsqlite3VdbeSerialPut(unsigned char*, Mem*, u32); +SQLITE_PRIVATE u32 tdsqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); +SQLITE_PRIVATE void tdsqlite3VdbeDeleteAuxData(tdsqlite3*, AuxData**, int, int); int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); -SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*); -SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*); -SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*); -SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*); -SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*); -SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int); -SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*); -SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); -SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); -SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64); +SQLITE_PRIVATE int tdsqlite3VdbeIdxKeyCompare(tdsqlite3*,VdbeCursor*,UnpackedRecord*,int*); +SQLITE_PRIVATE int tdsqlite3VdbeIdxRowid(tdsqlite3*, BtCursor*, i64*); +SQLITE_PRIVATE int tdsqlite3VdbeExec(Vdbe*); +#ifndef SQLITE_OMIT_EXPLAIN +SQLITE_PRIVATE int tdsqlite3VdbeList(Vdbe*); +#endif +SQLITE_PRIVATE int tdsqlite3VdbeHalt(Vdbe*); +SQLITE_PRIVATE int tdsqlite3VdbeChangeEncoding(Mem *, int); +SQLITE_PRIVATE int tdsqlite3VdbeMemTooBig(Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeMemCopy(Mem*, const Mem*); +SQLITE_PRIVATE void tdsqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); +SQLITE_PRIVATE void tdsqlite3VdbeMemMove(Mem*, Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeMemNulTerminate(Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); +SQLITE_PRIVATE void tdsqlite3VdbeMemSetInt64(Mem*, i64); #ifdef SQLITE_OMIT_FLOATING_POINT -# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 -#else -SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double); -#endif -SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16); -SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*); -SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int); -SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8); -SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*); -SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*); -SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*); -SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8); -SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*); -SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p); -SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*); -SQLITE_PRIVATE const char *sqlite3OpcodeName(int); -SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve); -SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n); -SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int); -SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); -SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *); +# define tdsqlite3VdbeMemSetDouble tdsqlite3VdbeMemSetInt64 +#else +SQLITE_PRIVATE void tdsqlite3VdbeMemSetDouble(Mem*, double); +#endif +SQLITE_PRIVATE void tdsqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*)); +SQLITE_PRIVATE void tdsqlite3VdbeMemInit(Mem*,tdsqlite3*,u16); +SQLITE_PRIVATE void tdsqlite3VdbeMemSetNull(Mem*); +SQLITE_PRIVATE void tdsqlite3VdbeMemSetZeroBlob(Mem*,int); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int tdsqlite3VdbeMemIsRowSet(const Mem*); +#endif +SQLITE_PRIVATE int tdsqlite3VdbeMemSetRowSet(Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeMemMakeWriteable(Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeMemStringify(Mem*, u8, u8); +SQLITE_PRIVATE i64 tdsqlite3VdbeIntValue(Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeMemIntegerify(Mem*); +SQLITE_PRIVATE double tdsqlite3VdbeRealValue(Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeBooleanValue(Mem*, int ifNull); +SQLITE_PRIVATE void tdsqlite3VdbeIntegerAffinity(Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeMemRealify(Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeMemNumerify(Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeMemCast(Mem*,u8,u8); +SQLITE_PRIVATE int tdsqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*); +SQLITE_PRIVATE void tdsqlite3VdbeMemRelease(Mem *p); +SQLITE_PRIVATE int tdsqlite3VdbeMemFinalize(Mem*, FuncDef*); +#ifndef SQLITE_OMIT_WINDOWFUNC +SQLITE_PRIVATE int tdsqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*); +#endif +#ifndef SQLITE_OMIT_EXPLAIN +SQLITE_PRIVATE const char *tdsqlite3OpcodeName(int); +#endif +SQLITE_PRIVATE int tdsqlite3VdbeMemGrow(Mem *pMem, int n, int preserve); +SQLITE_PRIVATE int tdsqlite3VdbeMemClearAndResize(Mem *pMem, int n); +SQLITE_PRIVATE int tdsqlite3VdbeCloseStatement(Vdbe *, int); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int tdsqlite3VdbeFrameIsValid(VdbeFrame*); +#endif +SQLITE_PRIVATE void tdsqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */ +SQLITE_PRIVATE void tdsqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */ +SQLITE_PRIVATE int tdsqlite3VdbeFrameRestore(VdbeFrame *); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK -SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int); +SQLITE_PRIVATE void tdsqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int); #endif -SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p); +SQLITE_PRIVATE int tdsqlite3VdbeTransferError(Vdbe *p); -SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *); -SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *); -SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *); -SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *); -SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *); -SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *); -SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *); -SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *); +SQLITE_PRIVATE int tdsqlite3VdbeSorterInit(tdsqlite3 *, int, VdbeCursor *); +SQLITE_PRIVATE void tdsqlite3VdbeSorterReset(tdsqlite3 *, VdbeSorter *); +SQLITE_PRIVATE void tdsqlite3VdbeSorterClose(tdsqlite3 *, VdbeCursor *); +SQLITE_PRIVATE int tdsqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *); +SQLITE_PRIVATE int tdsqlite3VdbeSorterNext(tdsqlite3 *, const VdbeCursor *); +SQLITE_PRIVATE int tdsqlite3VdbeSorterRewind(const VdbeCursor *, int *); +SQLITE_PRIVATE int tdsqlite3VdbeSorterWrite(const VdbeCursor *, Mem *); +SQLITE_PRIVATE int tdsqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *); + +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE void tdsqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*); +SQLITE_PRIVATE void tdsqlite3VdbeAssertAbortable(Vdbe*); +#else +# define tdsqlite3VdbeIncrWriteCounter(V,C) +# define tdsqlite3VdbeAssertAbortable(V) +#endif #if !defined(SQLITE_OMIT_SHARED_CACHE) -SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeEnter(Vdbe*); #else -# define sqlite3VdbeEnter(X) +# define tdsqlite3VdbeEnter(X) #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 -SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeLeave(Vdbe*); #else -# define sqlite3VdbeLeave(X) +# define tdsqlite3VdbeLeave(X) #endif #ifdef SQLITE_DEBUG -SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*); -SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*); +SQLITE_PRIVATE void tdsqlite3VdbeMemAboutToChange(Vdbe*,Mem*); +SQLITE_PRIVATE int tdsqlite3VdbeCheckMemInvariants(Mem*); #endif #ifndef SQLITE_OMIT_FOREIGN_KEY -SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int); +SQLITE_PRIVATE int tdsqlite3VdbeCheckFk(Vdbe *, int); #else -# define sqlite3VdbeCheckFk(p,i) 0 +# define tdsqlite3VdbeCheckFk(p,i) 0 #endif -SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8); #ifdef SQLITE_DEBUG -SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf); +SQLITE_PRIVATE void tdsqlite3VdbePrintSql(Vdbe*); +SQLITE_PRIVATE void tdsqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr); +#endif +#ifndef SQLITE_OMIT_UTF16 +SQLITE_PRIVATE int tdsqlite3VdbeMemTranslate(Mem*, u8); +SQLITE_PRIVATE int tdsqlite3VdbeMemHandleBom(Mem *pMem); #endif -SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem); #ifndef SQLITE_OMIT_INCRBLOB -SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *); - #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0) +SQLITE_PRIVATE int tdsqlite3VdbeMemExpandBlob(Mem *); + #define ExpandBlob(P) (((P)->flags&MEM_Zero)?tdsqlite3VdbeMemExpandBlob(P):0) #else - #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK + #define tdsqlite3VdbeMemExpandBlob(x) SQLITE_OK #define ExpandBlob(P) SQLITE_OK #endif @@ -22002,18 +25437,18 @@ SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *); ** Variables in which to record status information. */ #if SQLITE_PTRSIZE>4 -typedef sqlite3_int64 sqlite3StatValueType; +typedef tdsqlite3_int64 tdsqlite3StatValueType; #else -typedef u32 sqlite3StatValueType; +typedef u32 tdsqlite3StatValueType; #endif -typedef struct sqlite3StatType sqlite3StatType; -static SQLITE_WSD struct sqlite3StatType { - sqlite3StatValueType nowValue[10]; /* Current value */ - sqlite3StatValueType mxValue[10]; /* Maximum value */ -} sqlite3Stat = { {0,}, {0,} }; +typedef struct tdsqlite3StatType tdsqlite3StatType; +static SQLITE_WSD struct tdsqlite3StatType { + tdsqlite3StatValueType nowValue[10]; /* Current value */ + tdsqlite3StatValueType mxValue[10]; /* Maximum value */ +} tdsqlite3Stat = { {0,}, {0,} }; /* -** Elements of sqlite3Stat[] are protected by either the memory allocator +** Elements of tdsqlite3Stat[] are protected by either the memory allocator ** mutex, or by the pcache1 mutex. The following array determines which. */ static const char statMutex[] = { @@ -22034,26 +25469,26 @@ static const char statMutex[] = { ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly -** to the "sqlite3Stat" state vector declared above. +** to the "tdsqlite3Stat" state vector declared above. */ #ifdef SQLITE_OMIT_WSD -# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat) +# define wsdStatInit tdsqlite3StatType *x = &GLOBAL(tdsqlite3StatType,tdsqlite3Stat) # define wsdStat x[0] #else # define wsdStatInit -# define wsdStat sqlite3Stat +# define wsdStat tdsqlite3Stat #endif /* ** Return the current value of a status parameter. The caller must ** be holding the appropriate mutex. */ -SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){ +SQLITE_PRIVATE tdsqlite3_int64 tdsqlite3StatusValue(int op){ wsdStatInit; assert( op>=0 && op<ArraySize(wsdStat.nowValue) ); assert( op>=0 && op<ArraySize(statMutex) ); - assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex() - : sqlite3MallocMutex()) ); + assert( tdsqlite3_mutex_held(statMutex[op] ? tdsqlite3Pcache1Mutex() + : tdsqlite3MallocMutex()) ); return wsdStat.nowValue[op]; } @@ -22068,23 +25503,23 @@ SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){ ** The StatusDown() routine lowers the current value by N. The highwater ** mark is unchanged. N must be non-negative for StatusDown(). */ -SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){ +SQLITE_PRIVATE void tdsqlite3StatusUp(int op, int N){ wsdStatInit; assert( op>=0 && op<ArraySize(wsdStat.nowValue) ); assert( op>=0 && op<ArraySize(statMutex) ); - assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex() - : sqlite3MallocMutex()) ); + assert( tdsqlite3_mutex_held(statMutex[op] ? tdsqlite3Pcache1Mutex() + : tdsqlite3MallocMutex()) ); wsdStat.nowValue[op] += N; if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){ wsdStat.mxValue[op] = wsdStat.nowValue[op]; } } -SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){ +SQLITE_PRIVATE void tdsqlite3StatusDown(int op, int N){ wsdStatInit; assert( N>=0 ); assert( op>=0 && op<ArraySize(statMutex) ); - assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex() - : sqlite3MallocMutex()) ); + assert( tdsqlite3_mutex_held(statMutex[op] ? tdsqlite3Pcache1Mutex() + : tdsqlite3MallocMutex()) ); assert( op>=0 && op<ArraySize(wsdStat.nowValue) ); wsdStat.nowValue[op] -= N; } @@ -22093,18 +25528,17 @@ SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){ ** Adjust the highwater mark if necessary. ** The caller must hold the appropriate mutex. */ -SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){ - sqlite3StatValueType newValue; +SQLITE_PRIVATE void tdsqlite3StatusHighwater(int op, int X){ + tdsqlite3StatValueType newValue; wsdStatInit; assert( X>=0 ); - newValue = (sqlite3StatValueType)X; + newValue = (tdsqlite3StatValueType)X; assert( op>=0 && op<ArraySize(wsdStat.nowValue) ); assert( op>=0 && op<ArraySize(statMutex) ); - assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex() - : sqlite3MallocMutex()) ); + assert( tdsqlite3_mutex_held(statMutex[op] ? tdsqlite3Pcache1Mutex() + : tdsqlite3MallocMutex()) ); assert( op==SQLITE_STATUS_MALLOC_SIZE || op==SQLITE_STATUS_PAGECACHE_SIZE - || op==SQLITE_STATUS_SCRATCH_SIZE || op==SQLITE_STATUS_PARSER_STACK ); if( newValue>wsdStat.mxValue[op] ){ wsdStat.mxValue[op] = newValue; @@ -22114,13 +25548,13 @@ SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){ /* ** Query status information. */ -SQLITE_API int sqlite3_status64( +SQLITE_API int tdsqlite3_status64( int op, - sqlite3_int64 *pCurrent, - sqlite3_int64 *pHighwater, + tdsqlite3_int64 *pCurrent, + tdsqlite3_int64 *pHighwater, int resetFlag ){ - sqlite3_mutex *pMutex; + tdsqlite3_mutex *pMutex; wsdStatInit; if( op<0 || op>=ArraySize(wsdStat.nowValue) ){ return SQLITE_MISUSE_BKPT; @@ -22128,24 +25562,24 @@ SQLITE_API int sqlite3_status64( #ifdef SQLITE_ENABLE_API_ARMOR if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT; #endif - pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex(); - sqlite3_mutex_enter(pMutex); + pMutex = statMutex[op] ? tdsqlite3Pcache1Mutex() : tdsqlite3MallocMutex(); + tdsqlite3_mutex_enter(pMutex); *pCurrent = wsdStat.nowValue[op]; *pHighwater = wsdStat.mxValue[op]; if( resetFlag ){ wsdStat.mxValue[op] = wsdStat.nowValue[op]; } - sqlite3_mutex_leave(pMutex); + tdsqlite3_mutex_leave(pMutex); (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */ return SQLITE_OK; } -SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){ - sqlite3_int64 iCur = 0, iHwtr = 0; +SQLITE_API int tdsqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){ + tdsqlite3_int64 iCur = 0, iHwtr = 0; int rc; #ifdef SQLITE_ENABLE_API_ARMOR if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT; #endif - rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag); + rc = tdsqlite3_status64(op, &iCur, &iHwtr, resetFlag); if( rc==0 ){ *pCurrent = (int)iCur; *pHighwater = (int)iHwtr; @@ -22154,10 +25588,36 @@ SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetF } /* +** Return the number of LookasideSlot elements on the linked list +*/ +static u32 countLookasideSlots(LookasideSlot *p){ + u32 cnt = 0; + while( p ){ + p = p->pNext; + cnt++; + } + return cnt; +} + +/* +** Count the number of slots of lookaside memory that are outstanding +*/ +SQLITE_PRIVATE int tdsqlite3LookasideUsed(tdsqlite3 *db, int *pHighwater){ + u32 nInit = countLookasideSlots(db->lookaside.pInit); + u32 nFree = countLookasideSlots(db->lookaside.pFree); +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + nInit += countLookasideSlots(db->lookaside.pSmallInit); + nFree += countLookasideSlots(db->lookaside.pSmallFree); +#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ + if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit; + return db->lookaside.nSlot - (nInit+nFree); +} + +/* ** Query status information for a single database connection */ -SQLITE_API int sqlite3_db_status( - sqlite3 *db, /* The database connection whose status is desired */ +SQLITE_API int tdsqlite3_db_status( + tdsqlite3 *db, /* The database connection whose status is desired */ int op, /* Status verb */ int *pCurrent, /* Write current value here */ int *pHighwater, /* Write high-water mark here */ @@ -22165,17 +25625,31 @@ SQLITE_API int sqlite3_db_status( ){ int rc = SQLITE_OK; /* Return code */ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){ + if( !tdsqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){ return SQLITE_MISUSE_BKPT; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); switch( op ){ case SQLITE_DBSTATUS_LOOKASIDE_USED: { - *pCurrent = db->lookaside.nOut; - *pHighwater = db->lookaside.mxOut; + *pCurrent = tdsqlite3LookasideUsed(db, pHighwater); if( resetFlag ){ - db->lookaside.mxOut = db->lookaside.nOut; + LookasideSlot *p = db->lookaside.pFree; + if( p ){ + while( p->pNext ) p = p->pNext; + p->pNext = db->lookaside.pInit; + db->lookaside.pInit = db->lookaside.pFree; + db->lookaside.pFree = 0; + } +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + p = db->lookaside.pSmallFree; + if( p ){ + while( p->pNext ) p = p->pNext; + p->pNext = db->lookaside.pSmallInit; + db->lookaside.pSmallInit = db->lookaside.pSmallFree; + db->lookaside.pSmallFree = 0; + } +#endif } break; } @@ -22205,19 +25679,19 @@ SQLITE_API int sqlite3_db_status( case SQLITE_DBSTATUS_CACHE_USED: { int totalUsed = 0; int i; - sqlite3BtreeEnterAll(db); + tdsqlite3BtreeEnterAll(db); for(i=0; i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ - Pager *pPager = sqlite3BtreePager(pBt); - int nByte = sqlite3PagerMemUsed(pPager); + Pager *pPager = tdsqlite3BtreePager(pBt); + int nByte = tdsqlite3PagerMemUsed(pPager); if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){ - nByte = nByte / sqlite3BtreeConnectionCount(pBt); + nByte = nByte / tdsqlite3BtreeConnectionCount(pBt); } totalUsed += nByte; } } - sqlite3BtreeLeaveAll(db); + tdsqlite3BtreeLeaveAll(db); *pCurrent = totalUsed; *pHighwater = 0; break; @@ -22232,34 +25706,34 @@ SQLITE_API int sqlite3_db_status( int i; /* Used to iterate through schemas */ int nByte = 0; /* Used to accumulate return value */ - sqlite3BtreeEnterAll(db); + tdsqlite3BtreeEnterAll(db); db->pnBytesFreed = &nByte; for(i=0; i<db->nDb; i++){ Schema *pSchema = db->aDb[i].pSchema; if( ALWAYS(pSchema!=0) ){ HashElem *p; - nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * ( + nByte += tdsqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * ( pSchema->tblHash.count + pSchema->trigHash.count + pSchema->idxHash.count + pSchema->fkeyHash.count ); - nByte += sqlite3_msize(pSchema->tblHash.ht); - nByte += sqlite3_msize(pSchema->trigHash.ht); - nByte += sqlite3_msize(pSchema->idxHash.ht); - nByte += sqlite3_msize(pSchema->fkeyHash.ht); + nByte += tdsqlite3_msize(pSchema->tblHash.ht); + nByte += tdsqlite3_msize(pSchema->trigHash.ht); + nByte += tdsqlite3_msize(pSchema->idxHash.ht); + nByte += tdsqlite3_msize(pSchema->fkeyHash.ht); for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){ - sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p)); + tdsqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p)); } for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ - sqlite3DeleteTable(db, (Table *)sqliteHashData(p)); + tdsqlite3DeleteTable(db, (Table *)sqliteHashData(p)); } } } db->pnBytesFreed = 0; - sqlite3BtreeLeaveAll(db); + tdsqlite3BtreeLeaveAll(db); *pHighwater = 0; *pCurrent = nByte; @@ -22277,8 +25751,8 @@ SQLITE_API int sqlite3_db_status( db->pnBytesFreed = &nByte; for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){ - sqlite3VdbeClearObject(db, pVdbe); - sqlite3DbFree(db, pVdbe); + tdsqlite3VdbeClearObject(db, pVdbe); + tdsqlite3DbFree(db, pVdbe); } db->pnBytesFreed = 0; @@ -22293,6 +25767,9 @@ SQLITE_API int sqlite3_db_status( ** pagers the database handle is connected to. *pHighwater is always set ** to zero. */ + case SQLITE_DBSTATUS_CACHE_SPILL: + op = SQLITE_DBSTATUS_CACHE_WRITE+1; + /* Fall through into the next case */ case SQLITE_DBSTATUS_CACHE_HIT: case SQLITE_DBSTATUS_CACHE_MISS: case SQLITE_DBSTATUS_CACHE_WRITE:{ @@ -22303,8 +25780,8 @@ SQLITE_API int sqlite3_db_status( for(i=0; i<db->nDb; i++){ if( db->aDb[i].pBt ){ - Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt); - sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet); + Pager *pPager = tdsqlite3BtreePager(db->aDb[i].pBt); + tdsqlite3PagerCacheStat(pPager, op, resetFlag, &nRet); } } *pHighwater = 0; /* IMP: R-42420-56072 */ @@ -22328,7 +25805,7 @@ SQLITE_API int sqlite3_db_status( rc = SQLITE_ERROR; } } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -22349,7 +25826,7 @@ SQLITE_API int sqlite3_db_status( ** functions for SQLite. ** ** There is only one exported symbol in this file - the function -** sqlite3RegisterDateTimeFunctions() found at the bottom of the file. +** tdsqlite3RegisterDateTimeFunctions() found at the bottom of the file. ** All other code has file scope. ** ** SQLite processes all times and dates as julian day numbers. The @@ -22375,7 +25852,7 @@ SQLITE_API int sqlite3_db_status( ** ** Jean Meeus ** Astronomical Algorithms, 2nd Edition, 1998 -** ISBM 0-943396-61-1 +** ISBN 0-943396-61-1 ** Willmann-Bell, Inc ** Richmond, Virginia (USA) */ @@ -22401,16 +25878,18 @@ struct tm *__cdecl localtime(const time_t *); */ typedef struct DateTime DateTime; struct DateTime { - sqlite3_int64 iJD; /* The julian day number times 86400000 */ - int Y, M, D; /* Year, month, and day */ - int h, m; /* Hour and minutes */ - int tz; /* Timezone offset in minutes */ - double s; /* Seconds */ - char validYMD; /* True (1) if Y,M,D are valid */ - char validHMS; /* True (1) if h,m,s are valid */ - char validJD; /* True (1) if iJD is valid */ - char validTZ; /* True (1) if tz is valid */ - char tzSet; /* Timezone was set explicitly */ + tdsqlite3_int64 iJD; /* The julian day number times 86400000 */ + int Y, M, D; /* Year, month, and day */ + int h, m; /* Hour and minutes */ + int tz; /* Timezone offset in minutes */ + double s; /* Seconds */ + char validJD; /* True (1) if iJD is valid */ + char rawS; /* Raw numeric value stored in s */ + char validYMD; /* True (1) if Y,M,D are valid */ + char validHMS; /* True (1) if h,m,s are valid */ + char validTZ; /* True (1) if tz is valid */ + char tzSet; /* Timezone was set explicitly */ + char isError; /* An overflow has occurred */ }; @@ -22460,7 +25939,7 @@ static int getDigits(const char *zDate, const char *zFormat, ...){ nextC = zFormat[3]; val = 0; while( N-- ){ - if( !sqlite3Isdigit(*zDate) ){ + if( !tdsqlite3Isdigit(*zDate) ){ goto end_getDigits; } val = val*10 + *zDate - '0'; @@ -22499,7 +25978,7 @@ static int parseTimezone(const char *zDate, DateTime *p){ int sgn = 0; int nHr, nMn; int c; - while( sqlite3Isspace(*zDate) ){ zDate++; } + while( tdsqlite3Isspace(*zDate) ){ zDate++; } p->tz = 0; c = *zDate; if( c=='-' ){ @@ -22519,7 +25998,7 @@ static int parseTimezone(const char *zDate, DateTime *p){ zDate += 5; p->tz = sgn*(nMn + nHr*60); zulu_time: - while( sqlite3Isspace(*zDate) ){ zDate++; } + while( tdsqlite3Isspace(*zDate) ){ zDate++; } p->tzSet = 1; return *zDate!=0; } @@ -22544,10 +26023,10 @@ static int parseHhMmSs(const char *zDate, DateTime *p){ return 1; } zDate += 2; - if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){ + if( *zDate=='.' && tdsqlite3Isdigit(zDate[1]) ){ double rScale = 1.0; zDate++; - while( sqlite3Isdigit(*zDate) ){ + while( tdsqlite3Isdigit(*zDate) ){ ms = ms*10.0 + *zDate - '0'; rScale *= 10.0; zDate++; @@ -22558,6 +26037,7 @@ static int parseHhMmSs(const char *zDate, DateTime *p){ s = 0; } p->validJD = 0; + p->rawS = 0; p->validHMS = 1; p->h = h; p->m = m; @@ -22568,6 +26048,14 @@ static int parseHhMmSs(const char *zDate, DateTime *p){ } /* +** Put the DateTime object into its error state. +*/ +static void datetimeError(DateTime *p){ + memset(p, 0, sizeof(*p)); + p->isError = 1; +} + +/* ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume ** that the YYYY-MM-DD is according to the Gregorian calendar. ** @@ -22586,6 +26074,10 @@ static void computeJD(DateTime *p){ M = 1; D = 1; } + if( Y<-4713 || Y>9999 || p->rawS ){ + datetimeError(p); + return; + } if( M<=2 ){ Y--; M += 12; @@ -22594,10 +26086,10 @@ static void computeJD(DateTime *p){ B = 2 - A + (A/4); X1 = 36525*(Y+4716)/100; X2 = 306001*(M+1)/10000; - p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000); + p->iJD = (tdsqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000); p->validJD = 1; if( p->validHMS ){ - p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000); + p->iJD += p->h*3600000 + p->m*60000 + (tdsqlite3_int64)(p->s*1000); if( p->validTZ ){ p->iJD -= p->tz*60000; p->validYMD = 0; @@ -22632,7 +26124,7 @@ static int parseYyyyMmDd(const char *zDate, DateTime *p){ return 1; } zDate += 10; - while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; } + while( tdsqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; } if( parseHhMmSs(zDate, p)==0 ){ /* We got the time */ }else if( *zDate==0 ){ @@ -22656,8 +26148,8 @@ static int parseYyyyMmDd(const char *zDate, DateTime *p){ ** ** Return the number of errors. */ -static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){ - p->iJD = sqlite3StmtCurrentTime(context); +static int setDateTimeToCurrent(tdsqlite3_context *context, DateTime *p){ + p->iJD = tdsqlite3StmtCurrentTime(context); if( p->iJD>0 ){ p->validJD = 1; return 0; @@ -22667,6 +26159,21 @@ static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){ } /* +** Input "r" is a numeric quantity which might be a julian day number, +** or the number of seconds since 1970. If the value if r is within +** range of a julian day number, install it as such and set validJD. +** If the value is a valid unix timestamp, put it in p->s and set p->rawS. +*/ +static void setRawDateNumber(DateTime *p, double r){ + p->s = r; + p->rawS = 1; + if( r>=0.0 && r<5373484.5 ){ + p->iJD = (tdsqlite3_int64)(r*86400000.0 + 0.5); + p->validJD = 1; + } +} + +/* ** Attempt to parse the given string into a julian day number. Return ** the number of errors. ** @@ -22683,7 +26190,7 @@ static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){ ** as there is a year and date. */ static int parseDateOrTime( - sqlite3_context *context, + tdsqlite3_context *context, const char *zDate, DateTime *p ){ @@ -22692,16 +26199,33 @@ static int parseDateOrTime( return 0; }else if( parseHhMmSs(zDate, p)==0 ){ return 0; - }else if( sqlite3StrICmp(zDate,"now")==0){ + }else if( tdsqlite3StrICmp(zDate,"now")==0 && tdsqlite3NotPureFunc(context) ){ return setDateTimeToCurrent(context, p); - }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){ - p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5); - p->validJD = 1; + }else if( tdsqlite3AtoF(zDate, &r, tdsqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){ + setRawDateNumber(p, r); return 0; } return 1; } +/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999. +** Multiplying this by 86400000 gives 464269060799999 as the maximum value +** for DateTime.iJD. +** +** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with +** such a large integer literal, so we have to encode it. +*/ +#define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff) + +/* +** Return TRUE if the given julian day number is within range. +** +** The input is the JulianDay times 86400000. +*/ +static int validJulianDay(tdsqlite3_int64 iJD){ + return iJD>=0 && iJD<=INT_464269060799999; +} + /* ** Compute the Year, Month, and Day from the julian day number. */ @@ -22712,6 +26236,9 @@ static void computeYMD(DateTime *p){ p->Y = 2000; p->M = 1; p->D = 1; + }else if( !validJulianDay(p->iJD) ){ + datetimeError(p); + return; }else{ Z = (int)((p->iJD + 43200000)/86400000); A = (int)((Z - 1867216.25)/36524.25); @@ -22743,6 +26270,7 @@ static void computeHMS(DateTime *p){ s -= p->h*3600; p->m = s/60; p->s += s - p->m*60; + p->rawS = 0; p->validHMS = 1; } @@ -22788,7 +26316,7 @@ static void clearYMD_HMS_TZ(DateTime *p){ ** is available. This routine returns 0 on success and ** non-zero on any kind of error. ** -** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this +** If the tdsqlite3GlobalConfig.bLocaltimeFault variable is true then this ** routine will always fail. ** ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C @@ -22800,19 +26328,19 @@ static int osLocaltime(time_t *t, struct tm *pTm){ #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S struct tm *pX; #if SQLITE_THREADSAFE>0 - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); + tdsqlite3_mutex *mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif - sqlite3_mutex_enter(mutex); + tdsqlite3_mutex_enter(mutex); pX = localtime(t); -#ifndef SQLITE_OMIT_BUILTIN_TEST - if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0; +#ifndef SQLITE_UNTESTABLE + if( tdsqlite3GlobalConfig.bLocaltimeFault ) pX = 0; #endif if( pX ) *pTm = *pX; - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); rc = pX==0; #else -#ifndef SQLITE_OMIT_BUILTIN_TEST - if( sqlite3GlobalConfig.bLocaltimeFault ) return 1; +#ifndef SQLITE_UNTESTABLE + if( tdsqlite3GlobalConfig.bLocaltimeFault ) return 1; #endif #if HAVE_LOCALTIME_R rc = localtime_r(t, pTm)==0; @@ -22834,9 +26362,9 @@ static int osLocaltime(time_t *t, struct tm *pTm){ ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value ** is undefined in this case. */ -static sqlite3_int64 localtimeOffset( +static tdsqlite3_int64 localtimeOffset( DateTime *p, /* Date at which to calculate offset */ - sqlite3_context *pCtx, /* Write error here if one occurs */ + tdsqlite3_context *pCtx, /* Write error here if one occurs */ int *pRc /* OUT: Error code. SQLITE_OK or ERROR */ ){ DateTime x, y; @@ -22869,7 +26397,7 @@ static sqlite3_int64 localtimeOffset( computeJD(&x); t = (time_t)(x.iJD/1000 - 21086676*(i64)10000); if( osLocaltime(&t, &sLocal) ){ - sqlite3_result_error(pCtx, "local time unavailable", -1); + tdsqlite3_result_error(pCtx, "local time unavailable", -1); *pRc = SQLITE_ERROR; return 0; } @@ -22882,7 +26410,9 @@ static sqlite3_int64 localtimeOffset( y.validYMD = 1; y.validHMS = 1; y.validJD = 0; + y.rawS = 0; y.validTZ = 0; + y.isError = 0; computeJD(&y); *pRc = SQLITE_OK; return y.iJD - x.iJD; @@ -22890,6 +26420,29 @@ static sqlite3_int64 localtimeOffset( #endif /* SQLITE_OMIT_LOCALTIME */ /* +** The following table defines various date transformations of the form +** +** 'NNN days' +** +** Where NNN is an arbitrary floating-point number and "days" can be one +** of several units of time. +*/ +static const struct { + u8 eType; /* Transformation type code */ + u8 nName; /* Length of th name */ + char *zName; /* Name of the transformation */ + double rLimit; /* Maximum NNN value for this transform */ + double rXform; /* Constant used for this transform */ +} aXformType[] = { + { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) }, + { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) }, + { 0, 4, "hour", 128963628.0, 86400000.0/24.0 }, + { 0, 3, "day", 5373485.0, 86400000.0 }, + { 1, 5, "month", 176546.0, 30.0*86400000.0 }, + { 2, 4, "year", 14713.0, 365.0*86400000.0 }, +}; + +/* ** Process a modifier to a date-time stamp. The modifiers are ** as follows: ** @@ -22913,17 +26466,15 @@ static sqlite3_int64 localtimeOffset( ** to context pCtx. If the error is an unrecognized modifier, no error is ** written to pCtx. */ -static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ +static int parseModifier( + tdsqlite3_context *pCtx, /* Function context */ + const char *z, /* The text of the modifier */ + int n, /* Length of zMod in bytes */ + DateTime *p /* The date/time value to be modified */ +){ int rc = 1; - int n; double r; - char *z, zBuf[30]; - z = zBuf; - for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){ - z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]]; - } - z[n] = 0; - switch( z[0] ){ + switch(tdsqlite3UpperToLower[(u8)z[0]] ){ #ifndef SQLITE_OMIT_LOCALTIME case 'l': { /* localtime @@ -22931,7 +26482,7 @@ static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ ** Assuming the current time value is UTC (a.k.a. GMT), shift it to ** show local time. */ - if( strcmp(z, "localtime")==0 ){ + if( tdsqlite3_stricmp(z, "localtime")==0 && tdsqlite3NotPureFunc(pCtx) ){ computeJD(p); p->iJD += localtimeOffset(p, pCtx, &rc); clearYMD_HMS_TZ(p); @@ -22943,18 +26494,23 @@ static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ /* ** unixepoch ** - ** Treat the current value of p->iJD as the number of + ** Treat the current value of p->s as the number of ** seconds since 1970. Convert to a real julian day number. */ - if( strcmp(z, "unixepoch")==0 && p->validJD ){ - p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000; - clearYMD_HMS_TZ(p); - rc = 0; + if( tdsqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){ + r = p->s*1000.0 + 210866760000000.0; + if( r>=0.0 && r<464269060800000.0 ){ + clearYMD_HMS_TZ(p); + p->iJD = (tdsqlite3_int64)(r + 0.5); + p->validJD = 1; + p->rawS = 0; + rc = 0; + } } #ifndef SQLITE_OMIT_LOCALTIME - else if( strcmp(z, "utc")==0 ){ + else if( tdsqlite3_stricmp(z, "utc")==0 && tdsqlite3NotPureFunc(pCtx) ){ if( p->tzSet==0 ){ - sqlite3_int64 c1; + tdsqlite3_int64 c1; computeJD(p); c1 = localtimeOffset(p, pCtx, &rc); if( rc==SQLITE_OK ){ @@ -22978,10 +26534,10 @@ static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ ** weekday N where 0==Sunday, 1==Monday, and so forth. If the ** date is already on the appropriate weekday, this is a no-op. */ - if( strncmp(z, "weekday ", 8)==0 - && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8) + if( tdsqlite3_strnicmp(z, "weekday ", 8)==0 + && tdsqlite3AtoF(&z[8], &r, tdsqlite3Strlen30(&z[8]), SQLITE_UTF8)>0 && (n=(int)r)==r && n>=0 && r<7 ){ - sqlite3_int64 Z; + tdsqlite3_int64 Z; computeYMD_HMS(p); p->validTZ = 0; p->validJD = 0; @@ -23001,23 +26557,24 @@ static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ ** Move the date backwards to the beginning of the current day, ** or month or year. */ - if( strncmp(z, "start of ", 9)!=0 ) break; + if( tdsqlite3_strnicmp(z, "start of ", 9)!=0 ) break; + if( !p->validJD && !p->validYMD && !p->validHMS ) break; z += 9; computeYMD(p); p->validHMS = 1; p->h = p->m = 0; p->s = 0.0; + p->rawS = 0; p->validTZ = 0; p->validJD = 0; - if( strcmp(z,"month")==0 ){ + if( tdsqlite3_stricmp(z,"month")==0 ){ p->D = 1; rc = 0; - }else if( strcmp(z,"year")==0 ){ - computeYMD(p); + }else if( tdsqlite3_stricmp(z,"year")==0 ){ p->M = 1; p->D = 1; rc = 0; - }else if( strcmp(z,"day")==0 ){ + }else if( tdsqlite3_stricmp(z,"day")==0 ){ rc = 0; } break; @@ -23035,8 +26592,9 @@ static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ case '8': case '9': { double rRounder; - for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){} - if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){ + int i; + for(n=1; z[n] && z[n]!=':' && !tdsqlite3Isspace(z[n]); n++){} + if( tdsqlite3AtoF(z, &r, n, SQLITE_UTF8)<=0 ){ rc = 1; break; } @@ -23048,8 +26606,8 @@ static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ */ const char *z2 = z; DateTime tx; - sqlite3_int64 day; - if( !sqlite3Isdigit(*z2) ) z2++; + tdsqlite3_int64 day; + if( !tdsqlite3Isdigit(*z2) ) z2++; memset(&tx, 0, sizeof(tx)); if( parseHhMmSs(z2, &tx) ) break; computeJD(&tx); @@ -23063,46 +26621,48 @@ static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ rc = 0; break; } + + /* If control reaches this point, it means the transformation is + ** one of the forms like "+NNN days". */ z += n; - while( sqlite3Isspace(*z) ) z++; - n = sqlite3Strlen30(z); + while( tdsqlite3Isspace(*z) ) z++; + n = tdsqlite3Strlen30(z); if( n>10 || n<3 ) break; - if( z[n-1]=='s' ){ z[n-1] = 0; n--; } + if( tdsqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--; computeJD(p); - rc = 0; + rc = 1; rRounder = r<0 ? -0.5 : +0.5; - if( n==3 && strcmp(z,"day")==0 ){ - p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder); - }else if( n==4 && strcmp(z,"hour")==0 ){ - p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder); - }else if( n==6 && strcmp(z,"minute")==0 ){ - p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder); - }else if( n==6 && strcmp(z,"second")==0 ){ - p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder); - }else if( n==5 && strcmp(z,"month")==0 ){ - int x, y; - computeYMD_HMS(p); - p->M += (int)r; - x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; - p->Y += x; - p->M -= x*12; - p->validJD = 0; - computeJD(p); - y = (int)r; - if( y!=r ){ - p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder); - } - }else if( n==4 && strcmp(z,"year")==0 ){ - int y = (int)r; - computeYMD_HMS(p); - p->Y += y; - p->validJD = 0; - computeJD(p); - if( y!=r ){ - p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder); + for(i=0; i<ArraySize(aXformType); i++){ + if( aXformType[i].nName==n + && tdsqlite3_strnicmp(aXformType[i].zName, z, n)==0 + && r>-aXformType[i].rLimit && r<aXformType[i].rLimit + ){ + switch( aXformType[i].eType ){ + case 1: { /* Special processing to add months */ + int x; + computeYMD_HMS(p); + p->M += (int)r; + x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; + p->Y += x; + p->M -= x*12; + p->validJD = 0; + r -= (int)r; + break; + } + case 2: { /* Special processing to add years */ + int y = (int)r; + computeYMD_HMS(p); + p->Y += y; + p->validJD = 0; + r -= (int)r; + break; + } + } + computeJD(p); + p->iJD += (tdsqlite3_int64)(r*aXformType[i].rXform + rRounder); + rc = 0; + break; } - }else{ - rc = 1; } clearYMD_HMS_TZ(p); break; @@ -23124,32 +26684,34 @@ static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){ ** then assume a default value of "now" for argv[0]. */ static int isDate( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv, + tdsqlite3_value **argv, DateTime *p ){ - int i; + int i, n; const unsigned char *z; int eType; memset(p, 0, sizeof(*p)); if( argc==0 ){ return setDateTimeToCurrent(context, p); } - if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT + if( (eType = tdsqlite3_value_type(argv[0]))==SQLITE_FLOAT || eType==SQLITE_INTEGER ){ - p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5); - p->validJD = 1; + setRawDateNumber(p, tdsqlite3_value_double(argv[0])); }else{ - z = sqlite3_value_text(argv[0]); + z = tdsqlite3_value_text(argv[0]); if( !z || parseDateOrTime(context, (char*)z, p) ){ return 1; } } for(i=1; i<argc; i++){ - z = sqlite3_value_text(argv[i]); - if( z==0 || parseModifier(context, (char*)z, p) ) return 1; + z = tdsqlite3_value_text(argv[i]); + n = tdsqlite3_value_bytes(argv[i]); + if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1; } + computeJD(p); + if( p->isError || !validJulianDay(p->iJD) ) return 1; return 0; } @@ -23165,14 +26727,14 @@ static int isDate( ** Return the julian day number of the date specified in the arguments */ static void juliandayFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ DateTime x; if( isDate(context, argc, argv, &x)==0 ){ computeJD(&x); - sqlite3_result_double(context, x.iJD/86400000.0); + tdsqlite3_result_double(context, x.iJD/86400000.0); } } @@ -23182,17 +26744,17 @@ static void juliandayFunc( ** Return YYYY-MM-DD HH:MM:SS */ static void datetimeFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ DateTime x; if( isDate(context, argc, argv, &x)==0 ){ char zBuf[100]; computeYMD_HMS(&x); - sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d", + tdsqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d", x.Y, x.M, x.D, x.h, x.m, (int)(x.s)); - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + tdsqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } } @@ -23202,16 +26764,16 @@ static void datetimeFunc( ** Return HH:MM:SS */ static void timeFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ DateTime x; if( isDate(context, argc, argv, &x)==0 ){ char zBuf[100]; computeHMS(&x); - sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s); - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + tdsqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s); + tdsqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } } @@ -23221,16 +26783,16 @@ static void timeFunc( ** Return YYYY-MM-DD */ static void dateFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ DateTime x; if( isDate(context, argc, argv, &x)==0 ){ char zBuf[100]; computeYMD(&x); - sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D); - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + tdsqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D); + tdsqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } } @@ -23254,21 +26816,21 @@ static void dateFunc( ** %% % */ static void strftimeFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ DateTime x; u64 n; size_t i,j; char *z; - sqlite3 *db; + tdsqlite3 *db; const char *zFmt; char zBuf[100]; if( argc==0 ) return; - zFmt = (const char*)sqlite3_value_text(argv[0]); + zFmt = (const char*)tdsqlite3_value_text(argv[0]); if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return; - db = sqlite3_context_db_handle(context); + db = tdsqlite3_context_db_handle(context); for(i=0, n=1; zFmt[i]; i++, n++){ if( zFmt[i]=='%' ){ switch( zFmt[i+1] ){ @@ -23309,12 +26871,12 @@ static void strftimeFunc( if( n<sizeof(zBuf) ){ z = zBuf; }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){ - sqlite3_result_error_toobig(context); + tdsqlite3_result_error_toobig(context); return; }else{ - z = sqlite3DbMallocRawNN(db, (int)n); + z = tdsqlite3DbMallocRawNN(db, (int)n); if( z==0 ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); return; } } @@ -23326,15 +26888,15 @@ static void strftimeFunc( }else{ i++; switch( zFmt[i] ){ - case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break; + case 'd': tdsqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break; case 'f': { double s = x.s; if( s>59.999 ) s = 59.999; - sqlite3_snprintf(7, &z[j],"%06.3f", s); - j += sqlite3Strlen30(&z[j]); + tdsqlite3_snprintf(7, &z[j],"%06.3f", s); + j += tdsqlite3Strlen30(&z[j]); break; } - case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break; + case 'H': tdsqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break; case 'W': /* Fall thru */ case 'j': { int nDay; /* Number of days since 1st day of year */ @@ -23347,34 +26909,34 @@ static void strftimeFunc( if( zFmt[i]=='W' ){ int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */ wd = (int)(((x.iJD+43200000)/86400000)%7); - sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7); + tdsqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7); j += 2; }else{ - sqlite3_snprintf(4, &z[j],"%03d",nDay+1); + tdsqlite3_snprintf(4, &z[j],"%03d",nDay+1); j += 3; } break; } case 'J': { - sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0); - j+=sqlite3Strlen30(&z[j]); + tdsqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0); + j+=tdsqlite3Strlen30(&z[j]); break; } - case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break; - case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break; + case 'm': tdsqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break; + case 'M': tdsqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break; case 's': { - sqlite3_snprintf(30,&z[j],"%lld", + tdsqlite3_snprintf(30,&z[j],"%lld", (i64)(x.iJD/1000 - 21086676*(i64)10000)); - j += sqlite3Strlen30(&z[j]); + j += tdsqlite3Strlen30(&z[j]); break; } - case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break; + case 'S': tdsqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break; case 'w': { z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0'; break; } case 'Y': { - sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]); + tdsqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=tdsqlite3Strlen30(&z[j]); break; } default: z[j++] = '%'; break; @@ -23382,7 +26944,7 @@ static void strftimeFunc( } } z[j] = 0; - sqlite3_result_text(context, z, -1, + tdsqlite3_result_text(context, z, -1, z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC); } @@ -23392,9 +26954,9 @@ static void strftimeFunc( ** This function returns the same value as time('now'). */ static void ctimeFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **NotUsed2 + tdsqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); timeFunc(context, 0, 0); @@ -23406,9 +26968,9 @@ static void ctimeFunc( ** This function returns the same value as date('now'). */ static void cdateFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **NotUsed2 + tdsqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); dateFunc(context, 0, 0); @@ -23420,9 +26982,9 @@ static void cdateFunc( ** This function returns the same value as datetime('now'). */ static void ctimestampFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **NotUsed2 + tdsqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); datetimeFunc(context, 0, 0); @@ -23442,13 +27004,13 @@ static void ctimestampFunc( ** as the user-data for the function. */ static void currentTimeFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ time_t t; - char *zFormat = (char *)sqlite3_user_data(context); - sqlite3_int64 iT; + char *zFormat = (char *)tdsqlite3_user_data(context); + tdsqlite3_int64 iT; struct tm *pTm; struct tm sNow; char zBuf[20]; @@ -23456,20 +27018,20 @@ static void currentTimeFunc( UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); - iT = sqlite3StmtCurrentTime(context); + iT = tdsqlite3StmtCurrentTime(context); if( iT<=0 ) return; - t = iT/1000 - 10000*(sqlite3_int64)21086676; + t = iT/1000 - 10000*(tdsqlite3_int64)21086676; #if HAVE_GMTIME_R pTm = gmtime_r(&t, &sNow); #else - sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); + tdsqlite3_mutex_enter(tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); pTm = gmtime(&t); if( pTm ) memcpy(&sNow, pTm, sizeof(sNow)); - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); + tdsqlite3_mutex_leave(tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); #endif if( pTm ){ strftime(zBuf, 20, zFormat, &sNow); - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + tdsqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } } #endif @@ -23479,14 +27041,14 @@ static void currentTimeFunc( ** functions. This should be the only routine in this file with ** external linkage. */ -SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){ +SQLITE_PRIVATE void tdsqlite3RegisterDateTimeFunctions(void){ static FuncDef aDateTimeFuncs[] = { #ifndef SQLITE_OMIT_DATETIME_FUNCS - DFUNCTION(julianday, -1, 0, 0, juliandayFunc ), - DFUNCTION(date, -1, 0, 0, dateFunc ), - DFUNCTION(time, -1, 0, 0, timeFunc ), - DFUNCTION(datetime, -1, 0, 0, datetimeFunc ), - DFUNCTION(strftime, -1, 0, 0, strftimeFunc ), + PURE_DATE(julianday, -1, 0, 0, juliandayFunc ), + PURE_DATE(date, -1, 0, 0, dateFunc ), + PURE_DATE(time, -1, 0, 0, timeFunc ), + PURE_DATE(datetime, -1, 0, 0, datetimeFunc ), + PURE_DATE(strftime, -1, 0, 0, strftimeFunc ), DFUNCTION(current_time, 0, 0, 0, ctimeFunc ), DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc), DFUNCTION(current_date, 0, 0, 0, cdateFunc ), @@ -23496,7 +27058,7 @@ SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){ STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), #endif }; - sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs)); + tdsqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs)); } /************** End of date.c ************************************************/ @@ -23524,53 +27086,53 @@ SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){ ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) -SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ -SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ -SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ -SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ -SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */ -SQLITE_API int sqlite3_diskfull_pending = 0; -SQLITE_API int sqlite3_diskfull = 0; +SQLITE_API int tdsqlite3_io_error_hit = 0; /* Total number of I/O Errors */ +SQLITE_API int tdsqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ +SQLITE_API int tdsqlite3_io_error_pending = 0; /* Count down to first I/O error */ +SQLITE_API int tdsqlite3_io_error_persist = 0; /* True if I/O errors persist */ +SQLITE_API int tdsqlite3_io_error_benign = 0; /* True if errors are benign */ +SQLITE_API int tdsqlite3_diskfull_pending = 0; +SQLITE_API int tdsqlite3_diskfull = 0; #endif /* defined(SQLITE_TEST) */ /* ** When testing, also keep a count of the number of open files. */ #if defined(SQLITE_TEST) -SQLITE_API int sqlite3_open_file_count = 0; +SQLITE_API int tdsqlite3_open_file_count = 0; #endif /* defined(SQLITE_TEST) */ /* -** The default SQLite sqlite3_vfs implementations do not allocate +** The default SQLite tdsqlite3_vfs implementations do not allocate ** memory (actually, os_unix.c allocates a small amount of memory ** from within OsOpen()), but some third-party implementations may. -** So we test the effects of a malloc() failing and the sqlite3OsXXX() +** So we test the effects of a malloc() failing and the tdsqlite3OsXXX() ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. ** ** The following functions are instrumented for malloc() failure ** testing: ** -** sqlite3OsRead() -** sqlite3OsWrite() -** sqlite3OsSync() -** sqlite3OsFileSize() -** sqlite3OsLock() -** sqlite3OsCheckReservedLock() -** sqlite3OsFileControl() -** sqlite3OsShmMap() -** sqlite3OsOpen() -** sqlite3OsDelete() -** sqlite3OsAccess() -** sqlite3OsFullPathname() +** tdsqlite3OsRead() +** tdsqlite3OsWrite() +** tdsqlite3OsSync() +** tdsqlite3OsFileSize() +** tdsqlite3OsLock() +** tdsqlite3OsCheckReservedLock() +** tdsqlite3OsFileControl() +** tdsqlite3OsShmMap() +** tdsqlite3OsOpen() +** tdsqlite3OsDelete() +** tdsqlite3OsAccess() +** tdsqlite3OsFullPathname() ** */ #if defined(SQLITE_TEST) -SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1; +SQLITE_API int tdsqlite3_memdebug_vfs_oom_test = 1; #define DO_OS_MALLOC_TEST(x) \ - if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \ - void *pTstAlloc = sqlite3Malloc(10); \ + if (tdsqlite3_memdebug_vfs_oom_test && (!x || !tdsqlite3JournalIsInMemory(x))) { \ + void *pTstAlloc = tdsqlite3Malloc(10); \ if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \ - sqlite3_free(pTstAlloc); \ + tdsqlite3_free(pTstAlloc); \ } #else #define DO_OS_MALLOC_TEST(x) @@ -23578,58 +27140,61 @@ SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1; /* ** The following routines are convenience wrappers around methods -** of the sqlite3_file object. This is mostly just syntactic sugar. All +** of the tdsqlite3_file object. This is mostly just syntactic sugar. All ** of this would be completely automatic if SQLite were coded using ** C++ instead of plain old C. */ -SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){ +SQLITE_PRIVATE void tdsqlite3OsClose(tdsqlite3_file *pId){ if( pId->pMethods ){ pId->pMethods->xClose(pId); pId->pMethods = 0; } } -SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){ +SQLITE_PRIVATE int tdsqlite3OsRead(tdsqlite3_file *id, void *pBuf, int amt, i64 offset){ DO_OS_MALLOC_TEST(id); return id->pMethods->xRead(id, pBuf, amt, offset); } -SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){ +SQLITE_PRIVATE int tdsqlite3OsWrite(tdsqlite3_file *id, const void *pBuf, int amt, i64 offset){ DO_OS_MALLOC_TEST(id); return id->pMethods->xWrite(id, pBuf, amt, offset); } -SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){ +SQLITE_PRIVATE int tdsqlite3OsTruncate(tdsqlite3_file *id, i64 size){ return id->pMethods->xTruncate(id, size); } -SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){ +SQLITE_PRIVATE int tdsqlite3OsSync(tdsqlite3_file *id, int flags){ DO_OS_MALLOC_TEST(id); - return id->pMethods->xSync(id, flags); + return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK; } -SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){ +SQLITE_PRIVATE int tdsqlite3OsFileSize(tdsqlite3_file *id, i64 *pSize){ DO_OS_MALLOC_TEST(id); return id->pMethods->xFileSize(id, pSize); } -SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){ +SQLITE_PRIVATE int tdsqlite3OsLock(tdsqlite3_file *id, int lockType){ DO_OS_MALLOC_TEST(id); return id->pMethods->xLock(id, lockType); } -SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){ +SQLITE_PRIVATE int tdsqlite3OsUnlock(tdsqlite3_file *id, int lockType){ return id->pMethods->xUnlock(id, lockType); } -SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){ +SQLITE_PRIVATE int tdsqlite3OsCheckReservedLock(tdsqlite3_file *id, int *pResOut){ DO_OS_MALLOC_TEST(id); return id->pMethods->xCheckReservedLock(id, pResOut); } /* -** Use sqlite3OsFileControl() when we are doing something that might fail -** and we need to know about the failures. Use sqlite3OsFileControlHint() +** Use tdsqlite3OsFileControl() when we are doing something that might fail +** and we need to know about the failures. Use tdsqlite3OsFileControlHint() ** when simply tossing information over the wall to the VFS and we do not ** really care if the VFS receives and understands the information since it -** is only a hint and can be safely ignored. The sqlite3OsFileControlHint() +** is only a hint and can be safely ignored. The tdsqlite3OsFileControlHint() ** routine has no return value since the return value would be meaningless. */ -SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){ +SQLITE_PRIVATE int tdsqlite3OsFileControl(tdsqlite3_file *id, int op, void *pArg){ + if( id->pMethods==0 ) return SQLITE_NOTFOUND; #ifdef SQLITE_TEST - if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){ + if( op!=SQLITE_FCNTL_COMMIT_PHASETWO + && op!=SQLITE_FCNTL_LOCK_TIMEOUT + ){ /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite ** is using a regular VFS, it is called after the corresponding ** transaction has been committed. Injecting a fault at this point @@ -23645,28 +27210,29 @@ SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){ #endif return id->pMethods->xFileControl(id, op, pArg); } -SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){ - (void)id->pMethods->xFileControl(id, op, pArg); +SQLITE_PRIVATE void tdsqlite3OsFileControlHint(tdsqlite3_file *id, int op, void *pArg){ + if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg); } -SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){ - int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; +SQLITE_PRIVATE int tdsqlite3OsSectorSize(tdsqlite3_file *id){ + int (*xSectorSize)(tdsqlite3_file*) = id->pMethods->xSectorSize; return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); } -SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ +SQLITE_PRIVATE int tdsqlite3OsDeviceCharacteristics(tdsqlite3_file *id){ return id->pMethods->xDeviceCharacteristics(id); } -SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){ +#ifndef SQLITE_OMIT_WAL +SQLITE_PRIVATE int tdsqlite3OsShmLock(tdsqlite3_file *id, int offset, int n, int flags){ return id->pMethods->xShmLock(id, offset, n, flags); } -SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){ +SQLITE_PRIVATE void tdsqlite3OsShmBarrier(tdsqlite3_file *id){ id->pMethods->xShmBarrier(id); } -SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){ +SQLITE_PRIVATE int tdsqlite3OsShmUnmap(tdsqlite3_file *id, int deleteFlag){ return id->pMethods->xShmUnmap(id, deleteFlag); } -SQLITE_PRIVATE int sqlite3OsShmMap( - sqlite3_file *id, /* Database file handle */ +SQLITE_PRIVATE int tdsqlite3OsShmMap( + tdsqlite3_file *id, /* Database file handle */ int iPage, int pgsz, int bExtend, /* True to extend file if necessary */ @@ -23675,23 +27241,24 @@ SQLITE_PRIVATE int sqlite3OsShmMap( DO_OS_MALLOC_TEST(id); return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp); } +#endif /* SQLITE_OMIT_WAL */ #if SQLITE_MAX_MMAP_SIZE>0 /* The real implementation of xFetch and xUnfetch */ -SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ +SQLITE_PRIVATE int tdsqlite3OsFetch(tdsqlite3_file *id, i64 iOff, int iAmt, void **pp){ DO_OS_MALLOC_TEST(id); return id->pMethods->xFetch(id, iOff, iAmt, pp); } -SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ +SQLITE_PRIVATE int tdsqlite3OsUnfetch(tdsqlite3_file *id, i64 iOff, void *p){ return id->pMethods->xUnfetch(id, iOff, p); } #else /* No-op stubs to use when memory-mapped I/O is disabled */ -SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ +SQLITE_PRIVATE int tdsqlite3OsFetch(tdsqlite3_file *id, i64 iOff, int iAmt, void **pp){ *pp = 0; return SQLITE_OK; } -SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ +SQLITE_PRIVATE int tdsqlite3OsUnfetch(tdsqlite3_file *id, i64 iOff, void *p){ return SQLITE_OK; } #endif @@ -23700,10 +27267,10 @@ SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ ** The next group of routines are convenience wrappers around the ** VFS methods. */ -SQLITE_PRIVATE int sqlite3OsOpen( - sqlite3_vfs *pVfs, +SQLITE_PRIVATE int tdsqlite3OsOpen( + tdsqlite3_vfs *pVfs, const char *zPath, - sqlite3_file *pFile, + tdsqlite3_file *pFile, int flags, int *pFlagsOut ){ @@ -23713,17 +27280,17 @@ SQLITE_PRIVATE int sqlite3OsOpen( ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before ** reaching the VFS. */ - rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut); + rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut); assert( rc==SQLITE_OK || pFile->pMethods==0 ); return rc; } -SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ +SQLITE_PRIVATE int tdsqlite3OsDelete(tdsqlite3_vfs *pVfs, const char *zPath, int dirSync){ DO_OS_MALLOC_TEST(0); assert( dirSync==0 || dirSync==1 ); return pVfs->xDelete(pVfs, zPath, dirSync); } -SQLITE_PRIVATE int sqlite3OsAccess( - sqlite3_vfs *pVfs, +SQLITE_PRIVATE int tdsqlite3OsAccess( + tdsqlite3_vfs *pVfs, const char *zPath, int flags, int *pResOut @@ -23731,8 +27298,8 @@ SQLITE_PRIVATE int sqlite3OsAccess( DO_OS_MALLOC_TEST(0); return pVfs->xAccess(pVfs, zPath, flags, pResOut); } -SQLITE_PRIVATE int sqlite3OsFullPathname( - sqlite3_vfs *pVfs, +SQLITE_PRIVATE int tdsqlite3OsFullPathname( + tdsqlite3_vfs *pVfs, const char *zPath, int nPathOut, char *zPathOut @@ -23742,29 +27309,37 @@ SQLITE_PRIVATE int sqlite3OsFullPathname( return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); } #ifndef SQLITE_OMIT_LOAD_EXTENSION -SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ +SQLITE_PRIVATE void *tdsqlite3OsDlOpen(tdsqlite3_vfs *pVfs, const char *zPath){ return pVfs->xDlOpen(pVfs, zPath); } -SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ +SQLITE_PRIVATE void tdsqlite3OsDlError(tdsqlite3_vfs *pVfs, int nByte, char *zBufOut){ pVfs->xDlError(pVfs, nByte, zBufOut); } -SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){ +SQLITE_PRIVATE void (*tdsqlite3OsDlSym(tdsqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){ return pVfs->xDlSym(pVfs, pHdle, zSym); } -SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){ +SQLITE_PRIVATE void tdsqlite3OsDlClose(tdsqlite3_vfs *pVfs, void *pHandle){ pVfs->xDlClose(pVfs, pHandle); } #endif /* SQLITE_OMIT_LOAD_EXTENSION */ -SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ - return pVfs->xRandomness(pVfs, nByte, zBufOut); +SQLITE_PRIVATE int tdsqlite3OsRandomness(tdsqlite3_vfs *pVfs, int nByte, char *zBufOut){ + if( tdsqlite3Config.iPrngSeed ){ + memset(zBufOut, 0, nByte); + if( ALWAYS(nByte>(signed)sizeof(unsigned)) ) nByte = sizeof(unsigned int); + memcpy(zBufOut, &tdsqlite3Config.iPrngSeed, nByte); + return SQLITE_OK; + }else{ + return pVfs->xRandomness(pVfs, nByte, zBufOut); + } + } -SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){ +SQLITE_PRIVATE int tdsqlite3OsSleep(tdsqlite3_vfs *pVfs, int nMicro){ return pVfs->xSleep(pVfs, nMicro); } -SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){ +SQLITE_PRIVATE int tdsqlite3OsGetLastError(tdsqlite3_vfs *pVfs){ return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0; } -SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ +SQLITE_PRIVATE int tdsqlite3OsCurrentTimeInt64(tdsqlite3_vfs *pVfs, tdsqlite3_int64 *pTimeOut){ int rc; /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() ** method to get the current date and time if that method is available @@ -23777,25 +27352,25 @@ SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p }else{ double r; rc = pVfs->xCurrentTime(pVfs, &r); - *pTimeOut = (sqlite3_int64)(r*86400000.0); + *pTimeOut = (tdsqlite3_int64)(r*86400000.0); } return rc; } -SQLITE_PRIVATE int sqlite3OsOpenMalloc( - sqlite3_vfs *pVfs, +SQLITE_PRIVATE int tdsqlite3OsOpenMalloc( + tdsqlite3_vfs *pVfs, const char *zFile, - sqlite3_file **ppFile, + tdsqlite3_file **ppFile, int flags, int *pOutFlags ){ int rc; - sqlite3_file *pFile; - pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile); + tdsqlite3_file *pFile; + pFile = (tdsqlite3_file *)tdsqlite3MallocZero(pVfs->szOsFile); if( pFile ){ - rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags); + rc = tdsqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags); if( rc!=SQLITE_OK ){ - sqlite3_free(pFile); + tdsqlite3_free(pFile); }else{ *ppFile = pFile; } @@ -23804,67 +27379,67 @@ SQLITE_PRIVATE int sqlite3OsOpenMalloc( } return rc; } -SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){ +SQLITE_PRIVATE void tdsqlite3OsCloseFree(tdsqlite3_file *pFile){ assert( pFile ); - sqlite3OsClose(pFile); - sqlite3_free(pFile); + tdsqlite3OsClose(pFile); + tdsqlite3_free(pFile); } /* ** This function is a wrapper around the OS specific implementation of -** sqlite3_os_init(). The purpose of the wrapper is to provide the +** tdsqlite3_os_init(). The purpose of the wrapper is to provide the ** ability to simulate a malloc failure, so that the handling of an -** error in sqlite3_os_init() by the upper layers can be tested. +** error in tdsqlite3_os_init() by the upper layers can be tested. */ -SQLITE_PRIVATE int sqlite3OsInit(void){ - void *p = sqlite3_malloc(10); +SQLITE_PRIVATE int tdsqlite3OsInit(void){ + void *p = tdsqlite3_malloc(10); if( p==0 ) return SQLITE_NOMEM_BKPT; - sqlite3_free(p); - return sqlite3_os_init(); + tdsqlite3_free(p); + return tdsqlite3_os_init(); } /* ** The list of all registered VFS implementations. */ -static sqlite3_vfs * SQLITE_WSD vfsList = 0; -#define vfsList GLOBAL(sqlite3_vfs *, vfsList) +static tdsqlite3_vfs * SQLITE_WSD vfsList = 0; +#define vfsList GLOBAL(tdsqlite3_vfs *, vfsList) /* ** Locate a VFS by name. If no name is given, simply return the ** first VFS on the list. */ -SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){ - sqlite3_vfs *pVfs = 0; +SQLITE_API tdsqlite3_vfs *tdsqlite3_vfs_find(const char *zVfs){ + tdsqlite3_vfs *pVfs = 0; #if SQLITE_THREADSAFE - sqlite3_mutex *mutex; + tdsqlite3_mutex *mutex; #endif #ifndef SQLITE_OMIT_AUTOINIT - int rc = sqlite3_initialize(); + int rc = tdsqlite3_initialize(); if( rc ) return 0; #endif #if SQLITE_THREADSAFE - mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); + mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif - sqlite3_mutex_enter(mutex); + tdsqlite3_mutex_enter(mutex); for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){ if( zVfs==0 ) break; if( strcmp(zVfs, pVfs->zName)==0 ) break; } - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); return pVfs; } /* ** Unlink a VFS from the linked list */ -static void vfsUnlink(sqlite3_vfs *pVfs){ - assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ); +static void vfsUnlink(tdsqlite3_vfs *pVfs){ + assert( tdsqlite3_mutex_held(tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ); if( pVfs==0 ){ /* No-op */ }else if( vfsList==pVfs ){ vfsList = pVfs->pNext; }else if( vfsList ){ - sqlite3_vfs *p = vfsList; + tdsqlite3_vfs *p = vfsList; while( p->pNext && p->pNext!=pVfs ){ p = p->pNext; } @@ -23879,18 +27454,18 @@ static void vfsUnlink(sqlite3_vfs *pVfs){ ** VFS multiple times. The new VFS becomes the default if makeDflt is ** true. */ -SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){ - MUTEX_LOGIC(sqlite3_mutex *mutex;) +SQLITE_API int tdsqlite3_vfs_register(tdsqlite3_vfs *pVfs, int makeDflt){ + MUTEX_LOGIC(tdsqlite3_mutex *mutex;) #ifndef SQLITE_OMIT_AUTOINIT - int rc = sqlite3_initialize(); + int rc = tdsqlite3_initialize(); if( rc ) return rc; #endif #ifdef SQLITE_ENABLE_API_ARMOR if( pVfs==0 ) return SQLITE_MISUSE_BKPT; #endif - MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) - sqlite3_mutex_enter(mutex); + MUTEX_LOGIC( mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + tdsqlite3_mutex_enter(mutex); vfsUnlink(pVfs); if( makeDflt || vfsList==0 ){ pVfs->pNext = vfsList; @@ -23900,20 +27475,23 @@ SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){ vfsList->pNext = pVfs; } assert(vfsList); - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); return SQLITE_OK; } /* ** Unregister a VFS so that it is no longer accessible. */ -SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ -#if SQLITE_THREADSAFE - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); +SQLITE_API int tdsqlite3_vfs_unregister(tdsqlite3_vfs *pVfs){ + MUTEX_LOGIC(tdsqlite3_mutex *mutex;) +#ifndef SQLITE_OMIT_AUTOINIT + int rc = tdsqlite3_initialize(); + if( rc ) return rc; #endif - sqlite3_mutex_enter(mutex); + MUTEX_LOGIC( mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + tdsqlite3_mutex_enter(mutex); vfsUnlink(pVfs); - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); return SQLITE_OK; } @@ -23933,7 +27511,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ ** ** This file contains code to support the concept of "benign" ** malloc failures (when the xMalloc() or xRealloc() method of the -** sqlite3_mem_methods structure fails to allocate a block of memory +** tdsqlite3_mem_methods structure fails to allocate a block of memory ** and returns 0). ** ** Most malloc failures are non-benign. After they occur, SQLite @@ -23947,7 +27525,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ /* #include "sqliteInt.h" */ -#ifndef SQLITE_OMIT_BUILTIN_TEST +#ifndef SQLITE_UNTESTABLE /* ** Global variables. @@ -23956,29 +27534,29 @@ typedef struct BenignMallocHooks BenignMallocHooks; static SQLITE_WSD struct BenignMallocHooks { void (*xBenignBegin)(void); void (*xBenignEnd)(void); -} sqlite3Hooks = { 0, 0 }; +} tdsqlite3Hooks = { 0, 0 }; /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks ** structure. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdHooks can refer directly -** to the "sqlite3Hooks" state vector declared above. +** to the "tdsqlite3Hooks" state vector declared above. */ #ifdef SQLITE_OMIT_WSD # define wsdHooksInit \ - BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks) + BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,tdsqlite3Hooks) # define wsdHooks x[0] #else # define wsdHooksInit -# define wsdHooks sqlite3Hooks +# define wsdHooks tdsqlite3Hooks #endif /* -** Register hooks to call when sqlite3BeginBenignMalloc() and -** sqlite3EndBenignMalloc() are called, respectively. +** Register hooks to call when tdsqlite3BeginBenignMalloc() and +** tdsqlite3EndBenignMalloc() are called, respectively. */ -SQLITE_PRIVATE void sqlite3BenignMallocHooks( +SQLITE_PRIVATE void tdsqlite3BenignMallocHooks( void (*xBenignBegin)(void), void (*xBenignEnd)(void) ){ @@ -23988,24 +27566,24 @@ SQLITE_PRIVATE void sqlite3BenignMallocHooks( } /* -** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that -** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc() +** This (tdsqlite3EndBenignMalloc()) is called by SQLite code to indicate that +** subsequent malloc failures are benign. A call to tdsqlite3EndBenignMalloc() ** indicates that subsequent malloc failures are non-benign. */ -SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){ +SQLITE_PRIVATE void tdsqlite3BeginBenignMalloc(void){ wsdHooksInit; if( wsdHooks.xBenignBegin ){ wsdHooks.xBenignBegin(); } } -SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){ +SQLITE_PRIVATE void tdsqlite3EndBenignMalloc(void){ wsdHooksInit; if( wsdHooks.xBenignEnd ){ wsdHooks.xBenignEnd(); } } -#endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */ +#endif /* #ifndef SQLITE_UNTESTABLE */ /************** End of fault.c ***********************************************/ /************** Begin file mem0.c ********************************************/ @@ -24025,7 +27603,7 @@ SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){ ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented ** here always fail. SQLite will not operate with these drivers. These ** are merely placeholders. Real drivers must be substituted using -** sqlite3_config() before SQLite will operate. +** tdsqlite3_config() before SQLite will operate. */ /* #include "sqliteInt.h" */ @@ -24039,32 +27617,32 @@ SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){ /* ** No-op versions of all memory allocation routines */ -static void *sqlite3MemMalloc(int nByte){ return 0; } -static void sqlite3MemFree(void *pPrior){ return; } -static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; } -static int sqlite3MemSize(void *pPrior){ return 0; } -static int sqlite3MemRoundup(int n){ return n; } -static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; } -static void sqlite3MemShutdown(void *NotUsed){ return; } +static void *tdsqlite3MemMalloc(int nByte){ return 0; } +static void tdsqlite3MemFree(void *pPrior){ return; } +static void *tdsqlite3MemRealloc(void *pPrior, int nByte){ return 0; } +static int tdsqlite3MemSize(void *pPrior){ return 0; } +static int tdsqlite3MemRoundup(int n){ return n; } +static int tdsqlite3MemInit(void *NotUsed){ return SQLITE_OK; } +static void tdsqlite3MemShutdown(void *NotUsed){ return; } /* ** This routine is the only routine in this file with external linkage. ** ** Populate the low-level memory allocation function pointers in -** sqlite3GlobalConfig.m with pointers to the routines in this file. -*/ -SQLITE_PRIVATE void sqlite3MemSetDefault(void){ - static const sqlite3_mem_methods defaultMethods = { - sqlite3MemMalloc, - sqlite3MemFree, - sqlite3MemRealloc, - sqlite3MemSize, - sqlite3MemRoundup, - sqlite3MemInit, - sqlite3MemShutdown, +** tdsqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +SQLITE_PRIVATE void tdsqlite3MemSetDefault(void){ + static const tdsqlite3_mem_methods defaultMethods = { + tdsqlite3MemMalloc, + tdsqlite3MemFree, + tdsqlite3MemRealloc, + tdsqlite3MemSize, + tdsqlite3MemRoundup, + tdsqlite3MemInit, + tdsqlite3MemShutdown, 0 }; - sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); + tdsqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } #endif /* SQLITE_ZERO_MALLOC */ @@ -24088,7 +27666,7 @@ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ ** to obtain the memory it needs. ** ** This file contains implementations of the low-level memory allocation -** routines specified in the sqlite3_mem_methods object. The content of +** routines specified in the tdsqlite3_mem_methods object. The content of ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The @@ -24130,7 +27708,9 @@ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ */ #include <sys/sysctl.h> #include <malloc/malloc.h> +#ifdef SQLITE_MIGHT_BE_SINGLE_CORE #include <libkern/OSAtomic.h> +#endif /* SQLITE_MIGHT_BE_SINGLE_CORE */ static malloc_zone_t* _sqliteZone_; #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x)) #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x)); @@ -24190,49 +27770,51 @@ static malloc_zone_t* _sqliteZone_; /* ** Like malloc(), but remember the size of the allocation -** so that we can find it later using sqlite3MemSize(). +** so that we can find it later using tdsqlite3MemSize(). ** ** For this low-level routine, we are guaranteed that nByte>0 because ** cases of nByte<=0 will be intercepted and dealt with by higher level ** routines. */ -static void *sqlite3MemMalloc(int nByte){ +static void *tdsqlite3MemMalloc(int nByte){ #ifdef SQLITE_MALLOCSIZE - void *p = SQLITE_MALLOC( nByte ); + void *p; + testcase( ROUND8(nByte)==nByte ); + p = SQLITE_MALLOC( nByte ); if( p==0 ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + tdsqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); } return p; #else - sqlite3_int64 *p; + tdsqlite3_int64 *p; assert( nByte>0 ); - nByte = ROUND8(nByte); + testcase( ROUND8(nByte)!=nByte ); p = SQLITE_MALLOC( nByte+8 ); if( p ){ p[0] = nByte; p++; }else{ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + tdsqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); } return (void *)p; #endif } /* -** Like free() but works for allocations obtained from sqlite3MemMalloc() -** or sqlite3MemRealloc(). +** Like free() but works for allocations obtained from tdsqlite3MemMalloc() +** or tdsqlite3MemRealloc(). ** ** For this low-level routine, we already know that pPrior!=0 since ** cases where pPrior==0 will have been intecepted and dealt with ** by higher-level routines. */ -static void sqlite3MemFree(void *pPrior){ +static void tdsqlite3MemFree(void *pPrior){ #ifdef SQLITE_MALLOCSIZE SQLITE_FREE(pPrior); #else - sqlite3_int64 *p = (sqlite3_int64*)pPrior; + tdsqlite3_int64 *p = (tdsqlite3_int64*)pPrior; assert( pPrior!=0 ); p--; SQLITE_FREE(p); @@ -24243,14 +27825,14 @@ static void sqlite3MemFree(void *pPrior){ ** Report the allocated size of a prior return from xMalloc() ** or xRealloc(). */ -static int sqlite3MemSize(void *pPrior){ +static int tdsqlite3MemSize(void *pPrior){ #ifdef SQLITE_MALLOCSIZE assert( pPrior!=0 ); return (int)SQLITE_MALLOCSIZE(pPrior); #else - sqlite3_int64 *p; + tdsqlite3_int64 *p; assert( pPrior!=0 ); - p = (sqlite3_int64*)pPrior; + p = (tdsqlite3_int64*)pPrior; p--; return (int)p[0]; #endif @@ -24258,7 +27840,7 @@ static int sqlite3MemSize(void *pPrior){ /* ** Like realloc(). Resize an allocation previously obtained from -** sqlite3MemMalloc(). +** tdsqlite3MemMalloc(). ** ** For this low-level interface, we know that pPrior!=0. Cases where ** pPrior==0 while have been intercepted by higher-level routine and @@ -24266,18 +27848,18 @@ static int sqlite3MemSize(void *pPrior){ ** cases where nByte<=0 will have been intercepted by higher-level ** routines and redirected to xFree. */ -static void *sqlite3MemRealloc(void *pPrior, int nByte){ +static void *tdsqlite3MemRealloc(void *pPrior, int nByte){ #ifdef SQLITE_MALLOCSIZE void *p = SQLITE_REALLOC(pPrior, nByte); if( p==0 ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + tdsqlite3_log(SQLITE_NOMEM, "failed memory resize %u to %u bytes", SQLITE_MALLOCSIZE(pPrior), nByte); } return p; #else - sqlite3_int64 *p = (sqlite3_int64*)pPrior; + tdsqlite3_int64 *p = (tdsqlite3_int64*)pPrior; assert( pPrior!=0 && nByte>0 ); assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */ p--; @@ -24286,10 +27868,10 @@ static void *sqlite3MemRealloc(void *pPrior, int nByte){ p[0] = nByte; p++; }else{ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + tdsqlite3_log(SQLITE_NOMEM, "failed memory resize %u to %u bytes", - sqlite3MemSize(pPrior), nByte); + tdsqlite3MemSize(pPrior), nByte); } return (void*)p; #endif @@ -24298,14 +27880,14 @@ static void *sqlite3MemRealloc(void *pPrior, int nByte){ /* ** Round up a request size to the next valid allocation size. */ -static int sqlite3MemRoundup(int n){ +static int tdsqlite3MemRoundup(int n){ return ROUND8(n); } /* ** Initialize this module. */ -static int sqlite3MemInit(void *NotUsed){ +static int tdsqlite3MemInit(void *NotUsed){ #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) int cpuCount; size_t len; @@ -24321,19 +27903,10 @@ static int sqlite3MemInit(void *NotUsed){ }else{ /* only 1 core, use our own zone to contention over global locks, ** e.g. we have our own dedicated locks */ - bool success; - malloc_zone_t* newzone = malloc_create_zone(4096, 0); - malloc_set_zone_name(newzone, "Sqlite_Heap"); - do{ - success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, - (void * volatile *)&_sqliteZone_); - }while(!_sqliteZone_); - if( !success ){ - /* somebody registered a zone first */ - malloc_destroy_zone(newzone); - } + _sqliteZone_ = malloc_create_zone(4096, 0); + malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap"); } -#endif +#endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */ UNUSED_PARAMETER(NotUsed); return SQLITE_OK; } @@ -24341,7 +27914,7 @@ static int sqlite3MemInit(void *NotUsed){ /* ** Deinitialize this module. */ -static void sqlite3MemShutdown(void *NotUsed){ +static void tdsqlite3MemShutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); return; } @@ -24350,20 +27923,20 @@ static void sqlite3MemShutdown(void *NotUsed){ ** This routine is the only routine in this file with external linkage. ** ** Populate the low-level memory allocation function pointers in -** sqlite3GlobalConfig.m with pointers to the routines in this file. -*/ -SQLITE_PRIVATE void sqlite3MemSetDefault(void){ - static const sqlite3_mem_methods defaultMethods = { - sqlite3MemMalloc, - sqlite3MemFree, - sqlite3MemRealloc, - sqlite3MemSize, - sqlite3MemRoundup, - sqlite3MemInit, - sqlite3MemShutdown, +** tdsqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +SQLITE_PRIVATE void tdsqlite3MemSetDefault(void){ + static const tdsqlite3_mem_methods defaultMethods = { + tdsqlite3MemMalloc, + tdsqlite3MemFree, + tdsqlite3MemRealloc, + tdsqlite3MemSize, + tdsqlite3MemRoundup, + tdsqlite3MemInit, + tdsqlite3MemShutdown, 0 }; - sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); + tdsqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } #endif /* SQLITE_SYSTEM_MALLOC */ @@ -24389,7 +27962,7 @@ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ ** leaks and memory usage errors. ** ** This file contains implementations of the low-level memory allocation -** routines specified in the sqlite3_mem_methods object. +** routines specified in the tdsqlite3_mem_methods object. */ /* #include "sqliteInt.h" */ @@ -24456,7 +28029,7 @@ static struct { /* ** Mutex to control access to the memory allocation subsystem. */ - sqlite3_mutex *mutex; + tdsqlite3_mutex *mutex; /* ** Head and tail of a linked list of all outstanding allocations @@ -24477,8 +28050,8 @@ static struct { char zTitle[100]; /* The title text */ /* - ** sqlite3MallocDisallow() increments the following counter. - ** sqlite3MallocAllow() decrements it. + ** tdsqlite3MallocDisallow() increments the following counter. + ** tdsqlite3MallocAllow() decrements it. */ int disallow; /* Do not allow memory allocation */ @@ -24521,7 +28094,7 @@ static void adjustStats(int iSize, int increment){ ** This routine checks the guards at either end of the allocation and ** if they are incorrect it asserts. */ -static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){ +static struct MemBlockHdr *tdsqlite3MemsysGetHeader(void *pAllocation){ struct MemBlockHdr *p; int *pInt; u8 *pU8; @@ -24545,25 +28118,25 @@ static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){ /* ** Return the number of bytes currently allocated at address p. */ -static int sqlite3MemSize(void *p){ +static int tdsqlite3MemSize(void *p){ struct MemBlockHdr *pHdr; if( !p ){ return 0; } - pHdr = sqlite3MemsysGetHeader(p); + pHdr = tdsqlite3MemsysGetHeader(p); return (int)pHdr->iSize; } /* ** Initialize the memory allocation subsystem. */ -static int sqlite3MemInit(void *NotUsed){ +static int tdsqlite3MemInit(void *NotUsed){ UNUSED_PARAMETER(NotUsed); assert( (sizeof(struct MemBlockHdr)&7) == 0 ); - if( !sqlite3GlobalConfig.bMemstat ){ + if( !tdsqlite3GlobalConfig.bMemstat ){ /* If memory status is enabled, then the malloc.c wrapper will already ** hold the STATIC_MEM mutex when the routines here are invoked. */ - mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + mem.mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } return SQLITE_OK; } @@ -24571,7 +28144,7 @@ static int sqlite3MemInit(void *NotUsed){ /* ** Deinitialize the memory allocation subsystem. */ -static void sqlite3MemShutdown(void *NotUsed){ +static void tdsqlite3MemShutdown(void *NotUsed){ UNUSED_PARAMETER(NotUsed); mem.mutex = 0; } @@ -24579,7 +28152,7 @@ static void sqlite3MemShutdown(void *NotUsed){ /* ** Round up a request size to the next valid allocation size. */ -static int sqlite3MemRoundup(int n){ +static int tdsqlite3MemRoundup(int n){ return ROUND8(n); } @@ -24611,7 +28184,7 @@ static void randomFill(char *pBuf, int nByte){ /* ** Allocate nByte bytes of memory. */ -static void *sqlite3MemMalloc(int nByte){ +static void *tdsqlite3MemMalloc(int nByte){ struct MemBlockHdr *pHdr; void **pBt; char *z; @@ -24619,7 +28192,7 @@ static void *sqlite3MemMalloc(int nByte){ void *p = 0; int totalSize; int nReserve; - sqlite3_mutex_enter(mem.mutex); + tdsqlite3_mutex_enter(mem.mutex); assert( mem.disallow==0 ); nReserve = ROUND8(nByte); totalSize = nReserve + sizeof(*pHdr) + sizeof(int) + @@ -24663,23 +28236,23 @@ static void *sqlite3MemMalloc(int nByte){ memset(((char*)pInt)+nByte, 0x65, nReserve-nByte); p = (void*)pInt; } - sqlite3_mutex_leave(mem.mutex); + tdsqlite3_mutex_leave(mem.mutex); return p; } /* ** Free memory. */ -static void sqlite3MemFree(void *pPrior){ +static void tdsqlite3MemFree(void *pPrior){ struct MemBlockHdr *pHdr; void **pBt; char *z; - assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 + assert( tdsqlite3GlobalConfig.bMemstat || tdsqlite3GlobalConfig.bCoreMutex==0 || mem.mutex!=0 ); - pHdr = sqlite3MemsysGetHeader(pPrior); + pHdr = tdsqlite3MemsysGetHeader(pPrior); pBt = (void**)pHdr; pBt -= pHdr->nBacktraceSlots; - sqlite3_mutex_enter(mem.mutex); + tdsqlite3_mutex_enter(mem.mutex); if( pHdr->pPrev ){ assert( pHdr->pPrev->pNext==pHdr ); pHdr->pPrev->pNext = pHdr->pNext; @@ -24700,7 +28273,7 @@ static void sqlite3MemFree(void *pPrior){ randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + (int)pHdr->iSize + sizeof(int) + pHdr->nTitle); free(z); - sqlite3_mutex_leave(mem.mutex); + tdsqlite3_mutex_leave(mem.mutex); } /* @@ -24712,48 +28285,48 @@ static void sqlite3MemFree(void *pPrior){ ** much more likely to break and we are much more liking to find ** the error. */ -static void *sqlite3MemRealloc(void *pPrior, int nByte){ +static void *tdsqlite3MemRealloc(void *pPrior, int nByte){ struct MemBlockHdr *pOldHdr; void *pNew; assert( mem.disallow==0 ); assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */ - pOldHdr = sqlite3MemsysGetHeader(pPrior); - pNew = sqlite3MemMalloc(nByte); + pOldHdr = tdsqlite3MemsysGetHeader(pPrior); + pNew = tdsqlite3MemMalloc(nByte); if( pNew ){ memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize)); if( nByte>pOldHdr->iSize ){ randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize); } - sqlite3MemFree(pPrior); + tdsqlite3MemFree(pPrior); } return pNew; } /* ** Populate the low-level memory allocation function pointers in -** sqlite3GlobalConfig.m with pointers to the routines in this file. -*/ -SQLITE_PRIVATE void sqlite3MemSetDefault(void){ - static const sqlite3_mem_methods defaultMethods = { - sqlite3MemMalloc, - sqlite3MemFree, - sqlite3MemRealloc, - sqlite3MemSize, - sqlite3MemRoundup, - sqlite3MemInit, - sqlite3MemShutdown, +** tdsqlite3GlobalConfig.m with pointers to the routines in this file. +*/ +SQLITE_PRIVATE void tdsqlite3MemSetDefault(void){ + static const tdsqlite3_mem_methods defaultMethods = { + tdsqlite3MemMalloc, + tdsqlite3MemFree, + tdsqlite3MemRealloc, + tdsqlite3MemSize, + tdsqlite3MemRoundup, + tdsqlite3MemInit, + tdsqlite3MemShutdown, 0 }; - sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); + tdsqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); } /* ** Set the "type" of an allocation. */ -SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){ - if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ +SQLITE_PRIVATE void tdsqlite3MemdebugSetType(void *p, u8 eType){ + if( p && tdsqlite3GlobalConfig.m.xMalloc==tdsqlite3MemMalloc ){ struct MemBlockHdr *pHdr; - pHdr = sqlite3MemsysGetHeader(p); + pHdr = tdsqlite3MemsysGetHeader(p); assert( pHdr->iForeGuard==FOREGUARD ); pHdr->eType = eType; } @@ -24766,13 +28339,13 @@ SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){ ** This routine is designed for use within an assert() statement, to ** verify the type of an allocation. For example: ** -** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); +** assert( tdsqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); */ -SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){ +SQLITE_PRIVATE int tdsqlite3MemdebugHasType(void *p, u8 eType){ int rc = 1; - if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ + if( p && tdsqlite3GlobalConfig.m.xMalloc==tdsqlite3MemMalloc ){ struct MemBlockHdr *pHdr; - pHdr = sqlite3MemsysGetHeader(p); + pHdr = tdsqlite3MemsysGetHeader(p); assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ if( (pHdr->eType&eType)==0 ){ rc = 0; @@ -24788,13 +28361,13 @@ SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){ ** This routine is designed for use within an assert() statement, to ** verify the type of an allocation. For example: ** -** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); +** assert( tdsqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); */ -SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){ +SQLITE_PRIVATE int tdsqlite3MemdebugNoType(void *p, u8 eType){ int rc = 1; - if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ + if( p && tdsqlite3GlobalConfig.m.xMalloc==tdsqlite3MemMalloc ){ struct MemBlockHdr *pHdr; - pHdr = sqlite3MemsysGetHeader(p); + pHdr = tdsqlite3MemsysGetHeader(p); assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ if( (pHdr->eType&eType)!=0 ){ rc = 0; @@ -24808,31 +28381,31 @@ SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){ ** A value of zero turns off backtracing. The number is always rounded ** up to a multiple of 2. */ -SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){ +SQLITE_PRIVATE void tdsqlite3MemdebugBacktrace(int depth){ if( depth<0 ){ depth = 0; } if( depth>20 ){ depth = 20; } depth = (depth+1)&0xfe; mem.nBacktrace = depth; } -SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ +SQLITE_PRIVATE void tdsqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ mem.xBacktrace = xBacktrace; } /* ** Set the title string for subsequent allocations. */ -SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){ - unsigned int n = sqlite3Strlen30(zTitle) + 1; - sqlite3_mutex_enter(mem.mutex); +SQLITE_PRIVATE void tdsqlite3MemdebugSettitle(const char *zTitle){ + unsigned int n = tdsqlite3Strlen30(zTitle) + 1; + tdsqlite3_mutex_enter(mem.mutex); if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; memcpy(mem.zTitle, zTitle, n); mem.zTitle[n] = 0; mem.nTitle = ROUND8(n); - sqlite3_mutex_leave(mem.mutex); + tdsqlite3_mutex_leave(mem.mutex); } -SQLITE_PRIVATE void sqlite3MemdebugSync(){ +SQLITE_PRIVATE void tdsqlite3MemdebugSync(){ struct MemBlockHdr *pHdr; for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ void **pBt = (void**)pHdr; @@ -24845,7 +28418,7 @@ SQLITE_PRIVATE void sqlite3MemdebugSync(){ ** Open the file indicated and write a log of all unfreed memory ** allocations into that log. */ -SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){ +SQLITE_PRIVATE void tdsqlite3MemdebugDump(const char *zFilename){ FILE *out; struct MemBlockHdr *pHdr; void **pBt; @@ -24885,9 +28458,9 @@ SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){ } /* -** Return the number of times sqlite3MemMalloc() has been called. +** Return the number of times tdsqlite3MemMalloc() has been called. */ -SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){ +SQLITE_PRIVATE int tdsqlite3MemdebugMallocCount(){ int i; int nTotal = 0; for(i=0; i<NCSIZE; i++){ @@ -24917,9 +28490,9 @@ SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){ ** ** This version of the memory allocation subsystem omits all ** use of malloc(). The SQLite user supplies a block of memory -** before calling sqlite3_initialize() from which allocations +** before calling tdsqlite3_initialize() from which allocations ** are made and returned by the xMalloc() and xRealloc() -** implementations. Once sqlite3_initialize() has been called, +** implementations. Once tdsqlite3_initialize() has been called, ** the amount of memory available to SQLite is fixed and cannot ** be changed. ** @@ -24933,7 +28506,7 @@ SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){ ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not ** mean that the library will use a memory-pool by default, just that ** it is available. The mempool allocator is activated by calling -** sqlite3_config(). +** tdsqlite3_config(). */ #ifdef SQLITE_ENABLE_MEMSYS3 @@ -25016,7 +28589,7 @@ static SQLITE_WSD struct Mem3Global { /* ** Mutex to control access to the memory allocation subsystem. */ - sqlite3_mutex *mutex; + tdsqlite3_mutex *mutex; /* ** The minimum amount of free space that we have seen. @@ -25050,7 +28623,7 @@ static SQLITE_WSD struct Mem3Global { static void memsys3UnlinkFromList(u32 i, u32 *pRoot){ u32 next = mem3.aPool[i].u.list.next; u32 prev = mem3.aPool[i].u.list.prev; - assert( sqlite3_mutex_held(mem3.mutex) ); + assert( tdsqlite3_mutex_held(mem3.mutex) ); if( prev==0 ){ *pRoot = next; }else{ @@ -25069,7 +28642,7 @@ static void memsys3UnlinkFromList(u32 i, u32 *pRoot){ */ static void memsys3Unlink(u32 i){ u32 size, hash; - assert( sqlite3_mutex_held(mem3.mutex) ); + assert( tdsqlite3_mutex_held(mem3.mutex) ); assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); assert( i>=1 ); size = mem3.aPool[i-1].u.hdr.size4x/4; @@ -25088,7 +28661,7 @@ static void memsys3Unlink(u32 i){ ** at *pRoot. */ static void memsys3LinkIntoList(u32 i, u32 *pRoot){ - assert( sqlite3_mutex_held(mem3.mutex) ); + assert( tdsqlite3_mutex_held(mem3.mutex) ); mem3.aPool[i].u.list.next = *pRoot; mem3.aPool[i].u.list.prev = 0; if( *pRoot ){ @@ -25103,7 +28676,7 @@ static void memsys3LinkIntoList(u32 i, u32 *pRoot){ */ static void memsys3Link(u32 i){ u32 size, hash; - assert( sqlite3_mutex_held(mem3.mutex) ); + assert( tdsqlite3_mutex_held(mem3.mutex) ); assert( i>=1 ); assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); size = mem3.aPool[i-1].u.hdr.size4x/4; @@ -25120,16 +28693,16 @@ static void memsys3Link(u32 i){ /* ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex ** will already be held (obtained by code in malloc.c) if -** sqlite3GlobalConfig.bMemStat is true. +** tdsqlite3GlobalConfig.bMemStat is true. */ static void memsys3Enter(void){ - if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){ - mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + if( tdsqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){ + mem3.mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } - sqlite3_mutex_enter(mem3.mutex); + tdsqlite3_mutex_enter(mem3.mutex); } static void memsys3Leave(void){ - sqlite3_mutex_leave(mem3.mutex); + tdsqlite3_mutex_leave(mem3.mutex); } /* @@ -25138,10 +28711,10 @@ static void memsys3Leave(void){ static void memsys3OutOfMemory(int nByte){ if( !mem3.alarmBusy ){ mem3.alarmBusy = 1; - assert( sqlite3_mutex_held(mem3.mutex) ); - sqlite3_mutex_leave(mem3.mutex); - sqlite3_release_memory(nByte); - sqlite3_mutex_enter(mem3.mutex); + assert( tdsqlite3_mutex_held(mem3.mutex) ); + tdsqlite3_mutex_leave(mem3.mutex); + tdsqlite3_release_memory(nByte); + tdsqlite3_mutex_enter(mem3.mutex); mem3.alarmBusy = 0; } } @@ -25154,7 +28727,7 @@ static void memsys3OutOfMemory(int nByte){ */ static void *memsys3Checkout(u32 i, u32 nBlock){ u32 x; - assert( sqlite3_mutex_held(mem3.mutex) ); + assert( tdsqlite3_mutex_held(mem3.mutex) ); assert( i>=1 ); assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ); assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock ); @@ -25171,7 +28744,7 @@ static void *memsys3Checkout(u32 i, u32 nBlock){ ** is not large enough, return 0. */ static void *memsys3FromMaster(u32 nBlock){ - assert( sqlite3_mutex_held(mem3.mutex) ); + assert( tdsqlite3_mutex_held(mem3.mutex) ); assert( mem3.szMaster>=nBlock ); if( nBlock>=mem3.szMaster-1 ){ /* Use the entire master */ @@ -25218,7 +28791,7 @@ static void *memsys3FromMaster(u32 nBlock){ static void memsys3Merge(u32 *pRoot){ u32 iNext, prev, size, i, x; - assert( sqlite3_mutex_held(mem3.mutex) ); + assert( tdsqlite3_mutex_held(mem3.mutex) ); for(i=*pRoot; i>0; i=iNext){ iNext = mem3.aPool[i].u.list.next; size = mem3.aPool[i-1].u.hdr.size4x; @@ -25259,7 +28832,7 @@ static void *memsys3MallocUnsafe(int nByte){ u32 nBlock; u32 toFree; - assert( sqlite3_mutex_held(mem3.mutex) ); + assert( tdsqlite3_mutex_held(mem3.mutex) ); assert( sizeof(Mem3Block)==8 ); if( nByte<=12 ){ nBlock = 2; @@ -25340,7 +28913,7 @@ static void memsys3FreeUnsafe(void *pOld){ Mem3Block *p = (Mem3Block*)pOld; int i; u32 size, x; - assert( sqlite3_mutex_held(mem3.mutex) ); + assert( tdsqlite3_mutex_held(mem3.mutex) ); assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] ); i = p - mem3.aPool; assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 ); @@ -25400,7 +28973,7 @@ static int memsys3Roundup(int n){ ** Allocate nBytes of memory. */ static void *memsys3Malloc(int nBytes){ - sqlite3_int64 *p; + tdsqlite3_int64 *p; assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */ memsys3Enter(); p = memsys3MallocUnsafe(nBytes); @@ -25425,10 +28998,10 @@ static void *memsys3Realloc(void *pPrior, int nBytes){ int nOld; void *p; if( pPrior==0 ){ - return sqlite3_malloc(nBytes); + return tdsqlite3_malloc(nBytes); } if( nBytes<=0 ){ - sqlite3_free(pPrior); + tdsqlite3_free(pPrior); return 0; } nOld = memsys3Size(pPrior); @@ -25454,14 +29027,14 @@ static void *memsys3Realloc(void *pPrior, int nBytes){ */ static int memsys3Init(void *NotUsed){ UNUSED_PARAMETER(NotUsed); - if( !sqlite3GlobalConfig.pHeap ){ + if( !tdsqlite3GlobalConfig.pHeap ){ return SQLITE_ERROR; } /* Store a pointer to the memory block in global structure mem3. */ assert( sizeof(Mem3Block)==8 ); - mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap; - mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2; + mem3.aPool = (Mem3Block *)tdsqlite3GlobalConfig.pHeap; + mem3.nPool = (tdsqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2; /* Initialize the master block. */ mem3.szMaster = mem3.nPool; @@ -25489,7 +29062,7 @@ static void memsys3Shutdown(void *NotUsed){ ** Open the file indicated and write a log of all unfreed memory ** allocations into that log. */ -SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){ +SQLITE_PRIVATE void tdsqlite3Memsys3Dump(const char *zFilename){ #ifdef SQLITE_DEBUG FILE *out; u32 i, j; @@ -25551,7 +29124,7 @@ SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){ fprintf(out, "master=%d\n", mem3.iMaster); fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8); fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8); - sqlite3_mutex_leave(mem3.mutex); + tdsqlite3_mutex_leave(mem3.mutex); if( out==stdout ){ fflush(stdout); }else{ @@ -25567,14 +29140,14 @@ SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){ ** linkage. ** ** Populate the low-level memory allocation function pointers in -** sqlite3GlobalConfig.m with pointers to the routines in this file. The +** tdsqlite3GlobalConfig.m with pointers to the routines in this file. The ** arguments specify the block of memory to manage. ** -** This routine is only called by sqlite3_config(), and therefore +** This routine is only called by tdsqlite3_config(), and therefore ** is not required to be threadsafe (it is not). */ -SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){ - static const sqlite3_mem_methods mempoolMethods = { +SQLITE_PRIVATE const tdsqlite3_mem_methods *tdsqlite3MemGetMemsys3(void){ + static const tdsqlite3_mem_methods mempoolMethods = { memsys3Malloc, memsys3Free, memsys3Realloc, @@ -25607,9 +29180,9 @@ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){ ** ** This version of the memory allocation subsystem omits all ** use of malloc(). The application gives SQLite a block of memory -** before calling sqlite3_initialize() from which allocations +** before calling tdsqlite3_initialize() from which allocations ** are made and returned by the xMalloc() and xRealloc() -** implementations. Once sqlite3_initialize() has been called, +** implementations. Once tdsqlite3_initialize() has been called, ** the amount of memory available to SQLite is fixed and cannot ** be changed. ** @@ -25638,7 +29211,7 @@ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){ ** ** N >= M*(1 + log2(n)/2) - n + 1 ** -** The sqlite3_status() logic tracks the maximum values of n and M so +** The tdsqlite3_status() logic tracks the maximum values of n and M so ** that an application can, at any time, verify this constraint. */ /* #include "sqliteInt.h" */ @@ -25693,7 +29266,7 @@ static SQLITE_WSD struct Mem5Global { /* ** Mutex to control access to the memory allocation subsystem. */ - sqlite3_mutex *mutex; + tdsqlite3_mutex *mutex; #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* @@ -25763,7 +29336,7 @@ static void memsys5Unlink(int i, int iLogsize){ */ static void memsys5Link(int i, int iLogsize){ int x; - assert( sqlite3_mutex_held(mem5.mutex) ); + assert( tdsqlite3_mutex_held(mem5.mutex) ); assert( i>=0 && i<mem5.nBlock ); assert( iLogsize>=0 && iLogsize<=LOGMAX ); assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); @@ -25781,10 +29354,10 @@ static void memsys5Link(int i, int iLogsize){ ** Obtain or release the mutex needed to access global data structures. */ static void memsys5Enter(void){ - sqlite3_mutex_enter(mem5.mutex); + tdsqlite3_mutex_enter(mem5.mutex); } static void memsys5Leave(void){ - sqlite3_mutex_leave(mem5.mutex); + tdsqlite3_mutex_leave(mem5.mutex); } /* @@ -25840,8 +29413,8 @@ static void *memsys5MallocUnsafe(int nByte){ */ for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){} if( iBin>LOGMAX ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte); + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + tdsqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte); return 0; } i = mem5.aiFreelist[iBin]; @@ -25947,7 +29520,7 @@ static void memsys5FreeUnsafe(void *pOld){ ** Allocate nBytes of memory. */ static void *memsys5Malloc(int nBytes){ - sqlite3_int64 *p = 0; + tdsqlite3_int64 *p = 0; if( nBytes>0 ){ memsys5Enter(); p = memsys5MallocUnsafe(nBytes); @@ -26057,12 +29630,12 @@ static int memsys5Init(void *NotUsed){ */ assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 ); - nByte = sqlite3GlobalConfig.nHeap; - zByte = (u8*)sqlite3GlobalConfig.pHeap; - assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */ + nByte = tdsqlite3GlobalConfig.nHeap; + zByte = (u8*)tdsqlite3GlobalConfig.pHeap; + assert( zByte!=0 ); /* tdsqlite3_config() does not allow otherwise */ - /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */ - nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq); + /* boundaries on tdsqlite3GlobalConfig.mnReq are enforced in tdsqlite3_config() */ + nMinLog = memsys5Log(tdsqlite3GlobalConfig.mnReq); mem5.szAtom = (1<<nMinLog); while( (int)sizeof(Mem5Link)>mem5.szAtom ){ mem5.szAtom = mem5.szAtom << 1; @@ -26088,8 +29661,8 @@ static int memsys5Init(void *NotUsed){ } /* If a mutex is required for normal operation, allocate one */ - if( sqlite3GlobalConfig.bMemstat==0 ){ - mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + if( tdsqlite3GlobalConfig.bMemstat==0 ){ + mem5.mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); } return SQLITE_OK; @@ -26109,7 +29682,7 @@ static void memsys5Shutdown(void *NotUsed){ ** Open the file indicated and write a log of all unfreed memory ** allocations into that log. */ -SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){ +SQLITE_PRIVATE void tdsqlite3Memsys5Dump(const char *zFilename){ FILE *out; int i, j, n; int nMinLog; @@ -26149,11 +29722,11 @@ SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){ /* ** This routine is the only routine in this file with external -** linkage. It returns a pointer to a static sqlite3_mem_methods +** linkage. It returns a pointer to a static tdsqlite3_mem_methods ** struct populated with the memsys5 methods. */ -SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){ - static const sqlite3_mem_methods memsys5Methods = { +SQLITE_PRIVATE const tdsqlite3_mem_methods *tdsqlite3MemGetMemsys5(void){ + static const tdsqlite3_mem_methods memsys5Methods = { memsys5Malloc, memsys5Free, memsys5Realloc, @@ -26198,24 +29771,215 @@ static SQLITE_WSD int mutexIsInit = 0; #ifndef SQLITE_MUTEX_OMIT + +#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS +/* +** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains +** the implementation of a wrapper around the system default mutex +** implementation (tdsqlite3DefaultMutex()). +** +** Most calls are passed directly through to the underlying default +** mutex implementation. Except, if a mutex is configured by calling +** tdsqlite3MutexWarnOnContention() on it, then if contention is ever +** encountered within xMutexEnter() a warning is emitted via tdsqlite3_log(). +** +** This type of mutex is used as the database handle mutex when testing +** apps that usually use SQLITE_CONFIG_MULTITHREAD mode. +*/ + +/* +** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS +** is defined. Variable CheckMutex.mutex is a pointer to the real mutex +** allocated by the system mutex implementation. Variable iType is usually set +** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST +** or one of the static mutex identifiers. Or, if this is a recursive mutex +** that has been configured using tdsqlite3MutexWarnOnContention(), it is +** set to SQLITE_MUTEX_WARNONCONTENTION. +*/ +typedef struct CheckMutex CheckMutex; +struct CheckMutex { + int iType; + tdsqlite3_mutex *mutex; +}; + +#define SQLITE_MUTEX_WARNONCONTENTION (-1) + +/* +** Pointer to real mutex methods object used by the CheckMutex +** implementation. Set by checkMutexInit(). +*/ +static SQLITE_WSD const tdsqlite3_mutex_methods *pGlobalMutexMethods; + +#ifdef SQLITE_DEBUG +static int checkMutexHeld(tdsqlite3_mutex *p){ + return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex); +} +static int checkMutexNotheld(tdsqlite3_mutex *p){ + return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex); +} +#endif + +/* +** Initialize and deinitialize the mutex subsystem. +*/ +static int checkMutexInit(void){ + pGlobalMutexMethods = tdsqlite3DefaultMutex(); + return SQLITE_OK; +} +static int checkMutexEnd(void){ + pGlobalMutexMethods = 0; + return SQLITE_OK; +} + +/* +** Allocate a mutex. +*/ +static tdsqlite3_mutex *checkMutexAlloc(int iType){ + static CheckMutex staticMutexes[] = { + {2, 0}, {3, 0}, {4, 0}, {5, 0}, + {6, 0}, {7, 0}, {8, 0}, {9, 0}, + {10, 0}, {11, 0}, {12, 0}, {13, 0} + }; + CheckMutex *p = 0; + + assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 ); + if( iType<2 ){ + p = tdsqlite3MallocZero(sizeof(CheckMutex)); + if( p==0 ) return 0; + p->iType = iType; + }else{ +#ifdef SQLITE_ENABLE_API_ARMOR + if( iType-2>=ArraySize(staticMutexes) ){ + (void)SQLITE_MISUSE_BKPT; + return 0; + } +#endif + p = &staticMutexes[iType-2]; + } + + if( p->mutex==0 ){ + p->mutex = pGlobalMutexMethods->xMutexAlloc(iType); + if( p->mutex==0 ){ + if( iType<2 ){ + tdsqlite3_free(p); + } + p = 0; + } + } + + return (tdsqlite3_mutex*)p; +} + +/* +** Free a mutex. +*/ +static void checkMutexFree(tdsqlite3_mutex *p){ + assert( SQLITE_MUTEX_RECURSIVE<2 ); + assert( SQLITE_MUTEX_FAST<2 ); + assert( SQLITE_MUTEX_WARNONCONTENTION<2 ); + +#if SQLITE_ENABLE_API_ARMOR + if( ((CheckMutex*)p)->iType<2 ) +#endif + { + CheckMutex *pCheck = (CheckMutex*)p; + pGlobalMutexMethods->xMutexFree(pCheck->mutex); + tdsqlite3_free(pCheck); + } +#ifdef SQLITE_ENABLE_API_ARMOR + else{ + (void)SQLITE_MISUSE_BKPT; + } +#endif +} + +/* +** Enter the mutex. +*/ +static void checkMutexEnter(tdsqlite3_mutex *p){ + CheckMutex *pCheck = (CheckMutex*)p; + if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){ + if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){ + return; + } + tdsqlite3_log(SQLITE_MISUSE, + "illegal multi-threaded access to database connection" + ); + } + pGlobalMutexMethods->xMutexEnter(pCheck->mutex); +} + +/* +** Enter the mutex (do not block). +*/ +static int checkMutexTry(tdsqlite3_mutex *p){ + CheckMutex *pCheck = (CheckMutex*)p; + return pGlobalMutexMethods->xMutexTry(pCheck->mutex); +} + +/* +** Leave the mutex. +*/ +static void checkMutexLeave(tdsqlite3_mutex *p){ + CheckMutex *pCheck = (CheckMutex*)p; + pGlobalMutexMethods->xMutexLeave(pCheck->mutex); +} + +tdsqlite3_mutex_methods const *multiThreadedCheckMutex(void){ + static const tdsqlite3_mutex_methods sMutex = { + checkMutexInit, + checkMutexEnd, + checkMutexAlloc, + checkMutexFree, + checkMutexEnter, + checkMutexTry, + checkMutexLeave, +#ifdef SQLITE_DEBUG + checkMutexHeld, + checkMutexNotheld +#else + 0, + 0 +#endif + }; + return &sMutex; +} + +/* +** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as +** one on which there should be no contention. +*/ +SQLITE_PRIVATE void tdsqlite3MutexWarnOnContention(tdsqlite3_mutex *p){ + if( tdsqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){ + CheckMutex *pCheck = (CheckMutex*)p; + assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE ); + pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION; + } +} +#endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */ + /* ** Initialize the mutex system. */ -SQLITE_PRIVATE int sqlite3MutexInit(void){ +SQLITE_PRIVATE int tdsqlite3MutexInit(void){ int rc = SQLITE_OK; - if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){ + if( !tdsqlite3GlobalConfig.mutex.xMutexAlloc ){ /* If the xMutexAlloc method has not been set, then the user did not - ** install a mutex implementation via sqlite3_config() prior to - ** sqlite3_initialize() being called. This block copies pointers to - ** the default implementation into the sqlite3GlobalConfig structure. + ** install a mutex implementation via tdsqlite3_config() prior to + ** tdsqlite3_initialize() being called. This block copies pointers to + ** the default implementation into the tdsqlite3GlobalConfig structure. */ - sqlite3_mutex_methods const *pFrom; - sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex; + tdsqlite3_mutex_methods const *pFrom; + tdsqlite3_mutex_methods *pTo = &tdsqlite3GlobalConfig.mutex; - if( sqlite3GlobalConfig.bCoreMutex ){ - pFrom = sqlite3DefaultMutex(); + if( tdsqlite3GlobalConfig.bCoreMutex ){ +#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS + pFrom = multiThreadedCheckMutex(); +#else + pFrom = tdsqlite3DefaultMutex(); +#endif }else{ - pFrom = sqlite3NoopMutex(); + pFrom = tdsqlite3NoopMutex(); } pTo->xMutexInit = pFrom->xMutexInit; pTo->xMutexEnd = pFrom->xMutexEnd; @@ -26225,11 +29989,11 @@ SQLITE_PRIVATE int sqlite3MutexInit(void){ pTo->xMutexLeave = pFrom->xMutexLeave; pTo->xMutexHeld = pFrom->xMutexHeld; pTo->xMutexNotheld = pFrom->xMutexNotheld; - sqlite3MemoryBarrier(); + tdsqlite3MemoryBarrier(); pTo->xMutexAlloc = pFrom->xMutexAlloc; } - assert( sqlite3GlobalConfig.mutex.xMutexInit ); - rc = sqlite3GlobalConfig.mutex.xMutexInit(); + assert( tdsqlite3GlobalConfig.mutex.xMutexInit ); + rc = tdsqlite3GlobalConfig.mutex.xMutexInit(); #ifdef SQLITE_DEBUG GLOBAL(int, mutexIsInit) = 1; @@ -26240,12 +30004,12 @@ SQLITE_PRIVATE int sqlite3MutexInit(void){ /* ** Shutdown the mutex system. This call frees resources allocated by -** sqlite3MutexInit(). +** tdsqlite3MutexInit(). */ -SQLITE_PRIVATE int sqlite3MutexEnd(void){ +SQLITE_PRIVATE int tdsqlite3MutexEnd(void){ int rc = SQLITE_OK; - if( sqlite3GlobalConfig.mutex.xMutexEnd ){ - rc = sqlite3GlobalConfig.mutex.xMutexEnd(); + if( tdsqlite3GlobalConfig.mutex.xMutexEnd ){ + rc = tdsqlite3GlobalConfig.mutex.xMutexEnd(); } #ifdef SQLITE_DEBUG @@ -26258,31 +30022,31 @@ SQLITE_PRIVATE int sqlite3MutexEnd(void){ /* ** Retrieve a pointer to a static mutex or allocate a new dynamic one. */ -SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){ +SQLITE_API tdsqlite3_mutex *tdsqlite3_mutex_alloc(int id){ #ifndef SQLITE_OMIT_AUTOINIT - if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0; - if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0; + if( id<=SQLITE_MUTEX_RECURSIVE && tdsqlite3_initialize() ) return 0; + if( id>SQLITE_MUTEX_RECURSIVE && tdsqlite3MutexInit() ) return 0; #endif - assert( sqlite3GlobalConfig.mutex.xMutexAlloc ); - return sqlite3GlobalConfig.mutex.xMutexAlloc(id); + assert( tdsqlite3GlobalConfig.mutex.xMutexAlloc ); + return tdsqlite3GlobalConfig.mutex.xMutexAlloc(id); } -SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){ - if( !sqlite3GlobalConfig.bCoreMutex ){ +SQLITE_PRIVATE tdsqlite3_mutex *tdsqlite3MutexAlloc(int id){ + if( !tdsqlite3GlobalConfig.bCoreMutex ){ return 0; } assert( GLOBAL(int, mutexIsInit) ); - assert( sqlite3GlobalConfig.mutex.xMutexAlloc ); - return sqlite3GlobalConfig.mutex.xMutexAlloc(id); + assert( tdsqlite3GlobalConfig.mutex.xMutexAlloc ); + return tdsqlite3GlobalConfig.mutex.xMutexAlloc(id); } /* ** Free a dynamic mutex. */ -SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){ +SQLITE_API void tdsqlite3_mutex_free(tdsqlite3_mutex *p){ if( p ){ - assert( sqlite3GlobalConfig.mutex.xMutexFree ); - sqlite3GlobalConfig.mutex.xMutexFree(p); + assert( tdsqlite3GlobalConfig.mutex.xMutexFree ); + tdsqlite3GlobalConfig.mutex.xMutexFree(p); } } @@ -26290,10 +30054,10 @@ SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){ ** Obtain the mutex p. If some other thread already has the mutex, block ** until it can be obtained. */ -SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){ +SQLITE_API void tdsqlite3_mutex_enter(tdsqlite3_mutex *p){ if( p ){ - assert( sqlite3GlobalConfig.mutex.xMutexEnter ); - sqlite3GlobalConfig.mutex.xMutexEnter(p); + assert( tdsqlite3GlobalConfig.mutex.xMutexEnter ); + tdsqlite3GlobalConfig.mutex.xMutexEnter(p); } } @@ -26301,40 +30065,40 @@ SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){ ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY. */ -SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){ +SQLITE_API int tdsqlite3_mutex_try(tdsqlite3_mutex *p){ int rc = SQLITE_OK; if( p ){ - assert( sqlite3GlobalConfig.mutex.xMutexTry ); - return sqlite3GlobalConfig.mutex.xMutexTry(p); + assert( tdsqlite3GlobalConfig.mutex.xMutexTry ); + return tdsqlite3GlobalConfig.mutex.xMutexTry(p); } return rc; } /* -** The sqlite3_mutex_leave() routine exits a mutex that was previously +** The tdsqlite3_mutex_leave() routine exits a mutex that was previously ** entered by the same thread. The behavior is undefined if the mutex ** is not currently entered. If a NULL pointer is passed as an argument ** this function is a no-op. */ -SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){ +SQLITE_API void tdsqlite3_mutex_leave(tdsqlite3_mutex *p){ if( p ){ - assert( sqlite3GlobalConfig.mutex.xMutexLeave ); - sqlite3GlobalConfig.mutex.xMutexLeave(p); + assert( tdsqlite3GlobalConfig.mutex.xMutexLeave ); + tdsqlite3GlobalConfig.mutex.xMutexLeave(p); } } #ifndef NDEBUG /* -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** The tdsqlite3_mutex_held() and tdsqlite3_mutex_notheld() routine are ** intended for use inside assert() statements. */ -SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){ - assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld ); - return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p); +SQLITE_API int tdsqlite3_mutex_held(tdsqlite3_mutex *p){ + assert( p==0 || tdsqlite3GlobalConfig.mutex.xMutexHeld ); + return p==0 || tdsqlite3GlobalConfig.mutex.xMutexHeld(p); } -SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){ - assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld ); - return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p); +SQLITE_API int tdsqlite3_mutex_notheld(tdsqlite3_mutex *p){ + assert( p==0 || tdsqlite3GlobalConfig.mutex.xMutexNotheld ); + return p==0 || tdsqlite3GlobalConfig.mutex.xMutexNotheld(p); } #endif @@ -26361,7 +30125,7 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){ ** here are place-holders. Applications can substitute working ** mutex routines at start-time using the ** -** sqlite3_config(SQLITE_CONFIG_MUTEX,...) +** tdsqlite3_config(SQLITE_CONFIG_MUTEX,...) ** ** interface. ** @@ -26381,20 +30145,20 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){ */ static int noopMutexInit(void){ return SQLITE_OK; } static int noopMutexEnd(void){ return SQLITE_OK; } -static sqlite3_mutex *noopMutexAlloc(int id){ +static tdsqlite3_mutex *noopMutexAlloc(int id){ UNUSED_PARAMETER(id); - return (sqlite3_mutex*)8; + return (tdsqlite3_mutex*)8; } -static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } -static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } -static int noopMutexTry(sqlite3_mutex *p){ +static void noopMutexFree(tdsqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } +static void noopMutexEnter(tdsqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } +static int noopMutexTry(tdsqlite3_mutex *p){ UNUSED_PARAMETER(p); return SQLITE_OK; } -static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } +static void noopMutexLeave(tdsqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ - static const sqlite3_mutex_methods sMutex = { +SQLITE_PRIVATE tdsqlite3_mutex_methods const *tdsqlite3NoopMutex(void){ + static const tdsqlite3_mutex_methods sMutex = { noopMutexInit, noopMutexEnd, noopMutexAlloc, @@ -26421,21 +30185,21 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ /* ** The mutex object */ -typedef struct sqlite3_debug_mutex { +typedef struct tdsqlite3_debug_mutex { int id; /* The mutex type */ int cnt; /* Number of entries without a matching leave */ -} sqlite3_debug_mutex; +} tdsqlite3_debug_mutex; /* -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** The tdsqlite3_mutex_held() and tdsqlite3_mutex_notheld() routine are ** intended for use inside assert() statements. */ -static int debugMutexHeld(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; +static int debugMutexHeld(tdsqlite3_mutex *pX){ + tdsqlite3_debug_mutex *p = (tdsqlite3_debug_mutex*)pX; return p==0 || p->cnt>0; } -static int debugMutexNotheld(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; +static int debugMutexNotheld(tdsqlite3_mutex *pX){ + tdsqlite3_debug_mutex *p = (tdsqlite3_debug_mutex*)pX; return p==0 || p->cnt==0; } @@ -26446,17 +30210,17 @@ static int debugMutexInit(void){ return SQLITE_OK; } static int debugMutexEnd(void){ return SQLITE_OK; } /* -** The sqlite3_mutex_alloc() routine allocates a new +** The tdsqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. */ -static sqlite3_mutex *debugMutexAlloc(int id){ - static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1]; - sqlite3_debug_mutex *pNew = 0; +static tdsqlite3_mutex *debugMutexAlloc(int id){ + static tdsqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1]; + tdsqlite3_debug_mutex *pNew = 0; switch( id ){ case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { - pNew = sqlite3Malloc(sizeof(*pNew)); + pNew = tdsqlite3Malloc(sizeof(*pNew)); if( pNew ){ pNew->id = id; pNew->cnt = 0; @@ -26475,17 +30239,17 @@ static sqlite3_mutex *debugMutexAlloc(int id){ break; } } - return (sqlite3_mutex*)pNew; + return (tdsqlite3_mutex*)pNew; } /* ** This routine deallocates a previously allocated mutex. */ -static void debugMutexFree(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; +static void debugMutexFree(tdsqlite3_mutex *pX){ + tdsqlite3_debug_mutex *p = (tdsqlite3_debug_mutex*)pX; assert( p->cnt==0 ); if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){ - sqlite3_free(p); + tdsqlite3_free(p); }else{ #ifdef SQLITE_ENABLE_API_ARMOR (void)SQLITE_MISUSE_BKPT; @@ -26494,43 +30258,43 @@ static void debugMutexFree(sqlite3_mutex *pX){ } /* -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** The tdsqlite3_mutex_enter() and tdsqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** tdsqlite3_mutex_enter() will block and tdsqlite3_mutex_try() will return +** SQLITE_BUSY. The tdsqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ -static void debugMutexEnter(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; +static void debugMutexEnter(tdsqlite3_mutex *pX){ + tdsqlite3_debug_mutex *p = (tdsqlite3_debug_mutex*)pX; assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); p->cnt++; } -static int debugMutexTry(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; +static int debugMutexTry(tdsqlite3_mutex *pX){ + tdsqlite3_debug_mutex *p = (tdsqlite3_debug_mutex*)pX; assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); p->cnt++; return SQLITE_OK; } /* -** The sqlite3_mutex_leave() routine exits a mutex that was +** The tdsqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ -static void debugMutexLeave(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; +static void debugMutexLeave(tdsqlite3_mutex *pX){ + tdsqlite3_debug_mutex *p = (tdsqlite3_debug_mutex*)pX; assert( debugMutexHeld(pX) ); p->cnt--; assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); } -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ - static const sqlite3_mutex_methods sMutex = { +SQLITE_PRIVATE tdsqlite3_mutex_methods const *tdsqlite3NoopMutex(void){ + static const tdsqlite3_mutex_methods sMutex = { debugMutexInit, debugMutexEnd, debugMutexAlloc, @@ -26552,8 +30316,8 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ ** is used regardless of the run-time threadsafety setting. */ #ifdef SQLITE_MUTEX_NOOP -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ - return sqlite3NoopMutex(); +SQLITE_PRIVATE tdsqlite3_mutex_methods const *tdsqlite3DefaultMutex(void){ + return tdsqlite3NoopMutex(); } #endif /* defined(SQLITE_MUTEX_NOOP) */ #endif /* !defined(SQLITE_MUTEX_OMIT) */ @@ -26587,7 +30351,7 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ #include <pthread.h> /* -** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields +** The tdsqlite3_mutex.id, tdsqlite3_mutex.nRef, and tdsqlite3_mutex.owner fields ** are necessary under two condidtions: (1) Debug builds and (2) using ** home-grown mutexes. Encapsulate these conditions into a single #define. */ @@ -26600,7 +30364,7 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ /* ** Each recursive mutex is an instance of the following structure. */ -struct sqlite3_mutex { +struct tdsqlite3_mutex { pthread_mutex_t mutex; /* Mutex controlling the lock */ #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR) int id; /* Mutex type */ @@ -26612,15 +30376,16 @@ struct sqlite3_mutex { #endif }; #if SQLITE_MUTEX_NREF -#define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0} +# define SQLITE3_MUTEX_INITIALIZER(id) \ + {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0} #elif defined(SQLITE_ENABLE_API_ARMOR) -#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 } +# define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id } #else -#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER } +#define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER } #endif /* -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** The tdsqlite3_mutex_held() and tdsqlite3_mutex_notheld() routine are ** intended for use only inside assert() statements. On some platforms, ** there might be race conditions that can cause these routines to ** deliver incorrect results. In particular, if pthread_equal() is @@ -26636,10 +30401,10 @@ struct sqlite3_mutex { ** routines are never called. */ #if !defined(NDEBUG) || defined(SQLITE_DEBUG) -static int pthreadMutexHeld(sqlite3_mutex *p){ +static int pthreadMutexHeld(tdsqlite3_mutex *p){ return (p->nRef!=0 && pthread_equal(p->owner, pthread_self())); } -static int pthreadMutexNotheld(sqlite3_mutex *p){ +static int pthreadMutexNotheld(tdsqlite3_mutex *p){ return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0; } #endif @@ -26649,7 +30414,7 @@ static int pthreadMutexNotheld(sqlite3_mutex *p){ ** and also for the implementation of xShmBarrier in the VFS in cases ** where SQLite is compiled without mutexes. */ -SQLITE_PRIVATE void sqlite3MemoryBarrier(void){ +SQLITE_PRIVATE void tdsqlite3MemoryBarrier(void){ #if defined(SQLITE_MEMORY_BARRIER) SQLITE_MEMORY_BARRIER; #elif defined(__GNUC__) && GCC_VERSION>=4001000 @@ -26664,11 +30429,11 @@ static int pthreadMutexInit(void){ return SQLITE_OK; } static int pthreadMutexEnd(void){ return SQLITE_OK; } /* -** The sqlite3_mutex_alloc() routine allocates a new +** The tdsqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. SQLite ** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: +** to tdsqlite3_mutex_alloc() is one of these integer constants: ** ** <ul> ** <li> SQLITE_MUTEX_FAST @@ -26687,7 +30452,7 @@ static int pthreadMutexEnd(void){ return SQLITE_OK; } ** <li> SQLITE_MUTEX_STATIC_VFS3 ** </ul> ** -** The first two constants cause sqlite3_mutex_alloc() to create +** The first two constants cause tdsqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction @@ -26697,7 +30462,7 @@ static int pthreadMutexEnd(void){ return SQLITE_OK; } ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** -** The other allowed parameters to sqlite3_mutex_alloc() each return +** The other allowed parameters to tdsqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. Six static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal @@ -26706,30 +30471,30 @@ static int pthreadMutexEnd(void){ return SQLITE_OK; } ** SQLITE_MUTEX_RECURSIVE. ** ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST -** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** or SQLITE_MUTEX_RECURSIVE) is used then tdsqlite3_mutex_alloc() ** returns a different mutex on every call. But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. */ -static sqlite3_mutex *pthreadMutexAlloc(int iType){ - static sqlite3_mutex staticMutexes[] = { - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER +static tdsqlite3_mutex *pthreadMutexAlloc(int iType){ + static tdsqlite3_mutex staticMutexes[] = { + SQLITE3_MUTEX_INITIALIZER(2), + SQLITE3_MUTEX_INITIALIZER(3), + SQLITE3_MUTEX_INITIALIZER(4), + SQLITE3_MUTEX_INITIALIZER(5), + SQLITE3_MUTEX_INITIALIZER(6), + SQLITE3_MUTEX_INITIALIZER(7), + SQLITE3_MUTEX_INITIALIZER(8), + SQLITE3_MUTEX_INITIALIZER(9), + SQLITE3_MUTEX_INITIALIZER(10), + SQLITE3_MUTEX_INITIALIZER(11), + SQLITE3_MUTEX_INITIALIZER(12), + SQLITE3_MUTEX_INITIALIZER(13) }; - sqlite3_mutex *p; + tdsqlite3_mutex *p; switch( iType ){ case SQLITE_MUTEX_RECURSIVE: { - p = sqlite3MallocZero( sizeof(*p) ); + p = tdsqlite3MallocZero( sizeof(*p) ); if( p ){ #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX /* If recursive mutexes are not available, we will have to @@ -26743,13 +30508,19 @@ static sqlite3_mutex *pthreadMutexAlloc(int iType){ pthread_mutex_init(&p->mutex, &recursiveAttr); pthread_mutexattr_destroy(&recursiveAttr); #endif +#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR) + p->id = SQLITE_MUTEX_RECURSIVE; +#endif } break; } case SQLITE_MUTEX_FAST: { - p = sqlite3MallocZero( sizeof(*p) ); + p = tdsqlite3MallocZero( sizeof(*p) ); if( p ){ pthread_mutex_init(&p->mutex, 0); +#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR) + p->id = SQLITE_MUTEX_FAST; +#endif } break; } @@ -26765,7 +30536,7 @@ static sqlite3_mutex *pthreadMutexAlloc(int iType){ } } #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR) - if( p ) p->id = iType; + assert( p==0 || p->id==iType ); #endif return p; } @@ -26776,14 +30547,14 @@ static sqlite3_mutex *pthreadMutexAlloc(int iType){ ** allocated mutex. SQLite is careful to deallocate every ** mutex that it allocates. */ -static void pthreadMutexFree(sqlite3_mutex *p){ +static void pthreadMutexFree(tdsqlite3_mutex *p){ assert( p->nRef==0 ); #if SQLITE_ENABLE_API_ARMOR if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ) #endif { pthread_mutex_destroy(&p->mutex); - sqlite3_free(p); + tdsqlite3_free(p); } #ifdef SQLITE_ENABLE_API_ARMOR else{ @@ -26793,17 +30564,17 @@ static void pthreadMutexFree(sqlite3_mutex *p){ } /* -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** The tdsqlite3_mutex_enter() and tdsqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** tdsqlite3_mutex_enter() will block and tdsqlite3_mutex_try() will return +** SQLITE_BUSY. The tdsqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ -static void pthreadMutexEnter(sqlite3_mutex *p){ +static void pthreadMutexEnter(tdsqlite3_mutex *p){ assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX @@ -26845,7 +30616,7 @@ static void pthreadMutexEnter(sqlite3_mutex *p){ } #endif } -static int pthreadMutexTry(sqlite3_mutex *p){ +static int pthreadMutexTry(tdsqlite3_mutex *p){ int rc; assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); @@ -26897,12 +30668,12 @@ static int pthreadMutexTry(sqlite3_mutex *p){ } /* -** The sqlite3_mutex_leave() routine exits a mutex that was +** The tdsqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ -static void pthreadMutexLeave(sqlite3_mutex *p){ +static void pthreadMutexLeave(tdsqlite3_mutex *p){ assert( pthreadMutexHeld(p) ); #if SQLITE_MUTEX_NREF p->nRef--; @@ -26925,8 +30696,8 @@ static void pthreadMutexLeave(sqlite3_mutex *p){ #endif } -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ - static const sqlite3_mutex_methods sMutex = { +SQLITE_PRIVATE tdsqlite3_mutex_methods const *tdsqlite3DefaultMutex(void){ + static const tdsqlite3_mutex_methods sMutex = { pthreadMutexInit, pthreadMutexEnd, pthreadMutexAlloc, @@ -27027,7 +30798,7 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" -** counters for x86 class CPUs. +** counters for x86 and x86_64 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H @@ -27038,12 +30809,13 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ ** processor and returns that value. This can be used for high-res ** profiling. */ -#if (defined(__GNUC__) || defined(_MSC_VER)) && \ - (defined(i386) || defined(__i386__) || defined(_M_IX86)) +#if !defined(__STRICT_ANSI__) && \ + (defined(__GNUC__) || defined(_MSC_VER)) && \ + (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; @@ -27051,7 +30823,7 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ #elif defined(_MSC_VER) - __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ + __declspec(naked) __inline sqlite_uint64 __cdecl tdsqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX @@ -27060,17 +30832,17 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ #endif -#elif (defined(__GNUC__) && defined(__x86_64__)) +#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__)) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } -#elif (defined(__GNUC__) && defined(__ppc__)) +#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__)) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ @@ -27085,16 +30857,15 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ #else - #error Need implementation of sqlite3Hwtime() for your platform. - /* - ** To compile without implementing sqlite3Hwtime() for your platform, - ** you can remove the above #error and use the following - ** stub function. You will lose timing support for many - ** of the debugging and testing utilities, but it should at - ** least compile and run. + ** asm() is needed for hardware timing support. Without asm(), + ** disable the tdsqlite3Hwtime() routine. + ** + ** tdsqlite3Hwtime() is only used for some obscure debugging + ** and analysis configurations, not in any deliverable, so this + ** should not be a great loss. */ -SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } +SQLITE_PRIVATE sqlite_uint64 tdsqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif @@ -27105,8 +30876,8 @@ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; -#define TIMER_START g_start=sqlite3Hwtime() -#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start +#define TIMER_START g_start=tdsqlite3Hwtime() +#define TIMER_END g_elapsed=tdsqlite3Hwtime()-g_start #define TIMER_ELAPSED g_elapsed #else #define TIMER_START @@ -27120,32 +30891,32 @@ static sqlite_uint64 g_elapsed; ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_io_error_hit; -SQLITE_API extern int sqlite3_io_error_hardhit; -SQLITE_API extern int sqlite3_io_error_pending; -SQLITE_API extern int sqlite3_io_error_persist; -SQLITE_API extern int sqlite3_io_error_benign; -SQLITE_API extern int sqlite3_diskfull_pending; -SQLITE_API extern int sqlite3_diskfull; -#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) +SQLITE_API extern int tdsqlite3_io_error_hit; +SQLITE_API extern int tdsqlite3_io_error_hardhit; +SQLITE_API extern int tdsqlite3_io_error_pending; +SQLITE_API extern int tdsqlite3_io_error_persist; +SQLITE_API extern int tdsqlite3_io_error_benign; +SQLITE_API extern int tdsqlite3_diskfull_pending; +SQLITE_API extern int tdsqlite3_diskfull; +#define SimulateIOErrorBenign(X) tdsqlite3_io_error_benign=(X) #define SimulateIOError(CODE) \ - if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ - || sqlite3_io_error_pending-- == 1 ) \ + if( (tdsqlite3_io_error_persist && tdsqlite3_io_error_hit) \ + || tdsqlite3_io_error_pending-- == 1 ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); - sqlite3_io_error_hit++; - if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; + tdsqlite3_io_error_hit++; + if( !tdsqlite3_io_error_benign ) tdsqlite3_io_error_hardhit++; } #define SimulateDiskfullError(CODE) \ - if( sqlite3_diskfull_pending ){ \ - if( sqlite3_diskfull_pending == 1 ){ \ + if( tdsqlite3_diskfull_pending ){ \ + if( tdsqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ - sqlite3_diskfull = 1; \ - sqlite3_io_error_hit = 1; \ + tdsqlite3_diskfull = 1; \ + tdsqlite3_io_error_hit = 1; \ CODE; \ }else{ \ - sqlite3_diskfull_pending--; \ + tdsqlite3_diskfull_pending--; \ } \ } #else @@ -27158,8 +30929,8 @@ static void local_ioerr(){ ** When testing, keep a count of the number of open files. */ #if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_open_file_count; -#define OpenCounter(X) sqlite3_open_file_count+=(X) +SQLITE_API extern int tdsqlite3_open_file_count; +#define OpenCounter(X) tdsqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* defined(SQLITE_TEST) */ @@ -27197,8 +30968,11 @@ SQLITE_API extern int sqlite3_open_file_count; /* #include "windows.h" */ #ifdef __CYGWIN__ +# define NOCRYPT +# include <windows.h> + # include <sys/cygwin.h> -# include <errno.h> /* amalgamator: dontcache */ +/* # include <errno.h> ** amalgamator: dontcache ** */ #endif /* @@ -27276,13 +31050,13 @@ SQLITE_API extern int sqlite3_open_file_count; /* ** Each recursive mutex is an instance of the following structure. */ -struct sqlite3_mutex { +struct tdsqlite3_mutex { CRITICAL_SECTION mutex; /* Mutex controlling the lock */ int id; /* Mutex type */ #ifdef SQLITE_DEBUG volatile int nRef; /* Number of enterances */ volatile DWORD owner; /* Thread holding this mutex */ - volatile int trace; /* True to trace changes */ + volatile LONG trace; /* True to trace changes */ #endif }; @@ -27294,26 +31068,26 @@ struct sqlite3_mutex { #define SQLITE_W32_MUTEX_INITIALIZER { 0 } #ifdef SQLITE_DEBUG -#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \ +#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \ 0L, (DWORD)0, 0 } #else -#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 } +#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id } #endif #ifdef SQLITE_DEBUG /* -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are +** The tdsqlite3_mutex_held() and tdsqlite3_mutex_notheld() routine are ** intended for use only inside assert() statements. */ -static int winMutexHeld(sqlite3_mutex *p){ +static int winMutexHeld(tdsqlite3_mutex *p){ return p->nRef!=0 && p->owner==GetCurrentThreadId(); } -static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){ +static int winMutexNotheld2(tdsqlite3_mutex *p, DWORD tid){ return p->nRef==0 || p->owner!=tid; } -static int winMutexNotheld(sqlite3_mutex *p){ +static int winMutexNotheld(tdsqlite3_mutex *p){ DWORD tid = GetCurrentThreadId(); return winMutexNotheld2(p, tid); } @@ -27324,13 +31098,12 @@ static int winMutexNotheld(sqlite3_mutex *p){ ** and also for the xShmBarrier method of the VFS in cases when SQLite is ** compiled without mutexes (SQLITE_THREADSAFE=0). */ -SQLITE_PRIVATE void sqlite3MemoryBarrier(void){ +SQLITE_PRIVATE void tdsqlite3MemoryBarrier(void){ #if defined(SQLITE_MEMORY_BARRIER) SQLITE_MEMORY_BARRIER; #elif defined(__GNUC__) __sync_synchronize(); -#elif !defined(SQLITE_DISABLE_INTRINSIC) && \ - defined(_MSC_VER) && _MSC_VER>=1300 +#elif MSVC_VERSION>=1300 _ReadWriteBarrier(); #elif defined(MemoryBarrier) MemoryBarrier(); @@ -27340,32 +31113,32 @@ SQLITE_PRIVATE void sqlite3MemoryBarrier(void){ /* ** Initialize and deinitialize the mutex subsystem. */ -static sqlite3_mutex winMutex_staticMutexes[] = { - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER +static tdsqlite3_mutex winMutex_staticMutexes[] = { + SQLITE3_MUTEX_INITIALIZER(2), + SQLITE3_MUTEX_INITIALIZER(3), + SQLITE3_MUTEX_INITIALIZER(4), + SQLITE3_MUTEX_INITIALIZER(5), + SQLITE3_MUTEX_INITIALIZER(6), + SQLITE3_MUTEX_INITIALIZER(7), + SQLITE3_MUTEX_INITIALIZER(8), + SQLITE3_MUTEX_INITIALIZER(9), + SQLITE3_MUTEX_INITIALIZER(10), + SQLITE3_MUTEX_INITIALIZER(11), + SQLITE3_MUTEX_INITIALIZER(12), + SQLITE3_MUTEX_INITIALIZER(13) }; static int winMutex_isInit = 0; static int winMutex_isNt = -1; /* <0 means "need to query" */ /* As the winMutexInit() and winMutexEnd() functions are called as part -** of the sqlite3_initialize() and sqlite3_shutdown() processing, the +** of the tdsqlite3_initialize() and tdsqlite3_shutdown() processing, the ** "interlocked" magic used here is probably not strictly necessary. */ static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0; -SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */ -SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */ +SQLITE_API int tdsqlite3_win32_is_nt(void); /* os_win.c */ +SQLITE_API void tdsqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */ static int winMutexInit(void){ /* The first to increment to 1 does actual initialization */ @@ -27383,7 +31156,7 @@ static int winMutexInit(void){ /* Another thread is (in the process of) initializing the static ** mutexes */ while( !winMutex_isInit ){ - sqlite3_win32_sleep(1); + tdsqlite3_win32_sleep(1); } } return SQLITE_OK; @@ -27405,11 +31178,11 @@ static int winMutexEnd(void){ } /* -** The sqlite3_mutex_alloc() routine allocates a new +** The tdsqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. SQLite ** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: +** to tdsqlite3_mutex_alloc() is one of these integer constants: ** ** <ul> ** <li> SQLITE_MUTEX_FAST @@ -27428,7 +31201,7 @@ static int winMutexEnd(void){ ** <li> SQLITE_MUTEX_STATIC_VFS3 ** </ul> ** -** The first two constants cause sqlite3_mutex_alloc() to create +** The first two constants cause tdsqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction @@ -27438,7 +31211,7 @@ static int winMutexEnd(void){ ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** -** The other allowed parameters to sqlite3_mutex_alloc() each return +** The other allowed parameters to tdsqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. Six static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal @@ -27447,18 +31220,18 @@ static int winMutexEnd(void){ ** SQLITE_MUTEX_RECURSIVE. ** ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST -** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** or SQLITE_MUTEX_RECURSIVE) is used then tdsqlite3_mutex_alloc() ** returns a different mutex on every call. But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. */ -static sqlite3_mutex *winMutexAlloc(int iType){ - sqlite3_mutex *p; +static tdsqlite3_mutex *winMutexAlloc(int iType){ + tdsqlite3_mutex *p; switch( iType ){ case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { - p = sqlite3MallocZero( sizeof(*p) ); + p = tdsqlite3MallocZero( sizeof(*p) ); if( p ){ p->id = iType; #ifdef SQLITE_DEBUG @@ -27482,15 +31255,15 @@ static sqlite3_mutex *winMutexAlloc(int iType){ } #endif p = &winMutex_staticMutexes[iType-2]; - p->id = iType; #ifdef SQLITE_DEBUG #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC - p->trace = 1; + InterlockedCompareExchange(&p->trace, 1, 0); #endif #endif break; } } + assert( p==0 || p->id==iType ); return p; } @@ -27500,12 +31273,12 @@ static sqlite3_mutex *winMutexAlloc(int iType){ ** allocated mutex. SQLite is careful to deallocate every ** mutex that it allocates. */ -static void winMutexFree(sqlite3_mutex *p){ +static void winMutexFree(tdsqlite3_mutex *p){ assert( p ); assert( p->nRef==0 && p->owner==0 ); if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){ DeleteCriticalSection(&p->mutex); - sqlite3_free(p); + tdsqlite3_free(p); }else{ #ifdef SQLITE_ENABLE_API_ARMOR (void)SQLITE_MISUSE_BKPT; @@ -27514,17 +31287,17 @@ static void winMutexFree(sqlite3_mutex *p){ } /* -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** The tdsqlite3_mutex_enter() and tdsqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK +** tdsqlite3_mutex_enter() will block and tdsqlite3_mutex_try() will return +** SQLITE_BUSY. The tdsqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ -static void winMutexEnter(sqlite3_mutex *p){ +static void winMutexEnter(tdsqlite3_mutex *p){ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) DWORD tid = GetCurrentThreadId(); #endif @@ -27541,13 +31314,13 @@ static void winMutexEnter(sqlite3_mutex *p){ p->owner = tid; p->nRef++; if( p->trace ){ - OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n", - tid, p, p->trace, p->nRef)); + OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", + tid, p->id, p, p->trace, p->nRef)); } #endif } -static int winMutexTry(sqlite3_mutex *p){ +static int winMutexTry(tdsqlite3_mutex *p){ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) DWORD tid = GetCurrentThreadId(); #endif @@ -27555,7 +31328,7 @@ static int winMutexTry(sqlite3_mutex *p){ assert( p ); assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); /* - ** The sqlite3_mutex_try() routine is very rarely used, and when it + ** The tdsqlite3_mutex_try() routine is very rarely used, and when it ** is used it is merely an optimization. So it is OK for it to always ** fail. ** @@ -27569,7 +31342,7 @@ static int winMutexTry(sqlite3_mutex *p){ assert( winMutex_isInit==1 ); assert( winMutex_isNt>=-1 && winMutex_isNt<=1 ); if( winMutex_isNt<0 ){ - winMutex_isNt = sqlite3_win32_is_nt(); + winMutex_isNt = tdsqlite3_win32_is_nt(); } assert( winMutex_isNt==0 || winMutex_isNt==1 ); if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){ @@ -27584,20 +31357,20 @@ static int winMutexTry(sqlite3_mutex *p){ #endif #ifdef SQLITE_DEBUG if( p->trace ){ - OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n", - tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc))); + OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n", + tid, p->id, p, p->trace, p->owner, p->nRef, tdsqlite3ErrName(rc))); } #endif return rc; } /* -** The sqlite3_mutex_leave() routine exits a mutex that was +** The tdsqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ -static void winMutexLeave(sqlite3_mutex *p){ +static void winMutexLeave(tdsqlite3_mutex *p){ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) DWORD tid = GetCurrentThreadId(); #endif @@ -27613,14 +31386,14 @@ static void winMutexLeave(sqlite3_mutex *p){ LeaveCriticalSection(&p->mutex); #ifdef SQLITE_DEBUG if( p->trace ){ - OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n", - tid, p, p->trace, p->nRef)); + OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", + tid, p->id, p, p->trace, p->nRef)); } #endif } -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ - static const sqlite3_mutex_methods sMutex = { +SQLITE_PRIVATE tdsqlite3_mutex_methods const *tdsqlite3DefaultMutex(void){ + static const tdsqlite3_mutex_methods sMutex = { winMutexInit, winMutexEnd, winMutexAlloc, @@ -27665,11 +31438,11 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ ** held by SQLite. An example of non-essential memory is memory used to ** cache database pages that are not currently in use. */ -SQLITE_API int sqlite3_release_memory(int n){ +SQLITE_API int tdsqlite3_release_memory(int n){ #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT - return sqlite3PcacheReleaseMemory(n); + return tdsqlite3PcacheReleaseMemory(n); #else - /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine + /* IMPLEMENTATION-OF: R-34391-24921 The tdsqlite3_release_memory() routine ** is a no-op returning zero if SQLite is not compiled with ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */ UNUSED_PARAMETER(n); @@ -27678,43 +31451,33 @@ SQLITE_API int sqlite3_release_memory(int n){ } /* -** An instance of the following object records the location of -** each unused scratch buffer. +** Default value of the hard heap limit. 0 means "no limit". */ -typedef struct ScratchFreeslot { - struct ScratchFreeslot *pNext; /* Next unused scratch buffer */ -} ScratchFreeslot; +#ifndef SQLITE_MAX_MEMORY +# define SQLITE_MAX_MEMORY 0 +#endif /* ** State information local to the memory allocation subsystem. */ static SQLITE_WSD struct Mem0Global { - sqlite3_mutex *mutex; /* Mutex to serialize access */ - sqlite3_int64 alarmThreshold; /* The soft heap limit */ - - /* - ** Pointers to the end of sqlite3GlobalConfig.pScratch memory - ** (so that a range test can be used to determine if an allocation - ** being freed came from pScratch) and a pointer to the list of - ** unused scratch allocations. - */ - void *pScratchEnd; - ScratchFreeslot *pScratchFree; - u32 nScratchFree; + tdsqlite3_mutex *mutex; /* Mutex to serialize access */ + tdsqlite3_int64 alarmThreshold; /* The soft heap limit */ + tdsqlite3_int64 hardLimit; /* The hard upper bound on memory */ /* ** True if heap is nearly "full" where "full" is defined by the - ** sqlite3_soft_heap_limit() setting. + ** tdsqlite3_soft_heap_limit() setting. */ int nearlyFull; -} mem0 = { 0, 0, 0, 0, 0, 0 }; +} mem0 = { 0, SQLITE_MAX_MEMORY, SQLITE_MAX_MEMORY, 0 }; #define mem0 GLOBAL(struct Mem0Global, mem0) /* -** Return the memory allocator mutex. sqlite3_status() needs it. +** Return the memory allocator mutex. tdsqlite3_status() needs it. */ -SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){ +SQLITE_PRIVATE tdsqlite3_mutex *tdsqlite3MallocMutex(void){ return mem0.mutex; } @@ -27724,10 +31487,10 @@ SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){ ** that was invoked when memory usage grew too large. Now it is a ** no-op. */ -SQLITE_API int sqlite3_memory_alarm( - void(*xCallback)(void *pArg, sqlite3_int64 used,int N), +SQLITE_API int tdsqlite3_memory_alarm( + void(*xCallback)(void *pArg, tdsqlite3_int64 used,int N), void *pArg, - sqlite3_int64 iThreshold + tdsqlite3_int64 iThreshold ){ (void)xCallback; (void)pArg; @@ -27737,93 +31500,122 @@ SQLITE_API int sqlite3_memory_alarm( #endif /* -** Set the soft heap-size limit for the library. Passing a zero or -** negative value indicates no limit. +** Set the soft heap-size limit for the library. An argument of +** zero disables the limit. A negative argument is a no-op used to +** obtain the return value. +** +** The return value is the value of the heap limit just before this +** interface was called. +** +** If the hard heap limit is enabled, then the soft heap limit cannot +** be disabled nor raised above the hard heap limit. */ -SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){ - sqlite3_int64 priorLimit; - sqlite3_int64 excess; - sqlite3_int64 nUsed; +SQLITE_API tdsqlite3_int64 tdsqlite3_soft_heap_limit64(tdsqlite3_int64 n){ + tdsqlite3_int64 priorLimit; + tdsqlite3_int64 excess; + tdsqlite3_int64 nUsed; #ifndef SQLITE_OMIT_AUTOINIT - int rc = sqlite3_initialize(); + int rc = tdsqlite3_initialize(); if( rc ) return -1; #endif - sqlite3_mutex_enter(mem0.mutex); + tdsqlite3_mutex_enter(mem0.mutex); priorLimit = mem0.alarmThreshold; if( n<0 ){ - sqlite3_mutex_leave(mem0.mutex); + tdsqlite3_mutex_leave(mem0.mutex); return priorLimit; } + if( mem0.hardLimit>0 && (n>mem0.hardLimit || n==0) ){ + n = mem0.hardLimit; + } mem0.alarmThreshold = n; - nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + nUsed = tdsqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); mem0.nearlyFull = (n>0 && n<=nUsed); - sqlite3_mutex_leave(mem0.mutex); - excess = sqlite3_memory_used() - n; - if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff)); + tdsqlite3_mutex_leave(mem0.mutex); + excess = tdsqlite3_memory_used() - n; + if( excess>0 ) tdsqlite3_release_memory((int)(excess & 0x7fffffff)); return priorLimit; } -SQLITE_API void sqlite3_soft_heap_limit(int n){ +SQLITE_API void tdsqlite3_soft_heap_limit(int n){ if( n<0 ) n = 0; - sqlite3_soft_heap_limit64(n); + tdsqlite3_soft_heap_limit64(n); } /* +** Set the hard heap-size limit for the library. An argument of zero +** disables the hard heap limit. A negative argument is a no-op used +** to obtain the return value without affecting the hard heap limit. +** +** The return value is the value of the hard heap limit just prior to +** calling this interface. +** +** Setting the hard heap limit will also activate the soft heap limit +** and constrain the soft heap limit to be no more than the hard heap +** limit. +*/ +SQLITE_API tdsqlite3_int64 tdsqlite3_hard_heap_limit64(tdsqlite3_int64 n){ + tdsqlite3_int64 priorLimit; +#ifndef SQLITE_OMIT_AUTOINIT + int rc = tdsqlite3_initialize(); + if( rc ) return -1; +#endif + tdsqlite3_mutex_enter(mem0.mutex); + priorLimit = mem0.hardLimit; + if( n>=0 ){ + mem0.hardLimit = n; + if( n<mem0.alarmThreshold || mem0.alarmThreshold==0 ){ + mem0.alarmThreshold = n; + } + } + tdsqlite3_mutex_leave(mem0.mutex); + return priorLimit; +} + + +/* ** Initialize the memory allocation subsystem. */ -SQLITE_PRIVATE int sqlite3MallocInit(void){ +SQLITE_PRIVATE int tdsqlite3MallocInit(void){ int rc; - if( sqlite3GlobalConfig.m.xMalloc==0 ){ - sqlite3MemSetDefault(); + if( tdsqlite3GlobalConfig.m.xMalloc==0 ){ + tdsqlite3MemSetDefault(); } memset(&mem0, 0, sizeof(mem0)); - mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); - if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100 - && sqlite3GlobalConfig.nScratch>0 ){ - int i, n, sz; - ScratchFreeslot *pSlot; - sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch); - sqlite3GlobalConfig.szScratch = sz; - pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch; - n = sqlite3GlobalConfig.nScratch; - mem0.pScratchFree = pSlot; - mem0.nScratchFree = n; - for(i=0; i<n-1; i++){ - pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot); - pSlot = pSlot->pNext; - } - pSlot->pNext = 0; - mem0.pScratchEnd = (void*)&pSlot[1]; - }else{ - mem0.pScratchEnd = 0; - sqlite3GlobalConfig.pScratch = 0; - sqlite3GlobalConfig.szScratch = 0; - sqlite3GlobalConfig.nScratch = 0; - } - if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512 - || sqlite3GlobalConfig.nPage<=0 ){ - sqlite3GlobalConfig.pPage = 0; - sqlite3GlobalConfig.szPage = 0; - } - rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData); + mem0.mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); + if( tdsqlite3GlobalConfig.pPage==0 || tdsqlite3GlobalConfig.szPage<512 + || tdsqlite3GlobalConfig.nPage<=0 ){ + tdsqlite3GlobalConfig.pPage = 0; + tdsqlite3GlobalConfig.szPage = 0; + } + rc = tdsqlite3GlobalConfig.m.xInit(tdsqlite3GlobalConfig.m.pAppData); if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0)); +/* BEGIN SQLCIPHER */ +#ifdef SQLITE_HAS_CODEC + /* install wrapping functions for memory management + that will wipe all memory allocated by SQLite + when freed */ + if( rc==SQLITE_OK ) { + sqlcipher_init_memmethods(); + } +#endif +/* END SQLCIPHER */ return rc; } /* ** Return true if the heap is currently under memory pressure - in other ** words if the amount of heap used is close to the limit set by -** sqlite3_soft_heap_limit(). +** tdsqlite3_soft_heap_limit(). */ -SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){ +SQLITE_PRIVATE int tdsqlite3HeapNearlyFull(void){ return mem0.nearlyFull; } /* ** Deinitialize the memory allocation subsystem. */ -SQLITE_PRIVATE void sqlite3MallocEnd(void){ - if( sqlite3GlobalConfig.m.xShutdown ){ - sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData); +SQLITE_PRIVATE void tdsqlite3MallocEnd(void){ + if( tdsqlite3GlobalConfig.m.xShutdown ){ + tdsqlite3GlobalConfig.m.xShutdown(tdsqlite3GlobalConfig.m.pAppData); } memset(&mem0, 0, sizeof(mem0)); } @@ -27831,9 +31623,9 @@ SQLITE_PRIVATE void sqlite3MallocEnd(void){ /* ** Return the amount of memory currently checked out. */ -SQLITE_API sqlite3_int64 sqlite3_memory_used(void){ - sqlite3_int64 res, mx; - sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0); +SQLITE_API tdsqlite3_int64 tdsqlite3_memory_used(void){ + tdsqlite3_int64 res, mx; + tdsqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0); return res; } @@ -27842,76 +31634,90 @@ SQLITE_API sqlite3_int64 sqlite3_memory_used(void){ ** checked out since either the beginning of this process ** or since the most recent reset. */ -SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){ - sqlite3_int64 res, mx; - sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag); +SQLITE_API tdsqlite3_int64 tdsqlite3_memory_highwater(int resetFlag){ + tdsqlite3_int64 res, mx; + tdsqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag); return mx; } /* ** Trigger the alarm */ -static void sqlite3MallocAlarm(int nByte){ +static void tdsqlite3MallocAlarm(int nByte){ if( mem0.alarmThreshold<=0 ) return; - sqlite3_mutex_leave(mem0.mutex); - sqlite3_release_memory(nByte); - sqlite3_mutex_enter(mem0.mutex); + tdsqlite3_mutex_leave(mem0.mutex); + tdsqlite3_release_memory(nByte); + tdsqlite3_mutex_enter(mem0.mutex); } /* ** Do a memory allocation with statistics and alarms. Assume the ** lock is already held. */ -static int mallocWithAlarm(int n, void **pp){ - int nFull; +static void mallocWithAlarm(int n, void **pp){ void *p; - assert( sqlite3_mutex_held(mem0.mutex) ); - nFull = sqlite3GlobalConfig.m.xRoundup(n); - sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n); + int nFull; + assert( tdsqlite3_mutex_held(mem0.mutex) ); + assert( n>0 ); + + /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal + ** implementation of malloc_good_size(), which must be called in debug + ** mode and specifically when the DMD "Dark Matter Detector" is enabled + ** or else a crash results. Hence, do not attempt to optimize out the + ** following xRoundup() call. */ + nFull = tdsqlite3GlobalConfig.m.xRoundup(n); + + tdsqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n); if( mem0.alarmThreshold>0 ){ - sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + tdsqlite3_int64 nUsed = tdsqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); if( nUsed >= mem0.alarmThreshold - nFull ){ mem0.nearlyFull = 1; - sqlite3MallocAlarm(nFull); + tdsqlite3MallocAlarm(nFull); + if( mem0.hardLimit ){ + nUsed = tdsqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); + if( nUsed >= mem0.hardLimit - nFull ){ + *pp = 0; + return; + } + } }else{ mem0.nearlyFull = 0; } } - p = sqlite3GlobalConfig.m.xMalloc(nFull); + p = tdsqlite3GlobalConfig.m.xMalloc(nFull); #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT if( p==0 && mem0.alarmThreshold>0 ){ - sqlite3MallocAlarm(nFull); - p = sqlite3GlobalConfig.m.xMalloc(nFull); + tdsqlite3MallocAlarm(nFull); + p = tdsqlite3GlobalConfig.m.xMalloc(nFull); } #endif if( p ){ - nFull = sqlite3MallocSize(p); - sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull); - sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1); + nFull = tdsqlite3MallocSize(p); + tdsqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull); + tdsqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1); } *pp = p; - return nFull; } /* -** Allocate memory. This routine is like sqlite3_malloc() except that it +** Allocate memory. This routine is like tdsqlite3_malloc() except that it ** assumes the memory subsystem has already been initialized. */ -SQLITE_PRIVATE void *sqlite3Malloc(u64 n){ +SQLITE_PRIVATE void *tdsqlite3Malloc(u64 n){ void *p; if( n==0 || n>=0x7fffff00 ){ /* A memory allocation of a number of bytes which is near the maximum ** signed integer value might cause an integer overflow inside of the ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving ** 255 bytes of overhead. SQLite itself will never use anything near - ** this amount. The only way to reach the limit is with sqlite3_malloc() */ + ** this amount. The only way to reach the limit is with tdsqlite3_malloc() */ p = 0; - }else if( sqlite3GlobalConfig.bMemstat ){ - sqlite3_mutex_enter(mem0.mutex); + }else if( tdsqlite3GlobalConfig.bMemstat ){ + tdsqlite3_mutex_enter(mem0.mutex); mallocWithAlarm((int)n, &p); - sqlite3_mutex_leave(mem0.mutex); + tdsqlite3_mutex_leave(mem0.mutex); }else{ - p = sqlite3GlobalConfig.m.xMalloc((int)n); + p = tdsqlite3GlobalConfig.m.xMalloc((int)n); } assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */ return p; @@ -27922,123 +31728,24 @@ SQLITE_PRIVATE void *sqlite3Malloc(u64 n){ ** First make sure the memory subsystem is initialized, then do the ** allocation. */ -SQLITE_API void *sqlite3_malloc(int n){ +SQLITE_API void *tdsqlite3_malloc(int n){ #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif - return n<=0 ? 0 : sqlite3Malloc(n); + return n<=0 ? 0 : tdsqlite3Malloc(n); } -SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){ +SQLITE_API void *tdsqlite3_malloc64(tdsqlite3_uint64 n){ #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; -#endif - return sqlite3Malloc(n); -} - -/* -** Each thread may only have a single outstanding allocation from -** xScratchMalloc(). We verify this constraint in the single-threaded -** case by setting scratchAllocOut to 1 when an allocation -** is outstanding clearing it when the allocation is freed. -*/ -#if SQLITE_THREADSAFE==0 && !defined(NDEBUG) -static int scratchAllocOut = 0; -#endif - - -/* -** Allocate memory that is to be used and released right away. -** This routine is similar to alloca() in that it is not intended -** for situations where the memory might be held long-term. This -** routine is intended to get memory to old large transient data -** structures that would not normally fit on the stack of an -** embedded processor. -*/ -SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){ - void *p; - assert( n>0 ); - - sqlite3_mutex_enter(mem0.mutex); - sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n); - if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){ - p = mem0.pScratchFree; - mem0.pScratchFree = mem0.pScratchFree->pNext; - mem0.nScratchFree--; - sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1); - sqlite3_mutex_leave(mem0.mutex); - }else{ - sqlite3_mutex_leave(mem0.mutex); - p = sqlite3Malloc(n); - if( sqlite3GlobalConfig.bMemstat && p ){ - sqlite3_mutex_enter(mem0.mutex); - sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p)); - sqlite3_mutex_leave(mem0.mutex); - } - sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH); - } - assert( sqlite3_mutex_notheld(mem0.mutex) ); - - -#if SQLITE_THREADSAFE==0 && !defined(NDEBUG) - /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch - ** buffers per thread. - ** - ** This can only be checked in single-threaded mode. - */ - assert( scratchAllocOut==0 ); - if( p ) scratchAllocOut++; + if( tdsqlite3_initialize() ) return 0; #endif - - return p; -} -SQLITE_PRIVATE void sqlite3ScratchFree(void *p){ - if( p ){ - -#if SQLITE_THREADSAFE==0 && !defined(NDEBUG) - /* Verify that no more than two scratch allocation per thread - ** is outstanding at one time. (This is only checked in the - ** single-threaded case since checking in the multi-threaded case - ** would be much more complicated.) */ - assert( scratchAllocOut>=1 && scratchAllocOut<=2 ); - scratchAllocOut--; -#endif - - if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){ - /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */ - ScratchFreeslot *pSlot; - pSlot = (ScratchFreeslot*)p; - sqlite3_mutex_enter(mem0.mutex); - pSlot->pNext = mem0.pScratchFree; - mem0.pScratchFree = pSlot; - mem0.nScratchFree++; - assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch ); - sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1); - sqlite3_mutex_leave(mem0.mutex); - }else{ - /* Release memory back to the heap */ - assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) ); - assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) ); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); - if( sqlite3GlobalConfig.bMemstat ){ - int iSize = sqlite3MallocSize(p); - sqlite3_mutex_enter(mem0.mutex); - sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize); - sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize); - sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); - sqlite3GlobalConfig.m.xFree(p); - sqlite3_mutex_leave(mem0.mutex); - }else{ - sqlite3GlobalConfig.m.xFree(p); - } - } - } + return tdsqlite3Malloc(n); } /* ** TRUE if p is a lookaside memory allocation from db */ #ifndef SQLITE_OMIT_LOOKASIDE -static int isLookaside(sqlite3 *db, void *p){ +static int isLookaside(tdsqlite3 *db, void *p){ return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd); } #else @@ -28047,51 +31754,69 @@ static int isLookaside(sqlite3 *db, void *p){ /* ** Return the size of a memory allocation previously obtained from -** sqlite3Malloc() or sqlite3_malloc(). +** tdsqlite3Malloc() or tdsqlite3_malloc(). */ -SQLITE_PRIVATE int sqlite3MallocSize(void *p){ - assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); - return sqlite3GlobalConfig.m.xSize(p); +SQLITE_PRIVATE int tdsqlite3MallocSize(void *p){ + assert( tdsqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); + return tdsqlite3GlobalConfig.m.xSize(p); +} +static int lookasideMallocSize(tdsqlite3 *db, void *p){ +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL; +#else + return db->lookaside.szTrue; +#endif } -SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){ +SQLITE_PRIVATE int tdsqlite3DbMallocSize(tdsqlite3 *db, void *p){ assert( p!=0 ); +#ifdef SQLITE_DEBUG if( db==0 || !isLookaside(db,p) ){ -#if SQLITE_DEBUG if( db==0 ){ - assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); - assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); + assert( tdsqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); + assert( tdsqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); }else{ - assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); + assert( tdsqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); + assert( tdsqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); } + } #endif - return sqlite3GlobalConfig.m.xSize(p); - }else{ - assert( sqlite3_mutex_held(db->mutex) ); - return db->lookaside.sz; + if( db ){ + if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){ +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ + assert( tdsqlite3_mutex_held(db->mutex) ); + return LOOKASIDE_SMALL; + } +#endif + if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ + assert( tdsqlite3_mutex_held(db->mutex) ); + return db->lookaside.szTrue; + } + } } + return tdsqlite3GlobalConfig.m.xSize(p); } -SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){ - assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); - assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); - return p ? sqlite3GlobalConfig.m.xSize(p) : 0; +SQLITE_API tdsqlite3_uint64 tdsqlite3_msize(void *p){ + assert( tdsqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); + assert( tdsqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); + return p ? tdsqlite3GlobalConfig.m.xSize(p) : 0; } /* -** Free memory previously obtained from sqlite3Malloc(). +** Free memory previously obtained from tdsqlite3Malloc(). */ -SQLITE_API void sqlite3_free(void *p){ +SQLITE_API void tdsqlite3_free(void *p){ if( p==0 ) return; /* IMP: R-49053-54554 */ - assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); - assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); - if( sqlite3GlobalConfig.bMemstat ){ - sqlite3_mutex_enter(mem0.mutex); - sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p)); - sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); - sqlite3GlobalConfig.m.xFree(p); - sqlite3_mutex_leave(mem0.mutex); + assert( tdsqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); + assert( tdsqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); + if( tdsqlite3GlobalConfig.bMemstat ){ + tdsqlite3_mutex_enter(mem0.mutex); + tdsqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, tdsqlite3MallocSize(p)); + tdsqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); + tdsqlite3GlobalConfig.m.xFree(p); + tdsqlite3_mutex_leave(mem0.mutex); }else{ - sqlite3GlobalConfig.m.xFree(p); + tdsqlite3GlobalConfig.m.xFree(p); } } @@ -28099,116 +31824,132 @@ SQLITE_API void sqlite3_free(void *p){ ** Add the size of memory allocation "p" to the count in ** *db->pnBytesFreed. */ -static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){ - *db->pnBytesFreed += sqlite3DbMallocSize(db,p); +static SQLITE_NOINLINE void measureAllocationSize(tdsqlite3 *db, void *p){ + *db->pnBytesFreed += tdsqlite3DbMallocSize(db,p); } /* ** Free memory that might be associated with a particular database -** connection. +** connection. Calling tdsqlite3DbFree(D,X) for X==0 is a harmless no-op. +** The tdsqlite3DbFreeNN(D,X) version requires that X be non-NULL. */ -SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){ - assert( db==0 || sqlite3_mutex_held(db->mutex) ); - if( p==0 ) return; +SQLITE_PRIVATE void tdsqlite3DbFreeNN(tdsqlite3 *db, void *p){ + assert( db==0 || tdsqlite3_mutex_held(db->mutex) ); + assert( p!=0 ); if( db ){ if( db->pnBytesFreed ){ measureAllocationSize(db, p); return; } - if( isLookaside(db, p) ){ - LookasideSlot *pBuf = (LookasideSlot*)p; -#if SQLITE_DEBUG - /* Trash all content in the buffer being freed */ - memset(p, 0xaa, db->lookaside.sz); + if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){ +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ + LookasideSlot *pBuf = (LookasideSlot*)p; +#ifdef SQLITE_DEBUG + memset(p, 0xaa, LOOKASIDE_SMALL); /* Trash freed content */ #endif - pBuf->pNext = db->lookaside.pFree; - db->lookaside.pFree = pBuf; - db->lookaside.nOut--; - return; + pBuf->pNext = db->lookaside.pSmallFree; + db->lookaside.pSmallFree = pBuf; + return; + } +#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ + if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ + LookasideSlot *pBuf = (LookasideSlot*)p; +#ifdef SQLITE_DEBUG + memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */ +#endif + pBuf->pNext = db->lookaside.pFree; + db->lookaside.pFree = pBuf; + return; + } } } - assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); - sqlite3_free(p); + assert( tdsqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); + assert( tdsqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); + assert( db!=0 || tdsqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); + tdsqlite3MemdebugSetType(p, MEMTYPE_HEAP); + tdsqlite3_free(p); +} +SQLITE_PRIVATE void tdsqlite3DbFree(tdsqlite3 *db, void *p){ + assert( db==0 || tdsqlite3_mutex_held(db->mutex) ); + if( p ) tdsqlite3DbFreeNN(db, p); } /* ** Change the size of an existing memory allocation */ -SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){ +SQLITE_PRIVATE void *tdsqlite3Realloc(void *pOld, u64 nBytes){ int nOld, nNew, nDiff; void *pNew; - assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) ); - assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) ); + assert( tdsqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) ); + assert( tdsqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) ); if( pOld==0 ){ - return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */ + return tdsqlite3Malloc(nBytes); /* IMP: R-04300-56712 */ } if( nBytes==0 ){ - sqlite3_free(pOld); /* IMP: R-26507-47431 */ + tdsqlite3_free(pOld); /* IMP: R-26507-47431 */ return 0; } if( nBytes>=0x7fffff00 ){ - /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ + /* The 0x7ffff00 limit term is explained in comments on tdsqlite3Malloc() */ return 0; } - nOld = sqlite3MallocSize(pOld); + nOld = tdsqlite3MallocSize(pOld); /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second ** argument to xRealloc is always a value returned by a prior call to ** xRoundup. */ - nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes); + nNew = tdsqlite3GlobalConfig.m.xRoundup((int)nBytes); if( nOld==nNew ){ pNew = pOld; - }else if( sqlite3GlobalConfig.bMemstat ){ - sqlite3_mutex_enter(mem0.mutex); - sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes); + }else if( tdsqlite3GlobalConfig.bMemstat ){ + tdsqlite3_mutex_enter(mem0.mutex); + tdsqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes); nDiff = nNew - nOld; - if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= + if( nDiff>0 && tdsqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= mem0.alarmThreshold-nDiff ){ - sqlite3MallocAlarm(nDiff); + tdsqlite3MallocAlarm(nDiff); } - pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + pNew = tdsqlite3GlobalConfig.m.xRealloc(pOld, nNew); if( pNew==0 && mem0.alarmThreshold>0 ){ - sqlite3MallocAlarm((int)nBytes); - pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + tdsqlite3MallocAlarm((int)nBytes); + pNew = tdsqlite3GlobalConfig.m.xRealloc(pOld, nNew); } if( pNew ){ - nNew = sqlite3MallocSize(pNew); - sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld); + nNew = tdsqlite3MallocSize(pNew); + tdsqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld); } - sqlite3_mutex_leave(mem0.mutex); + tdsqlite3_mutex_leave(mem0.mutex); }else{ - pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); + pNew = tdsqlite3GlobalConfig.m.xRealloc(pOld, nNew); } assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */ return pNew; } /* -** The public interface to sqlite3Realloc. Make sure that the memory +** The public interface to tdsqlite3Realloc. Make sure that the memory ** subsystem is initialized prior to invoking sqliteRealloc. */ -SQLITE_API void *sqlite3_realloc(void *pOld, int n){ +SQLITE_API void *tdsqlite3_realloc(void *pOld, int n){ #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif if( n<0 ) n = 0; /* IMP: R-26507-47431 */ - return sqlite3Realloc(pOld, n); + return tdsqlite3Realloc(pOld, n); } -SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){ +SQLITE_API void *tdsqlite3_realloc64(void *pOld, tdsqlite3_uint64 n){ #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif - return sqlite3Realloc(pOld, n); + return tdsqlite3Realloc(pOld, n); } /* ** Allocate and zero memory. */ -SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){ - void *p = sqlite3Malloc(n); +SQLITE_PRIVATE void *tdsqlite3MallocZero(u64 n){ + void *p = tdsqlite3Malloc(n); if( p ){ memset(p, 0, (size_t)n); } @@ -28219,24 +31960,24 @@ SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){ ** Allocate and zero memory. If the allocation fails, make ** the mallocFailed flag in the connection pointer. */ -SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){ +SQLITE_PRIVATE void *tdsqlite3DbMallocZero(tdsqlite3 *db, u64 n){ void *p; testcase( db==0 ); - p = sqlite3DbMallocRaw(db, n); + p = tdsqlite3DbMallocRaw(db, n); if( p ) memset(p, 0, (size_t)n); return p; } -/* Finish the work of sqlite3DbMallocRawNN for the unusual and +/* Finish the work of tdsqlite3DbMallocRawNN for the unusual and ** slower case when the allocation cannot be fulfilled using lookaside. */ -static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){ +static SQLITE_NOINLINE void *dbMallocRawFinish(tdsqlite3 *db, u64 n){ void *p; assert( db!=0 ); - p = sqlite3Malloc(n); - if( !p ) sqlite3OomFault(db); - sqlite3MemdebugSetType(p, + p = tdsqlite3Malloc(n); + if( !p ) tdsqlite3OomFault(db); + tdsqlite3MemdebugSetType(p, (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP); return p; } @@ -28253,50 +31994,64 @@ static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){ ** This is an important assumption. There are many places in the ** code that do things like this: ** -** int *a = (int*)sqlite3DbMallocRaw(db, 100); -** int *b = (int*)sqlite3DbMallocRaw(db, 200); +** int *a = (int*)tdsqlite3DbMallocRaw(db, 100); +** int *b = (int*)tdsqlite3DbMallocRaw(db, 200); ** if( b ) a[10] = 9; ** ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed ** that all prior mallocs (ex: "a") worked too. ** -** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is +** The tdsqlite3MallocRawNN() variant guarantees that the "db" parameter is ** not a NULL pointer. */ -SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){ +SQLITE_PRIVATE void *tdsqlite3DbMallocRaw(tdsqlite3 *db, u64 n){ void *p; - if( db ) return sqlite3DbMallocRawNN(db, n); - p = sqlite3Malloc(n); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); + if( db ) return tdsqlite3DbMallocRawNN(db, n); + p = tdsqlite3Malloc(n); + tdsqlite3MemdebugSetType(p, MEMTYPE_HEAP); return p; } -SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){ +SQLITE_PRIVATE void *tdsqlite3DbMallocRawNN(tdsqlite3 *db, u64 n){ #ifndef SQLITE_OMIT_LOOKASIDE LookasideSlot *pBuf; assert( db!=0 ); - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); assert( db->pnBytesFreed==0 ); - if( db->lookaside.bDisable==0 ){ - assert( db->mallocFailed==0 ); - if( n>db->lookaside.sz ){ - db->lookaside.anStat[1]++; - }else if( (pBuf = db->lookaside.pFree)==0 ){ - db->lookaside.anStat[2]++; - }else{ - db->lookaside.pFree = pBuf->pNext; - db->lookaside.nOut++; + if( n>db->lookaside.sz ){ + if( !db->lookaside.bDisable ){ + db->lookaside.anStat[1]++; + }else if( db->mallocFailed ){ + return 0; + } + return dbMallocRawFinish(db, n); + } +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + if( n<=LOOKASIDE_SMALL ){ + if( (pBuf = db->lookaside.pSmallFree)!=0 ){ + db->lookaside.pSmallFree = pBuf->pNext; + db->lookaside.anStat[0]++; + return (void*)pBuf; + }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){ + db->lookaside.pSmallInit = pBuf->pNext; db->lookaside.anStat[0]++; - if( db->lookaside.nOut>db->lookaside.mxOut ){ - db->lookaside.mxOut = db->lookaside.nOut; - } return (void*)pBuf; } - }else if( db->mallocFailed ){ - return 0; + } +#endif + if( (pBuf = db->lookaside.pFree)!=0 ){ + db->lookaside.pFree = pBuf->pNext; + db->lookaside.anStat[0]++; + return (void*)pBuf; + }else if( (pBuf = db->lookaside.pInit)!=0 ){ + db->lookaside.pInit = pBuf->pNext; + db->lookaside.anStat[0]++; + return (void*)pBuf; + }else{ + db->lookaside.anStat[2]++; } #else assert( db!=0 ); - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); assert( db->pnBytesFreed==0 ); if( db->mallocFailed ){ return 0; @@ -28306,39 +32061,48 @@ SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){ } /* Forward declaration */ -static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n); +static SQLITE_NOINLINE void *dbReallocFinish(tdsqlite3 *db, void *p, u64 n); /* ** Resize the block of memory pointed to by p to n bytes. If the ** resize fails, set the mallocFailed flag in the connection object. */ -SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){ +SQLITE_PRIVATE void *tdsqlite3DbRealloc(tdsqlite3 *db, void *p, u64 n){ assert( db!=0 ); - if( p==0 ) return sqlite3DbMallocRawNN(db, n); - assert( sqlite3_mutex_held(db->mutex) ); - if( isLookaside(db,p) && n<=db->lookaside.sz ) return p; + if( p==0 ) return tdsqlite3DbMallocRawNN(db, n); + assert( tdsqlite3_mutex_held(db->mutex) ); + if( ((uptr)p)<(uptr)db->lookaside.pEnd ){ +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){ + if( n<=LOOKASIDE_SMALL ) return p; + }else +#endif + if( ((uptr)p)>=(uptr)db->lookaside.pStart ){ + if( n<=db->lookaside.szTrue ) return p; + } + } return dbReallocFinish(db, p, n); } -static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){ +static SQLITE_NOINLINE void *dbReallocFinish(tdsqlite3 *db, void *p, u64 n){ void *pNew = 0; assert( db!=0 ); assert( p!=0 ); if( db->mallocFailed==0 ){ if( isLookaside(db, p) ){ - pNew = sqlite3DbMallocRawNN(db, n); + pNew = tdsqlite3DbMallocRawNN(db, n); if( pNew ){ - memcpy(pNew, p, db->lookaside.sz); - sqlite3DbFree(db, p); + memcpy(pNew, p, lookasideMallocSize(db, p)); + tdsqlite3DbFree(db, p); } }else{ - assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); - pNew = sqlite3_realloc64(p, n); + assert( tdsqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); + assert( tdsqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); + tdsqlite3MemdebugSetType(p, MEMTYPE_HEAP); + pNew = tdsqlite3_realloc64(p, n); if( !pNew ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); } - sqlite3MemdebugSetType(pNew, + tdsqlite3MemdebugSetType(pNew, (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); } } @@ -28349,44 +32113,43 @@ static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){ ** Attempt to reallocate p. If the reallocation fails, then free p ** and set the mallocFailed flag in the database connection. */ -SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){ +SQLITE_PRIVATE void *tdsqlite3DbReallocOrFree(tdsqlite3 *db, void *p, u64 n){ void *pNew; - pNew = sqlite3DbRealloc(db, p, n); + pNew = tdsqlite3DbRealloc(db, p, n); if( !pNew ){ - sqlite3DbFree(db, p); + tdsqlite3DbFree(db, p); } return pNew; } /* ** Make a copy of a string in memory obtained from sqliteMalloc(). These -** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This +** functions call tdsqlite3MallocRaw() directly instead of sqliteMalloc(). This ** is because when memory debugging is turned on, these two functions are ** called via macros that record the current file and line number in the ** ThreadData structure. */ -SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){ +SQLITE_PRIVATE char *tdsqlite3DbStrDup(tdsqlite3 *db, const char *z){ char *zNew; size_t n; if( z==0 ){ return 0; } - n = sqlite3Strlen30(z) + 1; - assert( (n&0x7fffffff)==n ); - zNew = sqlite3DbMallocRaw(db, (int)n); + n = strlen(z) + 1; + zNew = tdsqlite3DbMallocRaw(db, n); if( zNew ){ memcpy(zNew, z, n); } return zNew; } -SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){ +SQLITE_PRIVATE char *tdsqlite3DbStrNDup(tdsqlite3 *db, const char *z, u64 n){ char *zNew; assert( db!=0 ); if( z==0 ){ return 0; } assert( (n&0x7fffffff)==n ); - zNew = sqlite3DbMallocRawNN(db, n+1); + zNew = tdsqlite3DbMallocRawNN(db, n+1); if( zNew ){ memcpy(zNew, z, (size_t)n); zNew[n] = 0; @@ -28395,11 +32158,24 @@ SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){ } /* +** The text between zStart and zEnd represents a phrase within a larger +** SQL statement. Make a copy of this phrase in space obtained form +** tdsqlite3DbMalloc(). Omit leading and trailing whitespace. +*/ +SQLITE_PRIVATE char *tdsqlite3DbSpanDup(tdsqlite3 *db, const char *zStart, const char *zEnd){ + int n; + while( tdsqlite3Isspace(zStart[0]) ) zStart++; + n = (int)(zEnd - zStart); + while( ALWAYS(n>0) && tdsqlite3Isspace(zStart[n-1]) ) n--; + return tdsqlite3DbStrNDup(db, zStart, n); +} + +/* ** Free any prior content in *pz and replace it with a copy of zNew. */ -SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){ - sqlite3DbFree(db, *pz); - *pz = sqlite3DbStrDup(db, zNew); +SQLITE_PRIVATE void tdsqlite3SetString(char **pz, tdsqlite3 *db, const char *zNew){ + tdsqlite3DbFree(db, *pz); + *pz = tdsqlite3DbStrDup(db, zNew); } /* @@ -28408,13 +32184,16 @@ SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){ ** temporarily disable the lookaside memory allocator and interrupt ** any running VDBEs. */ -SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3OomFault(tdsqlite3 *db){ if( db->mallocFailed==0 && db->bBenignMalloc==0 ){ db->mallocFailed = 1; if( db->nVdbeExec>0 ){ db->u1.isInterrupted = 1; } - db->lookaside.bDisable++; + DisableLookaside; + if( db->pParse ){ + db->pParse->rc = SQLITE_NOMEM_BKPT; + } } } @@ -28425,43 +32204,43 @@ SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){ ** The memory allocator is not restarted if there are running ** VDBEs. */ -SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3OomClear(tdsqlite3 *db){ if( db->mallocFailed && db->nVdbeExec==0 ){ db->mallocFailed = 0; db->u1.isInterrupted = 0; assert( db->lookaside.bDisable>0 ); - db->lookaside.bDisable--; + EnableLookaside; } } /* ** Take actions at the end of an API call to indicate an OOM error */ -static SQLITE_NOINLINE int apiOomError(sqlite3 *db){ - sqlite3OomClear(db); - sqlite3Error(db, SQLITE_NOMEM); +static SQLITE_NOINLINE int apiOomError(tdsqlite3 *db){ + tdsqlite3OomClear(db); + tdsqlite3Error(db, SQLITE_NOMEM); return SQLITE_NOMEM_BKPT; } /* ** This function must be called before exiting any API function (i.e. -** returning control to the user) that has called sqlite3_malloc or -** sqlite3_realloc. +** returning control to the user) that has called tdsqlite3_malloc or +** tdsqlite3_realloc. ** ** The returned value is normally a copy of the second argument to this ** function. However, if a malloc() failure has occurred since the previous ** invocation SQLITE_NOMEM is returned instead. ** ** If an OOM as occurred, then the connection error-code (the value -** returned by sqlite3_errcode()) is set to SQLITE_NOMEM. +** returned by tdsqlite3_errcode()) is set to SQLITE_NOMEM. */ -SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){ +SQLITE_PRIVATE int tdsqlite3ApiExit(tdsqlite3* db, int rc){ /* If the db handle must hold the connection handle mutex here. ** Otherwise the read (and possible write) of db->mallocFailed - ** is unsafe, as is the call to sqlite3Error(). + ** is unsafe, as is the call to tdsqlite3Error(). */ assert( db!=0 ); - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){ return apiOomError(db); } @@ -28487,7 +32266,7 @@ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){ ** Conversion types fall into various categories as defined by the ** following enumeration. */ -#define etRADIX 0 /* Integer types. %d, %x, %o, and so forth */ +#define etRADIX 0 /* non-decimal integer types. %x %o */ #define etFLOAT 1 /* Floating point. %f */ #define etEXP 2 /* Exponentional notation. %e and %E */ #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */ @@ -28505,8 +32284,9 @@ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){ #define etPOINTER 13 /* The %p conversion */ #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */ #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ +#define etDECIMAL 16 /* %d or %u, but not %x, %o */ -#define etINVALID 16 /* Any unrecognized conversion type */ +#define etINVALID 17 /* Any unrecognized conversion type */ /* @@ -28530,9 +32310,8 @@ typedef struct et_info { /* Information about each format field */ /* ** Allowed values for et_info.flags */ -#define FLAG_SIGNED 1 /* True if the value to convert is signed */ -#define FLAG_INTERN 2 /* True if for internal use only */ -#define FLAG_STRING 4 /* Allow infinity precision */ +#define FLAG_SIGNED 1 /* True if the value to convert is signed */ +#define FLAG_STRING 4 /* Allow infinite precision */ /* @@ -28542,7 +32321,7 @@ typedef struct et_info { /* Information about each format field */ static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; static const char aPrefix[] = "-x0\000X0"; static const et_info fmtinfo[] = { - { 'd', 10, 1, etRADIX, 0, 0 }, + { 'd', 10, 1, etDECIMAL, 0, 0 }, { 's', 0, 4, etSTRING, 0, 0 }, { 'g', 0, 1, etGENERIC, 30, 0 }, { 'z', 0, 4, etDYNSTRING, 0, 0 }, @@ -28551,7 +32330,7 @@ static const et_info fmtinfo[] = { { 'w', 0, 4, etSQLESCAPE3, 0, 0 }, { 'c', 0, 0, etCHARX, 0, 0 }, { 'o', 8, 0, etRADIX, 0, 2 }, - { 'u', 10, 0, etRADIX, 0, 0 }, + { 'u', 10, 0, etDECIMAL, 0, 0 }, { 'x', 16, 0, etRADIX, 16, 1 }, { 'X', 16, 0, etRADIX, 0, 4 }, #ifndef SQLITE_OMIT_FLOATING_POINT @@ -28560,16 +32339,21 @@ static const et_info fmtinfo[] = { { 'E', 0, 1, etEXP, 14, 0 }, { 'G', 0, 1, etGENERIC, 14, 0 }, #endif - { 'i', 10, 1, etRADIX, 0, 0 }, + { 'i', 10, 1, etDECIMAL, 0, 0 }, { 'n', 0, 0, etSIZE, 0, 0 }, { '%', 0, 0, etPERCENT, 0, 0 }, { 'p', 16, 0, etPOINTER, 0, 1 }, -/* All the rest have the FLAG_INTERN bit set and are thus for internal -** use only */ - { 'T', 0, 2, etTOKEN, 0, 0 }, - { 'S', 0, 2, etSRCLIST, 0, 0 }, - { 'r', 10, 3, etORDINAL, 0, 0 }, + /* All the rest are undocumented and are for internal use only */ + { 'T', 0, 0, etTOKEN, 0, 0 }, + { 'S', 0, 0, etSRCLIST, 0, 0 }, + { 'r', 10, 1, etORDINAL, 0, 0 }, +}; + +/* Floating point constants used for rounding */ +static const double arRound[] = { + 5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05, + 5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10, }; /* @@ -28607,27 +32391,50 @@ static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){ ** Set the StrAccum object to an error mode. */ static void setStrAccumError(StrAccum *p, u8 eError){ - assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG ); + assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG ); p->accError = eError; - p->nAlloc = 0; + if( p->mxAlloc ) tdsqlite3_str_reset(p); + if( eError==SQLITE_TOOBIG ) tdsqlite3ErrorToParser(p->db, eError); } /* ** Extra argument values from a PrintfArguments object */ -static sqlite3_int64 getIntArg(PrintfArguments *p){ +static tdsqlite3_int64 getIntArg(PrintfArguments *p){ if( p->nArg<=p->nUsed ) return 0; - return sqlite3_value_int64(p->apArg[p->nUsed++]); + return tdsqlite3_value_int64(p->apArg[p->nUsed++]); } static double getDoubleArg(PrintfArguments *p){ if( p->nArg<=p->nUsed ) return 0.0; - return sqlite3_value_double(p->apArg[p->nUsed++]); + return tdsqlite3_value_double(p->apArg[p->nUsed++]); } static char *getTextArg(PrintfArguments *p){ if( p->nArg<=p->nUsed ) return 0; - return (char*)sqlite3_value_text(p->apArg[p->nUsed++]); + return (char*)tdsqlite3_value_text(p->apArg[p->nUsed++]); } +/* +** Allocate memory for a temporary buffer needed for printf rendering. +** +** If the requested size of the temp buffer is larger than the size +** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error. +** Do the size check before the memory allocation to prevent rogue +** SQL from requesting large allocations using the precision or width +** field of the printf() function. +*/ +static char *printfTempBuf(tdsqlite3_str *pAccum, tdsqlite3_int64 n){ + char *z; + if( pAccum->accError ) return 0; + if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){ + setStrAccumError(pAccum, SQLITE_TOOBIG); + return 0; + } + z = tdsqlite3DbMallocRaw(pAccum->db, n); + if( z==0 ){ + setStrAccumError(pAccum, SQLITE_NOMEM); + } + return z; +} /* ** On machines with a small stack size, you can redefine the @@ -28641,8 +32448,8 @@ static char *getTextArg(PrintfArguments *p){ /* ** Render a string given by "fmt" into the StrAccum object. */ -SQLITE_PRIVATE void sqlite3VXPrintf( - StrAccum *pAccum, /* Accumulate results here */ +SQLITE_API void tdsqlite3_str_vappendf( + tdsqlite3_str *pAccum, /* Accumulate results here */ const char *fmt, /* Format string */ va_list ap /* arguments */ ){ @@ -28653,17 +32460,15 @@ SQLITE_PRIVATE void sqlite3VXPrintf( int idx; /* A general purpose loop counter */ int width; /* Width of the current field */ etByte flag_leftjustify; /* True if "-" flag is present */ - etByte flag_plussign; /* True if "+" flag is present */ - etByte flag_blanksign; /* True if " " flag is present */ + etByte flag_prefix; /* '+' or ' ' or 0 for prefix */ etByte flag_alternateform; /* True if "#" flag is present */ etByte flag_altform2; /* True if "!" flag is present */ etByte flag_zeropad; /* True if field width constant starts with zero */ - etByte flag_long; /* True if "l" flag is present */ - etByte flag_longlong; /* True if the "ll" flag is present */ + etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */ etByte done; /* Loop termination flag */ + etByte cThousand; /* Thousands separator for %d and %u */ etByte xtype = etINVALID; /* Conversion paradigm */ u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */ - u8 useIntern; /* Ok to use internal conversions (ex: %T) */ char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ sqlite_uint64 longvalue; /* Value for integer types */ LONGDOUBLE_TYPE realvalue; /* Value for real types */ @@ -28681,14 +32486,17 @@ SQLITE_PRIVATE void sqlite3VXPrintf( PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */ char buf[etBUFSIZE]; /* Conversion buffer */ + /* pAccum never starts out with an empty buffer that was obtained from + ** malloc(). This precondition is required by the mprintf("%z...") + ** optimization. */ + assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 ); + bufpt = 0; - if( pAccum->printfFlags ){ - if( (bArgList = (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){ - pArgList = va_arg(ap, PrintfArguments*); - } - useIntern = pAccum->printfFlags & SQLITE_PRINTF_INTERNAL; + if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){ + pArgList = va_arg(ap, PrintfArguments*); + bArgList = 1; }else{ - bArgList = useIntern = 0; + bArgList = 0; } for(; (c=(*fmt))!=0; ++fmt){ if( c!='%' ){ @@ -28698,113 +32506,124 @@ SQLITE_PRIVATE void sqlite3VXPrintf( #else do{ fmt++; }while( *fmt && *fmt != '%' ); #endif - sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt)); + tdsqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt)); if( *fmt==0 ) break; } if( (c=(*++fmt))==0 ){ - sqlite3StrAccumAppend(pAccum, "%", 1); + tdsqlite3_str_append(pAccum, "%", 1); break; } /* Find out what flags are present */ - flag_leftjustify = flag_plussign = flag_blanksign = + flag_leftjustify = flag_prefix = cThousand = flag_alternateform = flag_altform2 = flag_zeropad = 0; done = 0; + width = 0; + flag_long = 0; + precision = -1; do{ switch( c ){ case '-': flag_leftjustify = 1; break; - case '+': flag_plussign = 1; break; - case ' ': flag_blanksign = 1; break; + case '+': flag_prefix = '+'; break; + case ' ': flag_prefix = ' '; break; case '#': flag_alternateform = 1; break; case '!': flag_altform2 = 1; break; case '0': flag_zeropad = 1; break; + case ',': cThousand = ','; break; default: done = 1; break; - } - }while( !done && (c=(*++fmt))!=0 ); - /* Get the field width */ - if( c=='*' ){ - if( bArgList ){ - width = (int)getIntArg(pArgList); - }else{ - width = va_arg(ap,int); - } - if( width<0 ){ - flag_leftjustify = 1; - width = width >= -2147483647 ? -width : 0; - } - c = *++fmt; - }else{ - unsigned wx = 0; - while( c>='0' && c<='9' ){ - wx = wx*10 + c - '0'; - c = *++fmt; - } - testcase( wx>0x7fffffff ); - width = wx & 0x7fffffff; - } - assert( width>=0 ); + case 'l': { + flag_long = 1; + c = *++fmt; + if( c=='l' ){ + c = *++fmt; + flag_long = 2; + } + done = 1; + break; + } + case '1': case '2': case '3': case '4': case '5': + case '6': case '7': case '8': case '9': { + unsigned wx = c - '0'; + while( (c = *++fmt)>='0' && c<='9' ){ + wx = wx*10 + c - '0'; + } + testcase( wx>0x7fffffff ); + width = wx & 0x7fffffff; #ifdef SQLITE_PRINTF_PRECISION_LIMIT - if( width>SQLITE_PRINTF_PRECISION_LIMIT ){ - width = SQLITE_PRINTF_PRECISION_LIMIT; - } + if( width>SQLITE_PRINTF_PRECISION_LIMIT ){ + width = SQLITE_PRINTF_PRECISION_LIMIT; + } #endif - - /* Get the precision */ - if( c=='.' ){ - c = *++fmt; - if( c=='*' ){ - if( bArgList ){ - precision = (int)getIntArg(pArgList); - }else{ - precision = va_arg(ap,int); + if( c!='.' && c!='l' ){ + done = 1; + }else{ + fmt--; + } + break; } - c = *++fmt; - if( precision<0 ){ - precision = precision >= -2147483647 ? -precision : -1; + case '*': { + if( bArgList ){ + width = (int)getIntArg(pArgList); + }else{ + width = va_arg(ap,int); + } + if( width<0 ){ + flag_leftjustify = 1; + width = width >= -2147483647 ? -width : 0; + } +#ifdef SQLITE_PRINTF_PRECISION_LIMIT + if( width>SQLITE_PRINTF_PRECISION_LIMIT ){ + width = SQLITE_PRINTF_PRECISION_LIMIT; + } +#endif + if( (c = fmt[1])!='.' && c!='l' ){ + c = *++fmt; + done = 1; + } + break; } - }else{ - unsigned px = 0; - while( c>='0' && c<='9' ){ - px = px*10 + c - '0'; + case '.': { c = *++fmt; - } - testcase( px>0x7fffffff ); - precision = px & 0x7fffffff; - } - }else{ - precision = -1; - } - assert( precision>=(-1) ); + if( c=='*' ){ + if( bArgList ){ + precision = (int)getIntArg(pArgList); + }else{ + precision = va_arg(ap,int); + } + if( precision<0 ){ + precision = precision >= -2147483647 ? -precision : -1; + } + c = *++fmt; + }else{ + unsigned px = 0; + while( c>='0' && c<='9' ){ + px = px*10 + c - '0'; + c = *++fmt; + } + testcase( px>0x7fffffff ); + precision = px & 0x7fffffff; + } #ifdef SQLITE_PRINTF_PRECISION_LIMIT - if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){ - precision = SQLITE_PRINTF_PRECISION_LIMIT; - } + if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){ + precision = SQLITE_PRINTF_PRECISION_LIMIT; + } #endif - - - /* Get the conversion type modifier */ - if( c=='l' ){ - flag_long = 1; - c = *++fmt; - if( c=='l' ){ - flag_longlong = 1; - c = *++fmt; - }else{ - flag_longlong = 0; + if( c=='l' ){ + --fmt; + }else{ + done = 1; + } + break; + } } - }else{ - flag_long = flag_longlong = 0; - } + }while( !done && (c=(*++fmt))!=0 ); + /* Fetch the info entry for the field */ infop = &fmtinfo[0]; xtype = etINVALID; for(idx=0; idx<ArraySize(fmtinfo); idx++){ if( c==fmtinfo[idx].fmttype ){ infop = &fmtinfo[idx]; - if( useIntern || (infop->flags & FLAG_INTERN)==0 ){ - xtype = infop->type; - }else{ - return; - } + xtype = infop->type; break; } } @@ -28814,15 +32633,11 @@ SQLITE_PRIVATE void sqlite3VXPrintf( ** ** flag_alternateform TRUE if a '#' is present. ** flag_altform2 TRUE if a '!' is present. - ** flag_plussign TRUE if a '+' is present. + ** flag_prefix '+' or ' ' or zero ** flag_leftjustify TRUE if a '-' is present or if the ** field width was negative. ** flag_zeropad TRUE if the width began with 0. - ** flag_long TRUE if the letter 'l' (ell) prefixed - ** the conversion character. - ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed - ** the conversion character. - ** flag_blanksign TRUE if a ' ' is present. + ** flag_long 1 for "l", 2 for "ll" ** width The specified field width. This is ** always non-negative. Zero is the default. ** precision The specified precision. The default @@ -28832,19 +32647,24 @@ SQLITE_PRIVATE void sqlite3VXPrintf( */ switch( xtype ){ case etPOINTER: - flag_longlong = sizeof(char*)==sizeof(i64); - flag_long = sizeof(char*)==sizeof(long int); + flag_long = sizeof(char*)==sizeof(i64) ? 2 : + sizeof(char*)==sizeof(long int) ? 1 : 0; /* Fall through into the next case */ case etORDINAL: - case etRADIX: + case etRADIX: + cThousand = 0; + /* Fall through into the next case */ + case etDECIMAL: if( infop->flags & FLAG_SIGNED ){ i64 v; if( bArgList ){ v = getIntArg(pArgList); - }else if( flag_longlong ){ - v = va_arg(ap,i64); }else if( flag_long ){ - v = va_arg(ap,long int); + if( flag_long==2 ){ + v = va_arg(ap,i64) ; + }else{ + v = va_arg(ap,long int); + } }else{ v = va_arg(ap,int); } @@ -28857,17 +32677,17 @@ SQLITE_PRIVATE void sqlite3VXPrintf( prefix = '-'; }else{ longvalue = v; - if( flag_plussign ) prefix = '+'; - else if( flag_blanksign ) prefix = ' '; - else prefix = 0; + prefix = flag_prefix; } }else{ if( bArgList ){ longvalue = (u64)getIntArg(pArgList); - }else if( flag_longlong ){ - longvalue = va_arg(ap,u64); }else if( flag_long ){ - longvalue = va_arg(ap,unsigned long int); + if( flag_long==2 ){ + longvalue = va_arg(ap,u64); + }else{ + longvalue = va_arg(ap,unsigned long int); + } }else{ longvalue = va_arg(ap,unsigned int); } @@ -28877,16 +32697,16 @@ SQLITE_PRIVATE void sqlite3VXPrintf( if( flag_zeropad && precision<width-(prefix!=0) ){ precision = width-(prefix!=0); } - if( precision<etBUFSIZE-10 ){ + if( precision<etBUFSIZE-10-etBUFSIZE/3 ){ nOut = etBUFSIZE; zOut = buf; }else{ - nOut = precision + 10; - zOut = zExtra = sqlite3Malloc( nOut ); - if( zOut==0 ){ - setStrAccumError(pAccum, STRACCUM_NOMEM); - return; - } + u64 n; + n = (u64)precision + 10; + if( cThousand ) n += precision/3; + zOut = zExtra = printfTempBuf(pAccum, n); + if( zOut==0 ) return; + nOut = (int)n; } bufpt = &zOut[nOut-1]; if( xtype==etORDINAL ){ @@ -28907,8 +32727,23 @@ SQLITE_PRIVATE void sqlite3VXPrintf( }while( longvalue>0 ); } length = (int)(&zOut[nOut-1]-bufpt); - for(idx=precision-length; idx>0; idx--){ + while( precision>length ){ *(--bufpt) = '0'; /* Zero pad */ + length++; + } + if( cThousand ){ + int nn = (length - 1)/3; /* Number of "," to insert */ + int ix = (length - 1)%3 + 1; + bufpt -= nn; + for(idx=0; nn>0; idx++){ + bufpt[idx] = bufpt[idx+nn]; + ix--; + if( ix==0 ){ + bufpt[++idx] = cThousand; + nn--; + ix = 3; + } + } } if( prefix ) *(--bufpt) = prefix; /* Add sign */ if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ @@ -28935,17 +32770,25 @@ SQLITE_PRIVATE void sqlite3VXPrintf( realvalue = -realvalue; prefix = '-'; }else{ - if( flag_plussign ) prefix = '+'; - else if( flag_blanksign ) prefix = ' '; - else prefix = 0; + prefix = flag_prefix; } if( xtype==etGENERIC && precision>0 ) precision--; testcase( precision>0xfff ); - for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){} - if( xtype==etFLOAT ) realvalue += rounder; + idx = precision & 0xfff; + rounder = arRound[idx%10]; + while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; } + if( xtype==etFLOAT ){ + double rx = (double)realvalue; + tdsqlite3_uint64 u; + int ex; + memcpy(&u, &rx, sizeof(u)); + ex = -1023 + (int)((u>>52)&0x7ff); + if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16; + realvalue += rounder; + } /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ exp = 0; - if( sqlite3IsNaN((double)realvalue) ){ + if( tdsqlite3IsNaN((double)realvalue) ){ bufpt = "NaN"; length = 3; break; @@ -28991,12 +32834,12 @@ SQLITE_PRIVATE void sqlite3VXPrintf( }else{ e2 = exp; } - if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){ - bufpt = zExtra - = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 ); - if( bufpt==0 ){ - setStrAccumError(pAccum, STRACCUM_NOMEM); - return; + { + i64 szBufNeeded; /* Size of a temporary buffer needed */ + szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15; + if( szBufNeeded > etBUFSIZE ){ + bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded); + if( bufpt==0 ) return; } } zOut = bufpt; @@ -29091,22 +32934,52 @@ SQLITE_PRIVATE void sqlite3VXPrintf( case etCHARX: if( bArgList ){ bufpt = getTextArg(pArgList); - c = bufpt ? bufpt[0] : 0; + length = 1; + if( bufpt ){ + buf[0] = c = *(bufpt++); + if( (c&0xc0)==0xc0 ){ + while( length<4 && (bufpt[0]&0xc0)==0x80 ){ + buf[length++] = *(bufpt++); + } + } + }else{ + buf[0] = 0; + } }else{ - c = va_arg(ap,int); + unsigned int ch = va_arg(ap,unsigned int); + if( ch<0x00080 ){ + buf[0] = ch & 0xff; + length = 1; + }else if( ch<0x00800 ){ + buf[0] = 0xc0 + (u8)((ch>>6)&0x1f); + buf[1] = 0x80 + (u8)(ch & 0x3f); + length = 2; + }else if( ch<0x10000 ){ + buf[0] = 0xe0 + (u8)((ch>>12)&0x0f); + buf[1] = 0x80 + (u8)((ch>>6) & 0x3f); + buf[2] = 0x80 + (u8)(ch & 0x3f); + length = 3; + }else{ + buf[0] = 0xf0 + (u8)((ch>>18) & 0x07); + buf[1] = 0x80 + (u8)((ch>>12) & 0x3f); + buf[2] = 0x80 + (u8)((ch>>6) & 0x3f); + buf[3] = 0x80 + (u8)(ch & 0x3f); + length = 4; + } } if( precision>1 ){ width -= precision-1; if( width>1 && !flag_leftjustify ){ - sqlite3AppendChar(pAccum, width-1, ' '); + tdsqlite3_str_appendchar(pAccum, width-1, ' '); width = 0; } - sqlite3AppendChar(pAccum, precision-1, c); + while( precision-- > 1 ){ + tdsqlite3_str_append(pAccum, buf, length); + } } - length = 1; - buf[0] = c; bufpt = buf; - break; + flag_altform2 = 1; + goto adjust_width_for_utf8; case etSTRING: case etDYNSTRING: if( bArgList ){ @@ -29118,17 +32991,50 @@ SQLITE_PRIVATE void sqlite3VXPrintf( if( bufpt==0 ){ bufpt = ""; }else if( xtype==etDYNSTRING ){ + if( pAccum->nChar==0 + && pAccum->mxAlloc + && width==0 + && precision<0 + && pAccum->accError==0 + ){ + /* Special optimization for tdsqlite3_mprintf("%z..."): + ** Extend an existing memory allocation rather than creating + ** a new one. */ + assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 ); + pAccum->zText = bufpt; + pAccum->nAlloc = tdsqlite3DbMallocSize(pAccum->db, bufpt); + pAccum->nChar = 0x7fffffff & (int)strlen(bufpt); + pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED; + length = 0; + break; + } zExtra = bufpt; } if( precision>=0 ){ - for(length=0; length<precision && bufpt[length]; length++){} + if( flag_altform2 ){ + /* Set length to the number of bytes needed in order to display + ** precision characters */ + unsigned char *z = (unsigned char*)bufpt; + while( precision-- > 0 && z[0] ){ + SQLITE_SKIP_UTF8(z); + } + length = (int)(z - (unsigned char*)bufpt); + }else{ + for(length=0; length<precision && bufpt[length]; length++){} + } }else{ - length = sqlite3Strlen30(bufpt); + length = 0x7fffffff & (int)strlen(bufpt); + } + adjust_width_for_utf8: + if( flag_altform2 && width>0 ){ + /* Adjust width to account for extra bytes in UTF-8 characters */ + int ii = length - 1; + while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++; } break; - case etSQLESCAPE: /* Escape ' characters */ - case etSQLESCAPE2: /* Escape ' and enclose in '...' */ - case etSQLESCAPE3: { /* Escape " characters */ + case etSQLESCAPE: /* %q: Escape ' characters */ + case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */ + case etSQLESCAPE3: { /* %w: Escape " characters */ int i, j, k, n, isnull; int needQuote; char ch; @@ -29142,18 +33048,23 @@ SQLITE_PRIVATE void sqlite3VXPrintf( } isnull = escarg==0; if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)"); + /* For %q, %Q, and %w, the precision is the number of byte (or + ** characters if the ! flags is present) to use from the input. + ** Because of the extra quoting characters inserted, the number + ** of output characters may be larger than the precision. + */ k = precision; for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){ if( ch==q ) n++; + if( flag_altform2 && (ch&0xc0)==0xc0 ){ + while( (escarg[i+1]&0xc0)==0x80 ){ i++; } + } } needQuote = !isnull && xtype==etSQLESCAPE2; n += i + 3; if( n>etBUFSIZE ){ - bufpt = zExtra = sqlite3Malloc( n ); - if( bufpt==0 ){ - setStrAccumError(pAccum, STRACCUM_NOMEM); - return; - } + bufpt = zExtra = printfTempBuf(pAccum, n); + if( bufpt==0 ) return; }else{ bufpt = buf; } @@ -29167,31 +33078,34 @@ SQLITE_PRIVATE void sqlite3VXPrintf( if( needQuote ) bufpt[j++] = q; bufpt[j] = 0; length = j; - /* The precision in %q and %Q means how many input characters to - ** consume, not the length of the output... - ** if( precision>=0 && precision<length ) length = precision; */ - break; + goto adjust_width_for_utf8; } case etTOKEN: { - Token *pToken = va_arg(ap, Token*); + Token *pToken; + if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return; + pToken = va_arg(ap, Token*); assert( bArgList==0 ); if( pToken && pToken->n ){ - sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n); + tdsqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n); } length = width = 0; break; } case etSRCLIST: { - SrcList *pSrc = va_arg(ap, SrcList*); - int k = va_arg(ap, int); - struct SrcList_item *pItem = &pSrc->a[k]; + SrcList *pSrc; + int k; + struct SrcList_item *pItem; + if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return; + pSrc = va_arg(ap, SrcList*); + k = va_arg(ap, int); + pItem = &pSrc->a[k]; assert( bArgList==0 ); assert( k>=0 && k<pSrc->nSrc ); if( pItem->zDatabase ){ - sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase); - sqlite3StrAccumAppend(pAccum, ".", 1); + tdsqlite3_str_appendall(pAccum, pItem->zDatabase); + tdsqlite3_str_append(pAccum, ".", 1); } - sqlite3StrAccumAppendAll(pAccum, pItem->zName); + tdsqlite3_str_appendall(pAccum, pItem->zName); length = width = 0; break; } @@ -29203,15 +33117,22 @@ SQLITE_PRIVATE void sqlite3VXPrintf( /* ** The text of the conversion is pointed to by "bufpt" and is ** "length" characters long. The field width is "width". Do - ** the output. + ** the output. Both length and width are in bytes, not characters, + ** at this point. If the "!" flag was present on string conversions + ** indicating that width and precision should be expressed in characters, + ** then the values have been translated prior to reaching this point. */ width -= length; - if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); - sqlite3StrAccumAppend(pAccum, bufpt, length); - if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); + if( width>0 ){ + if( !flag_leftjustify ) tdsqlite3_str_appendchar(pAccum, width, ' '); + tdsqlite3_str_append(pAccum, bufpt, length); + if( flag_leftjustify ) tdsqlite3_str_appendchar(pAccum, width, ' '); + }else{ + tdsqlite3_str_append(pAccum, bufpt, length); + } if( zExtra ){ - sqlite3DbFree(pAccum->db, zExtra); + tdsqlite3DbFree(pAccum->db, zExtra); zExtra = 0; } }/* End for loop over the format string */ @@ -29224,22 +33145,20 @@ SQLITE_PRIVATE void sqlite3VXPrintf( ** Return the number of bytes of text that StrAccum is able to accept ** after the attempted enlargement. The value returned might be zero. */ -static int sqlite3StrAccumEnlarge(StrAccum *p, int N){ +static int tdsqlite3StrAccumEnlarge(StrAccum *p, int N){ char *zNew; assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */ if( p->accError ){ - testcase(p->accError==STRACCUM_TOOBIG); - testcase(p->accError==STRACCUM_NOMEM); + testcase(p->accError==SQLITE_TOOBIG); + testcase(p->accError==SQLITE_NOMEM); return 0; } if( p->mxAlloc==0 ){ - N = p->nAlloc - p->nChar - 1; - setStrAccumError(p, STRACCUM_TOOBIG); - return N; + setStrAccumError(p, SQLITE_TOOBIG); + return p->nAlloc - p->nChar - 1; }else{ char *zOld = isMalloced(p) ? p->zText : 0; i64 szNew = p->nChar; - assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) ); szNew += N + 1; if( szNew+p->nChar<=p->mxAlloc ){ /* Force exponential buffer size growth as long as it does not overflow, @@ -29247,26 +33166,26 @@ static int sqlite3StrAccumEnlarge(StrAccum *p, int N){ szNew += p->nChar; } if( szNew > p->mxAlloc ){ - sqlite3StrAccumReset(p); - setStrAccumError(p, STRACCUM_TOOBIG); + tdsqlite3_str_reset(p); + setStrAccumError(p, SQLITE_TOOBIG); return 0; }else{ p->nAlloc = (int)szNew; } if( p->db ){ - zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); + zNew = tdsqlite3DbRealloc(p->db, zOld, p->nAlloc); }else{ - zNew = sqlite3_realloc64(zOld, p->nAlloc); + zNew = tdsqlite3_realloc64(zOld, p->nAlloc); } if( zNew ){ assert( p->zText!=0 || p->nChar==0 ); if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); p->zText = zNew; - p->nAlloc = sqlite3DbMallocSize(p->db, zNew); + p->nAlloc = tdsqlite3DbMallocSize(p->db, zNew); p->printfFlags |= SQLITE_PRINTF_MALLOCED; }else{ - sqlite3StrAccumReset(p); - setStrAccumError(p, STRACCUM_NOMEM); + tdsqlite3_str_reset(p); + setStrAccumError(p, SQLITE_NOMEM); return 0; } } @@ -29276,12 +33195,11 @@ static int sqlite3StrAccumEnlarge(StrAccum *p, int N){ /* ** Append N copies of character c to the given string buffer. */ -SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){ +SQLITE_API void tdsqlite3_str_appendchar(tdsqlite3_str *p, int N, char c){ testcase( p->nChar + (i64)N > 0x7fffffff ); - if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){ + if( p->nChar+(i64)N >= p->nAlloc && (N = tdsqlite3StrAccumEnlarge(p, N))<=0 ){ return; } - assert( (p->zText==p->zBase)==!isMalloced(p) ); while( (N--)>0 ) p->zText[p->nChar++] = c; } @@ -29289,31 +33207,30 @@ SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){ ** The StrAccum "p" is not large enough to accept N new bytes of z[]. ** So enlarge if first, then do the append. ** -** This is a helper routine to sqlite3StrAccumAppend() that does special-case +** This is a helper routine to tdsqlite3_str_append() that does special-case ** work (enlarging the buffer) using tail recursion, so that the -** sqlite3StrAccumAppend() routine can use fast calling semantics. +** tdsqlite3_str_append() routine can use fast calling semantics. */ static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){ - N = sqlite3StrAccumEnlarge(p, N); + N = tdsqlite3StrAccumEnlarge(p, N); if( N>0 ){ memcpy(&p->zText[p->nChar], z, N); p->nChar += N; } - assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) ); } /* ** Append N bytes of text from z to the StrAccum object. Increase the ** size of the memory allocation for StrAccum if necessary. */ -SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ +SQLITE_API void tdsqlite3_str_append(tdsqlite3_str *p, const char *z, int N){ assert( z!=0 || N==0 ); assert( p->zText!=0 || p->nChar==0 || p->accError ); assert( N>=0 ); - assert( p->accError==0 || p->nAlloc==0 ); + assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 ); if( p->nChar+N >= p->nAlloc ){ enlargeAndAppend(p,z,N); - }else{ + }else if( N ){ assert( p->zText ); p->nChar += N; memcpy(&p->zText[p->nChar-N], z, N); @@ -29323,8 +33240,8 @@ SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ /* ** Append the complete text of zero-terminated string z[] to the p string. */ -SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){ - sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z)); +SQLITE_API void tdsqlite3_str_appendall(tdsqlite3_str *p, const char *z){ + tdsqlite3_str_append(p, z, tdsqlite3Strlen30(z)); } @@ -29333,32 +33250,79 @@ SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){ ** Return a pointer to the resulting string. Return a NULL ** pointer if any kind of error was encountered. */ -SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){ +static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){ + char *zText; + assert( p->mxAlloc>0 && !isMalloced(p) ); + zText = tdsqlite3DbMallocRaw(p->db, p->nChar+1 ); + if( zText ){ + memcpy(zText, p->zText, p->nChar+1); + p->printfFlags |= SQLITE_PRINTF_MALLOCED; + }else{ + setStrAccumError(p, SQLITE_NOMEM); + } + p->zText = zText; + return zText; +} +SQLITE_PRIVATE char *tdsqlite3StrAccumFinish(StrAccum *p){ if( p->zText ){ - assert( (p->zText==p->zBase)==!isMalloced(p) ); p->zText[p->nChar] = 0; if( p->mxAlloc>0 && !isMalloced(p) ){ - p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 ); - if( p->zText ){ - memcpy(p->zText, p->zBase, p->nChar+1); - p->printfFlags |= SQLITE_PRINTF_MALLOCED; - }else{ - setStrAccumError(p, STRACCUM_NOMEM); - } + return strAccumFinishRealloc(p); } } return p->zText; } /* +** This singleton is an tdsqlite3_str object that is returned if +** tdsqlite3_malloc() fails to provide space for a real one. This +** tdsqlite3_str object accepts no new text and always returns +** an SQLITE_NOMEM error. +*/ +static tdsqlite3_str tdsqlite3OomStr = { + 0, 0, 0, 0, 0, SQLITE_NOMEM, 0 +}; + +/* Finalize a string created using tdsqlite3_str_new(). +*/ +SQLITE_API char *tdsqlite3_str_finish(tdsqlite3_str *p){ + char *z; + if( p!=0 && p!=&tdsqlite3OomStr ){ + z = tdsqlite3StrAccumFinish(p); + tdsqlite3_free(p); + }else{ + z = 0; + } + return z; +} + +/* Return any error code associated with p */ +SQLITE_API int tdsqlite3_str_errcode(tdsqlite3_str *p){ + return p ? p->accError : SQLITE_NOMEM; +} + +/* Return the current length of p in bytes */ +SQLITE_API int tdsqlite3_str_length(tdsqlite3_str *p){ + return p ? p->nChar : 0; +} + +/* Return the current value for p */ +SQLITE_API char *tdsqlite3_str_value(tdsqlite3_str *p){ + if( p==0 || p->nChar==0 ) return 0; + p->zText[p->nChar] = 0; + return p->zText; +} + +/* ** Reset an StrAccum string. Reclaim all malloced memory. */ -SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){ - assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) ); +SQLITE_API void tdsqlite3_str_reset(StrAccum *p){ if( isMalloced(p) ){ - sqlite3DbFree(p->db, p->zText); + tdsqlite3DbFree(p->db, p->zText); p->printfFlags &= ~SQLITE_PRINTF_MALLOCED; } + p->nAlloc = 0; + p->nChar = 0; p->zText = 0; } @@ -29376,32 +33340,44 @@ SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){ ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory ** allocations will ever occur. */ -SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){ - p->zText = p->zBase = zBase; +SQLITE_PRIVATE void tdsqlite3StrAccumInit(StrAccum *p, tdsqlite3 *db, char *zBase, int n, int mx){ + p->zText = zBase; p->db = db; - p->nChar = 0; p->nAlloc = n; p->mxAlloc = mx; + p->nChar = 0; p->accError = 0; p->printfFlags = 0; } +/* Allocate and initialize a new dynamic string object */ +SQLITE_API tdsqlite3_str *tdsqlite3_str_new(tdsqlite3 *db){ + tdsqlite3_str *p = tdsqlite3_malloc64(sizeof(*p)); + if( p ){ + tdsqlite3StrAccumInit(p, 0, 0, 0, + db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH); + }else{ + p = &tdsqlite3OomStr; + } + return p; +} + /* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */ -SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){ +SQLITE_PRIVATE char *tdsqlite3VMPrintf(tdsqlite3 *db, const char *zFormat, va_list ap){ char *z; char zBase[SQLITE_PRINT_BUF_SIZE]; StrAccum acc; assert( db!=0 ); - sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase), + tdsqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase), db->aLimit[SQLITE_LIMIT_LENGTH]); acc.printfFlags = SQLITE_PRINTF_INTERNAL; - sqlite3VXPrintf(&acc, zFormat, ap); - z = sqlite3StrAccumFinish(&acc); - if( acc.accError==STRACCUM_NOMEM ){ - sqlite3OomFault(db); + tdsqlite3_str_vappendf(&acc, zFormat, ap); + z = tdsqlite3StrAccumFinish(&acc); + if( acc.accError==SQLITE_NOMEM ){ + tdsqlite3OomFault(db); } return z; } @@ -29410,20 +33386,20 @@ SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list a ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */ -SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){ +SQLITE_PRIVATE char *tdsqlite3MPrintf(tdsqlite3 *db, const char *zFormat, ...){ va_list ap; char *z; va_start(ap, zFormat); - z = sqlite3VMPrintf(db, zFormat, ap); + z = tdsqlite3VMPrintf(db, zFormat, ap); va_end(ap); return z; } /* -** Print into memory obtained from sqlite3_malloc(). Omit the internal +** Print into memory obtained from tdsqlite3_malloc(). Omit the internal ** %-conversion extensions. */ -SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){ +SQLITE_API char *tdsqlite3_vmprintf(const char *zFormat, va_list ap){ char *z; char zBase[SQLITE_PRINT_BUF_SIZE]; StrAccum acc; @@ -29435,44 +33411,44 @@ SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){ } #endif #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif - sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH); - sqlite3VXPrintf(&acc, zFormat, ap); - z = sqlite3StrAccumFinish(&acc); + tdsqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH); + tdsqlite3_str_vappendf(&acc, zFormat, ap); + z = tdsqlite3StrAccumFinish(&acc); return z; } /* -** Print into memory obtained from sqlite3_malloc()(). Omit the internal +** Print into memory obtained from tdsqlite3_malloc()(). Omit the internal ** %-conversion extensions. */ -SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){ +SQLITE_API char *tdsqlite3_mprintf(const char *zFormat, ...){ va_list ap; char *z; #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif va_start(ap, zFormat); - z = sqlite3_vmprintf(zFormat, ap); + z = tdsqlite3_vmprintf(zFormat, ap); va_end(ap); return z; } /* -** sqlite3_snprintf() works like snprintf() except that it ignores the +** tdsqlite3_snprintf() works like snprintf() except that it ignores the ** current locale settings. This is important for SQLite because we ** are not able to use a "," as the decimal point in place of "." as ** specified by some locales. ** -** Oops: The first two arguments of sqlite3_snprintf() are backwards +** Oops: The first two arguments of tdsqlite3_snprintf() are backwards ** from the snprintf() standard. Unfortunately, it is too late to change ** this without breaking compatibility, so we just have to live with the ** mistake. ** -** sqlite3_vsnprintf() is the varargs version. +** tdsqlite3_vsnprintf() is the varargs version. */ -SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){ +SQLITE_API char *tdsqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){ StrAccum acc; if( n<=0 ) return zBuf; #ifdef SQLITE_ENABLE_API_ARMOR @@ -29482,49 +33458,50 @@ SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_li return zBuf; } #endif - sqlite3StrAccumInit(&acc, 0, zBuf, n, 0); - sqlite3VXPrintf(&acc, zFormat, ap); - return sqlite3StrAccumFinish(&acc); + tdsqlite3StrAccumInit(&acc, 0, zBuf, n, 0); + tdsqlite3_str_vappendf(&acc, zFormat, ap); + zBuf[acc.nChar] = 0; + return zBuf; } -SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ +SQLITE_API char *tdsqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ char *z; va_list ap; va_start(ap,zFormat); - z = sqlite3_vsnprintf(n, zBuf, zFormat, ap); + z = tdsqlite3_vsnprintf(n, zBuf, zFormat, ap); va_end(ap); return z; } /* -** This is the routine that actually formats the sqlite3_log() message. -** We house it in a separate routine from sqlite3_log() to avoid using +** This is the routine that actually formats the tdsqlite3_log() message. +** We house it in a separate routine from tdsqlite3_log() to avoid using ** stack space on small-stack systems when logging is disabled. ** -** sqlite3_log() must render into a static buffer. It cannot dynamically +** tdsqlite3_log() must render into a static buffer. It cannot dynamically ** allocate memory because it might be called while the memory allocator ** mutex is held. ** -** sqlite3VXPrintf() might ask for *temporary* memory allocations for +** tdsqlite3_str_vappendf() might ask for *temporary* memory allocations for ** certain format characters (%q) or for very large precisions or widths. -** Care must be taken that any sqlite3_log() calls that occur while the +** Care must be taken that any tdsqlite3_log() calls that occur while the ** memory mutex is held do not use these mechanisms. */ static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ StrAccum acc; /* String accumulator */ char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ - sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0); - sqlite3VXPrintf(&acc, zFormat, ap); - sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode, - sqlite3StrAccumFinish(&acc)); + tdsqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0); + tdsqlite3_str_vappendf(&acc, zFormat, ap); + tdsqlite3GlobalConfig.xLog(tdsqlite3GlobalConfig.pLogArg, iErrCode, + tdsqlite3StrAccumFinish(&acc)); } /* ** Format and write a message to the log if logging is enabled. */ -SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){ +SQLITE_API void tdsqlite3_log(int iErrCode, const char *zFormat, ...){ va_list ap; /* Vararg list */ - if( sqlite3GlobalConfig.xLog ){ + if( tdsqlite3GlobalConfig.xLog ){ va_start(ap, zFormat); renderLogMsg(iErrCode, zFormat, ap); va_end(ap); @@ -29537,29 +33514,36 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){ ** The printf() built into some versions of windows does not understand %lld ** and segfaults if you give it a long long int. */ -SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){ +SQLITE_PRIVATE void tdsqlite3DebugPrintf(const char *zFormat, ...){ va_list ap; StrAccum acc; char zBuf[500]; - sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); + tdsqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); va_start(ap,zFormat); - sqlite3VXPrintf(&acc, zFormat, ap); + tdsqlite3_str_vappendf(&acc, zFormat, ap); va_end(ap); - sqlite3StrAccumFinish(&acc); + tdsqlite3StrAccumFinish(&acc); +#ifdef SQLITE_OS_TRACE_PROC + { + extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf); + SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf)); + } +#else fprintf(stdout,"%s", zBuf); fflush(stdout); +#endif } #endif /* -** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument +** variable-argument wrapper around tdsqlite3_str_vappendf(). The bFlags argument ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats. */ -SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){ +SQLITE_API void tdsqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){ va_list ap; va_start(ap,zFormat); - sqlite3VXPrintf(p, zFormat, ap); + tdsqlite3_str_vappendf(p, zFormat, ap); va_end(ap); } @@ -29591,9 +33575,9 @@ SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){ ** Add a new subitem to the tree. The moreToFollow flag indicates that this ** is not the last item in the tree. */ -static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){ +static TreeView *tdsqlite3TreeViewPush(TreeView *p, u8 moreToFollow){ if( p==0 ){ - p = sqlite3_malloc64( sizeof(*p) ); + p = tdsqlite3_malloc64( sizeof(*p) ); if( p==0 ) return 0; memset(p, 0, sizeof(*p)); }else{ @@ -29607,33 +33591,36 @@ static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){ /* ** Finished with one layer of the tree */ -static void sqlite3TreeViewPop(TreeView *p){ +static void tdsqlite3TreeViewPop(TreeView *p){ if( p==0 ) return; p->iLevel--; - if( p->iLevel<0 ) sqlite3_free(p); + if( p->iLevel<0 ) tdsqlite3_free(p); } /* ** Generate a single line of output for the tree, with a prefix that contains ** all the appropriate tree lines */ -static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){ +static void tdsqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){ va_list ap; int i; StrAccum acc; char zBuf[500]; - sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); + tdsqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); if( p ){ for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){ - sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4); + tdsqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4); } - sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4); + tdsqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4); } - va_start(ap, zFormat); - sqlite3VXPrintf(&acc, zFormat, ap); - va_end(ap); - if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1); - sqlite3StrAccumFinish(&acc); + if( zFormat!=0 ){ + va_start(ap, zFormat); + tdsqlite3_str_vappendf(&acc, zFormat, ap); + va_end(ap); + assert( acc.nChar>0 || acc.accError ); + tdsqlite3_str_append(&acc, "\n", 1); + } + tdsqlite3StrAccumFinish(&acc); fprintf(stdout,"%s", zBuf); fflush(stdout); } @@ -29641,70 +33628,120 @@ static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){ /* ** Shorthand for starting a new tree item that consists of a single label */ -static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){ - p = sqlite3TreeViewPush(p, moreFollows); - sqlite3TreeViewLine(p, "%s", zLabel); +static void tdsqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){ + p = tdsqlite3TreeViewPush(p, moreFollows); + tdsqlite3TreeViewLine(p, "%s", zLabel); } /* ** Generate a human-readable description of a WITH clause. */ -SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){ +SQLITE_PRIVATE void tdsqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){ int i; if( pWith==0 ) return; if( pWith->nCte==0 ) return; if( pWith->pOuter ){ - sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter); + tdsqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter); }else{ - sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith); + tdsqlite3TreeViewLine(pView, "WITH (0x%p)", pWith); } if( pWith->nCte>0 ){ - pView = sqlite3TreeViewPush(pView, 1); + pView = tdsqlite3TreeViewPush(pView, 1); for(i=0; i<pWith->nCte; i++){ StrAccum x; char zLine[1000]; const struct Cte *pCte = &pWith->a[i]; - sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); - sqlite3XPrintf(&x, "%s", pCte->zName); + tdsqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); + tdsqlite3_str_appendf(&x, "%s", pCte->zName); if( pCte->pCols && pCte->pCols->nExpr>0 ){ char cSep = '('; int j; for(j=0; j<pCte->pCols->nExpr; j++){ - sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName); + tdsqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zEName); cSep = ','; } - sqlite3XPrintf(&x, ")"); + tdsqlite3_str_appendf(&x, ")"); } - sqlite3XPrintf(&x, " AS"); - sqlite3StrAccumFinish(&x); - sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1); - sqlite3TreeViewSelect(pView, pCte->pSelect, 0); - sqlite3TreeViewPop(pView); + tdsqlite3_str_appendf(&x, " AS"); + tdsqlite3StrAccumFinish(&x); + tdsqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1); + tdsqlite3TreeViewSelect(pView, pCte->pSelect, 0); + tdsqlite3TreeViewPop(pView); } - sqlite3TreeViewPop(pView); + tdsqlite3TreeViewPop(pView); } } +/* +** Generate a human-readable description of a SrcList object. +*/ +SQLITE_PRIVATE void tdsqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){ + int i; + for(i=0; i<pSrc->nSrc; i++){ + const struct SrcList_item *pItem = &pSrc->a[i]; + StrAccum x; + char zLine[100]; + tdsqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); + tdsqlite3_str_appendf(&x, "{%d:*}", pItem->iCursor); + if( pItem->zDatabase ){ + tdsqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName); + }else if( pItem->zName ){ + tdsqlite3_str_appendf(&x, " %s", pItem->zName); + } + if( pItem->pTab ){ + tdsqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p", + pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab); + } + if( pItem->zAlias ){ + tdsqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias); + } + if( pItem->fg.jointype & JT_LEFT ){ + tdsqlite3_str_appendf(&x, " LEFT-JOIN"); + } + if( pItem->fg.fromDDL ){ + tdsqlite3_str_appendf(&x, " DDL"); + } + tdsqlite3StrAccumFinish(&x); + tdsqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1); + if( pItem->pSelect ){ + tdsqlite3TreeViewSelect(pView, pItem->pSelect, 0); + } + if( pItem->fg.isTabFunc ){ + tdsqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:"); + } + tdsqlite3TreeViewPop(pView); + } +} /* ** Generate a human-readable description of a Select object. */ -SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){ +SQLITE_PRIVATE void tdsqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){ int n = 0; int cnt = 0; - pView = sqlite3TreeViewPush(pView, moreToFollow); + if( p==0 ){ + tdsqlite3TreeViewLine(pView, "nil-SELECT"); + return; + } + pView = tdsqlite3TreeViewPush(pView, moreToFollow); if( p->pWith ){ - sqlite3TreeViewWith(pView, p->pWith, 1); + tdsqlite3TreeViewWith(pView, p->pWith, 1); cnt = 1; - sqlite3TreeViewPush(pView, 1); + tdsqlite3TreeViewPush(pView, 1); } do{ - sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d", - ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""), - ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags, - (int)p->nSelectRow - ); - if( cnt++ ) sqlite3TreeViewPop(pView); + if( p->selFlags & SF_WhereBegin ){ + tdsqlite3TreeViewLine(pView, "tdsqlite3WhereBegin()"); + }else{ + tdsqlite3TreeViewLine(pView, + "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d", + ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""), + ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), + p->selId, p, p->selFlags, + (int)p->nSelectRow + ); + } + if( cnt++ ) tdsqlite3TreeViewPop(pView); if( p->pPrior ){ n = 1000; }else{ @@ -29715,70 +33752,67 @@ SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 m if( p->pHaving ) n++; if( p->pOrderBy ) n++; if( p->pLimit ) n++; - if( p->pOffset ) n++; +#ifndef SQLITE_OMIT_WINDOWFUNC + if( p->pWin ) n++; + if( p->pWinDefn ) n++; +#endif } - sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set"); - if( p->pSrc && p->pSrc->nSrc ){ - int i; - pView = sqlite3TreeViewPush(pView, (n--)>0); - sqlite3TreeViewLine(pView, "FROM"); - for(i=0; i<p->pSrc->nSrc; i++){ - struct SrcList_item *pItem = &p->pSrc->a[i]; - StrAccum x; - char zLine[100]; - sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); - sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor); - if( pItem->zDatabase ){ - sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName); - }else if( pItem->zName ){ - sqlite3XPrintf(&x, " %s", pItem->zName); - } - if( pItem->pTab ){ - sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName); - } - if( pItem->zAlias ){ - sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias); - } - if( pItem->fg.jointype & JT_LEFT ){ - sqlite3XPrintf(&x, " LEFT-JOIN"); - } - sqlite3StrAccumFinish(&x); - sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1); - if( pItem->pSelect ){ - sqlite3TreeViewSelect(pView, pItem->pSelect, 0); - } - if( pItem->fg.isTabFunc ){ - sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:"); - } - sqlite3TreeViewPop(pView); + if( p->pEList ){ + tdsqlite3TreeViewExprList(pView, p->pEList, n>0, "result-set"); + } + n--; +#ifndef SQLITE_OMIT_WINDOWFUNC + if( p->pWin ){ + Window *pX; + pView = tdsqlite3TreeViewPush(pView, (n--)>0); + tdsqlite3TreeViewLine(pView, "window-functions"); + for(pX=p->pWin; pX; pX=pX->pNextWin){ + tdsqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0); } - sqlite3TreeViewPop(pView); + tdsqlite3TreeViewPop(pView); + } +#endif + if( p->pSrc && p->pSrc->nSrc ){ + pView = tdsqlite3TreeViewPush(pView, (n--)>0); + tdsqlite3TreeViewLine(pView, "FROM"); + tdsqlite3TreeViewSrcList(pView, p->pSrc); + tdsqlite3TreeViewPop(pView); } if( p->pWhere ){ - sqlite3TreeViewItem(pView, "WHERE", (n--)>0); - sqlite3TreeViewExpr(pView, p->pWhere, 0); - sqlite3TreeViewPop(pView); + tdsqlite3TreeViewItem(pView, "WHERE", (n--)>0); + tdsqlite3TreeViewExpr(pView, p->pWhere, 0); + tdsqlite3TreeViewPop(pView); } if( p->pGroupBy ){ - sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY"); + tdsqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY"); } if( p->pHaving ){ - sqlite3TreeViewItem(pView, "HAVING", (n--)>0); - sqlite3TreeViewExpr(pView, p->pHaving, 0); - sqlite3TreeViewPop(pView); + tdsqlite3TreeViewItem(pView, "HAVING", (n--)>0); + tdsqlite3TreeViewExpr(pView, p->pHaving, 0); + tdsqlite3TreeViewPop(pView); + } +#ifndef SQLITE_OMIT_WINDOWFUNC + if( p->pWinDefn ){ + Window *pX; + tdsqlite3TreeViewItem(pView, "WINDOW", (n--)>0); + for(pX=p->pWinDefn; pX; pX=pX->pNextWin){ + tdsqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0); + } + tdsqlite3TreeViewPop(pView); } +#endif if( p->pOrderBy ){ - sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY"); + tdsqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY"); } if( p->pLimit ){ - sqlite3TreeViewItem(pView, "LIMIT", (n--)>0); - sqlite3TreeViewExpr(pView, p->pLimit, 0); - sqlite3TreeViewPop(pView); - } - if( p->pOffset ){ - sqlite3TreeViewItem(pView, "OFFSET", (n--)>0); - sqlite3TreeViewExpr(pView, p->pOffset, 0); - sqlite3TreeViewPop(pView); + tdsqlite3TreeViewItem(pView, "LIMIT", (n--)>0); + tdsqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0); + if( p->pLimit->pRight ){ + tdsqlite3TreeViewItem(pView, "OFFSET", (n--)>0); + tdsqlite3TreeViewExpr(pView, p->pLimit->pRight, 0); + tdsqlite3TreeViewPop(pView); + } + tdsqlite3TreeViewPop(pView); } if( p->pPrior ){ const char *zOp = "UNION"; @@ -29787,93 +33821,234 @@ SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 m case TK_INTERSECT: zOp = "INTERSECT"; break; case TK_EXCEPT: zOp = "EXCEPT"; break; } - sqlite3TreeViewItem(pView, zOp, 1); + tdsqlite3TreeViewItem(pView, zOp, 1); } p = p->pPrior; }while( p!=0 ); - sqlite3TreeViewPop(pView); + tdsqlite3TreeViewPop(pView); +} + +#ifndef SQLITE_OMIT_WINDOWFUNC +/* +** Generate a description of starting or stopping bounds +*/ +SQLITE_PRIVATE void tdsqlite3TreeViewBound( + TreeView *pView, /* View context */ + u8 eBound, /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */ + Expr *pExpr, /* Value for PRECEDING or FOLLOWING */ + u8 moreToFollow /* True if more to follow */ +){ + switch( eBound ){ + case TK_UNBOUNDED: { + tdsqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow); + tdsqlite3TreeViewPop(pView); + break; + } + case TK_CURRENT: { + tdsqlite3TreeViewItem(pView, "CURRENT", moreToFollow); + tdsqlite3TreeViewPop(pView); + break; + } + case TK_PRECEDING: { + tdsqlite3TreeViewItem(pView, "PRECEDING", moreToFollow); + tdsqlite3TreeViewExpr(pView, pExpr, 0); + tdsqlite3TreeViewPop(pView); + break; + } + case TK_FOLLOWING: { + tdsqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow); + tdsqlite3TreeViewExpr(pView, pExpr, 0); + tdsqlite3TreeViewPop(pView); + break; + } + } } +#endif /* SQLITE_OMIT_WINDOWFUNC */ + +#ifndef SQLITE_OMIT_WINDOWFUNC +/* +** Generate a human-readable explanation for a Window object +*/ +SQLITE_PRIVATE void tdsqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){ + int nElement = 0; + if( pWin->pFilter ){ + tdsqlite3TreeViewItem(pView, "FILTER", 1); + tdsqlite3TreeViewExpr(pView, pWin->pFilter, 0); + tdsqlite3TreeViewPop(pView); + } + pView = tdsqlite3TreeViewPush(pView, more); + if( pWin->zName ){ + tdsqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin); + }else{ + tdsqlite3TreeViewLine(pView, "OVER (%p)", pWin); + } + if( pWin->zBase ) nElement++; + if( pWin->pOrderBy ) nElement++; + if( pWin->eFrmType ) nElement++; + if( pWin->eExclude ) nElement++; + if( pWin->zBase ){ + tdsqlite3TreeViewPush(pView, (--nElement)>0); + tdsqlite3TreeViewLine(pView, "window: %s", pWin->zBase); + tdsqlite3TreeViewPop(pView); + } + if( pWin->pPartition ){ + tdsqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY"); + } + if( pWin->pOrderBy ){ + tdsqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY"); + } + if( pWin->eFrmType ){ + char zBuf[30]; + const char *zFrmType = "ROWS"; + if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE"; + if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS"; + tdsqlite3_snprintf(sizeof(zBuf),zBuf,"%s%s",zFrmType, + pWin->bImplicitFrame ? " (implied)" : ""); + tdsqlite3TreeViewItem(pView, zBuf, (--nElement)>0); + tdsqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1); + tdsqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0); + tdsqlite3TreeViewPop(pView); + } + if( pWin->eExclude ){ + char zBuf[30]; + const char *zExclude; + switch( pWin->eExclude ){ + case TK_NO: zExclude = "NO OTHERS"; break; + case TK_CURRENT: zExclude = "CURRENT ROW"; break; + case TK_GROUP: zExclude = "GROUP"; break; + case TK_TIES: zExclude = "TIES"; break; + default: + tdsqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude); + zExclude = zBuf; + break; + } + tdsqlite3TreeViewPush(pView, 0); + tdsqlite3TreeViewLine(pView, "EXCLUDE %s", zExclude); + tdsqlite3TreeViewPop(pView); + } + tdsqlite3TreeViewPop(pView); +} +#endif /* SQLITE_OMIT_WINDOWFUNC */ + +#ifndef SQLITE_OMIT_WINDOWFUNC +/* +** Generate a human-readable explanation for a Window Function object +*/ +SQLITE_PRIVATE void tdsqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){ + pView = tdsqlite3TreeViewPush(pView, more); + tdsqlite3TreeViewLine(pView, "WINFUNC %s(%d)", + pWin->pFunc->zName, pWin->pFunc->nArg); + tdsqlite3TreeViewWindow(pView, pWin, 0); + tdsqlite3TreeViewPop(pView); +} +#endif /* SQLITE_OMIT_WINDOWFUNC */ /* ** Generate a human-readable explanation of an expression tree. */ -SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){ +SQLITE_PRIVATE void tdsqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){ const char *zBinOp = 0; /* Binary operator */ const char *zUniOp = 0; /* Unary operator */ - char zFlgs[30]; - pView = sqlite3TreeViewPush(pView, moreToFollow); + char zFlgs[60]; + pView = tdsqlite3TreeViewPush(pView, moreToFollow); if( pExpr==0 ){ - sqlite3TreeViewLine(pView, "nil"); - sqlite3TreeViewPop(pView); + tdsqlite3TreeViewLine(pView, "nil"); + tdsqlite3TreeViewPop(pView); return; } - if( pExpr->flags ){ - sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags); + if( pExpr->flags || pExpr->affExpr ){ + StrAccum x; + tdsqlite3StrAccumInit(&x, 0, zFlgs, sizeof(zFlgs), 0); + tdsqlite3_str_appendf(&x, " fg.af=%x.%c", + pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n'); + if( ExprHasProperty(pExpr, EP_FromJoin) ){ + tdsqlite3_str_appendf(&x, " iRJT=%d", pExpr->iRightJoinTable); + } + if( ExprHasProperty(pExpr, EP_FromDDL) ){ + tdsqlite3_str_appendf(&x, " DDL"); + } + tdsqlite3StrAccumFinish(&x); }else{ zFlgs[0] = 0; } switch( pExpr->op ){ case TK_AGG_COLUMN: { - sqlite3TreeViewLine(pView, "AGG{%d:%d}%s", + tdsqlite3TreeViewLine(pView, "AGG{%d:%d}%s", pExpr->iTable, pExpr->iColumn, zFlgs); break; } case TK_COLUMN: { if( pExpr->iTable<0 ){ /* This only happens when coding check constraints */ - sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs); + char zOp2[16]; + if( pExpr->op2 ){ + tdsqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2); + }else{ + zOp2[0] = 0; + } + tdsqlite3TreeViewLine(pView, "COLUMN(%d)%s%s", + pExpr->iColumn, zFlgs, zOp2); }else{ - sqlite3TreeViewLine(pView, "{%d:%d}%s", - pExpr->iTable, pExpr->iColumn, zFlgs); + tdsqlite3TreeViewLine(pView, "{%d:%d} pTab=%p%s", + pExpr->iTable, pExpr->iColumn, + pExpr->y.pTab, zFlgs); + } + if( ExprHasProperty(pExpr, EP_FixedCol) ){ + tdsqlite3TreeViewExpr(pView, pExpr->pLeft, 0); } break; } case TK_INTEGER: { if( pExpr->flags & EP_IntValue ){ - sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue); + tdsqlite3TreeViewLine(pView, "%d", pExpr->u.iValue); }else{ - sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken); + tdsqlite3TreeViewLine(pView, "%s", pExpr->u.zToken); } break; } #ifndef SQLITE_OMIT_FLOATING_POINT case TK_FLOAT: { - sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); + tdsqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); break; } #endif case TK_STRING: { - sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken); + tdsqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken); break; } case TK_NULL: { - sqlite3TreeViewLine(pView,"NULL"); + tdsqlite3TreeViewLine(pView,"NULL"); + break; + } + case TK_TRUEFALSE: { + tdsqlite3TreeViewLine(pView, + tdsqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE"); break; } #ifndef SQLITE_OMIT_BLOB_LITERAL case TK_BLOB: { - sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); + tdsqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); break; } #endif case TK_VARIABLE: { - sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)", + tdsqlite3TreeViewLine(pView,"VARIABLE(%s,%d)", pExpr->u.zToken, pExpr->iColumn); break; } case TK_REGISTER: { - sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable); + tdsqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable); break; } case TK_ID: { - sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken); + tdsqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken); break; } #ifndef SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ - sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); + tdsqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken); + tdsqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } #endif /* SQLITE_OMIT_CAST */ @@ -29906,55 +34081,98 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m case TK_ISNULL: zUniOp = "ISNULL"; break; case TK_NOTNULL: zUniOp = "NOTNULL"; break; + case TK_TRUTH: { + int x; + const char *azOp[] = { + "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE" + }; + assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT ); + assert( pExpr->pRight ); + assert( tdsqlite3ExprSkipCollate(pExpr->pRight)->op==TK_TRUEFALSE ); + x = (pExpr->op2==TK_ISNOT)*2 + tdsqlite3ExprTruthValue(pExpr->pRight); + zUniOp = azOp[x]; + break; + } + case TK_SPAN: { - sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); + tdsqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken); + tdsqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } case TK_COLLATE: { - sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); + /* COLLATE operators without the EP_Collate flag are intended to + ** emulate collation associated with a table column. These show + ** up in the treeview output as "SOFT-COLLATE". Explicit COLLATE + ** operators that appear in the original SQL always have the + ** EP_Collate bit set and appear in treeview output as just "COLLATE" */ + tdsqlite3TreeViewLine(pView, "%sCOLLATE %Q%s", + !ExprHasProperty(pExpr, EP_Collate) ? "SOFT-" : "", + pExpr->u.zToken, zFlgs); + tdsqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } case TK_AGG_FUNCTION: case TK_FUNCTION: { ExprList *pFarg; /* List of function arguments */ + Window *pWin; if( ExprHasProperty(pExpr, EP_TokenOnly) ){ pFarg = 0; + pWin = 0; }else{ pFarg = pExpr->x.pList; +#ifndef SQLITE_OMIT_WINDOWFUNC + pWin = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0; +#else + pWin = 0; +#endif } if( pExpr->op==TK_AGG_FUNCTION ){ - sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q", - pExpr->op2, pExpr->u.zToken); + tdsqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s", + pExpr->op2, pExpr->u.zToken, zFlgs); + }else if( pExpr->op2!=0 ){ + const char *zOp2; + char zBuf[8]; + tdsqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2); + zOp2 = zBuf; + if( pExpr->op2==NC_IsCheck ) zOp2 = "NC_IsCheck"; + if( pExpr->op2==NC_IdxExpr ) zOp2 = "NC_IdxExpr"; + if( pExpr->op2==NC_PartIdx ) zOp2 = "NC_PartIdx"; + if( pExpr->op2==NC_GenCol ) zOp2 = "NC_GenCol"; + tdsqlite3TreeViewLine(pView, "FUNCTION %Q%s op2=%s", + pExpr->u.zToken, zFlgs, zOp2); }else{ - sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken); + tdsqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs); } if( pFarg ){ - sqlite3TreeViewExprList(pView, pFarg, 0, 0); + tdsqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0); + } +#ifndef SQLITE_OMIT_WINDOWFUNC + if( pWin ){ + tdsqlite3TreeViewWindow(pView, pWin, 0); } +#endif break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_EXISTS: { - sqlite3TreeViewLine(pView, "EXISTS-expr"); - sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); + tdsqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags); + tdsqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); break; } case TK_SELECT: { - sqlite3TreeViewLine(pView, "SELECT-expr"); - sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); + tdsqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags); + tdsqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); break; } case TK_IN: { - sqlite3TreeViewLine(pView, "IN"); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); + tdsqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags); + tdsqlite3TreeViewExpr(pView, pExpr->pLeft, 1); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); + tdsqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); }else{ - sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); + tdsqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); } break; } @@ -29975,10 +34193,10 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m Expr *pX = pExpr->pLeft; Expr *pY = pExpr->x.pList->a[0].pExpr; Expr *pZ = pExpr->x.pList->a[1].pExpr; - sqlite3TreeViewLine(pView, "BETWEEN"); - sqlite3TreeViewExpr(pView, pX, 1); - sqlite3TreeViewExpr(pView, pY, 1); - sqlite3TreeViewExpr(pView, pZ, 0); + tdsqlite3TreeViewLine(pView, "BETWEEN"); + tdsqlite3TreeViewExpr(pView, pX, 1); + tdsqlite3TreeViewExpr(pView, pY, 1); + tdsqlite3TreeViewExpr(pView, pZ, 0); break; } case TK_TRIGGER: { @@ -29989,95 +34207,116 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m ** is set to the column of the pseudo-table to read, or to -1 to ** read the rowid field. */ - sqlite3TreeViewLine(pView, "%s(%d)", + tdsqlite3TreeViewLine(pView, "%s(%d)", pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn); break; } case TK_CASE: { - sqlite3TreeViewLine(pView, "CASE"); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); - sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); + tdsqlite3TreeViewLine(pView, "CASE"); + tdsqlite3TreeViewExpr(pView, pExpr->pLeft, 1); + tdsqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); break; } #ifndef SQLITE_OMIT_TRIGGER case TK_RAISE: { const char *zType = "unk"; - switch( pExpr->affinity ){ + switch( pExpr->affExpr ){ case OE_Rollback: zType = "rollback"; break; case OE_Abort: zType = "abort"; break; case OE_Fail: zType = "fail"; break; case OE_Ignore: zType = "ignore"; break; } - sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken); + tdsqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken); break; } #endif case TK_MATCH: { - sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s", + tdsqlite3TreeViewLine(pView, "MATCH {%d:%d}%s", pExpr->iTable, pExpr->iColumn, zFlgs); - sqlite3TreeViewExpr(pView, pExpr->pRight, 0); + tdsqlite3TreeViewExpr(pView, pExpr->pRight, 0); break; } case TK_VECTOR: { - sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR"); + char *z = tdsqlite3_mprintf("VECTOR%s",zFlgs); + tdsqlite3TreeViewBareExprList(pView, pExpr->x.pList, z); + tdsqlite3_free(z); break; } case TK_SELECT_COLUMN: { - sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn); - sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0); + tdsqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn); + tdsqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0); + break; + } + case TK_IF_NULL_ROW: { + tdsqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable); + tdsqlite3TreeViewExpr(pView, pExpr->pLeft, 0); break; } default: { - sqlite3TreeViewLine(pView, "op=%d", pExpr->op); + tdsqlite3TreeViewLine(pView, "op=%d", pExpr->op); break; } } if( zBinOp ){ - sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); - sqlite3TreeViewExpr(pView, pExpr->pRight, 0); + tdsqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs); + tdsqlite3TreeViewExpr(pView, pExpr->pLeft, 1); + tdsqlite3TreeViewExpr(pView, pExpr->pRight, 0); }else if( zUniOp ){ - sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); + tdsqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs); + tdsqlite3TreeViewExpr(pView, pExpr->pLeft, 0); } - sqlite3TreeViewPop(pView); + tdsqlite3TreeViewPop(pView); } /* ** Generate a human-readable explanation of an expression list. */ -SQLITE_PRIVATE void sqlite3TreeViewBareExprList( +SQLITE_PRIVATE void tdsqlite3TreeViewBareExprList( TreeView *pView, const ExprList *pList, const char *zLabel ){ if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST"; if( pList==0 ){ - sqlite3TreeViewLine(pView, "%s (empty)", zLabel); + tdsqlite3TreeViewLine(pView, "%s (empty)", zLabel); }else{ int i; - sqlite3TreeViewLine(pView, "%s", zLabel); + tdsqlite3TreeViewLine(pView, "%s", zLabel); for(i=0; i<pList->nExpr; i++){ int j = pList->a[i].u.x.iOrderByCol; - if( j ){ - sqlite3TreeViewPush(pView, 0); - sqlite3TreeViewLine(pView, "iOrderByCol=%d", j); + char *zName = pList->a[i].zEName; + int moreToFollow = i<pList->nExpr - 1; + if( pList->a[i].eEName!=ENAME_NAME ) zName = 0; + if( j || zName ){ + tdsqlite3TreeViewPush(pView, moreToFollow); + moreToFollow = 0; + tdsqlite3TreeViewLine(pView, 0); + if( zName ){ + fprintf(stdout, "AS %s ", zName); + } + if( j ){ + fprintf(stdout, "iOrderByCol=%d", j); + } + fprintf(stdout, "\n"); + fflush(stdout); + } + tdsqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow); + if( j || zName ){ + tdsqlite3TreeViewPop(pView); } - sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1); - if( j ) sqlite3TreeViewPop(pView); } } } -SQLITE_PRIVATE void sqlite3TreeViewExprList( +SQLITE_PRIVATE void tdsqlite3TreeViewExprList( TreeView *pView, const ExprList *pList, u8 moreToFollow, const char *zLabel ){ - pView = sqlite3TreeViewPush(pView, moreToFollow); - sqlite3TreeViewBareExprList(pView, pList, zLabel); - sqlite3TreeViewPop(pView); + pView = tdsqlite3TreeViewPush(pView, moreToFollow); + tdsqlite3TreeViewBareExprList(pView, pList, zLabel); + tdsqlite3TreeViewPop(pView); } #endif /* SQLITE_DEBUG */ @@ -30107,16 +34346,16 @@ SQLITE_PRIVATE void sqlite3TreeViewExprList( /* All threads share a single random number generator. ** This structure is the current state of the generator. */ -static SQLITE_WSD struct sqlite3PrngType { +static SQLITE_WSD struct tdsqlite3PrngType { unsigned char isInit; /* True if initialized */ unsigned char i, j; /* State variables */ unsigned char s[256]; /* State variables */ -} sqlite3Prng; +} tdsqlite3Prng; /* ** Return N random bytes. */ -SQLITE_API void sqlite3_randomness(int N, void *pBuf){ +SQLITE_API void tdsqlite3_randomness(int N, void *pBuf){ unsigned char t; unsigned char *zBuf = pBuf; @@ -30124,31 +34363,31 @@ SQLITE_API void sqlite3_randomness(int N, void *pBuf){ ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdPrng can refer directly - ** to the "sqlite3Prng" state vector declared above. + ** to the "tdsqlite3Prng" state vector declared above. */ #ifdef SQLITE_OMIT_WSD - struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); + struct tdsqlite3PrngType *p = &GLOBAL(struct tdsqlite3PrngType, tdsqlite3Prng); # define wsdPrng p[0] #else -# define wsdPrng sqlite3Prng +# define wsdPrng tdsqlite3Prng #endif #if SQLITE_THREADSAFE - sqlite3_mutex *mutex; + tdsqlite3_mutex *mutex; #endif #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return; + if( tdsqlite3_initialize() ) return; #endif #if SQLITE_THREADSAFE - mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); + mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); #endif - sqlite3_mutex_enter(mutex); + tdsqlite3_mutex_enter(mutex); if( N<=0 || pBuf==0 ){ wsdPrng.isInit = 0; - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); return; } @@ -30166,7 +34405,7 @@ SQLITE_API void sqlite3_randomness(int N, void *pBuf){ char k[256]; wsdPrng.j = 0; wsdPrng.i = 0; - sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k); + tdsqlite3OsRandomness(tdsqlite3_vfs_find(0), 256, k); for(i=0; i<256; i++){ wsdPrng.s[i] = (u8)i; } @@ -30189,35 +34428,35 @@ SQLITE_API void sqlite3_randomness(int N, void *pBuf){ t += wsdPrng.s[wsdPrng.i]; *(zBuf++) = wsdPrng.s[t]; }while( --N ); - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); } -#ifndef SQLITE_OMIT_BUILTIN_TEST +#ifndef SQLITE_UNTESTABLE /* ** For testing purposes, we sometimes want to preserve the state of ** PRNG and restore the PRNG to its saved state at a later time, or ** to reset the PRNG to its initial state. These routines accomplish ** those tasks. ** -** The sqlite3_test_control() interface calls these routines to +** The tdsqlite3_test_control() interface calls these routines to ** control the PRNG. */ -static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng; -SQLITE_PRIVATE void sqlite3PrngSaveState(void){ +static SQLITE_WSD struct tdsqlite3PrngType tdsqlite3SavedPrng; +SQLITE_PRIVATE void tdsqlite3PrngSaveState(void){ memcpy( - &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), - &GLOBAL(struct sqlite3PrngType, sqlite3Prng), - sizeof(sqlite3Prng) + &GLOBAL(struct tdsqlite3PrngType, tdsqlite3SavedPrng), + &GLOBAL(struct tdsqlite3PrngType, tdsqlite3Prng), + sizeof(tdsqlite3Prng) ); } -SQLITE_PRIVATE void sqlite3PrngRestoreState(void){ +SQLITE_PRIVATE void tdsqlite3PrngRestoreState(void){ memcpy( - &GLOBAL(struct sqlite3PrngType, sqlite3Prng), - &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), - sizeof(sqlite3Prng) + &GLOBAL(struct tdsqlite3PrngType, tdsqlite3Prng), + &GLOBAL(struct tdsqlite3PrngType, tdsqlite3SavedPrng), + sizeof(tdsqlite3Prng) ); } -#endif /* SQLITE_OMIT_BUILTIN_TEST */ +#endif /* SQLITE_UNTESTABLE */ /************** End of random.c **********************************************/ /************** Begin file threads.c *****************************************/ @@ -30236,13 +34475,13 @@ SQLITE_PRIVATE void sqlite3PrngRestoreState(void){ ** This file presents a simple cross-platform threading interface for ** use internally by SQLite. ** -** A "thread" can be created using sqlite3ThreadCreate(). This thread +** A "thread" can be created using tdsqlite3ThreadCreate(). This thread ** runs independently of its creator until it is joined using -** sqlite3ThreadJoin(), at which point it terminates. +** tdsqlite3ThreadJoin(), at which point it terminates. ** ** Threads do not have to be real. It could be that the work of the -** "thread" is done by the main thread at either the sqlite3ThreadCreate() -** or sqlite3ThreadJoin() call. This is, in fact, what happens in +** "thread" is done by the main thread at either the tdsqlite3ThreadCreate() +** or tdsqlite3ThreadJoin() call. This is, in fact, what happens in ** single threaded systems. Nothing in SQLite requires multiple threads. ** This interface exists so that applications that want to take advantage ** of multiple cores can do so, while also allowing applications to stay @@ -30271,7 +34510,7 @@ struct SQLiteThread { }; /* Create a new thread */ -SQLITE_PRIVATE int sqlite3ThreadCreate( +SQLITE_PRIVATE int tdsqlite3ThreadCreate( SQLiteThread **ppThread, /* OUT: Write the thread object here */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ @@ -30282,10 +34521,10 @@ SQLITE_PRIVATE int sqlite3ThreadCreate( assert( ppThread!=0 ); assert( xTask!=0 ); /* This routine is never used in single-threaded mode */ - assert( sqlite3GlobalConfig.bCoreMutex!=0 ); + assert( tdsqlite3GlobalConfig.bCoreMutex!=0 ); *ppThread = 0; - p = sqlite3Malloc(sizeof(*p)); + p = tdsqlite3Malloc(sizeof(*p)); if( p==0 ) return SQLITE_NOMEM_BKPT; memset(p, 0, sizeof(*p)); p->xTask = xTask; @@ -30294,7 +34533,7 @@ SQLITE_PRIVATE int sqlite3ThreadCreate( ** function that returns SQLITE_ERROR when passed the argument 200, that ** forces worker threads to run sequentially and deterministically ** for testing purposes. */ - if( sqlite3FaultSim(200) ){ + if( tdsqlite3FaultSim(200) ){ rc = 1; }else{ rc = pthread_create(&p->tid, 0, xTask, pIn); @@ -30308,7 +34547,7 @@ SQLITE_PRIVATE int sqlite3ThreadCreate( } /* Get the results of the thread */ -SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ +SQLITE_PRIVATE int tdsqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ int rc; assert( ppOut!=0 ); @@ -30319,7 +34558,7 @@ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ }else{ rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK; } - sqlite3_free(p); + tdsqlite3_free(p); return rc; } @@ -30343,7 +34582,7 @@ struct SQLiteThread { }; /* Thread procedure Win32 compatibility shim */ -static unsigned __stdcall sqlite3ThreadProc( +static unsigned __stdcall tdsqlite3ThreadProc( void *pArg /* IN: Pointer to the SQLiteThread structure */ ){ SQLiteThread *p = (SQLiteThread *)pArg; @@ -30366,7 +34605,7 @@ static unsigned __stdcall sqlite3ThreadProc( } /* Create a new thread */ -SQLITE_PRIVATE int sqlite3ThreadCreate( +SQLITE_PRIVATE int tdsqlite3ThreadCreate( SQLiteThread **ppThread, /* OUT: Write the thread object here */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ @@ -30376,19 +34615,19 @@ SQLITE_PRIVATE int sqlite3ThreadCreate( assert( ppThread!=0 ); assert( xTask!=0 ); *ppThread = 0; - p = sqlite3Malloc(sizeof(*p)); + p = tdsqlite3Malloc(sizeof(*p)); if( p==0 ) return SQLITE_NOMEM_BKPT; /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a ** function that returns SQLITE_ERROR when passed the argument 200, that ** forces worker threads to run sequentially and deterministically - ** (via the sqlite3FaultSim() term of the conditional) for testing + ** (via the tdsqlite3FaultSim() term of the conditional) for testing ** purposes. */ - if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){ + if( tdsqlite3GlobalConfig.bCoreMutex==0 || tdsqlite3FaultSim(200) ){ memset(p, 0, sizeof(*p)); }else{ p->xTask = xTask; p->pIn = pIn; - p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id); + p->tid = (void*)_beginthreadex(0, 0, tdsqlite3ThreadProc, p, 0, &p->id); if( p->tid==0 ){ memset(p, 0, sizeof(*p)); } @@ -30401,10 +34640,10 @@ SQLITE_PRIVATE int sqlite3ThreadCreate( return SQLITE_OK; } -SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */ +SQLITE_PRIVATE DWORD tdsqlite3Win32Wait(HANDLE hObject); /* os_win.c */ /* Get the results of the thread */ -SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ +SQLITE_PRIVATE int tdsqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ DWORD rc; BOOL bRc; @@ -30416,13 +34655,13 @@ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ assert( p->tid==0 ); }else{ assert( p->id!=0 && p->id!=GetCurrentThreadId() ); - rc = sqlite3Win32Wait((HANDLE)p->tid); + rc = tdsqlite3Win32Wait((HANDLE)p->tid); assert( rc!=WAIT_IO_COMPLETION ); bRc = CloseHandle((HANDLE)p->tid); assert( bRc ); } if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult; - sqlite3_free(p); + tdsqlite3_free(p); return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR; } @@ -30446,7 +34685,7 @@ struct SQLiteThread { }; /* Create a new thread */ -SQLITE_PRIVATE int sqlite3ThreadCreate( +SQLITE_PRIVATE int tdsqlite3ThreadCreate( SQLiteThread **ppThread, /* OUT: Write the thread object here */ void *(*xTask)(void*), /* Routine to run in a separate thread */ void *pIn /* Argument passed into xTask() */ @@ -30456,7 +34695,7 @@ SQLITE_PRIVATE int sqlite3ThreadCreate( assert( ppThread!=0 ); assert( xTask!=0 ); *ppThread = 0; - p = sqlite3Malloc(sizeof(*p)); + p = tdsqlite3Malloc(sizeof(*p)); if( p==0 ) return SQLITE_NOMEM_BKPT; if( (SQLITE_PTR_TO_INT(p)/17)&1 ){ p->xTask = xTask; @@ -30470,7 +34709,7 @@ SQLITE_PRIVATE int sqlite3ThreadCreate( } /* Get the results of the thread */ -SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ +SQLITE_PRIVATE int tdsqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ assert( ppOut!=0 ); if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; @@ -30479,13 +34718,13 @@ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ }else{ *ppOut = p->pResult; } - sqlite3_free(p); + tdsqlite3_free(p); #if defined(SQLITE_TEST) { - void *pTstAlloc = sqlite3Malloc(10); + void *pTstAlloc = tdsqlite3Malloc(10); if (!pTstAlloc) return SQLITE_NOMEM_BKPT; - sqlite3_free(pTstAlloc); + tdsqlite3_free(pTstAlloc); } #endif @@ -30542,14 +34781,14 @@ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ ** The following constant value is used by the SQLITE_BIGENDIAN and ** SQLITE_LITTLEENDIAN macros. */ -SQLITE_PRIVATE const int sqlite3one = 1; +SQLITE_PRIVATE const int tdsqlite3one = 1; #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */ /* ** This lookup table is used to help decode the first byte of ** a multi-byte UTF8 character. */ -static const unsigned char sqlite3Utf8Trans1[] = { +static const unsigned char tdsqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, @@ -30655,7 +34894,7 @@ static const unsigned char sqlite3Utf8Trans1[] = { #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ - c = sqlite3Utf8Trans1[c-0xc0]; \ + c = tdsqlite3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ @@ -30663,7 +34902,7 @@ static const unsigned char sqlite3Utf8Trans1[] = { || (c&0xFFFFF800)==0xD800 \ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } -SQLITE_PRIVATE u32 sqlite3Utf8Read( +SQLITE_PRIVATE u32 tdsqlite3Utf8Read( const unsigned char **pz /* Pointer to string from which to read char */ ){ unsigned int c; @@ -30673,7 +34912,7 @@ SQLITE_PRIVATE u32 sqlite3Utf8Read( */ c = *((*pz)++); if( c>=0xc0 ){ - c = sqlite3Utf8Trans1[c-0xc0]; + c = tdsqlite3Utf8Trans1[c-0xc0]; while( (*(*pz) & 0xc0)==0x80 ){ c = (c<<6) + (0x3f & *((*pz)++)); } @@ -30689,7 +34928,7 @@ SQLITE_PRIVATE u32 sqlite3Utf8Read( /* ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is -** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). +** printed on stderr on the way into and out of tdsqlite3VdbeMemTranslate(). */ /* #define TRANSLATE_TRACE 1 */ @@ -30699,15 +34938,15 @@ SQLITE_PRIVATE u32 sqlite3Utf8Read( ** desiredEnc. It is an error if the string is already of the desired ** encoding, or if *pMem does not contain a string value. */ -SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){ - int len; /* Maximum length of output string in bytes */ - unsigned char *zOut; /* Output buffer */ - unsigned char *zIn; /* Input iterator */ - unsigned char *zTerm; /* End of input */ - unsigned char *z; /* Output iterator */ +SQLITE_PRIVATE SQLITE_NOINLINE int tdsqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){ + tdsqlite3_int64 len; /* Maximum length of output string in bytes */ + unsigned char *zOut; /* Output buffer */ + unsigned char *zIn; /* Input iterator */ + unsigned char *zTerm; /* End of input */ + unsigned char *z; /* Output iterator */ unsigned int c; - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); assert( pMem->flags&MEM_Str ); assert( pMem->enc!=desiredEnc ); assert( pMem->enc!=0 ); @@ -30715,9 +34954,11 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desired #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) { - char zBuf[100]; - sqlite3VdbeMemPrettyPrint(pMem, zBuf); - fprintf(stderr, "INPUT: %s\n", zBuf); + StrAccum acc; + char zBuf[1000]; + tdsqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); + tdsqlite3VdbeMemPrettyPrint(pMem, &acc); + fprintf(stderr, "INPUT: %s\n", tdsqlite3StrAccumFinish(&acc)); } #endif @@ -30728,7 +34969,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desired if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ u8 temp; int rc; - rc = sqlite3VdbeMemMakeWriteable(pMem); + rc = tdsqlite3VdbeMemMakeWriteable(pMem); if( rc!=SQLITE_OK ){ assert( rc==SQLITE_NOMEM ); return SQLITE_NOMEM_BKPT; @@ -30753,25 +34994,25 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desired ** nul-terminator. */ pMem->n &= ~1; - len = pMem->n * 2 + 1; + len = 2 * (tdsqlite3_int64)pMem->n + 1; }else{ /* When converting from UTF-8 to UTF-16 the maximum growth is caused ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 ** character. Two bytes are required in the output buffer for the ** nul-terminator. */ - len = pMem->n * 2 + 2; + len = 2 * (tdsqlite3_int64)pMem->n + 2; } /* Set zIn to point at the start of the input buffer and zTerm to point 1 ** byte past the end. ** ** Variable zOut is set to point at the output buffer, space obtained - ** from sqlite3_malloc(). + ** from tdsqlite3_malloc(). */ zIn = (u8*)pMem->z; zTerm = &zIn[pMem->n]; - zOut = sqlite3DbMallocRaw(pMem->db, len); + zOut = tdsqlite3DbMallocRaw(pMem->db, len); if( !zOut ){ return SQLITE_NOMEM_BKPT; } @@ -30815,24 +35056,28 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desired assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); c = pMem->flags; - sqlite3VdbeMemRelease(pMem); + tdsqlite3VdbeMemRelease(pMem); pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype)); pMem->enc = desiredEnc; pMem->z = (char*)zOut; pMem->zMalloc = pMem->z; - pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z); + pMem->szMalloc = tdsqlite3DbMallocSize(pMem->db, pMem->z); translate_out: #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) { - char zBuf[100]; - sqlite3VdbeMemPrettyPrint(pMem, zBuf); - fprintf(stderr, "OUTPUT: %s\n", zBuf); + StrAccum acc; + char zBuf[1000]; + tdsqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); + tdsqlite3VdbeMemPrettyPrint(pMem, &acc); + fprintf(stderr, "OUTPUT: %s\n", tdsqlite3StrAccumFinish(&acc)); } #endif return SQLITE_OK; } +#endif /* SQLITE_OMIT_UTF16 */ +#ifndef SQLITE_OMIT_UTF16 /* ** This routine checks for a byte-order mark at the beginning of the ** UTF-16 string stored in *pMem. If one is present, it is removed and @@ -30842,7 +35087,7 @@ translate_out: ** The allocation (static, dynamic etc.) and encoding of the Mem may be ** changed by this function. */ -SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){ +SQLITE_PRIVATE int tdsqlite3VdbeMemHandleBom(Mem *pMem){ int rc = SQLITE_OK; u8 bom = 0; @@ -30859,7 +35104,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){ } if( bom ){ - rc = sqlite3VdbeMemMakeWriteable(pMem); + rc = tdsqlite3VdbeMemMakeWriteable(pMem); if( rc==SQLITE_OK ){ pMem->n -= 2; memmove(pMem->z, &pMem->z[2], pMem->n); @@ -30880,7 +35125,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){ ** number of unicode characters in the first nByte of pZ (or up to ** the first 0x00, whichever comes first). */ -SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){ +SQLITE_PRIVATE int tdsqlite3Utf8CharLen(const char *zIn, int nByte){ int r = 0; const u8 *z = (const u8*)zIn; const u8 *zTerm; @@ -30910,13 +35155,13 @@ SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){ ** The translation is done in-place and aborted if the output ** overruns the input. */ -SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){ +SQLITE_PRIVATE int tdsqlite3Utf8To8(unsigned char *zIn){ unsigned char *zOut = zIn; unsigned char *zStart = zIn; u32 c; while( zIn[0] && zOut<=zIn ){ - c = sqlite3Utf8Read((const u8**)&zIn); + c = tdsqlite3Utf8Read((const u8**)&zIn); if( c!=0xfffd ){ WRITE_UTF8(zOut, c); } @@ -30929,19 +35174,19 @@ SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){ #ifndef SQLITE_OMIT_UTF16 /* ** Convert a UTF-16 string in the native encoding into a UTF-8 string. -** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must +** Memory to hold the UTF-8 string is obtained from tdsqlite3_malloc and must ** be freed by the calling function. ** ** NULL is returned if there is an allocation error. */ -SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){ +SQLITE_PRIVATE char *tdsqlite3Utf16to8(tdsqlite3 *db, const void *z, int nByte, u8 enc){ Mem m; memset(&m, 0, sizeof(m)); m.db = db; - sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC); - sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8); + tdsqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC); + tdsqlite3VdbeChangeEncoding(&m, SQLITE_UTF8); if( db->mallocFailed ){ - sqlite3VdbeMemRelease(&m); + tdsqlite3VdbeMemRelease(&m); m.z = 0; } assert( (m.flags & MEM_Term)!=0 || db->mallocFailed ); @@ -30955,7 +35200,7 @@ SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 e ** Return the number of bytes in the first nChar unicode characters ** in pZ. nChar must be non-negative. */ -SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){ +SQLITE_PRIVATE int tdsqlite3Utf16ByteLen(const void *zIn, int nChar){ int c; unsigned char const *z = zIn; int n = 0; @@ -30980,7 +35225,7 @@ SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){ ** It checks that the primitives for serializing and deserializing ** characters in each encoding are inverses of each other. */ -SQLITE_PRIVATE void sqlite3UtfSelfTest(void){ +SQLITE_PRIVATE void tdsqlite3UtfSelfTest(void){ unsigned int i, t; unsigned char zBuf[20]; unsigned char *z; @@ -30994,7 +35239,7 @@ SQLITE_PRIVATE void sqlite3UtfSelfTest(void){ assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; - c = sqlite3Utf8Read((const u8**)&z); + c = tdsqlite3Utf8Read((const u8**)&z); t = i; if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; @@ -31050,34 +35295,42 @@ SQLITE_PRIVATE void sqlite3UtfSelfTest(void){ */ /* #include "sqliteInt.h" */ /* #include <stdarg.h> */ -#if HAVE_ISNAN || SQLITE_HAVE_ISNAN -# include <math.h> +#ifndef SQLITE_OMIT_FLOATING_POINT +#include <math.h> #endif /* ** Routine needed to support the testcase() macro. */ #ifdef SQLITE_COVERAGE_TEST -SQLITE_PRIVATE void sqlite3Coverage(int x){ +SQLITE_PRIVATE void tdsqlite3Coverage(int x){ static unsigned dummy = 0; dummy += (unsigned)x; } #endif /* -** Give a callback to the test harness that can be used to simulate faults -** in places where it is difficult or expensive to do so purely by means -** of inputs. +** Calls to tdsqlite3FaultSim() are used to simulate a failure during testing, +** or to bypass normal error detection during testing in order to let +** execute proceed futher downstream. +** +** In deployment, tdsqlite3FaultSim() *always* return SQLITE_OK (0). The +** tdsqlite3FaultSim() function only returns non-zero during testing. ** -** The intent of the integer argument is to let the fault simulator know -** which of multiple sqlite3FaultSim() calls has been hit. +** During testing, if the test harness has set a fault-sim callback using +** a call to tdsqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then +** each call to tdsqlite3FaultSim() is relayed to that application-supplied +** callback and the integer return value form the application-supplied +** callback is returned by tdsqlite3FaultSim(). ** -** Return whatever integer value the test callback returns, or return -** SQLITE_OK if no test callback is installed. +** The integer argument to tdsqlite3FaultSim() is a code to identify which +** tdsqlite3FaultSim() instance is being invoked. Each call to tdsqlite3FaultSim() +** should have a unique code. To prevent legacy testing applications from +** breaking, the codes should not be changed or reused. */ -#ifndef SQLITE_OMIT_BUILTIN_TEST -SQLITE_PRIVATE int sqlite3FaultSim(int iTest){ - int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback; +#ifndef SQLITE_UNTESTABLE +SQLITE_PRIVATE int tdsqlite3FaultSim(int iTest){ + int (*xCallback)(int) = tdsqlite3GlobalConfig.xTestCallback; return xCallback ? xCallback(iTest) : SQLITE_OK; } #endif @@ -31085,47 +35338,11 @@ SQLITE_PRIVATE int sqlite3FaultSim(int iTest){ #ifndef SQLITE_OMIT_FLOATING_POINT /* ** Return true if the floating point value is Not a Number (NaN). -** -** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN. -** Otherwise, we have our own implementation that works on most systems. */ -SQLITE_PRIVATE int sqlite3IsNaN(double x){ - int rc; /* The value return */ -#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN - /* - ** Systems that support the isnan() library function should probably - ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have - ** found that many systems do not have a working isnan() function so - ** this implementation is provided as an alternative. - ** - ** This NaN test sometimes fails if compiled on GCC with -ffast-math. - ** On the other hand, the use of -ffast-math comes with the following - ** warning: - ** - ** This option [-ffast-math] should never be turned on by any - ** -O option since it can result in incorrect output for programs - ** which depend on an exact implementation of IEEE or ISO - ** rules/specifications for math functions. - ** - ** Under MSVC, this NaN test may fail if compiled with a floating- - ** point precision mode other than /fp:precise. From the MSDN - ** documentation: - ** - ** The compiler [with /fp:precise] will properly handle comparisons - ** involving NaN. For example, x != x evaluates to true if x is NaN - ** ... - */ -#ifdef __FAST_MATH__ -# error SQLite will not work correctly with the -ffast-math option of GCC. -#endif - volatile double y = x; - volatile double z = y; - rc = (y!=z); -#else /* if HAVE_ISNAN */ - rc = isnan(x); -#endif /* HAVE_ISNAN */ - testcase( rc ); - return rc; +SQLITE_PRIVATE int tdsqlite3IsNaN(double x){ + u64 y; + memcpy(&y,&x,sizeof(y)); + return IsNaN(y); } #endif /* SQLITE_OMIT_FLOATING_POINT */ @@ -31137,7 +35354,7 @@ SQLITE_PRIVATE int sqlite3IsNaN(double x){ ** than the actual length of the string. For very long strings (greater ** than 1GiB) the value returned might be less than the true string length. */ -SQLITE_PRIVATE int sqlite3Strlen30(const char *z){ +SQLITE_PRIVATE int tdsqlite3Strlen30(const char *z){ if( z==0 ) return 0; return 0x3fffffff & (int)strlen(z); } @@ -31149,41 +35366,41 @@ SQLITE_PRIVATE int sqlite3Strlen30(const char *z){ ** The column type is an extra string stored after the zero-terminator on ** the column name if and only if the COLFLAG_HASTYPE flag is set. */ -SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){ +SQLITE_PRIVATE char *tdsqlite3ColumnType(Column *pCol, char *zDflt){ if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt; return pCol->zName + strlen(pCol->zName) + 1; } /* -** Helper function for sqlite3Error() - called rarely. Broken out into +** Helper function for tdsqlite3Error() - called rarely. Broken out into ** a separate routine to avoid unnecessary register saves on entry to -** sqlite3Error(). +** tdsqlite3Error(). */ -static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){ - if( db->pErr ) sqlite3ValueSetNull(db->pErr); - sqlite3SystemError(db, err_code); +static SQLITE_NOINLINE void tdsqlite3ErrorFinish(tdsqlite3 *db, int err_code){ + if( db->pErr ) tdsqlite3ValueSetNull(db->pErr); + tdsqlite3SystemError(db, err_code); } /* ** Set the current error code to err_code and clear any prior error message. -** Also set iSysErrno (by calling sqlite3System) if the err_code indicates +** Also set iSysErrno (by calling tdsqlite3System) if the err_code indicates ** that would be appropriate. */ -SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){ +SQLITE_PRIVATE void tdsqlite3Error(tdsqlite3 *db, int err_code){ assert( db!=0 ); db->errCode = err_code; - if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code); + if( err_code || db->pErr ) tdsqlite3ErrorFinish(db, err_code); } /* ** Load the sqlite3.iSysErrno field if that is an appropriate thing ** to do based on the SQLite error code in rc. */ -SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){ +SQLITE_PRIVATE void tdsqlite3SystemError(tdsqlite3 *db, int rc){ if( rc==SQLITE_IOERR_NOMEM ) return; rc &= 0xff; if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){ - db->iSysErrno = sqlite3OsGetLastError(db->pVfs); + db->iSysErrno = tdsqlite3OsGetLastError(db->pVfs); } } @@ -31204,23 +35421,23 @@ SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){ ** zFormat and any string tokens that follow it are assumed to be ** encoded in UTF-8. ** -** To clear the most recent error for sqlite handle "db", sqlite3Error +** To clear the most recent error for sqlite handle "db", tdsqlite3Error ** should be called with err_code set to SQLITE_OK and zFormat set ** to NULL. */ -SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){ +SQLITE_PRIVATE void tdsqlite3ErrorWithMsg(tdsqlite3 *db, int err_code, const char *zFormat, ...){ assert( db!=0 ); db->errCode = err_code; - sqlite3SystemError(db, err_code); + tdsqlite3SystemError(db, err_code); if( zFormat==0 ){ - sqlite3Error(db, err_code); - }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){ + tdsqlite3Error(db, err_code); + }else if( db->pErr || (db->pErr = tdsqlite3ValueNew(db))!=0 ){ char *z; va_list ap; va_start(ap, zFormat); - z = sqlite3VMPrintf(db, zFormat, ap); + z = tdsqlite3VMPrintf(db, zFormat, ap); va_end(ap); - sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC); + tdsqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC); } } @@ -31235,30 +35452,44 @@ SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *z ** %S Insert the first element of a SrcList ** ** This function should be used to report any error that occurs while -** compiling an SQL statement (i.e. within sqlite3_prepare()). The -** last thing the sqlite3_prepare() function does is copy the error -** stored by this function into the database handle using sqlite3Error(). -** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used -** during statement execution (sqlite3_step() etc.). +** compiling an SQL statement (i.e. within tdsqlite3_prepare()). The +** last thing the tdsqlite3_prepare() function does is copy the error +** stored by this function into the database handle using tdsqlite3Error(). +** Functions tdsqlite3Error() or tdsqlite3ErrorWithMsg() should be used +** during statement execution (tdsqlite3_step() etc.). */ -SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ +SQLITE_PRIVATE void tdsqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ char *zMsg; va_list ap; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; va_start(ap, zFormat); - zMsg = sqlite3VMPrintf(db, zFormat, ap); + zMsg = tdsqlite3VMPrintf(db, zFormat, ap); va_end(ap); if( db->suppressErr ){ - sqlite3DbFree(db, zMsg); + tdsqlite3DbFree(db, zMsg); }else{ pParse->nErr++; - sqlite3DbFree(db, pParse->zErrMsg); + tdsqlite3DbFree(db, pParse->zErrMsg); pParse->zErrMsg = zMsg; pParse->rc = SQLITE_ERROR; + pParse->pWith = 0; } } /* +** If database connection db is currently parsing SQL, then transfer +** error code errCode to that parser if the parser has not already +** encountered some other kind of error. +*/ +SQLITE_PRIVATE int tdsqlite3ErrorToParser(tdsqlite3 *db, int errCode){ + Parse *pParse; + if( db==0 || (pParse = db->pParse)==0 ) return errCode; + pParse->rc = errCode; + pParse->nErr++; + return errCode; +} + +/* ** Convert an SQL-style quoted string into a normal string by removing ** the quote characters. The conversion is done in-place. If the ** input does not begin with a quote character, then this routine @@ -31271,16 +35502,16 @@ SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ ** dequoted string, exclusive of the zero terminator, if dequoting does ** occur. ** -** 2002-Feb-14: This routine is extended to remove MS-Access style +** 2002-02-14: This routine is extended to remove MS-Access style ** brackets from around identifiers. For example: "[a-b-c]" becomes ** "a-b-c". */ -SQLITE_PRIVATE void sqlite3Dequote(char *z){ +SQLITE_PRIVATE void tdsqlite3Dequote(char *z){ char quote; int i, j; if( z==0 ) return; quote = z[0]; - if( !sqlite3Isquote(quote) ) return; + if( !tdsqlite3Isquote(quote) ) return; if( quote=='[' ) quote = ']'; for(i=1, j=0;; i++){ assert( z[i] ); @@ -31297,50 +35528,61 @@ SQLITE_PRIVATE void sqlite3Dequote(char *z){ } z[j] = 0; } +SQLITE_PRIVATE void tdsqlite3DequoteExpr(Expr *p){ + assert( tdsqlite3Isquote(p->u.zToken[0]) ); + p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted; + tdsqlite3Dequote(p->u.zToken); +} /* ** Generate a Token object from a string */ -SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){ +SQLITE_PRIVATE void tdsqlite3TokenInit(Token *p, char *z){ p->z = z; - p->n = sqlite3Strlen30(z); + p->n = tdsqlite3Strlen30(z); } /* Convenient short-hand */ -#define UpperToLower sqlite3UpperToLower +#define UpperToLower tdsqlite3UpperToLower /* ** Some systems have stricmp(). Others have strcasecmp(). Because ** there is no consistency, we will define our own. ** -** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and -** sqlite3_strnicmp() APIs allow applications and extensions to compare +** IMPLEMENTATION-OF: R-30243-02494 The tdsqlite3_stricmp() and +** tdsqlite3_strnicmp() APIs allow applications and extensions to compare ** the contents of two buffers containing UTF-8 strings in a ** case-independent fashion, using the same definition of "case ** independence" that SQLite uses internally when comparing identifiers. */ -SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){ +SQLITE_API int tdsqlite3_stricmp(const char *zLeft, const char *zRight){ if( zLeft==0 ){ return zRight ? -1 : 0; }else if( zRight==0 ){ return 1; } - return sqlite3StrICmp(zLeft, zRight); + return tdsqlite3StrICmp(zLeft, zRight); } -SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){ +SQLITE_PRIVATE int tdsqlite3StrICmp(const char *zLeft, const char *zRight){ unsigned char *a, *b; - int c; + int c, x; a = (unsigned char *)zLeft; b = (unsigned char *)zRight; for(;;){ - c = (int)UpperToLower[*a] - (int)UpperToLower[*b]; - if( c || *a==0 ) break; + c = *a; + x = *b; + if( c==x ){ + if( c==0 ) break; + }else{ + c = (int)UpperToLower[c] - (int)UpperToLower[x]; + if( c ) break; + } a++; b++; } return c; } -SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ +SQLITE_API int tdsqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ register unsigned char *a, *b; if( zLeft==0 ){ return zRight ? -1 : 0; @@ -31354,6 +35596,45 @@ SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ } /* +** Compute 10 to the E-th power. Examples: E==1 results in 10. +** E==2 results in 100. E==50 results in 1.0e50. +** +** This routine only works for values of E between 1 and 341. +*/ +static LONGDOUBLE_TYPE tdsqlite3Pow10(int E){ +#if defined(_MSC_VER) + static const LONGDOUBLE_TYPE x[] = { + 1.0e+001L, + 1.0e+002L, + 1.0e+004L, + 1.0e+008L, + 1.0e+016L, + 1.0e+032L, + 1.0e+064L, + 1.0e+128L, + 1.0e+256L + }; + LONGDOUBLE_TYPE r = 1.0; + int i; + assert( E>=0 && E<=307 ); + for(i=0; E!=0; i++, E >>=1){ + if( E & 1 ) r *= x[i]; + } + return r; +#else + LONGDOUBLE_TYPE x = 10.0; + LONGDOUBLE_TYPE r = 1.0; + while(1){ + if( E & 1 ) r *= x; + E >>= 1; + if( E==0 ) break; + x *= x; + } + return r; +#endif +} + +/* ** The string z[] is an text representation of a real number. ** Convert this string to a double and write it into *pResult. ** @@ -31361,8 +35642,15 @@ SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ ** uses the encoding enc. The string is not necessarily zero-terminated. ** ** Return TRUE if the result is a valid real number (or integer) and FALSE -** if the string is empty or contains extraneous text. Valid numbers -** are in one of these formats: +** if the string is empty or contains extraneous text. More specifically +** return +** 1 => The input string is a pure integer +** 2 or more => The input has a decimal point or eNNN clause +** 0 or less => The input string is not a valid number +** -1 => Not a valid number, but has a valid prefix which +** includes a decimal point and/or an eNNN clause +** +** Valid numbers are in one of these formats: ** ** [+-]digits[E[+-]digits] ** [+-]digits.[digits][E[+-]digits] @@ -31375,10 +35663,13 @@ SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ ** returns FALSE but it still converts the prefix and writes the result ** into *pResult. */ -SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ +#if defined(_MSC_VER) +#pragma warning(disable : 4756) +#endif +SQLITE_PRIVATE int tdsqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ #ifndef SQLITE_OMIT_FLOATING_POINT int incr; - const char *zEnd = z + length; + const char *zEnd; /* sign * significand * (10 ^ (esign * exponent)) */ int sign = 1; /* sign of significand */ i64 s = 0; /* significand */ @@ -31387,26 +35678,31 @@ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 en int e = 0; /* exponent */ int eValid = 1; /* True exponent is either not used or is well-formed */ double result; - int nDigits = 0; - int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ + int nDigit = 0; /* Number of digits processed */ + int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */ assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); *pResult = 0.0; /* Default return value, in case of an error */ + if( length==0 ) return 0; if( enc==SQLITE_UTF8 ){ incr = 1; + zEnd = z + length; }else{ int i; incr = 2; + length &= ~1; assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); + testcase( enc==SQLITE_UTF16LE ); + testcase( enc==SQLITE_UTF16BE ); for(i=3-enc; i<length && z[i]==0; i+=2){} - nonNum = i<length; + if( i<length ) eType = -100; zEnd = &z[i^1]; z += (enc&1); } /* skip leading spaces */ - while( z<zEnd && sqlite3Isspace(*z) ) z+=incr; + while( z<zEnd && tdsqlite3Isspace(*z) ) z+=incr; if( z>=zEnd ) return 0; /* get sign of significand */ @@ -31418,27 +35714,30 @@ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 en } /* copy max significant digits to significand */ - while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){ + while( z<zEnd && tdsqlite3Isdigit(*z) ){ s = s*10 + (*z - '0'); - z+=incr, nDigits++; + z+=incr; nDigit++; + if( s>=((LARGEST_INT64-9)/10) ){ + /* skip non-significant significand digits + ** (increase exponent by d to shift decimal left) */ + while( z<zEnd && tdsqlite3Isdigit(*z) ){ z+=incr; d++; } + } } - - /* skip non-significant significand digits - ** (increase exponent by d to shift decimal left) */ - while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++; if( z>=zEnd ) goto do_atof_calc; /* if decimal point is present */ if( *z=='.' ){ z+=incr; + eType++; /* copy digits from after decimal to significand ** (decrease exponent by d to shift decimal right) */ - while( z<zEnd && sqlite3Isdigit(*z) ){ + while( z<zEnd && tdsqlite3Isdigit(*z) ){ if( s<((LARGEST_INT64-9)/10) ){ s = s*10 + (*z - '0'); d--; + nDigit++; } - z+=incr, nDigits++; + z+=incr; } } if( z>=zEnd ) goto do_atof_calc; @@ -31447,6 +35746,7 @@ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 en if( *z=='e' || *z=='E' ){ z+=incr; eValid = 0; + eType++; /* This branch is needed to avoid a (harmless) buffer overread. The ** special comment alerts the mutation tester that the correct answer @@ -31461,7 +35761,7 @@ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 en z+=incr; } /* copy digits to exponent */ - while( z<zEnd && sqlite3Isdigit(*z) ){ + while( z<zEnd && tdsqlite3Isdigit(*z) ){ e = e<10000 ? (e*10 + (*z - '0')) : 10000; z+=incr; eValid = 1; @@ -31469,7 +35769,7 @@ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 en } /* skip trailing spaces */ - while( z<zEnd && sqlite3Isspace(*z) ) z+=incr; + while( z<zEnd && tdsqlite3Isspace(*z) ) z+=incr; do_atof_calc: /* adjust exponent by d, and update sign */ @@ -31508,11 +35808,10 @@ do_atof_calc: if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/ result = (double)s; }else{ - LONGDOUBLE_TYPE scale = 1.0; /* attempt to handle extremely small/large numbers better */ if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/ if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/ - while( e%308 ) { scale *= 1.0e+1; e -= 1; } + LONGDOUBLE_TYPE scale = tdsqlite3Pow10(e-308); if( esign<0 ){ result = s / scale; result /= 1.0e+308; @@ -31524,14 +35823,15 @@ do_atof_calc: if( esign<0 ){ result = 0.0*s; }else{ +#ifdef INFINITY + result = INFINITY*s; +#else result = 1e308*1e308*s; /* Infinity */ +#endif } } }else{ - /* 1.0e+22 is the largest power of 10 than can be - ** represented exactly. */ - while( e%22 ) { scale *= 1.0e+1; e -= 1; } - while( e>0 ) { scale *= 1.0e+22; e -= 22; } + LONGDOUBLE_TYPE scale = tdsqlite3Pow10(e); if( esign<0 ){ result = s / scale; }else{ @@ -31545,11 +35845,20 @@ do_atof_calc: *pResult = result; /* return true if number and no extra non-whitespace chracters after */ - return z==zEnd && nDigits>0 && eValid && nonNum==0; + if( z==zEnd && nDigit>0 && eValid && eType>0 ){ + return eType; + }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){ + return -1; + }else{ + return 0; + } #else - return !sqlite3Atoi64(z, pResult, length, enc); + return !tdsqlite3Atoi64(z, pResult, length, enc); #endif /* SQLITE_OMIT_FLOATING_POINT */ } +#if defined(_MSC_VER) +#pragma warning(default : 4756) +#endif /* ** Compare the 19-character string zNum against the text representation @@ -31586,28 +35895,26 @@ static int compare2pow63(const char *zNum, int incr){ ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This ** routine does *not* accept hexadecimal notation. ** -** If the zNum value is representable as a 64-bit twos-complement -** integer, then write that value into *pNum and return 0. -** -** If zNum is exactly 9223372036854775808, return 2. This special -** case is broken out because while 9223372036854775808 cannot be a -** signed 64-bit integer, its negative -9223372036854775808 can be. +** Returns: ** -** If zNum is too big for a 64-bit integer and is not -** 9223372036854775808 or if zNum contains any non-numeric text, -** then return 1. +** -1 Not even a prefix of the input text looks like an integer +** 0 Successful transformation. Fits in a 64-bit signed integer. +** 1 Excess non-space text after the integer value +** 2 Integer too large for a 64-bit signed integer or is malformed +** 3 Special case of 9223372036854775808 ** ** length is the number of bytes in the string (bytes, not characters). ** The string is not necessarily zero-terminated. The encoding is ** given by enc. */ -SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){ +SQLITE_PRIVATE int tdsqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){ int incr; u64 u = 0; int neg = 0; /* assume positive */ int i; int c = 0; int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ + int rc; /* Baseline return code */ const char *zStart; const char *zEnd = zNum + length; assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); @@ -31621,7 +35928,7 @@ SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc zEnd = &zNum[i^1]; zNum += (enc&1); } - while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr; + while( zNum<zEnd && tdsqlite3Isspace(*zNum) ) zNum+=incr; if( zNum<zEnd ){ if( *zNum=='-' ){ neg = 1; @@ -31635,43 +35942,57 @@ SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){ u = u*10 + c - '0'; } + testcase( i==18*incr ); + testcase( i==19*incr ); + testcase( i==20*incr ); if( u>LARGEST_INT64 ){ + /* This test and assignment is needed only to suppress UB warnings + ** from clang and -fsanitize=undefined. This test and assignment make + ** the code a little larger and slower, and no harm comes from omitting + ** them, but we must appaise the undefined-behavior pharisees. */ *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64; }else if( neg ){ *pNum = -(i64)u; }else{ *pNum = (i64)u; } - testcase( i==18 ); - testcase( i==19 ); - testcase( i==20 ); - if( &zNum[i]<zEnd /* Extra bytes at the end */ - || (i==0 && zStart==zNum) /* No digits */ - || i>19*incr /* Too many digits */ - || nonNum /* UTF16 with high-order bytes non-zero */ - ){ - /* zNum is empty or contains non-numeric text or is longer - ** than 19 digits (thus guaranteeing that it is too large) */ - return 1; - }else if( i<19*incr ){ + rc = 0; + if( i==0 && zStart==zNum ){ /* No digits */ + rc = -1; + }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */ + rc = 1; + }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */ + int jj = i; + do{ + if( !tdsqlite3Isspace(zNum[jj]) ){ + rc = 1; /* Extra non-space text after the integer */ + break; + } + jj += incr; + }while( &zNum[jj]<zEnd ); + } + if( i<19*incr ){ /* Less than 19 digits, so we know that it fits in 64 bits */ assert( u<=LARGEST_INT64 ); - return 0; + return rc; }else{ /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ - c = compare2pow63(zNum, incr); + c = i>19*incr ? 1 : compare2pow63(zNum, incr); if( c<0 ){ /* zNum is less than 9223372036854775808 so it fits */ assert( u<=LARGEST_INT64 ); - return 0; - }else if( c>0 ){ - /* zNum is greater than 9223372036854775808 so it overflows */ - return 1; + return rc; }else{ - /* zNum is exactly 9223372036854775808. Fits if negative. The - ** special case 2 overflow if positive */ - assert( u-1==LARGEST_INT64 ); - return neg ? 0 : 2; + *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64; + if( c>0 ){ + /* zNum is greater than 9223372036854775808 so it overflows */ + return 2; + }else{ + /* zNum is exactly 9223372036854775808. Fits if negative. The + ** special case 2 overflow if positive */ + assert( u-1==LARGEST_INT64 ); + return neg ? rc : 3; + } } } } @@ -31679,15 +36000,16 @@ SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc /* ** Transform a UTF-8 integer literal, in either decimal or hexadecimal, ** into a 64-bit signed integer. This routine accepts hexadecimal literals, -** whereas sqlite3Atoi64() does not. +** whereas tdsqlite3Atoi64() does not. ** ** Returns: ** ** 0 Successful transformation. Fits in a 64-bit signed integer. -** 1 Integer too large for a 64-bit signed integer or is malformed -** 2 Special case of 9223372036854775808 +** 1 Excess text after the integer value +** 2 Integer too large for a 64-bit signed integer or is malformed +** 3 Special case of 9223372036854775808 */ -SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){ +SQLITE_PRIVATE int tdsqlite3DecOrHexToI64(const char *z, i64 *pOut){ #ifndef SQLITE_OMIT_HEX_INTEGER if( z[0]=='0' && (z[1]=='x' || z[1]=='X') @@ -31695,15 +36017,15 @@ SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){ u64 u = 0; int i, k; for(i=2; z[i]=='0'; i++){} - for(k=i; sqlite3Isxdigit(z[k]); k++){ - u = u*16 + sqlite3HexToInt(z[k]); + for(k=i; tdsqlite3Isxdigit(z[k]); k++){ + u = u*16 + tdsqlite3HexToInt(z[k]); } memcpy(pOut, &u, 8); - return (z[k]==0 && k-i<=16) ? 0 : 1; + return (z[k]==0 && k-i<=16) ? 0 : 2; }else #endif /* SQLITE_OMIT_HEX_INTEGER */ { - return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8); + return tdsqlite3Atoi64(z, pOut, tdsqlite3Strlen30(z), SQLITE_UTF8); } } @@ -31714,10 +36036,10 @@ SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){ ** This routine accepts both decimal and hexadecimal notation for integers. ** ** Any non-numeric characters that following zNum are ignored. -** This is different from sqlite3Atoi64() which requires the +** This is different from tdsqlite3Atoi64() which requires the ** input number to be zero-terminated. */ -SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){ +SQLITE_PRIVATE int tdsqlite3GetInt32(const char *zNum, int *pValue){ sqlite_int64 v = 0; int i, c; int neg = 0; @@ -31730,15 +36052,15 @@ SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){ #ifndef SQLITE_OMIT_HEX_INTEGER else if( zNum[0]=='0' && (zNum[1]=='x' || zNum[1]=='X') - && sqlite3Isxdigit(zNum[2]) + && tdsqlite3Isxdigit(zNum[2]) ){ u32 u = 0; zNum += 2; while( zNum[0]=='0' ) zNum++; - for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){ - u = u*16 + sqlite3HexToInt(zNum[i]); + for(i=0; tdsqlite3Isxdigit(zNum[i]) && i<8; i++){ + u = u*16 + tdsqlite3HexToInt(zNum[i]); } - if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){ + if( (u&0x80000000)==0 && tdsqlite3Isxdigit(zNum[i])==0 ){ memcpy(pValue, &u, 4); return 1; }else{ @@ -31746,6 +36068,7 @@ SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){ } } #endif + if( !tdsqlite3Isdigit(zNum[0]) ) return 0; while( zNum[0]=='0' ) zNum++; for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){ v = v*10 + c; @@ -31775,9 +36098,9 @@ SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){ ** Return a 32-bit integer value extracted from a string. If the ** string is not an integer, just return 0. */ -SQLITE_PRIVATE int sqlite3Atoi(const char *z){ +SQLITE_PRIVATE int tdsqlite3Atoi(const char *z){ int x = 0; - if( z ) sqlite3GetInt32(z, &x); + if( z ) tdsqlite3GetInt32(z, &x); return x; } @@ -31834,7 +36157,7 @@ static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){ } return n; } -SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){ +SQLITE_PRIVATE int tdsqlite3PutVarint(unsigned char *p, u64 v){ if( v<=0x7f ){ p[0] = v&0x7f; return 1; @@ -31848,7 +36171,7 @@ SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){ } /* -** Bitmasks used by sqlite3GetVarint(). These precomputed constants +** Bitmasks used by tdsqlite3GetVarint(). These precomputed constants ** are defined here rather than simply putting the constant expressions ** inline in order to work around bugs in the RVT compiler. ** @@ -31864,26 +36187,15 @@ SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){ ** Read a 64-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read. The value is stored in *v. */ -SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ +SQLITE_PRIVATE u8 tdsqlite3GetVarint(const unsigned char *p, u64 *v){ u32 a,b,s; - a = *p; - /* a: p0 (unmasked) */ - if (!(a&0x80)) - { - *v = a; + if( ((signed char*)p)[0]>=0 ){ + *v = *p; return 1; } - - p++; - b = *p; - /* b: p1 (unmasked) */ - if (!(b&0x80)) - { - a &= 0x7f; - a = a<<7; - a |= b; - *v = a; + if( ((signed char*)p)[1]>=0 ){ + *v = ((u32)(p[0]&0x7f)<<7) | p[1]; return 2; } @@ -31891,8 +36203,9 @@ SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) ); assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) ); - p++; - a = a<<14; + a = ((u32)p[0])<<14; + b = p[1]; + p += 2; a |= *p; /* a: p0<<14 | p2 (unmasked) */ if (!(a&0x80)) @@ -32035,7 +36348,7 @@ SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ ** single-byte case. All code should use the MACRO version as ** this function assumes the single-byte case has already been handled. */ -SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ +SQLITE_PRIVATE u8 tdsqlite3GetVarint32(const unsigned char *p, u32 *v){ u32 a,b; /* The 1-byte case. Overwhelmingly the most common. Handled inline @@ -32094,7 +36407,7 @@ SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ u8 n; p -= 2; - n = sqlite3GetVarint(p, &v64); + n = tdsqlite3GetVarint(p, &v64); assert( n>3 && n<=9 ); if( (v64 & SQLITE_MAX_U32)!=v64 ){ *v = 0xffffffff; @@ -32139,14 +36452,14 @@ SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ /* We can only reach this point when reading a corrupt database ** file. In that case we are not in any hurry. Use the (relatively - ** slow) general-purpose sqlite3GetVarint() routine to extract the + ** slow) general-purpose tdsqlite3GetVarint() routine to extract the ** value. */ { u64 v64; u8 n; p -= 4; - n = sqlite3GetVarint(p, &v64); + n = tdsqlite3GetVarint(p, &v64); assert( n>5 && n<=9 ); *v = (u32)v64; return n; @@ -32158,7 +36471,7 @@ SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ ** Return the number of bytes that will be needed to store the given ** 64-bit integer. */ -SQLITE_PRIVATE int sqlite3VarintLen(u64 v){ +SQLITE_PRIVATE int tdsqlite3VarintLen(u64 v){ int i; for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); } return i; @@ -32168,18 +36481,16 @@ SQLITE_PRIVATE int sqlite3VarintLen(u64 v){ /* ** Read or write a four-byte big-endian integer value. */ -SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ +SQLITE_PRIVATE u32 tdsqlite3Get4byte(const u8 *p){ #if SQLITE_BYTEORDER==4321 u32 x; memcpy(&x,p,4); return x; -#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ - && defined(__GNUC__) && GCC_VERSION>=4003000 +#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 u32 x; memcpy(&x,p,4); return __builtin_bswap32(x); -#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ - && defined(_MSC_VER) && _MSC_VER>=1300 +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 u32 x; memcpy(&x,p,4); return _byteswap_ulong(x); @@ -32188,15 +36499,13 @@ SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]; #endif } -SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ +SQLITE_PRIVATE void tdsqlite3Put4byte(unsigned char *p, u32 v){ #if SQLITE_BYTEORDER==4321 memcpy(p,&v,4); -#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ - && defined(__GNUC__) && GCC_VERSION>=4003000 +#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 u32 x = __builtin_bswap32(v); memcpy(p,&x,4); -#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \ - && defined(_MSC_VER) && _MSC_VER>=1300 +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 u32 x = _byteswap_ulong(v); memcpy(p,&x,4); #else @@ -32214,7 +36523,7 @@ SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ ** This routine only works if h really is a valid hexadecimal ** character: 0..9a..fA..F */ -SQLITE_PRIVATE u8 sqlite3HexToInt(int h){ +SQLITE_PRIVATE u8 tdsqlite3HexToInt(int h){ assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); #ifdef SQLITE_ASCII h += 9*(1&(h>>6)); @@ -32232,15 +36541,15 @@ SQLITE_PRIVATE u8 sqlite3HexToInt(int h){ ** binary value has been obtained from malloc and must be freed by ** the calling routine. */ -SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){ +SQLITE_PRIVATE void *tdsqlite3HexToBlob(tdsqlite3 *db, const char *z, int n){ char *zBlob; int i; - zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1); + zBlob = (char *)tdsqlite3DbMallocRawNN(db, n/2 + 1); n--; if( zBlob ){ for(i=0; i<n; i+=2){ - zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]); + zBlob[i/2] = (tdsqlite3HexToInt(z[i])<<4) | tdsqlite3HexToInt(z[i+1]); } zBlob[i/2] = 0; } @@ -32254,7 +36563,7 @@ SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){ ** argument. The zType is a word like "NULL" or "closed" or "invalid". */ static void logBadConnection(const char *zType){ - sqlite3_log(SQLITE_MISUSE, + tdsqlite3_log(SQLITE_MISUSE, "API call with %s database connection pointer", zType ); @@ -32269,12 +36578,12 @@ static void logBadConnection(const char *zType){ ** dereferenced for any reason. The calling function should invoke ** SQLITE_MISUSE immediately. ** -** sqlite3SafetyCheckOk() requires that the db pointer be valid for -** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to +** tdsqlite3SafetyCheckOk() requires that the db pointer be valid for +** use. tdsqlite3SafetyCheckSickOrOk() allows a db pointer that failed to ** open properly and is not fit for general use but which can be -** used as an argument to sqlite3_errmsg() or sqlite3_close(). +** used as an argument to tdsqlite3_errmsg() or tdsqlite3_close(). */ -SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){ +SQLITE_PRIVATE int tdsqlite3SafetyCheckOk(tdsqlite3 *db){ u32 magic; if( db==0 ){ logBadConnection("NULL"); @@ -32282,8 +36591,8 @@ SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){ } magic = db->magic; if( magic!=SQLITE_MAGIC_OPEN ){ - if( sqlite3SafetyCheckSickOrOk(db) ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); + if( tdsqlite3SafetyCheckSickOrOk(db) ){ + testcase( tdsqlite3GlobalConfig.xLog!=0 ); logBadConnection("unopened"); } return 0; @@ -32291,13 +36600,13 @@ SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){ return 1; } } -SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ +SQLITE_PRIVATE int tdsqlite3SafetyCheckSickOrOk(tdsqlite3 *db){ u32 magic; magic = db->magic; if( magic!=SQLITE_MAGIC_SICK && magic!=SQLITE_MAGIC_OPEN && magic!=SQLITE_MAGIC_BUSY ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); + testcase( tdsqlite3GlobalConfig.xLog!=0 ); logBadConnection("invalid"); return 0; }else{ @@ -32311,7 +36620,10 @@ SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ ** Return 0 on success. Or if the operation would have resulted in an ** overflow, leave *pA unchanged and return 1. */ -SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){ +SQLITE_PRIVATE int tdsqlite3AddInt64(i64 *pA, i64 iB){ +#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER) + return __builtin_add_overflow(*pA, iB, pA); +#else i64 iA = *pA; testcase( iA==0 ); testcase( iA==1 ); testcase( iB==-1 ); testcase( iB==0 ); @@ -32326,8 +36638,12 @@ SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){ } *pA += iB; return 0; +#endif } -SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){ +SQLITE_PRIVATE int tdsqlite3SubInt64(i64 *pA, i64 iB){ +#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER) + return __builtin_sub_overflow(*pA, iB, pA); +#else testcase( iB==SMALLEST_INT64+1 ); if( iB==SMALLEST_INT64 ){ testcase( (*pA)==(-1) ); testcase( (*pA)==0 ); @@ -32335,10 +36651,14 @@ SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){ *pA -= iB; return 0; }else{ - return sqlite3AddInt64(pA, -iB); + return tdsqlite3AddInt64(pA, -iB); } +#endif } -SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){ +SQLITE_PRIVATE int tdsqlite3MulInt64(i64 *pA, i64 iB){ +#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER) + return __builtin_mul_overflow(*pA, iB, pA); +#else i64 iA = *pA; if( iB>0 ){ if( iA>LARGEST_INT64/iB ) return 1; @@ -32354,13 +36674,14 @@ SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){ } *pA = iA*iB; return 0; +#endif } /* ** Compute the absolute value of a 32-bit signed integer, of possible. Or ** if the integer has a value of -2147483648, return +2147483647 */ -SQLITE_PRIVATE int sqlite3AbsInt32(int x){ +SQLITE_PRIVATE int tdsqlite3AbsInt32(int x){ if( x>=0 ) return x; if( x==(int)0x80000000 ) return 0x7fffffff; return -x; @@ -32384,13 +36705,13 @@ SQLITE_PRIVATE int sqlite3AbsInt32(int x){ ** test.db-shm => test.shm ** test.db-mj7f3319fa => test.9fa */ -SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){ +SQLITE_PRIVATE void tdsqlite3FileSuffix3(const char *zBaseFilename, char *z){ #if SQLITE_ENABLE_8_3_NAMES<2 - if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) ) + if( tdsqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) ) #endif { int i, sz; - sz = sqlite3Strlen30(z); + sz = tdsqlite3Strlen30(z); for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4); } @@ -32403,7 +36724,7 @@ SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){ ** value. ** */ -SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){ +SQLITE_PRIVATE LogEst tdsqlite3LogEstAdd(LogEst a, LogEst b){ static const unsigned char x[] = { 10, 10, /* 0,1 */ 9, 9, /* 2,3 */ @@ -32430,15 +36751,21 @@ SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){ ** Convert an integer into a LogEst. In other words, compute an ** approximation for 10*log2(x). */ -SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){ +SQLITE_PRIVATE LogEst tdsqlite3LogEst(u64 x){ static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 }; LogEst y = 40; if( x<8 ){ if( x<2 ) return 0; while( x<8 ){ y -= 10; x <<= 1; } }else{ +#if GCC_VERSION>=5004000 + int i = 60 - __builtin_clzll(x); + y += i*10; + x >>= i; +#else while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/ while( x>15 ){ y += 10; x >>= 1; } +#endif } return a[x&7] + y - 10; } @@ -32448,12 +36775,12 @@ SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){ ** Convert a double into a LogEst ** In other words, compute an approximation for 10*log2(x). */ -SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){ +SQLITE_PRIVATE LogEst tdsqlite3LogEstFromDouble(double x){ u64 a; LogEst e; assert( sizeof(x)==8 && sizeof(a)==8 ); if( x<=1 ) return 0; - if( x<=2000000000 ) return sqlite3LogEst((u64)x); + if( x<=2000000000 ) return tdsqlite3LogEst((u64)x); memcpy(&a, &x, 8); e = (a>>52) - 1022; return e*10; @@ -32461,7 +36788,7 @@ SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){ #endif /* SQLITE_OMIT_VIRTUALTABLE */ #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ - defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \ + defined(SQLITE_ENABLE_STAT4) || \ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) /* ** Convert a LogEst into an integer. @@ -32469,7 +36796,7 @@ SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){ ** Note that this routine is only used when one or more of various ** non-standard compile-time options is enabled. */ -SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){ +SQLITE_PRIVATE u64 tdsqlite3LogEstToInt(LogEst x){ u64 n; n = x%10; x /= 10; @@ -32479,7 +36806,7 @@ SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){ defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) if( x>60 ) return (u64)LARGEST_INT64; #else - /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input + /* If only SQLITE_ENABLE_STAT4 is on, then the largest input ** possible to this routine is 310, resulting in a maximum x of 31 */ assert( x<=60 ); #endif @@ -32487,6 +36814,109 @@ SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){ } #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */ +/* +** Add a new name/number pair to a VList. This might require that the +** VList object be reallocated, so return the new VList. If an OOM +** error occurs, the original VList returned and the +** db->mallocFailed flag is set. +** +** A VList is really just an array of integers. To destroy a VList, +** simply pass it to tdsqlite3DbFree(). +** +** The first integer is the number of integers allocated for the whole +** VList. The second integer is the number of integers actually used. +** Each name/number pair is encoded by subsequent groups of 3 or more +** integers. +** +** Each name/number pair starts with two integers which are the numeric +** value for the pair and the size of the name/number pair, respectively. +** The text name overlays one or more following integers. The text name +** is always zero-terminated. +** +** Conceptually: +** +** struct VList { +** int nAlloc; // Number of allocated slots +** int nUsed; // Number of used slots +** struct VListEntry { +** int iValue; // Value for this entry +** int nSlot; // Slots used by this entry +** // ... variable name goes here +** } a[0]; +** } +** +** During code generation, pointers to the variable names within the +** VList are taken. When that happens, nAlloc is set to zero as an +** indication that the VList may never again be enlarged, since the +** accompanying realloc() would invalidate the pointers. +*/ +SQLITE_PRIVATE VList *tdsqlite3VListAdd( + tdsqlite3 *db, /* The database connection used for malloc() */ + VList *pIn, /* The input VList. Might be NULL */ + const char *zName, /* Name of symbol to add */ + int nName, /* Bytes of text in zName */ + int iVal /* Value to associate with zName */ +){ + int nInt; /* number of sizeof(int) objects needed for zName */ + char *z; /* Pointer to where zName will be stored */ + int i; /* Index in pIn[] where zName is stored */ + + nInt = nName/4 + 3; + assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */ + if( pIn==0 || pIn[1]+nInt > pIn[0] ){ + /* Enlarge the allocation */ + tdsqlite3_int64 nAlloc = (pIn ? 2*(tdsqlite3_int64)pIn[0] : 10) + nInt; + VList *pOut = tdsqlite3DbRealloc(db, pIn, nAlloc*sizeof(int)); + if( pOut==0 ) return pIn; + if( pIn==0 ) pOut[1] = 2; + pIn = pOut; + pIn[0] = nAlloc; + } + i = pIn[1]; + pIn[i] = iVal; + pIn[i+1] = nInt; + z = (char*)&pIn[i+2]; + pIn[1] = i+nInt; + assert( pIn[1]<=pIn[0] ); + memcpy(z, zName, nName); + z[nName] = 0; + return pIn; +} + +/* +** Return a pointer to the name of a variable in the given VList that +** has the value iVal. Or return a NULL if there is no such variable in +** the list +*/ +SQLITE_PRIVATE const char *tdsqlite3VListNumToName(VList *pIn, int iVal){ + int i, mx; + if( pIn==0 ) return 0; + mx = pIn[1]; + i = 2; + do{ + if( pIn[i]==iVal ) return (char*)&pIn[i+2]; + i += pIn[i+1]; + }while( i<mx ); + return 0; +} + +/* +** Return the number of the variable named zName, if it is in VList. +** or return 0 if there is no such variable. +*/ +SQLITE_PRIVATE int tdsqlite3VListNameToNum(VList *pIn, const char *zName, int nName){ + int i, mx; + if( pIn==0 ) return 0; + mx = pIn[1]; + i = 2; + do{ + const char *z = (const char*)&pIn[i+2]; + if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i]; + i += pIn[i+1]; + }while( i<mx ); + return 0; +} + /************** End of util.c ************************************************/ /************** Begin file hash.c ********************************************/ /* @@ -32511,7 +36941,7 @@ SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){ ** ** "pNew" is a pointer to the hash table that is to be initialized. */ -SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){ +SQLITE_PRIVATE void tdsqlite3HashInit(Hash *pNew){ assert( pNew!=0 ); pNew->first = 0; pNew->count = 0; @@ -32523,18 +36953,18 @@ SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){ ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ -SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){ +SQLITE_PRIVATE void tdsqlite3HashClear(Hash *pH){ HashElem *elem; /* For looping over all elements of the table */ assert( pH!=0 ); elem = pH->first; pH->first = 0; - sqlite3_free(pH->ht); + tdsqlite3_free(pH->ht); pH->ht = 0; pH->htsize = 0; while( elem ){ HashElem *next_elem = elem->next; - sqlite3_free(elem); + tdsqlite3_free(elem); elem = next_elem; } pH->count = 0; @@ -32550,7 +36980,7 @@ static unsigned int strHash(const char *z){ /* Knuth multiplicative hashing. (Sorting & Searching, p. 510). ** 0x9e3779b1 is 2654435761 which is the closest prime number to ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */ - h += sqlite3UpperToLower[c]; + h += tdsqlite3UpperToLower[c]; h *= 0x9e3779b1; } return h; @@ -32590,7 +37020,7 @@ static void insertElement( /* Resize the hash table so that it cantains "new_size" buckets. ** -** The hash table might fail to resize if sqlite3_malloc() fails or +** The hash table might fail to resize if tdsqlite3_malloc() fails or ** if the new size is the same as the prior size. ** Return TRUE if the resize occurs and false if not. */ @@ -32607,20 +37037,20 @@ static int rehash(Hash *pH, unsigned int new_size){ /* The inability to allocates space for a larger hash table is ** a performance hit but it is not a fatal error. So mark the - ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of - ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero() + ** allocation as a benign. Use tdsqlite3Malloc()/memset(0) instead of + ** tdsqlite3MallocZero() to make the allocation, as tdsqlite3MallocZero() ** only zeroes the requested number of bytes whereas this module will ** use the actual amount of space allocated for the hash table (which ** may be larger than the requested amount). */ - sqlite3BeginBenignMalloc(); - new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) ); - sqlite3EndBenignMalloc(); + tdsqlite3BeginBenignMalloc(); + new_ht = (struct _ht *)tdsqlite3Malloc( new_size*sizeof(struct _ht) ); + tdsqlite3EndBenignMalloc(); if( new_ht==0 ) return 0; - sqlite3_free(pH->ht); + tdsqlite3_free(pH->ht); pH->ht = new_ht; - pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); + pH->htsize = new_size = tdsqlite3MallocSize(new_ht)/sizeof(struct _ht); memset(new_ht, 0, new_size*sizeof(struct _ht)); for(elem=pH->first, pH->first=0; elem; elem = next_elem){ unsigned int h = strHash(elem->pKey) % new_size; @@ -32631,8 +37061,9 @@ static int rehash(Hash *pH, unsigned int new_size){ } /* This function (for internal use only) locates an element in an -** hash table that matches the given key. The hash for this key is -** also computed and returned in the *pH parameter. +** hash table that matches the given key. If no element is found, +** a pointer to a static null element with HashElem.data==0 is returned. +** If pH is not NULL, then the hash for this key is written to *pH. */ static HashElem *findElementWithHash( const Hash *pH, /* The pH to be searched */ @@ -32640,8 +37071,9 @@ static HashElem *findElementWithHash( unsigned int *pHash /* Write the hash value here */ ){ HashElem *elem; /* Used to loop thru the element list */ - int count; /* Number of elements left to test */ + unsigned int count; /* Number of elements left to test */ unsigned int h; /* The computed hash */ + static HashElem nullElement = { 0, 0, 0, 0 }; if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/ struct _ht *pEntry; @@ -32654,15 +37086,15 @@ static HashElem *findElementWithHash( elem = pH->first; count = pH->count; } - *pHash = h; + if( pHash ) *pHash = h; while( count-- ){ assert( elem!=0 ); - if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ + if( tdsqlite3StrICmp(elem->pKey,pKey)==0 ){ return elem; } elem = elem->next; } - return 0; + return &nullElement; } /* Remove a single entry from the hash table given a pointer to that @@ -32687,15 +37119,15 @@ static void removeElementGivenHash( if( pEntry->chain==elem ){ pEntry->chain = elem->next; } + assert( pEntry->count>0 ); pEntry->count--; - assert( pEntry->count>=0 ); } - sqlite3_free( elem ); + tdsqlite3_free( elem ); pH->count--; if( pH->count==0 ){ assert( pH->first==0 ); assert( pH->count==0 ); - sqlite3HashClear(pH); + tdsqlite3HashClear(pH); } } @@ -32703,14 +37135,10 @@ static void removeElementGivenHash( ** that matches pKey. Return the data for this element if it is ** found, or NULL if there is no match. */ -SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){ - HashElem *elem; /* The element that matches key */ - unsigned int h; /* A hash on key */ - +SQLITE_PRIVATE void *tdsqlite3HashFind(const Hash *pH, const char *pKey){ assert( pH!=0 ); assert( pKey!=0 ); - elem = findElementWithHash(pH, pKey, &h); - return elem ? elem->data : 0; + return findElementWithHash(pH, pKey, 0)->data; } /* Insert an element into the hash table pH. The key is pKey @@ -32727,7 +37155,7 @@ SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){ ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ -SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){ +SQLITE_PRIVATE void *tdsqlite3HashInsert(Hash *pH, const char *pKey, void *data){ unsigned int h; /* the hash of the key modulo hash table size */ HashElem *elem; /* Used to loop thru the element list */ HashElem *new_elem; /* New element added to the pH */ @@ -32735,7 +37163,7 @@ SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){ assert( pH!=0 ); assert( pKey!=0 ); elem = findElementWithHash(pH,pKey,&h); - if( elem ){ + if( elem->data ){ void *old_data = elem->data; if( data==0 ){ removeElementGivenHash(pH,elem,h); @@ -32746,7 +37174,7 @@ SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){ return old_data; } if( data==0 ) return 0; - new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) ); + new_elem = (HashElem*)tdsqlite3Malloc( sizeof(HashElem) ); if( new_elem==0 ) return data; new_elem->pKey = pKey; new_elem->data = data; @@ -32773,171 +37201,184 @@ SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){ #else # define OpHelp(X) #endif -SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ +SQLITE_PRIVATE const char *tdsqlite3OpcodeName(int i){ static const char *const azName[] = { /* 0 */ "Savepoint" OpHelp(""), /* 1 */ "AutoCommit" OpHelp(""), /* 2 */ "Transaction" OpHelp(""), /* 3 */ "SorterNext" OpHelp(""), - /* 4 */ "PrevIfOpen" OpHelp(""), - /* 5 */ "NextIfOpen" OpHelp(""), - /* 6 */ "Prev" OpHelp(""), - /* 7 */ "Next" OpHelp(""), - /* 8 */ "Checkpoint" OpHelp(""), - /* 9 */ "JournalMode" OpHelp(""), - /* 10 */ "Vacuum" OpHelp(""), - /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"), - /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"), - /* 13 */ "Goto" OpHelp(""), - /* 14 */ "Gosub" OpHelp(""), - /* 15 */ "InitCoroutine" OpHelp(""), - /* 16 */ "Yield" OpHelp(""), - /* 17 */ "MustBeInt" OpHelp(""), - /* 18 */ "Jump" OpHelp(""), + /* 4 */ "Prev" OpHelp(""), + /* 5 */ "Next" OpHelp(""), + /* 6 */ "Checkpoint" OpHelp(""), + /* 7 */ "JournalMode" OpHelp(""), + /* 8 */ "Vacuum" OpHelp(""), + /* 9 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"), + /* 10 */ "VUpdate" OpHelp("data=r[P3@P2]"), + /* 11 */ "Goto" OpHelp(""), + /* 12 */ "Gosub" OpHelp(""), + /* 13 */ "InitCoroutine" OpHelp(""), + /* 14 */ "Yield" OpHelp(""), + /* 15 */ "MustBeInt" OpHelp(""), + /* 16 */ "Jump" OpHelp(""), + /* 17 */ "Once" OpHelp(""), + /* 18 */ "If" OpHelp(""), /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"), - /* 20 */ "Once" OpHelp(""), - /* 21 */ "If" OpHelp(""), - /* 22 */ "IfNot" OpHelp(""), - /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"), - /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"), - /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"), - /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"), - /* 27 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"), - /* 28 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"), - /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"), - /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"), - /* 31 */ "Found" OpHelp("key=r[P3@P4]"), - /* 32 */ "SeekRowid" OpHelp("intkey=r[P3]"), - /* 33 */ "NotExists" OpHelp("intkey=r[P3]"), - /* 34 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"), - /* 35 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"), - /* 36 */ "Ne" OpHelp("IF r[P3]!=r[P1]"), - /* 37 */ "Eq" OpHelp("IF r[P3]==r[P1]"), - /* 38 */ "Gt" OpHelp("IF r[P3]>r[P1]"), - /* 39 */ "Le" OpHelp("IF r[P3]<=r[P1]"), - /* 40 */ "Lt" OpHelp("IF r[P3]<r[P1]"), - /* 41 */ "Ge" OpHelp("IF r[P3]>=r[P1]"), - /* 42 */ "ElseNotEq" OpHelp(""), - /* 43 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"), - /* 44 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"), - /* 45 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"), - /* 46 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"), - /* 47 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"), - /* 48 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"), - /* 49 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"), - /* 50 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"), - /* 51 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"), - /* 52 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"), - /* 53 */ "Last" OpHelp(""), - /* 54 */ "BitNot" OpHelp("r[P1]= ~r[P1]"), - /* 55 */ "SorterSort" OpHelp(""), - /* 56 */ "Sort" OpHelp(""), - /* 57 */ "Rewind" OpHelp(""), - /* 58 */ "IdxLE" OpHelp("key=r[P3@P4]"), - /* 59 */ "IdxGT" OpHelp("key=r[P3@P4]"), - /* 60 */ "IdxLT" OpHelp("key=r[P3@P4]"), - /* 61 */ "IdxGE" OpHelp("key=r[P3@P4]"), - /* 62 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"), - /* 63 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"), - /* 64 */ "Program" OpHelp(""), - /* 65 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"), - /* 66 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"), - /* 67 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"), - /* 68 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"), - /* 69 */ "IncrVacuum" OpHelp(""), - /* 70 */ "VNext" OpHelp(""), - /* 71 */ "Init" OpHelp("Start at P2"), - /* 72 */ "Return" OpHelp(""), - /* 73 */ "EndCoroutine" OpHelp(""), - /* 74 */ "HaltIfNull" OpHelp("if r[P3]=null halt"), - /* 75 */ "Halt" OpHelp(""), - /* 76 */ "Integer" OpHelp("r[P2]=P1"), - /* 77 */ "Int64" OpHelp("r[P2]=P4"), - /* 78 */ "String" OpHelp("r[P2]='P4' (len=P1)"), - /* 79 */ "Null" OpHelp("r[P2..P3]=NULL"), - /* 80 */ "SoftNull" OpHelp("r[P1]=NULL"), - /* 81 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"), - /* 82 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"), - /* 83 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"), - /* 84 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"), - /* 85 */ "SCopy" OpHelp("r[P2]=r[P1]"), - /* 86 */ "IntCopy" OpHelp("r[P2]=r[P1]"), - /* 87 */ "ResultRow" OpHelp("output=r[P1@P2]"), - /* 88 */ "CollSeq" OpHelp(""), - /* 89 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"), - /* 90 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"), - /* 91 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"), - /* 92 */ "RealAffinity" OpHelp(""), - /* 93 */ "Cast" OpHelp("affinity(r[P1])"), - /* 94 */ "Permutation" OpHelp(""), - /* 95 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), - /* 96 */ "Column" OpHelp("r[P3]=PX"), - /* 97 */ "String8" OpHelp("r[P2]='P4'"), - /* 98 */ "Affinity" OpHelp("affinity(r[P1@P2])"), - /* 99 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"), - /* 100 */ "Count" OpHelp("r[P2]=count()"), - /* 101 */ "ReadCookie" OpHelp(""), - /* 102 */ "SetCookie" OpHelp(""), - /* 103 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"), - /* 104 */ "OpenRead" OpHelp("root=P2 iDb=P3"), - /* 105 */ "OpenWrite" OpHelp("root=P2 iDb=P3"), - /* 106 */ "OpenAutoindex" OpHelp("nColumn=P2"), - /* 107 */ "OpenEphemeral" OpHelp("nColumn=P2"), - /* 108 */ "SorterOpen" OpHelp(""), - /* 109 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"), - /* 110 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"), - /* 111 */ "Close" OpHelp(""), - /* 112 */ "ColumnsUsed" OpHelp(""), - /* 113 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"), - /* 114 */ "NewRowid" OpHelp("r[P2]=rowid"), - /* 115 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"), - /* 116 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"), - /* 117 */ "Delete" OpHelp(""), - /* 118 */ "ResetCount" OpHelp(""), - /* 119 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"), - /* 120 */ "SorterData" OpHelp("r[P2]=data"), - /* 121 */ "RowKey" OpHelp("r[P2]=key"), - /* 122 */ "RowData" OpHelp("r[P2]=data"), - /* 123 */ "Rowid" OpHelp("r[P2]=rowid"), - /* 124 */ "NullRow" OpHelp(""), - /* 125 */ "SorterInsert" OpHelp(""), - /* 126 */ "IdxInsert" OpHelp("key=r[P2]"), - /* 127 */ "IdxDelete" OpHelp("key=r[P2@P3]"), - /* 128 */ "Seek" OpHelp("Move P3 to P1.rowid"), - /* 129 */ "IdxRowid" OpHelp("r[P2]=rowid"), - /* 130 */ "Destroy" OpHelp(""), - /* 131 */ "Clear" OpHelp(""), - /* 132 */ "Real" OpHelp("r[P2]=P4"), - /* 133 */ "ResetSorter" OpHelp(""), - /* 134 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"), - /* 135 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"), - /* 136 */ "ParseSchema" OpHelp(""), - /* 137 */ "LoadAnalysis" OpHelp(""), - /* 138 */ "DropTable" OpHelp(""), - /* 139 */ "DropIndex" OpHelp(""), - /* 140 */ "DropTrigger" OpHelp(""), - /* 141 */ "IntegrityCk" OpHelp(""), - /* 142 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"), - /* 143 */ "Param" OpHelp(""), - /* 144 */ "FkCounter" OpHelp("fkctr[P1]+=P2"), - /* 145 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"), - /* 146 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"), - /* 147 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"), - /* 148 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"), - /* 149 */ "AggFinal" OpHelp("accum=r[P1] N=P2"), - /* 150 */ "Expire" OpHelp(""), - /* 151 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"), - /* 152 */ "VBegin" OpHelp(""), - /* 153 */ "VCreate" OpHelp(""), - /* 154 */ "VDestroy" OpHelp(""), - /* 155 */ "VOpen" OpHelp(""), - /* 156 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"), - /* 157 */ "VRename" OpHelp(""), - /* 158 */ "Pagecount" OpHelp(""), - /* 159 */ "MaxPgcnt" OpHelp(""), - /* 160 */ "CursorHint" OpHelp(""), - /* 161 */ "Noop" OpHelp(""), - /* 162 */ "Explain" OpHelp(""), + /* 20 */ "IfNot" OpHelp(""), + /* 21 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"), + /* 22 */ "SeekLT" OpHelp("key=r[P3@P4]"), + /* 23 */ "SeekLE" OpHelp("key=r[P3@P4]"), + /* 24 */ "SeekGE" OpHelp("key=r[P3@P4]"), + /* 25 */ "SeekGT" OpHelp("key=r[P3@P4]"), + /* 26 */ "IfNotOpen" OpHelp("if( !csr[P1] ) goto P2"), + /* 27 */ "IfNoHope" OpHelp("key=r[P3@P4]"), + /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"), + /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"), + /* 30 */ "Found" OpHelp("key=r[P3@P4]"), + /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"), + /* 32 */ "NotExists" OpHelp("intkey=r[P3]"), + /* 33 */ "Last" OpHelp(""), + /* 34 */ "IfSmaller" OpHelp(""), + /* 35 */ "SorterSort" OpHelp(""), + /* 36 */ "Sort" OpHelp(""), + /* 37 */ "Rewind" OpHelp(""), + /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"), + /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"), + /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"), + /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"), + /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"), + /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"), + /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"), + /* 45 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"), + /* 46 */ "Program" OpHelp(""), + /* 47 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"), + /* 48 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"), + /* 49 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"), + /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"), + /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"), + /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"), + /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"), + /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"), + /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"), + /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"), + /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"), + /* 58 */ "ElseNotEq" OpHelp(""), + /* 59 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"), + /* 60 */ "IncrVacuum" OpHelp(""), + /* 61 */ "VNext" OpHelp(""), + /* 62 */ "Init" OpHelp("Start at P2"), + /* 63 */ "PureFunc" OpHelp("r[P3]=func(r[P2@P5])"), + /* 64 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"), + /* 65 */ "Return" OpHelp(""), + /* 66 */ "EndCoroutine" OpHelp(""), + /* 67 */ "HaltIfNull" OpHelp("if r[P3]=null halt"), + /* 68 */ "Halt" OpHelp(""), + /* 69 */ "Integer" OpHelp("r[P2]=P1"), + /* 70 */ "Int64" OpHelp("r[P2]=P4"), + /* 71 */ "String" OpHelp("r[P2]='P4' (len=P1)"), + /* 72 */ "Null" OpHelp("r[P2..P3]=NULL"), + /* 73 */ "SoftNull" OpHelp("r[P1]=NULL"), + /* 74 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"), + /* 75 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"), + /* 76 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"), + /* 77 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"), + /* 78 */ "SCopy" OpHelp("r[P2]=r[P1]"), + /* 79 */ "IntCopy" OpHelp("r[P2]=r[P1]"), + /* 80 */ "ResultRow" OpHelp("output=r[P1@P2]"), + /* 81 */ "CollSeq" OpHelp(""), + /* 82 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"), + /* 83 */ "RealAffinity" OpHelp(""), + /* 84 */ "Cast" OpHelp("affinity(r[P1])"), + /* 85 */ "Permutation" OpHelp(""), + /* 86 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), + /* 87 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"), + /* 88 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"), + /* 89 */ "Column" OpHelp("r[P3]=PX"), + /* 90 */ "Affinity" OpHelp("affinity(r[P1@P2])"), + /* 91 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"), + /* 92 */ "Count" OpHelp("r[P2]=count()"), + /* 93 */ "ReadCookie" OpHelp(""), + /* 94 */ "SetCookie" OpHelp(""), + /* 95 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"), + /* 96 */ "OpenRead" OpHelp("root=P2 iDb=P3"), + /* 97 */ "OpenWrite" OpHelp("root=P2 iDb=P3"), + /* 98 */ "OpenDup" OpHelp(""), + /* 99 */ "OpenAutoindex" OpHelp("nColumn=P2"), + /* 100 */ "OpenEphemeral" OpHelp("nColumn=P2"), + /* 101 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"), + /* 102 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"), + /* 103 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"), + /* 104 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"), + /* 105 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"), + /* 106 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"), + /* 107 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"), + /* 108 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"), + /* 109 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"), + /* 110 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"), + /* 111 */ "SorterOpen" OpHelp(""), + /* 112 */ "BitNot" OpHelp("r[P2]= ~r[P1]"), + /* 113 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"), + /* 114 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"), + /* 115 */ "String8" OpHelp("r[P2]='P4'"), + /* 116 */ "Close" OpHelp(""), + /* 117 */ "ColumnsUsed" OpHelp(""), + /* 118 */ "SeekHit" OpHelp("seekHit=P2"), + /* 119 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"), + /* 120 */ "NewRowid" OpHelp("r[P2]=rowid"), + /* 121 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"), + /* 122 */ "Delete" OpHelp(""), + /* 123 */ "ResetCount" OpHelp(""), + /* 124 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"), + /* 125 */ "SorterData" OpHelp("r[P2]=data"), + /* 126 */ "RowData" OpHelp("r[P2]=data"), + /* 127 */ "Rowid" OpHelp("r[P2]=rowid"), + /* 128 */ "NullRow" OpHelp(""), + /* 129 */ "SeekEnd" OpHelp(""), + /* 130 */ "SorterInsert" OpHelp("key=r[P2]"), + /* 131 */ "IdxInsert" OpHelp("key=r[P2]"), + /* 132 */ "IdxDelete" OpHelp("key=r[P2@P3]"), + /* 133 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"), + /* 134 */ "IdxRowid" OpHelp("r[P2]=rowid"), + /* 135 */ "FinishSeek" OpHelp(""), + /* 136 */ "Destroy" OpHelp(""), + /* 137 */ "Clear" OpHelp(""), + /* 138 */ "ResetSorter" OpHelp(""), + /* 139 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"), + /* 140 */ "SqlExec" OpHelp(""), + /* 141 */ "ParseSchema" OpHelp(""), + /* 142 */ "LoadAnalysis" OpHelp(""), + /* 143 */ "DropTable" OpHelp(""), + /* 144 */ "DropIndex" OpHelp(""), + /* 145 */ "DropTrigger" OpHelp(""), + /* 146 */ "IntegrityCk" OpHelp(""), + /* 147 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"), + /* 148 */ "Param" OpHelp(""), + /* 149 */ "FkCounter" OpHelp("fkctr[P1]+=P2"), + /* 150 */ "Real" OpHelp("r[P2]=P4"), + /* 151 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"), + /* 152 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"), + /* 153 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"), + /* 154 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"), + /* 155 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"), + /* 156 */ "AggValue" OpHelp("r[P3]=value N=P2"), + /* 157 */ "AggFinal" OpHelp("accum=r[P1] N=P2"), + /* 158 */ "Expire" OpHelp(""), + /* 159 */ "CursorLock" OpHelp(""), + /* 160 */ "CursorUnlock" OpHelp(""), + /* 161 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"), + /* 162 */ "VBegin" OpHelp(""), + /* 163 */ "VCreate" OpHelp(""), + /* 164 */ "VDestroy" OpHelp(""), + /* 165 */ "VOpen" OpHelp(""), + /* 166 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"), + /* 167 */ "VRename" OpHelp(""), + /* 168 */ "Pagecount" OpHelp(""), + /* 169 */ "MaxPgcnt" OpHelp(""), + /* 170 */ "Trace" OpHelp(""), + /* 171 */ "CursorHint" OpHelp(""), + /* 172 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"), + /* 173 */ "Noop" OpHelp(""), + /* 174 */ "Explain" OpHelp(""), + /* 175 */ "Abortable" OpHelp(""), }; return azName[i]; } @@ -32982,13 +37423,13 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ ** + for flock() locking ** + for named semaphore locks (VxWorks only) ** + for AFP filesystem locks (MacOSX only) -** * sqlite3_file methods not associated with locking. -** * Definitions of sqlite3_io_methods objects for all locking +** * tdsqlite3_file methods not associated with locking. +** * Definitions of tdsqlite3_io_methods objects for all locking ** methods plus "finder" functions for each locking method. -** * sqlite3_vfs method implementations. +** * tdsqlite3_vfs method implementations. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only) -** * Definitions of sqlite3_vfs objects for all locking methods -** plus implementations of sqlite3_os_init() and sqlite3_os_end(). +** * Definitions of tdsqlite3_vfs objects for all locking methods +** plus implementations of tdsqlite3_os_init() and tdsqlite3_os_end(). */ /* #include "sqliteInt.h" */ #if SQLITE_OS_UNIX /* This file is used on unix only */ @@ -33037,27 +37478,44 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> -#include <unistd.h> +#include <sys/ioctl.h> +/* #include <unistd.h> */ /* #include <time.h> */ #include <sys/time.h> -#include <errno.h> +/* #include <errno.h> */ #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 /* # include <sys/mman.h> */ #endif #if SQLITE_ENABLE_LOCKING_STYLE -# include <sys/ioctl.h> +/* # include <sys/ioctl.h> */ # include <sys/file.h> # include <sys/param.h> #endif /* SQLITE_ENABLE_LOCKING_STYLE */ -#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \ - (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000)) -# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \ - && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0)) -# define HAVE_GETHOSTUUID 1 -# else -# warning "gethostuuid() is disabled." +/* +** Try to determine if gethostuuid() is available based on standard +** macros. This might sometimes compute the wrong value for some +** obscure platforms. For those cases, simply compile with one of +** the following: +** +** -DHAVE_GETHOSTUUID=0 +** -DHAVE_GETHOSTUUID=1 +** +** None if this matters except when building on Apple products with +** -DSQLITE_ENABLE_LOCKING_STYLE. +*/ +#ifndef HAVE_GETHOSTUUID +# define HAVE_GETHOSTUUID 0 +# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \ + (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000)) +# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \ + && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0)) +# undef HAVE_GETHOSTUUID +# define HAVE_GETHOSTUUID 1 +# else +# warning "gethostuuid() is disabled." +# endif # endif #endif @@ -33082,12 +37540,10 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ #define SQLITE_FSFLAGS_IS_MSDOS 0x1 /* -** If we are to be thread-safe, include the pthreads header and define -** the SQLITE_UNIX_THREADS macro. +** If we are to be thread-safe, include the pthreads header. */ #if SQLITE_THREADSAFE /* # include <pthread.h> */ -# define SQLITE_UNIX_THREADS 1 #endif /* @@ -33143,40 +37599,41 @@ struct UnixUnusedFd { }; /* -** The unixFile structure is subclass of sqlite3_file specific to the unix +** The unixFile structure is subclass of tdsqlite3_file specific to the unix ** VFS implementations. */ typedef struct unixFile unixFile; struct unixFile { - sqlite3_io_methods const *pMethod; /* Always the first entry */ - sqlite3_vfs *pVfs; /* The VFS that created this unixFile */ + tdsqlite3_io_methods const *pMethod; /* Always the first entry */ + tdsqlite3_vfs *pVfs; /* The VFS that created this unixFile */ unixInodeInfo *pInode; /* Info about locks on this inode */ int h; /* The file descriptor */ unsigned char eFileLock; /* The type of lock held on this fd */ unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */ int lastErrno; /* The unix errno from last I/O error */ void *lockingContext; /* Locking style specific state */ - UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */ + UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */ const char *zPath; /* Name of the file */ unixShm *pShm; /* Shared memory segment information */ int szChunk; /* Configured by FCNTL_CHUNK_SIZE */ #if SQLITE_MAX_MMAP_SIZE>0 int nFetchOut; /* Number of outstanding xFetch refs */ - sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */ - sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */ - sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ + tdsqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */ + tdsqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */ + tdsqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ void *pMapRegion; /* Memory mapped region */ #endif -#ifdef __QNXNTO__ int sectorSize; /* Device sector size */ int deviceCharacteristics; /* Precomputed device characteristics */ -#endif #if SQLITE_ENABLE_LOCKING_STYLE int openFlags; /* The flags specified at open() */ #endif #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__) unsigned fsFlags; /* cached details from statfs() */ #endif +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + unsigned iBusyTimeout; /* Wait this many millisec on locks */ +#endif #if OS_VXWORKS struct vxworksFileId *pId; /* Unique file ID */ #endif @@ -33285,7 +37742,7 @@ static pid_t randomnessPid = 0; ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" -** counters for x86 class CPUs. +** counters for x86 and x86_64 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H @@ -33296,12 +37753,13 @@ static pid_t randomnessPid = 0; ** processor and returns that value. This can be used for high-res ** profiling. */ -#if (defined(__GNUC__) || defined(_MSC_VER)) && \ - (defined(i386) || defined(__i386__) || defined(_M_IX86)) +#if !defined(__STRICT_ANSI__) && \ + (defined(__GNUC__) || defined(_MSC_VER)) && \ + (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; @@ -33309,7 +37767,7 @@ static pid_t randomnessPid = 0; #elif defined(_MSC_VER) - __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ + __declspec(naked) __inline sqlite_uint64 __cdecl tdsqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX @@ -33318,17 +37776,17 @@ static pid_t randomnessPid = 0; #endif -#elif (defined(__GNUC__) && defined(__x86_64__)) +#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__)) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } -#elif (defined(__GNUC__) && defined(__ppc__)) +#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__)) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ @@ -33343,16 +37801,15 @@ static pid_t randomnessPid = 0; #else - #error Need implementation of sqlite3Hwtime() for your platform. - /* - ** To compile without implementing sqlite3Hwtime() for your platform, - ** you can remove the above #error and use the following - ** stub function. You will lose timing support for many - ** of the debugging and testing utilities, but it should at - ** least compile and run. + ** asm() is needed for hardware timing support. Without asm(), + ** disable the tdsqlite3Hwtime() routine. + ** + ** tdsqlite3Hwtime() is only used for some obscure debugging + ** and analysis configurations, not in any deliverable, so this + ** should not be a great loss. */ -SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } +SQLITE_PRIVATE sqlite_uint64 tdsqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif @@ -33363,8 +37820,8 @@ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; -#define TIMER_START g_start=sqlite3Hwtime() -#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start +#define TIMER_START g_start=tdsqlite3Hwtime() +#define TIMER_END g_elapsed=tdsqlite3Hwtime()-g_start #define TIMER_ELAPSED g_elapsed #else #define TIMER_START @@ -33378,32 +37835,32 @@ static sqlite_uint64 g_elapsed; ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_io_error_hit; -SQLITE_API extern int sqlite3_io_error_hardhit; -SQLITE_API extern int sqlite3_io_error_pending; -SQLITE_API extern int sqlite3_io_error_persist; -SQLITE_API extern int sqlite3_io_error_benign; -SQLITE_API extern int sqlite3_diskfull_pending; -SQLITE_API extern int sqlite3_diskfull; -#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) +SQLITE_API extern int tdsqlite3_io_error_hit; +SQLITE_API extern int tdsqlite3_io_error_hardhit; +SQLITE_API extern int tdsqlite3_io_error_pending; +SQLITE_API extern int tdsqlite3_io_error_persist; +SQLITE_API extern int tdsqlite3_io_error_benign; +SQLITE_API extern int tdsqlite3_diskfull_pending; +SQLITE_API extern int tdsqlite3_diskfull; +#define SimulateIOErrorBenign(X) tdsqlite3_io_error_benign=(X) #define SimulateIOError(CODE) \ - if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ - || sqlite3_io_error_pending-- == 1 ) \ + if( (tdsqlite3_io_error_persist && tdsqlite3_io_error_hit) \ + || tdsqlite3_io_error_pending-- == 1 ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); - sqlite3_io_error_hit++; - if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; + tdsqlite3_io_error_hit++; + if( !tdsqlite3_io_error_benign ) tdsqlite3_io_error_hardhit++; } #define SimulateDiskfullError(CODE) \ - if( sqlite3_diskfull_pending ){ \ - if( sqlite3_diskfull_pending == 1 ){ \ + if( tdsqlite3_diskfull_pending ){ \ + if( tdsqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ - sqlite3_diskfull = 1; \ - sqlite3_io_error_hit = 1; \ + tdsqlite3_diskfull = 1; \ + tdsqlite3_io_error_hit = 1; \ CODE; \ }else{ \ - sqlite3_diskfull_pending--; \ + tdsqlite3_diskfull_pending--; \ } \ } #else @@ -33416,8 +37873,8 @@ static void local_ioerr(){ ** When testing, keep a count of the number of open files. */ #if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_open_file_count; -#define OpenCounter(X) sqlite3_open_file_count+=(X) +SQLITE_API extern int tdsqlite3_open_file_count; +#define OpenCounter(X) tdsqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* defined(SQLITE_TEST) */ @@ -33473,6 +37930,20 @@ SQLITE_API extern int sqlite3_open_file_count; # define lseek lseek64 #endif +#ifdef __linux__ +/* +** Linux-specific IOCTL magic numbers used for controlling F2FS +*/ +#define F2FS_IOCTL_MAGIC 0xf5 +#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1) +#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2) +#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3) +#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5) +#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32) +#define F2FS_FEATURE_ATOMIC_WRITE 0x0004 +#endif /* __linux__ */ + + /* ** Different Unix systems declare open() in different ways. Same use ** open(const char*,int,mode_t). Others use open(const char*,int,...). @@ -33497,22 +37968,22 @@ static int unixGetpagesize(void); */ static struct unix_syscall { const char *zName; /* Name of the system call */ - sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ - sqlite3_syscall_ptr pDefault; /* Default value */ + tdsqlite3_syscall_ptr pCurrent; /* Current value of the system call */ + tdsqlite3_syscall_ptr pDefault; /* Default value */ } aSyscall[] = { - { "open", (sqlite3_syscall_ptr)posixOpen, 0 }, + { "open", (tdsqlite3_syscall_ptr)posixOpen, 0 }, #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent) - { "close", (sqlite3_syscall_ptr)close, 0 }, + { "close", (tdsqlite3_syscall_ptr)close, 0 }, #define osClose ((int(*)(int))aSyscall[1].pCurrent) - { "access", (sqlite3_syscall_ptr)access, 0 }, + { "access", (tdsqlite3_syscall_ptr)access, 0 }, #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent) - { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 }, + { "getcwd", (tdsqlite3_syscall_ptr)getcwd, 0 }, #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent) - { "stat", (sqlite3_syscall_ptr)stat, 0 }, + { "stat", (tdsqlite3_syscall_ptr)stat, 0 }, #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) /* @@ -33525,126 +37996,142 @@ static struct unix_syscall { { "fstat", 0, 0 }, #define osFstat(a,b,c) 0 #else - { "fstat", (sqlite3_syscall_ptr)fstat, 0 }, + { "fstat", (tdsqlite3_syscall_ptr)fstat, 0 }, #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent) #endif - { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 }, + { "ftruncate", (tdsqlite3_syscall_ptr)ftruncate, 0 }, #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent) - { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 }, + { "fcntl", (tdsqlite3_syscall_ptr)fcntl, 0 }, #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent) - { "read", (sqlite3_syscall_ptr)read, 0 }, + { "read", (tdsqlite3_syscall_ptr)read, 0 }, #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent) #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE - { "pread", (sqlite3_syscall_ptr)pread, 0 }, + { "pread", (tdsqlite3_syscall_ptr)pread, 0 }, #else - { "pread", (sqlite3_syscall_ptr)0, 0 }, + { "pread", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent) #if defined(USE_PREAD64) - { "pread64", (sqlite3_syscall_ptr)pread64, 0 }, + { "pread64", (tdsqlite3_syscall_ptr)pread64, 0 }, #else - { "pread64", (sqlite3_syscall_ptr)0, 0 }, + { "pread64", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent) - { "write", (sqlite3_syscall_ptr)write, 0 }, + { "write", (tdsqlite3_syscall_ptr)write, 0 }, #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent) #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE - { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 }, + { "pwrite", (tdsqlite3_syscall_ptr)pwrite, 0 }, #else - { "pwrite", (sqlite3_syscall_ptr)0, 0 }, + { "pwrite", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\ aSyscall[12].pCurrent) #if defined(USE_PREAD64) - { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 }, + { "pwrite64", (tdsqlite3_syscall_ptr)pwrite64, 0 }, #else - { "pwrite64", (sqlite3_syscall_ptr)0, 0 }, + { "pwrite64", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\ aSyscall[13].pCurrent) - { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 }, + { "fchmod", (tdsqlite3_syscall_ptr)fchmod, 0 }, #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent) #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE - { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 }, + { "fallocate", (tdsqlite3_syscall_ptr)posix_fallocate, 0 }, #else - { "fallocate", (sqlite3_syscall_ptr)0, 0 }, + { "fallocate", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent) - { "unlink", (sqlite3_syscall_ptr)unlink, 0 }, + { "unlink", (tdsqlite3_syscall_ptr)unlink, 0 }, #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent) - { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 }, + { "openDirectory", (tdsqlite3_syscall_ptr)openDirectory, 0 }, #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent) - { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 }, + { "mkdir", (tdsqlite3_syscall_ptr)mkdir, 0 }, #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent) - { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 }, + { "rmdir", (tdsqlite3_syscall_ptr)rmdir, 0 }, #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent) #if defined(HAVE_FCHOWN) - { "fchown", (sqlite3_syscall_ptr)fchown, 0 }, + { "fchown", (tdsqlite3_syscall_ptr)fchown, 0 }, #else - { "fchown", (sqlite3_syscall_ptr)0, 0 }, + { "fchown", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent) - { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 }, +#if defined(HAVE_FCHOWN) + { "geteuid", (tdsqlite3_syscall_ptr)geteuid, 0 }, +#else + { "geteuid", (tdsqlite3_syscall_ptr)0, 0 }, +#endif #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent) #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 - { "mmap", (sqlite3_syscall_ptr)mmap, 0 }, + { "mmap", (tdsqlite3_syscall_ptr)mmap, 0 }, #else - { "mmap", (sqlite3_syscall_ptr)0, 0 }, + { "mmap", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent) #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 - { "munmap", (sqlite3_syscall_ptr)munmap, 0 }, + { "munmap", (tdsqlite3_syscall_ptr)munmap, 0 }, #else - { "munmap", (sqlite3_syscall_ptr)0, 0 }, + { "munmap", (tdsqlite3_syscall_ptr)0, 0 }, #endif -#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent) +#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent) #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) - { "mremap", (sqlite3_syscall_ptr)mremap, 0 }, + { "mremap", (tdsqlite3_syscall_ptr)mremap, 0 }, #else - { "mremap", (sqlite3_syscall_ptr)0, 0 }, + { "mremap", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent) #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 - { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 }, + { "getpagesize", (tdsqlite3_syscall_ptr)unixGetpagesize, 0 }, #else - { "getpagesize", (sqlite3_syscall_ptr)0, 0 }, + { "getpagesize", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent) #if defined(HAVE_READLINK) - { "readlink", (sqlite3_syscall_ptr)readlink, 0 }, + { "readlink", (tdsqlite3_syscall_ptr)readlink, 0 }, #else - { "readlink", (sqlite3_syscall_ptr)0, 0 }, + { "readlink", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent) #if defined(HAVE_LSTAT) - { "lstat", (sqlite3_syscall_ptr)lstat, 0 }, + { "lstat", (tdsqlite3_syscall_ptr)lstat, 0 }, #else - { "lstat", (sqlite3_syscall_ptr)0, 0 }, + { "lstat", (tdsqlite3_syscall_ptr)0, 0 }, #endif #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent) +#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) +# ifdef __ANDROID__ + { "ioctl", (tdsqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 }, +#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent) +# else + { "ioctl", (tdsqlite3_syscall_ptr)ioctl, 0 }, +#define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent) +# endif +#else + { "ioctl", (tdsqlite3_syscall_ptr)0, 0 }, +#endif + }; /* End of the overrideable system calls */ @@ -33662,15 +38149,15 @@ static int robustFchown(int fd, uid_t uid, gid_t gid){ } /* -** This is the xSetSystemCall() method of sqlite3_vfs for all of the +** This is the xSetSystemCall() method of tdsqlite3_vfs for all of the ** "unix" VFSes. Return SQLITE_OK opon successfully updating the ** system call pointer, or SQLITE_NOTFOUND if there is no configurable ** system call named zName. */ static int unixSetSystemCall( - sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ + tdsqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ const char *zName, /* Name of system call to override */ - sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ + tdsqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ ){ unsigned int i; int rc = SQLITE_NOTFOUND; @@ -33710,8 +38197,8 @@ static int unixSetSystemCall( ** recognized system call name. NULL is also returned if the system call ** is currently undefined. */ -static sqlite3_syscall_ptr unixGetSystemCall( - sqlite3_vfs *pNotUsed, +static tdsqlite3_syscall_ptr unixGetSystemCall( + tdsqlite3_vfs *pNotUsed, const char *zName ){ unsigned int i; @@ -33729,7 +38216,7 @@ static sqlite3_syscall_ptr unixGetSystemCall( ** is the last system call or if zName is not the name of a valid ** system call. */ -static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){ +static const char *unixNextSystemCall(tdsqlite3_vfs *p, const char *zName){ int i = -1; UNUSED_PARAMETER(p); @@ -33785,7 +38272,7 @@ static int robust_open(const char *z, int f, mode_t m){ } if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break; osClose(fd); - sqlite3_log(SQLITE_WARNING, + tdsqlite3_log(SQLITE_WARNING, "attempt to open \"%s\" as file descriptor %d", z, fd); fd = -1; if( osOpen("/dev/null", f, m)<0 ) break; @@ -33820,16 +38307,30 @@ static int robust_open(const char *z, int f, mode_t m){ ** unixEnterMutex() ** assert( unixMutexHeld() ); ** unixEnterLeave() +** +** To prevent deadlock, the global unixBigLock must must be acquired +** before the unixInodeInfo.pLockMutex mutex, if both are held. It is +** OK to get the pLockMutex without holding unixBigLock first, but if +** that happens, the unixBigLock mutex must not be acquired until after +** pLockMutex is released. +** +** OK: enter(unixBigLock), enter(pLockInfo) +** OK: enter(unixBigLock) +** OK: enter(pLockInfo) +** ERROR: enter(pLockInfo), enter(unixBigLock) */ +static tdsqlite3_mutex *unixBigLock = 0; static void unixEnterMutex(void){ - sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); + assert( tdsqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */ + tdsqlite3_mutex_enter(unixBigLock); } static void unixLeaveMutex(void){ - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); + assert( tdsqlite3_mutex_held(unixBigLock) ); + tdsqlite3_mutex_leave(unixBigLock); } #ifdef SQLITE_DEBUG static int unixMutexHeld(void) { - return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); + return tdsqlite3_mutex_held(unixBigLock); } #endif @@ -33871,7 +38372,7 @@ static int lockTrace(int fd, int op, struct flock *p){ zOpName = "SETLK"; }else{ s = osFcntl(fd, op, p); - sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s); + tdsqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s); return s; } if( p->l_type==F_RDLCK ){ @@ -33886,7 +38387,7 @@ static int lockTrace(int fd, int op, struct flock *p){ assert( p->l_whence==SEEK_SET ); s = osFcntl(fd, op, p); savedErrno = errno; - sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n", + tdsqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n", threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len, (int)p->l_pid, s); if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){ @@ -33902,7 +38403,7 @@ static int lockTrace(int fd, int op, struct flock *p){ }else{ assert( 0 ); } - sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n", + tdsqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n", zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid); } errno = savedErrno; @@ -33919,14 +38420,14 @@ static int lockTrace(int fd, int op, struct flock *p){ ** this wrapper. On the Android platform, bypassing the logic below ** could lead to a corrupt database. */ -static int robust_ftruncate(int h, sqlite3_int64 sz){ +static int robust_ftruncate(int h, tdsqlite3_int64 sz){ int rc; #ifdef __ANDROID__ /* On Android, ftruncate() always uses 32-bit offsets, even if ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to ** truncate a file to any size larger than 2GiB. Silently ignore any ** such attempts. */ - if( sz>(sqlite3_int64)0x7FFFFFFF ){ + if( sz>(tdsqlite3_int64)0x7FFFFFFF ){ rc = SQLITE_OK; }else #endif @@ -33936,7 +38437,7 @@ static int robust_ftruncate(int h, sqlite3_int64 sz){ /* ** This routine translates a standard POSIX errno code into something -** useful to the clients of the sqlite3 functions. Specifically, it is +** useful to the clients of the tdsqlite3 functions. Specifically, it is ** intended to translate a variety of "try again" errors into SQLITE_BUSY ** and a variety of "please close the file descriptor NOW" errors into ** SQLITE_IOERR @@ -34054,7 +38555,7 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ assert( zAbsoluteName[0]=='/' ); n = (int)strlen(zAbsoluteName); - pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) ); + pNew = tdsqlite3_malloc64( sizeof(*pNew) + (n+1) ); if( pNew==0 ) return 0; pNew->zCanonicalName = (char*)&pNew[1]; memcpy(pNew->zCanonicalName, zAbsoluteName, n+1); @@ -34069,7 +38570,7 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ if( pCandidate->nName==n && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0 ){ - sqlite3_free(pNew); + tdsqlite3_free(pNew); pCandidate->nRef++; unixLeaveMutex(); return pCandidate; @@ -34098,7 +38599,7 @@ static void vxworksReleaseFileId(struct vxworksFileId *pId){ for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){} assert( *pp==pId ); *pp = pId->pNext; - sqlite3_free(pId); + tdsqlite3_free(pId); } unixLeaveMutex(); } @@ -34147,7 +38648,7 @@ static void vxworksReleaseFileId(struct vxworksFileId *pId){ ** For VxWorks, we have to use the alternative unique ID system based on ** canonical filename and implemented in the previous division.) ** -** The sqlite3_file structure for POSIX is no longer just an integer file +** The tdsqlite3_file structure for POSIX is no longer just an integer file ** descriptor. It is now a structure that holds the integer file ** descriptor and a pointer to a structure that describes the internal ** locks on the corresponding inode. There is one locking structure @@ -34206,28 +38707,52 @@ struct unixFileId { #if OS_VXWORKS struct vxworksFileId *pId; /* Unique file ID for vxworks. */ #else - ino_t ino; /* Inode number */ + /* We are told that some versions of Android contain a bug that + ** sizes ino_t at only 32-bits instead of 64-bits. (See + ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c) + ** To work around this, always allocate 64-bits for the inode number. + ** On small machines that only have 32-bit inodes, this wastes 4 bytes, + ** but that should not be a big deal. */ + /* WAS: ino_t ino; */ + u64 ino; /* Inode number */ #endif }; /* ** An instance of the following structure is allocated for each open -** inode. Or, on LinuxThreads, there is one of these structures for -** each inode opened by each thread. +** inode. ** ** A single inode can have multiple file descriptors, so each unixFile ** structure contains a pointer to an instance of this object and this ** object keeps a count of the number of unixFile pointing to it. +** +** Mutex rules: +** +** (1) Only the pLockMutex mutex must be held in order to read or write +** any of the locking fields: +** nShared, nLock, eFileLock, bProcessLock, pUnused +** +** (2) When nRef>0, then the following fields are unchanging and can +** be read (but not written) without holding any mutex: +** fileId, pLockMutex +** +** (3) With the exceptions above, all the fields may only be read +** or written while holding the global unixBigLock mutex. +** +** Deadlock prevention: The global unixBigLock mutex may not +** be acquired while holding the pLockMutex mutex. If both unixBigLock +** and pLockMutex are needed, then unixBigLock must be acquired first. */ struct unixInodeInfo { struct unixFileId fileId; /* The lookup key */ - int nShared; /* Number of SHARED locks held */ - unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ - unsigned char bProcessLock; /* An exclusive process lock is held */ + tdsqlite3_mutex *pLockMutex; /* Hold this mutex for... */ + int nShared; /* Number of SHARED locks held */ + int nLock; /* Number of outstanding file locks */ + unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ + unsigned char bProcessLock; /* An exclusive process lock is held */ + UnixUnusedFd *pUnused; /* Unused file descriptors to close */ int nRef; /* Number of pointers to this structure */ unixShmNode *pShmNode; /* Shared memory associated with this inode */ - int nLock; /* Number of outstanding file locks */ - UnixUnusedFd *pUnused; /* Unused file descriptors to close */ unixInodeInfo *pNext; /* List of all unixInodeInfo objects */ unixInodeInfo *pPrev; /* .... doubly linked */ #if SQLITE_ENABLE_LOCKING_STYLE @@ -34241,8 +38766,26 @@ struct unixInodeInfo { /* ** A lists of all unixInodeInfo objects. +** +** Must hold unixBigLock in order to read or write this variable. */ -static unixInodeInfo *inodeList = 0; +static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */ + +#ifdef SQLITE_DEBUG +/* +** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not. +** This routine is used only within assert() to help verify correct mutex +** usage. +*/ +int unixFileMutexHeld(unixFile *pFile){ + assert( pFile->pInode ); + return tdsqlite3_mutex_held(pFile->pInode->pLockMutex); +} +int unixFileMutexNotheld(unixFile *pFile){ + assert( pFile->pInode ); + return tdsqlite3_mutex_notheld(pFile->pInode->pLockMutex); +} +#endif /* ** @@ -34250,7 +38793,7 @@ static unixInodeInfo *inodeList = 0; ** unixLogError(). ** ** It is invoked after an error occurs in an OS function and errno has been -** set. It logs a message using sqlite3_log() containing the current value of +** set. It logs a message using tdsqlite3_log() containing the current value of ** errno and, if possible, the human-readable equivalent from strerror() or ** strerror_r(). ** @@ -34305,7 +38848,7 @@ static int unixLogErrorAtLine( #endif if( zPath==0 ) zPath = ""; - sqlite3_log(errcode, + tdsqlite3_log(errcode, "os_unix.c:%d: (%d) %s(%s) - %s", iLine, iErrno, zFunc, zPath, zErr ); @@ -34348,10 +38891,11 @@ static void closePendingFds(unixFile *pFile){ unixInodeInfo *pInode = pFile->pInode; UnixUnusedFd *p; UnixUnusedFd *pNext; + assert( unixFileMutexHeld(pFile) ); for(p=pInode->pUnused; p; p=pNext){ pNext = p->pNext; robust_close(pFile, p->fd, __LINE__); - sqlite3_free(p); + tdsqlite3_free(p); } pInode->pUnused = 0; } @@ -34359,17 +38903,20 @@ static void closePendingFds(unixFile *pFile){ /* ** Release a unixInodeInfo structure previously allocated by findInodeInfo(). ** -** The mutex entered using the unixEnterMutex() function must be held -** when this function is called. +** The global mutex must be held when this routine is called, but the mutex +** on the inode being deleted must NOT be held. */ static void releaseInodeInfo(unixFile *pFile){ unixInodeInfo *pInode = pFile->pInode; assert( unixMutexHeld() ); + assert( unixFileMutexNotheld(pFile) ); if( ALWAYS(pInode) ){ pInode->nRef--; if( pInode->nRef==0 ){ assert( pInode->pShmNode==0 ); + tdsqlite3_mutex_enter(pInode->pLockMutex); closePendingFds(pFile); + tdsqlite3_mutex_leave(pInode->pLockMutex); if( pInode->pPrev ){ assert( pInode->pPrev->pNext==pInode ); pInode->pPrev->pNext = pInode->pNext; @@ -34381,7 +38928,8 @@ static void releaseInodeInfo(unixFile *pFile){ assert( pInode->pNext->pPrev==pInode ); pInode->pNext->pPrev = pInode->pPrev; } - sqlite3_free(pInode); + tdsqlite3_mutex_free(pInode->pLockMutex); + tdsqlite3_free(pInode); } } } @@ -34391,8 +38939,7 @@ static void releaseInodeInfo(unixFile *pFile){ ** describes that file descriptor. Create a new one if necessary. The ** return value might be uninitialized if an error occurs. ** -** The mutex entered using the unixEnterMutex() function must be held -** when this function is called. +** The global mutex must held when calling this routine. ** ** Return an appropriate error code. */ @@ -34451,20 +38998,29 @@ static int findInodeInfo( #if OS_VXWORKS fileId.pId = pFile->pId; #else - fileId.ino = statbuf.st_ino; + fileId.ino = (u64)statbuf.st_ino; #endif + assert( unixMutexHeld() ); pInode = inodeList; while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){ pInode = pInode->pNext; } if( pInode==0 ){ - pInode = sqlite3_malloc64( sizeof(*pInode) ); + pInode = tdsqlite3_malloc64( sizeof(*pInode) ); if( pInode==0 ){ return SQLITE_NOMEM_BKPT; } memset(pInode, 0, sizeof(*pInode)); memcpy(&pInode->fileId, &fileId, sizeof(fileId)); + if( tdsqlite3GlobalConfig.bCoreMutex ){ + pInode->pLockMutex = tdsqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( pInode->pLockMutex==0 ){ + tdsqlite3_free(pInode); + return SQLITE_NOMEM_BKPT; + } + } pInode->nRef = 1; + assert( unixMutexHeld() ); pInode->pNext = inodeList; pInode->pPrev = 0; if( inodeList ) inodeList->pPrev = pInode; @@ -34485,7 +39041,8 @@ static int fileHasMoved(unixFile *pFile){ #else struct stat buf; return pFile->pInode!=0 && - (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino); + (osStat(pFile->zPath, &buf)!=0 + || (u64)buf.st_ino!=pFile->pInode->fileId.ino); #endif } @@ -34497,7 +39054,7 @@ static int fileHasMoved(unixFile *pFile){ ** (2) The file is not a symbolic link ** (3) The file has not been renamed or unlinked ** -** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right. +** Issue tdsqlite3_log(SQLITE_WARNING,...) messages if anything is not right. */ static void verifyDbFile(unixFile *pFile){ struct stat buf; @@ -34508,19 +39065,19 @@ static void verifyDbFile(unixFile *pFile){ rc = osFstat(pFile->h, &buf); if( rc!=0 ){ - sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath); + tdsqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath); return; } if( buf.st_nlink==0 ){ - sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath); + tdsqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath); return; } if( buf.st_nlink>1 ){ - sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath); + tdsqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath); return; } if( fileHasMoved(pFile) ){ - sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath); + tdsqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath); return; } } @@ -34532,7 +39089,7 @@ static void verifyDbFile(unixFile *pFile){ ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ -static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ +static int unixCheckReservedLock(tdsqlite3_file *id, int *pResOut){ int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; @@ -34541,7 +39098,7 @@ static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ assert( pFile ); assert( pFile->eFileLock<=SHARED_LOCK ); - unixEnterMutex(); /* Because pFile->pInode is shared across threads */ + tdsqlite3_mutex_enter(pFile->pInode->pLockMutex); /* Check if a thread in this process holds such a lock */ if( pFile->pInode->eFileLock>SHARED_LOCK ){ @@ -34566,7 +39123,7 @@ static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ } #endif - unixLeaveMutex(); + tdsqlite3_mutex_leave(pFile->pInode->pLockMutex); OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved)); *pResOut = reserved; @@ -34574,6 +39131,43 @@ static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ } /* +** Set a posix-advisory-lock. +** +** There are two versions of this routine. If compiled with +** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter +** which is a pointer to a unixFile. If the unixFile->iBusyTimeout +** value is set, then it is the number of milliseconds to wait before +** failing the lock. The iBusyTimeout value is always reset back to +** zero on each call. +** +** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking +** attempt to set the lock. +*/ +#ifndef SQLITE_ENABLE_SETLK_TIMEOUT +# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x) +#else +static int osSetPosixAdvisoryLock( + int h, /* The file descriptor on which to take the lock */ + struct flock *pLock, /* The description of the lock */ + unixFile *pFile /* Structure holding timeout value */ +){ + int rc = osFcntl(h,F_SETLK,pLock); + while( rc<0 && pFile->iBusyTimeout>0 ){ + /* On systems that support some kind of blocking file lock with a timeout, + ** make appropriate changes here to invoke that blocking file lock. On + ** generic posix, however, there is no such API. So we simply try the + ** lock once every millisecond until either the timeout expires, or until + ** the lock is obtained. */ + usleep(1000); + rc = osFcntl(h,F_SETLK,pLock); + pFile->iBusyTimeout--; + } + return rc; +} +#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ + + +/* ** Attempt to set a system-lock on the file pFile. The lock is ** described by pLock. ** @@ -34595,8 +39189,8 @@ static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ static int unixFileLock(unixFile *pFile, struct flock *pLock){ int rc; unixInodeInfo *pInode = pFile->pInode; - assert( unixMutexHeld() ); assert( pInode!=0 ); + assert( tdsqlite3_mutex_held(pInode->pLockMutex) ); if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){ if( pInode->bProcessLock==0 ){ struct flock lock; @@ -34605,7 +39199,7 @@ static int unixFileLock(unixFile *pFile, struct flock *pLock){ lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; lock.l_type = F_WRLCK; - rc = osFcntl(pFile->h, F_SETLK, &lock); + rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile); if( rc<0 ) return rc; pInode->bProcessLock = 1; pInode->nLock++; @@ -34613,7 +39207,7 @@ static int unixFileLock(unixFile *pFile, struct flock *pLock){ rc = 0; } }else{ - rc = osFcntl(pFile->h, F_SETLK, pLock); + rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile); } return rc; } @@ -34639,10 +39233,10 @@ static int unixFileLock(unixFile *pFile, struct flock *pLock){ ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** -** This routine will only increase a lock. Use the sqlite3OsUnlock() +** This routine will only increase a lock. Use the tdsqlite3OsUnlock() ** routine to lower a locking level. */ -static int unixLock(sqlite3_file *id, int eFileLock){ +static int unixLock(tdsqlite3_file *id, int eFileLock){ /* The following describes the implementation of the various locks and ** lock transitions in terms of the POSIX advisory shared and exclusive ** lock primitives (called read-locks and write-locks below, to avoid @@ -34715,8 +39309,8 @@ static int unixLock(sqlite3_file *id, int eFileLock){ /* This mutex is needed because pFile->pInode is shared across threads */ - unixEnterMutex(); pInode = pFile->pInode; + tdsqlite3_mutex_enter(pInode->pLockMutex); /* If some thread using this PID has a lock via a different unixFile* ** handle that precludes the requested lock, return BUSY. @@ -34859,7 +39453,7 @@ static int unixLock(sqlite3_file *id, int eFileLock){ } end_lock: - unixLeaveMutex(); + tdsqlite3_mutex_leave(pInode->pLockMutex); OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), rc==SQLITE_OK ? "ok" : "failed")); return rc; @@ -34871,11 +39465,12 @@ end_lock: */ static void setPendingFd(unixFile *pFile){ unixInodeInfo *pInode = pFile->pInode; - UnixUnusedFd *p = pFile->pUnused; + UnixUnusedFd *p = pFile->pPreallocatedUnused; + assert( unixFileMutexHeld(pFile) ); p->pNext = pInode->pUnused; pInode->pUnused = p; pFile->h = -1; - pFile->pUnused = 0; + pFile->pPreallocatedUnused = 0; } /* @@ -34891,7 +39486,7 @@ static void setPendingFd(unixFile *pFile){ ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to ** remove the write lock on a region when a read lock is set. */ -static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){ +static int posixUnlock(tdsqlite3_file *id, int eFileLock, int handleNFSUnlock){ unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode; struct flock lock; @@ -34906,8 +39501,8 @@ static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){ if( pFile->eFileLock<=eFileLock ){ return SQLITE_OK; } - unixEnterMutex(); pInode = pFile->pInode; + tdsqlite3_mutex_enter(pInode->pLockMutex); assert( pInode->nShared!=0 ); if( pFile->eFileLock>SHARED_LOCK ){ assert( pInode->eFileLock==pFile->eFileLock ); @@ -35033,14 +39628,14 @@ static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){ */ pInode->nLock--; assert( pInode->nLock>=0 ); - if( pInode->nLock==0 ){ - closePendingFds(pFile); - } + if( pInode->nLock==0 ) closePendingFds(pFile); } end_unlock: - unixLeaveMutex(); - if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock; + tdsqlite3_mutex_leave(pInode->pLockMutex); + if( rc==SQLITE_OK ){ + pFile->eFileLock = eFileLock; + } return rc; } @@ -35051,7 +39646,7 @@ end_unlock: ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ -static int unixUnlock(sqlite3_file *id, int eFileLock){ +static int unixUnlock(tdsqlite3_file *id, int eFileLock){ #if SQLITE_MAX_MMAP_SIZE>0 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 ); #endif @@ -35073,7 +39668,7 @@ static void unixUnmapfile(unixFile *pFd); ** even on VxWorks. A mutex will be acquired on VxWorks by the ** vxworksReleaseFileId() routine. */ -static int closeUnixFile(sqlite3_file *id){ +static int closeUnixFile(tdsqlite3_file *id){ unixFile *pFile = (unixFile*)id; #if SQLITE_MAX_MMAP_SIZE>0 unixUnmapfile(pFile); @@ -35094,13 +39689,13 @@ static int closeUnixFile(sqlite3_file *id){ #ifdef SQLITE_UNLINK_AFTER_CLOSE if( pFile->ctrlFlags & UNIXFILE_DELETE ){ osUnlink(pFile->zPath); - sqlite3_free(*(char**)&pFile->zPath); + tdsqlite3_free(*(char**)&pFile->zPath); pFile->zPath = 0; } #endif OSTRACE(("CLOSE %-3d\n", pFile->h)); OpenCounter(-1); - sqlite3_free(pFile->pUnused); + tdsqlite3_free(pFile->pPreallocatedUnused); memset(pFile, 0, sizeof(unixFile)); return SQLITE_OK; } @@ -35108,18 +39703,23 @@ static int closeUnixFile(sqlite3_file *id){ /* ** Close a file. */ -static int unixClose(sqlite3_file *id){ +static int unixClose(tdsqlite3_file *id){ int rc = SQLITE_OK; unixFile *pFile = (unixFile *)id; + unixInodeInfo *pInode = pFile->pInode; + + assert( pInode!=0 ); verifyDbFile(pFile); unixUnlock(id, NO_LOCK); + assert( unixFileMutexNotheld(pFile) ); unixEnterMutex(); /* unixFile.pInode is always valid here. Otherwise, a different close ** routine (e.g. nolockClose()) would be called instead. */ assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 ); - if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){ + tdsqlite3_mutex_enter(pInode->pLockMutex); + if( pInode->nLock ){ /* If there are outstanding locks, do not actually close the file just ** yet because that would clear those locks. Instead, add the file ** descriptor to pInode->pUnused list. It will be automatically closed @@ -35127,6 +39727,7 @@ static int unixClose(sqlite3_file *id){ */ setPendingFd(pFile); } + tdsqlite3_mutex_leave(pInode->pLockMutex); releaseInodeInfo(pFile); rc = closeUnixFile(id); unixLeaveMutex(); @@ -35153,16 +39754,16 @@ static int unixClose(sqlite3_file *id){ ** time and one or more of those connections are writing. */ -static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){ +static int nolockCheckReservedLock(tdsqlite3_file *NotUsed, int *pResOut){ UNUSED_PARAMETER(NotUsed); *pResOut = 0; return SQLITE_OK; } -static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){ +static int nolockLock(tdsqlite3_file *NotUsed, int NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return SQLITE_OK; } -static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){ +static int nolockUnlock(tdsqlite3_file *NotUsed, int NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return SQLITE_OK; } @@ -35170,7 +39771,7 @@ static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){ /* ** Close the file. */ -static int nolockClose(sqlite3_file *id) { +static int nolockClose(tdsqlite3_file *id) { return closeUnixFile(id); } @@ -35215,7 +39816,7 @@ static int nolockClose(sqlite3_file *id) { ** variation of CheckReservedLock(), *pResOut is set to true if any lock ** is held on the file and false if the file is unlocked. */ -static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { +static int dotlockCheckReservedLock(tdsqlite3_file *id, int *pResOut) { int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; @@ -35250,13 +39851,13 @@ static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** -** This routine will only increase a lock. Use the sqlite3OsUnlock() +** This routine will only increase a lock. Use the tdsqlite3OsUnlock() ** routine to lower a locking level. ** ** With dotfile locking, we really only support state (4): EXCLUSIVE. ** But we track the other locking levels internally. */ -static int dotlockLock(sqlite3_file *id, int eFileLock) { +static int dotlockLock(tdsqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; char *zLockFile = (char *)pFile->lockingContext; int rc = SQLITE_OK; @@ -35306,7 +39907,7 @@ static int dotlockLock(sqlite3_file *id, int eFileLock) { ** ** When the locking level reaches NO_LOCK, delete the lock file. */ -static int dotlockUnlock(sqlite3_file *id, int eFileLock) { +static int dotlockUnlock(tdsqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; char *zLockFile = (char *)pFile->lockingContext; int rc; @@ -35349,11 +39950,11 @@ static int dotlockUnlock(sqlite3_file *id, int eFileLock) { /* ** Close a file. Make sure the lock has been released before closing. */ -static int dotlockClose(sqlite3_file *id) { +static int dotlockClose(tdsqlite3_file *id) { unixFile *pFile = (unixFile*)id; assert( id!=0 ); dotlockUnlock(id, NO_LOCK); - sqlite3_free(pFile->lockingContext); + tdsqlite3_free(pFile->lockingContext); return closeUnixFile(id); } /****************** End of the dot-file lock implementation ******************* @@ -35395,7 +39996,7 @@ static int robust_flock(int fd, int op){ ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ -static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ +static int flockCheckReservedLock(tdsqlite3_file *id, int *pResOut){ int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; @@ -35437,7 +40038,7 @@ static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved)); #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS - if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ + if( (rc & 0xff) == SQLITE_IOERR ){ rc = SQLITE_OK; reserved=1; } @@ -35468,14 +40069,14 @@ static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ ** PENDING -> EXCLUSIVE ** ** flock() only really support EXCLUSIVE locks. We track intermediate -** lock states in the sqlite3_file structure, but all locks SHARED or +** lock states in the tdsqlite3_file structure, but all locks SHARED or ** above are really EXCLUSIVE locks and exclude all other processes from ** access the file. ** -** This routine will only increase a lock. Use the sqlite3OsUnlock() +** This routine will only increase a lock. Use the tdsqlite3OsUnlock() ** routine to lower a locking level. */ -static int flockLock(sqlite3_file *id, int eFileLock) { +static int flockLock(tdsqlite3_file *id, int eFileLock) { int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; @@ -35504,7 +40105,7 @@ static int flockLock(sqlite3_file *id, int eFileLock) { OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), rc==SQLITE_OK ? "ok" : "failed")); #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS - if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ + if( (rc & 0xff) == SQLITE_IOERR ){ rc = SQLITE_BUSY; } #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ @@ -35519,7 +40120,7 @@ static int flockLock(sqlite3_file *id, int eFileLock) { ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ -static int flockUnlock(sqlite3_file *id, int eFileLock) { +static int flockUnlock(tdsqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; assert( pFile ); @@ -35553,7 +40154,7 @@ static int flockUnlock(sqlite3_file *id, int eFileLock) { /* ** Close a file. */ -static int flockClose(sqlite3_file *id) { +static int flockClose(tdsqlite3_file *id) { assert( id!=0 ); flockUnlock(id, NO_LOCK); return closeUnixFile(id); @@ -35582,7 +40183,7 @@ static int flockClose(sqlite3_file *id) { ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ -static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) { +static int semXCheckReservedLock(tdsqlite3_file *id, int *pResOut) { int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; @@ -35642,14 +40243,14 @@ static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) { ** PENDING -> EXCLUSIVE ** ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate -** lock states in the sqlite3_file structure, but all locks SHARED or +** lock states in the tdsqlite3_file structure, but all locks SHARED or ** above are really EXCLUSIVE locks and exclude all other processes from ** access the file. ** -** This routine will only increase a lock. Use the sqlite3OsUnlock() +** This routine will only increase a lock. Use the tdsqlite3OsUnlock() ** routine to lower a locking level. */ -static int semXLock(sqlite3_file *id, int eFileLock) { +static int semXLock(tdsqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; sem_t *pSem = pFile->pInode->pSem; int rc = SQLITE_OK; @@ -35682,7 +40283,7 @@ static int semXLock(sqlite3_file *id, int eFileLock) { ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ -static int semXUnlock(sqlite3_file *id, int eFileLock) { +static int semXUnlock(tdsqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; sem_t *pSem = pFile->pInode->pSem; @@ -35719,11 +40320,12 @@ static int semXUnlock(sqlite3_file *id, int eFileLock) { /* ** Close a file. */ -static int semXClose(sqlite3_file *id) { +static int semXClose(tdsqlite3_file *id) { if( id ){ unixFile *pFile = (unixFile*)id; semXUnlock(id, NO_LOCK); assert( pFile ); + assert( unixFileMutexNotheld(pFile) ); unixEnterMutex(); releaseInodeInfo(pFile); unixLeaveMutex(); @@ -35824,7 +40426,7 @@ static int afpSetLock( ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ -static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ +static int afpCheckReservedLock(tdsqlite3_file *id, int *pResOut){ int rc = SQLITE_OK; int reserved = 0; unixFile *pFile = (unixFile*)id; @@ -35838,8 +40440,7 @@ static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ *pResOut = 1; return SQLITE_OK; } - unixEnterMutex(); /* Because pFile->pInode is shared across threads */ - + tdsqlite3_mutex_enter(pFile->pInode->pLockMutex); /* Check if a thread in this process holds such a lock */ if( pFile->pInode->eFileLock>SHARED_LOCK ){ reserved = 1; @@ -35863,7 +40464,7 @@ static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ } } - unixLeaveMutex(); + tdsqlite3_mutex_leave(pFile->pInode->pLockMutex); OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved)); *pResOut = reserved; @@ -35891,10 +40492,10 @@ static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** -** This routine will only increase a lock. Use the sqlite3OsUnlock() +** This routine will only increase a lock. Use the tdsqlite3OsUnlock() ** routine to lower a locking level. */ -static int afpLock(sqlite3_file *id, int eFileLock){ +static int afpLock(tdsqlite3_file *id, int eFileLock){ int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode = pFile->pInode; @@ -35926,8 +40527,8 @@ static int afpLock(sqlite3_file *id, int eFileLock){ /* This mutex is needed because pFile->pInode is shared across threads */ - unixEnterMutex(); pInode = pFile->pInode; + tdsqlite3_mutex_enter(pInode->pLockMutex); /* If some thread using this PID has a lock via a different unixFile* ** handle that precludes the requested lock, return BUSY. @@ -36041,7 +40642,7 @@ static int afpLock(sqlite3_file *id, int eFileLock){ /* Can't reestablish the shared lock. Sqlite can't deal, this is ** a critical I/O error */ - rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : + rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 : SQLITE_IOERR_LOCK; goto afp_end_lock; } @@ -36063,7 +40664,7 @@ static int afpLock(sqlite3_file *id, int eFileLock){ } afp_end_lock: - unixLeaveMutex(); + tdsqlite3_mutex_leave(pInode->pLockMutex); OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), rc==SQLITE_OK ? "ok" : "failed")); return rc; @@ -36076,7 +40677,7 @@ afp_end_lock: ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ -static int afpUnlock(sqlite3_file *id, int eFileLock) { +static int afpUnlock(tdsqlite3_file *id, int eFileLock) { int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; unixInodeInfo *pInode; @@ -36095,8 +40696,8 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) { if( pFile->eFileLock<=eFileLock ){ return SQLITE_OK; } - unixEnterMutex(); pInode = pFile->pInode; + tdsqlite3_mutex_enter(pInode->pLockMutex); assert( pInode->nShared!=0 ); if( pFile->eFileLock>SHARED_LOCK ){ assert( pInode->eFileLock==pFile->eFileLock ); @@ -36165,36 +40766,42 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) { if( rc==SQLITE_OK ){ pInode->nLock--; assert( pInode->nLock>=0 ); - if( pInode->nLock==0 ){ - closePendingFds(pFile); - } + if( pInode->nLock==0 ) closePendingFds(pFile); } } - unixLeaveMutex(); - if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock; + tdsqlite3_mutex_leave(pInode->pLockMutex); + if( rc==SQLITE_OK ){ + pFile->eFileLock = eFileLock; + } return rc; } /* ** Close a file & cleanup AFP specific locking context */ -static int afpClose(sqlite3_file *id) { +static int afpClose(tdsqlite3_file *id) { int rc = SQLITE_OK; unixFile *pFile = (unixFile*)id; assert( id!=0 ); afpUnlock(id, NO_LOCK); + assert( unixFileMutexNotheld(pFile) ); unixEnterMutex(); - if( pFile->pInode && pFile->pInode->nLock ){ - /* If there are outstanding locks, do not actually close the file just - ** yet because that would clear those locks. Instead, add the file - ** descriptor to pInode->aPending. It will be automatically closed when - ** the last lock is cleared. - */ - setPendingFd(pFile); + if( pFile->pInode ){ + unixInodeInfo *pInode = pFile->pInode; + tdsqlite3_mutex_enter(pInode->pLockMutex); + if( pInode->nLock ){ + /* If there are outstanding locks, do not actually close the file just + ** yet because that would clear those locks. Instead, add the file + ** descriptor to pInode->aPending. It will be automatically closed when + ** the last lock is cleared. + */ + setPendingFd(pFile); + } + tdsqlite3_mutex_leave(pInode->pLockMutex); } releaseInodeInfo(pFile); - sqlite3_free(pFile->lockingContext); + tdsqlite3_free(pFile->lockingContext); rc = closeUnixFile(id); unixLeaveMutex(); return rc; @@ -36221,7 +40828,7 @@ static int afpClose(sqlite3_file *id) { ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ -static int nfsUnlock(sqlite3_file *id, int eFileLock){ +static int nfsUnlock(tdsqlite3_file *id, int eFileLock){ return posixUnlock(id, eFileLock, 1); } @@ -36235,10 +40842,10 @@ static int nfsUnlock(sqlite3_file *id, int eFileLock){ ******************************************************************************/ /****************************************************************************** -**************** Non-locking sqlite3_file methods ***************************** +**************** Non-locking tdsqlite3_file methods ***************************** ** ** The next division contains implementations for all methods of the -** sqlite3_file object other than the locking methods. The locking +** tdsqlite3_file object other than the locking methods. The locking ** methods were defined in divisions above (one locking method per ** division). Those methods that are common to all locking modes ** are gather together into this division. @@ -36257,7 +40864,7 @@ static int nfsUnlock(sqlite3_file *id, int eFileLock){ ** To avoid stomping the errno value on a failed read the lastErrno value ** is set before returning. */ -static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ +static int seekAndRead(unixFile *id, tdsqlite3_int64 offset, void *pBuf, int cnt){ int got; int prior = 0; #if (!defined(USE_PREAD) && !defined(USE_PREAD64)) @@ -36307,10 +40914,10 @@ static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ ** wrong. */ static int unixRead( - sqlite3_file *id, + tdsqlite3_file *id, void *pBuf, int amt, - sqlite3_int64 offset + tdsqlite3_int64 offset ){ unixFile *pFile = (unixFile *)id; int got; @@ -36321,7 +40928,7 @@ static int unixRead( /* If this is a database file (not a journal, master-journal or temp ** file), the bytes in the locking range should never be read or written. */ #if 0 - assert( pFile->pUnused==0 + assert( pFile->pPreallocatedUnused==0 || offset>=PENDING_BYTE+512 || offset+amt<=PENDING_BYTE ); @@ -36421,10 +41028,10 @@ static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ ** or some other error code on failure. */ static int unixWrite( - sqlite3_file *id, + tdsqlite3_file *id, const void *pBuf, int amt, - sqlite3_int64 offset + tdsqlite3_int64 offset ){ unixFile *pFile = (unixFile*)id; int wrote = 0; @@ -36434,7 +41041,7 @@ static int unixWrite( /* If this is a database file (not a journal, master-journal or temp ** file), the bytes in the locking range should never be read or written. */ #if 0 - assert( pFile->pUnused==0 + assert( pFile->pPreallocatedUnused==0 || offset>=PENDING_BYTE+512 || offset+amt<=PENDING_BYTE ); @@ -36505,8 +41112,8 @@ static int unixWrite( ** Count the number of fullsyncs and normal syncs. This is used to test ** that syncs and fullsyncs are occurring at the right times. */ -SQLITE_API int sqlite3_sync_count = 0; -SQLITE_API int sqlite3_fullsync_count = 0; +SQLITE_API int tdsqlite3_sync_count = 0; +SQLITE_API int tdsqlite3_fullsync_count = 0; #endif /* @@ -36578,8 +41185,8 @@ static int full_fsync(int fd, int fullSync, int dataOnly){ ** gets called with the correct arguments. */ #ifdef SQLITE_TEST - if( fullSync ) sqlite3_fullsync_count++; - sqlite3_sync_count++; + if( fullSync ) tdsqlite3_fullsync_count++; + tdsqlite3_sync_count++; #endif /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a @@ -36656,7 +41263,7 @@ static int openDirectory(const char *zFilename, int *pFd){ int fd = -1; char zDirname[MAX_PATHNAME+1]; - sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); + tdsqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--); if( ii>0 ){ zDirname[ii] = '\0'; @@ -36664,7 +41271,7 @@ static int openDirectory(const char *zFilename, int *pFd){ if( zDirname[0]!='/' ) zDirname[0] = '.'; zDirname[1] = 0; } - fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0); + fd = robust_open(zDirname, O_RDONLY|O_BINARY|O_NOFOLLOW, 0); if( fd>=0 ){ OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); } @@ -36688,7 +41295,7 @@ static int openDirectory(const char *zFilename, int *pFd){ ** the directory entry for the journal was never created) and the transaction ** will not roll back - possibly leading to database corruption. */ -static int unixSync(sqlite3_file *id, int flags){ +static int unixSync(tdsqlite3_file *id, int flags){ int rc; unixFile *pFile = (unixFile*)id; @@ -36738,7 +41345,7 @@ static int unixSync(sqlite3_file *id, int flags){ /* ** Truncate an open file to a specified size */ -static int unixTruncate(sqlite3_file *id, i64 nByte){ +static int unixTruncate(tdsqlite3_file *id, i64 nByte){ unixFile *pFile = (unixFile *)id; int rc; assert( pFile ); @@ -36788,7 +41395,7 @@ static int unixTruncate(sqlite3_file *id, i64 nByte){ /* ** Determine the current size of a file in bytes */ -static int unixFileSize(sqlite3_file *id, i64 *pSize){ +static int unixFileSize(tdsqlite3_file *id, i64 *pSize){ int rc; struct stat buf; assert( id ); @@ -36817,7 +41424,7 @@ static int unixFileSize(sqlite3_file *id, i64 *pSize){ ** Handler for proxy-locking file-control verbs. Defined below in the ** proxying locking division. */ -static int proxyFileControl(sqlite3_file*,int,void*); +static int proxyFileControl(tdsqlite3_file*,int,void*); #endif /* @@ -36846,7 +41453,7 @@ static int fcntlSizeHint(unixFile *pFile, i64 nByte){ do{ err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size); }while( err==EINTR ); - if( err ) return SQLITE_IOERR_WRITE; + if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE; #else /* If the OS does not have posix_fallocate(), fake it. Write a ** single byte to the last byte in each block that falls entirely @@ -36911,9 +41518,24 @@ static int unixGetTempname(int nBuf, char *zBuf); /* ** Information and control of an open file handle. */ -static int unixFileControl(sqlite3_file *id, int op, void *pArg){ +static int unixFileControl(tdsqlite3_file *id, int op, void *pArg){ unixFile *pFile = (unixFile*)id; switch( op ){ +#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) + case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: { + int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE); + return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK; + } + case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: { + int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE); + return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK; + } + case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: { + int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE); + return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK; + } +#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ + case SQLITE_FCNTL_LOCKSTATE: { *(int*)pArg = pFile->eFileLock; return SQLITE_OK; @@ -36942,11 +41564,11 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){ return SQLITE_OK; } case SQLITE_FCNTL_VFSNAME: { - *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); + *(char**)pArg = tdsqlite3_mprintf("%s", pFile->pVfs->zName); return SQLITE_OK; } case SQLITE_FCNTL_TEMPFILENAME: { - char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname ); + char *zTFile = tdsqlite3_malloc64( pFile->pVfs->mxPathname ); if( zTFile ){ unixGetTempname(pFile->pVfs->mxPathname, zTFile); *(char**)pArg = zTFile; @@ -36957,13 +41579,27 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){ *(int*)pArg = fileHasMoved(pFile); return SQLITE_OK; } +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + case SQLITE_FCNTL_LOCK_TIMEOUT: { + pFile->iBusyTimeout = *(int*)pArg; + return SQLITE_OK; + } +#endif #if SQLITE_MAX_MMAP_SIZE>0 case SQLITE_FCNTL_MMAP_SIZE: { i64 newLimit = *(i64*)pArg; int rc = SQLITE_OK; - if( newLimit>sqlite3GlobalConfig.mxMmap ){ - newLimit = sqlite3GlobalConfig.mxMmap; + if( newLimit>tdsqlite3GlobalConfig.mxMmap ){ + newLimit = tdsqlite3GlobalConfig.mxMmap; + } + + /* The value of newLimit may be eventually cast to (size_t) and passed + ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a + ** 64-bit type. */ + if( newLimit>0 && sizeof(size_t)<8 ){ + newLimit = (newLimit & 0x7FFFFFFF); } + *(i64*)pArg = pFile->mmapSizeMax; if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ pFile->mmapSizeMax = newLimit; @@ -36997,30 +41633,41 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){ } /* -** Return the sector size in bytes of the underlying block device for -** the specified file. This is almost always 512 bytes, but may be -** larger for some devices. +** If pFd->sectorSize is non-zero when this function is called, it is a +** no-op. Otherwise, the values of pFd->sectorSize and +** pFd->deviceCharacteristics are set according to the file-system +** characteristics. ** -** SQLite code assumes this function cannot fail. It also assumes that -** if two files are created in the same file-system directory (i.e. -** a database and its journal file) that the sector size will be the -** same for both. +** There are two versions of this function. One for QNX and one for all +** other systems. */ -#ifndef __QNXNTO__ -static int unixSectorSize(sqlite3_file *NotUsed){ - UNUSED_PARAMETER(NotUsed); - return SQLITE_DEFAULT_SECTOR_SIZE; -} -#endif +#ifndef __QNXNTO__ +static void setDeviceCharacteristics(unixFile *pFd){ + assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 ); + if( pFd->sectorSize==0 ){ +#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) + int res; + u32 f = 0; -/* -** The following version of unixSectorSize() is optimized for QNX. -*/ -#ifdef __QNXNTO__ + /* Check for support for F2FS atomic batch writes. */ + res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f); + if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){ + pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC; + } +#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ + + /* Set the POWERSAFE_OVERWRITE flag if requested. */ + if( pFd->ctrlFlags & UNIXFILE_PSOW ){ + pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; + } + + pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; + } +} +#else #include <sys/dcmd_blk.h> #include <sys/statvfs.h> -static int unixSectorSize(sqlite3_file *id){ - unixFile *pFile = (unixFile*)id; +static void setDeviceCharacteristics(unixFile *pFile){ if( pFile->sectorSize == 0 ){ struct statvfs fsInfo; @@ -37028,7 +41675,7 @@ static int unixSectorSize(sqlite3_file *id){ pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; pFile->deviceCharacteristics = 0; if( fstatvfs(pFile->h, &fsInfo) == -1 ) { - return pFile->sectorSize; + return; } if( !strcmp(fsInfo.f_basetype, "tmp") ) { @@ -37089,9 +41736,24 @@ static int unixSectorSize(sqlite3_file *id){ pFile->deviceCharacteristics = 0; pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; } - return pFile->sectorSize; } -#endif /* __QNXNTO__ */ +#endif + +/* +** Return the sector size in bytes of the underlying block device for +** the specified file. This is almost always 512 bytes, but may be +** larger for some devices. +** +** SQLite code assumes this function cannot fail. It also assumes that +** if two files are created in the same file-system directory (i.e. +** a database and its journal file) that the sector size will be the +** same for both. +*/ +static int unixSectorSize(tdsqlite3_file *id){ + unixFile *pFd = (unixFile*)id; + setDeviceCharacteristics(pFd); + return pFd->sectorSize; +} /* ** Return the device characteristics for the file. @@ -37106,17 +41768,10 @@ static int unixSectorSize(sqlite3_file *id){ ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control ** available to turn it off and URI query parameter available to turn it off. */ -static int unixDeviceCharacteristics(sqlite3_file *id){ - unixFile *p = (unixFile*)id; - int rc = 0; -#ifdef __QNXNTO__ - if( p->sectorSize==0 ) unixSectorSize(id); - rc = p->deviceCharacteristics; -#endif - if( p->ctrlFlags & UNIXFILE_PSOW ){ - rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; - } - return rc; +static int unixDeviceCharacteristics(tdsqlite3_file *id){ + unixFile *pFd = (unixFile*)id; + setDeviceCharacteristics(pFd); + return pFd->deviceCharacteristics; } #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 @@ -37163,21 +41818,22 @@ static int unixGetpagesize(void){ ** ** The following fields are read-only after the object is created: ** -** fid +** hShm ** zFilename ** -** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and +** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and ** unixMutexHeld() is true when reading or writing any other field ** in this structure. */ struct unixShmNode { unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */ - sqlite3_mutex *mutex; /* Mutex to access this object */ + tdsqlite3_mutex *pShmMutex; /* Mutex to access this object */ char *zFilename; /* Name of the mmapped file */ - int h; /* Open file descriptor */ + int hShm; /* Open file descriptor */ int szRegion; /* Size of shared-memory regions */ u16 nRegion; /* Size of array apRegion */ u8 isReadonly; /* True if read-only */ + u8 isUnlocked; /* True if no DMS lock held */ char **apRegion; /* Array of mapped shared-memory regions */ int nRef; /* Number of unixShm objects pointing to this */ unixShm *pFirst; /* All unixShm objects pointing to this */ @@ -37195,16 +41851,16 @@ struct unixShmNode { ** The following fields are initialized when this object is created and ** are read-only thereafter: ** -** unixShm.pFile +** unixShm.pShmNode ** unixShm.id ** -** All other fields are read/write. The unixShm.pFile->mutex must be held -** while accessing any read/write fields. +** All other fields are read/write. The unixShm.pShmNode->pShmMutex must +** be held while accessing any read/write fields. */ struct unixShm { unixShmNode *pShmNode; /* The underlying unixShmNode object */ unixShm *pNext; /* Next unixShm with the same unixShmNode */ - u8 hasMutex; /* True if holding the unixShmNode mutex */ + u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */ u8 id; /* Id of this connection within its unixShmNode */ u16 sharedMask; /* Mask of shared locks held */ u16 exclMask; /* Mask of exclusive locks held */ @@ -37234,7 +41890,8 @@ static int unixShmSystemLock( /* Access to the unixShmNode object is serialized by the caller */ pShmNode = pFile->pInode->pShmNode; - assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 ); + assert( pShmNode->nRef==0 || tdsqlite3_mutex_held(pShmNode->pShmMutex) ); + assert( pShmNode->nRef>0 || unixMutexHeld() ); /* Shared locks never span more than one byte */ assert( n==1 || lockType!=F_RDLCK ); @@ -37242,15 +41899,13 @@ static int unixShmSystemLock( /* Locks are within range */ assert( n>=1 && n<=SQLITE_SHM_NLOCK ); - if( pShmNode->h>=0 ){ + if( pShmNode->hShm>=0 ){ /* Initialize the locking parameters */ - memset(&f, 0, sizeof(f)); f.l_type = lockType; f.l_whence = SEEK_SET; f.l_start = ofst; f.l_len = n; - - rc = osFcntl(pShmNode->h, F_SETLK, &f); + rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile); rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY; } @@ -37322,22 +41977,90 @@ static void unixShmPurge(unixFile *pFd){ int nShmPerMap = unixShmRegionPerMap(); int i; assert( p->pInode==pFd->pInode ); - sqlite3_mutex_free(p->mutex); + tdsqlite3_mutex_free(p->pShmMutex); for(i=0; i<p->nRegion; i+=nShmPerMap){ - if( p->h>=0 ){ + if( p->hShm>=0 ){ osMunmap(p->apRegion[i], p->szRegion); }else{ - sqlite3_free(p->apRegion[i]); + tdsqlite3_free(p->apRegion[i]); } } - sqlite3_free(p->apRegion); - if( p->h>=0 ){ - robust_close(pFd, p->h, __LINE__); - p->h = -1; + tdsqlite3_free(p->apRegion); + if( p->hShm>=0 ){ + robust_close(pFd, p->hShm, __LINE__); + p->hShm = -1; } p->pInode->pShmNode = 0; - sqlite3_free(p); + tdsqlite3_free(p); + } +} + +/* +** The DMS lock has not yet been taken on shm file pShmNode. Attempt to +** take it now. Return SQLITE_OK if successful, or an SQLite error +** code otherwise. +** +** If the DMS cannot be locked because this is a readonly_shm=1 +** connection and no other process already holds a lock, return +** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1. +*/ +static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){ + struct flock lock; + int rc = SQLITE_OK; + + /* Use F_GETLK to determine the locks other processes are holding + ** on the DMS byte. If it indicates that another process is holding + ** a SHARED lock, then this process may also take a SHARED lock + ** and proceed with opening the *-shm file. + ** + ** Or, if no other process is holding any lock, then this process + ** is the first to open it. In this case take an EXCLUSIVE lock on the + ** DMS byte and truncate the *-shm file to zero bytes in size. Then + ** downgrade to a SHARED lock on the DMS byte. + ** + ** If another process is holding an EXCLUSIVE lock on the DMS byte, + ** return SQLITE_BUSY to the caller (it will try again). An earlier + ** version of this code attempted the SHARED lock at this point. But + ** this introduced a subtle race condition: if the process holding + ** EXCLUSIVE failed just before truncating the *-shm file, then this + ** process might open and use the *-shm file without truncating it. + ** And if the *-shm file has been corrupted by a power failure or + ** system crash, the database itself may also become corrupt. */ + lock.l_whence = SEEK_SET; + lock.l_start = UNIX_SHM_DMS; + lock.l_len = 1; + lock.l_type = F_WRLCK; + if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) { + rc = SQLITE_IOERR_LOCK; + }else if( lock.l_type==F_UNLCK ){ + if( pShmNode->isReadonly ){ + pShmNode->isUnlocked = 1; + rc = SQLITE_READONLY_CANTINIT; + }else{ + rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1); + /* The first connection to attach must truncate the -shm file. We + ** truncate to 3 bytes (an arbitrary small number, less than the + ** -shm header size) rather than 0 as a system debugging aid, to + ** help detect if a -shm file truncation is legitimate or is the work + ** or a rogue process. */ +#ifdef __ANDROID__ + /* Fix SQLite DB corruption on some Samsung devices */ + if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 0) ){ +#else + if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){ +#endif + rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename); + } + } + }else if( lock.l_type==F_WRLCK ){ + rc = SQLITE_BUSY; + } + + if( rc==SQLITE_OK ){ + assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK ); + rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1); } + return rc; } /* @@ -37378,13 +42101,13 @@ static void unixShmPurge(unixFile *pFd){ static int unixOpenSharedMemory(unixFile *pDbFd){ struct unixShm *p = 0; /* The connection to be opened */ struct unixShmNode *pShmNode; /* The underlying mmapped file */ - int rc; /* Result code */ + int rc = SQLITE_OK; /* Result code */ unixInodeInfo *pInode; /* The inode of fd */ - char *zShmFilename; /* Name of the file used for SHM */ + char *zShm; /* Name of the file used for SHM */ int nShmFilename; /* Size of the SHM filename in bytes */ /* Allocate space for the new unixShm object. */ - p = sqlite3_malloc64( sizeof(*p) ); + p = tdsqlite3_malloc64( sizeof(*p) ); if( p==0 ) return SQLITE_NOMEM_BKPT; memset(p, 0, sizeof(*p)); assert( pDbFd->pShm==0 ); @@ -37392,6 +42115,7 @@ static int unixOpenSharedMemory(unixFile *pDbFd){ /* Check to see if a unixShmNode object already exists. Reuse an existing ** one if present. Create a new one if necessary. */ + assert( unixFileMutexNotheld(pDbFd) ); unixEnterMutex(); pInode = pDbFd->pInode; pShmNode = pInode->pShmNode; @@ -37415,63 +42139,55 @@ static int unixOpenSharedMemory(unixFile *pDbFd){ #else nShmFilename = 6 + (int)strlen(zBasePath); #endif - pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename ); + pShmNode = tdsqlite3_malloc64( sizeof(*pShmNode) + nShmFilename ); if( pShmNode==0 ){ rc = SQLITE_NOMEM_BKPT; goto shm_open_err; } memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename); - zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1]; + zShm = pShmNode->zFilename = (char*)&pShmNode[1]; #ifdef SQLITE_SHM_DIRECTORY - sqlite3_snprintf(nShmFilename, zShmFilename, + tdsqlite3_snprintf(nShmFilename, zShm, SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x", (u32)sStat.st_ino, (u32)sStat.st_dev); #else - sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath); - sqlite3FileSuffix3(pDbFd->zPath, zShmFilename); + tdsqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath); + tdsqlite3FileSuffix3(pDbFd->zPath, zShm); #endif - pShmNode->h = -1; + pShmNode->hShm = -1; pDbFd->pInode->pShmNode = pShmNode; pShmNode->pInode = pDbFd->pInode; - if( sqlite3GlobalConfig.bCoreMutex ){ - pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); - if( pShmNode->mutex==0 ){ + if( tdsqlite3GlobalConfig.bCoreMutex ){ + pShmNode->pShmMutex = tdsqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( pShmNode->pShmMutex==0 ){ rc = SQLITE_NOMEM_BKPT; goto shm_open_err; } } if( pInode->bProcessLock==0 ){ - int openFlags = O_RDWR | O_CREAT; - if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ - openFlags = O_RDONLY; - pShmNode->isReadonly = 1; + if( 0==tdsqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ + pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW, + (sStat.st_mode&0777)); } - pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777)); - if( pShmNode->h<0 ){ - rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename); - goto shm_open_err; + if( pShmNode->hShm<0 ){ + pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW, + (sStat.st_mode&0777)); + if( pShmNode->hShm<0 ){ + rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm); + goto shm_open_err; + } + pShmNode->isReadonly = 1; } /* If this process is running as root, make sure that the SHM file ** is owned by the same user that owns the original database. Otherwise, ** the original owner will not be able to connect. */ - robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid); - - /* Check to see if another process is holding the dead-man switch. - ** If not, truncate the file to zero length. - */ - rc = SQLITE_OK; - if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){ - if( robust_ftruncate(pShmNode->h, 0) ){ - rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename); - } - } - if( rc==SQLITE_OK ){ - rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1); - } - if( rc ) goto shm_open_err; + robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid); + + rc = unixLockSharedMemory(pDbFd, pShmNode); + if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err; } } @@ -37488,19 +42204,19 @@ static int unixOpenSharedMemory(unixFile *pDbFd){ ** the cover of the unixEnterMutex() mutex and the pointer from the ** new (struct unixShm) object to the pShmNode has been set. All that is ** left to do is to link the new object into the linked list starting - ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex - ** mutex. + ** at pShmNode->pFirst. This must be done while holding the + ** pShmNode->pShmMutex. */ - sqlite3_mutex_enter(pShmNode->mutex); + tdsqlite3_mutex_enter(pShmNode->pShmMutex); p->pNext = pShmNode->pFirst; pShmNode->pFirst = p; - sqlite3_mutex_leave(pShmNode->mutex); - return SQLITE_OK; + tdsqlite3_mutex_leave(pShmNode->pShmMutex); + return rc; /* Jump here on any error */ shm_open_err: unixShmPurge(pDbFd); /* This call frees pShmNode if required */ - sqlite3_free(p); + tdsqlite3_free(p); unixLeaveMutex(); return rc; } @@ -37525,7 +42241,7 @@ shm_open_err: ** memory and SQLITE_OK returned. */ static int unixShmMap( - sqlite3_file *fd, /* Handle open on database file */ + tdsqlite3_file *fd, /* Handle open on database file */ int iRegion, /* Region to retrieve */ int szRegion, /* Size of regions */ int bExtend, /* True to extend file if necessary */ @@ -37546,11 +42262,16 @@ static int unixShmMap( p = pDbFd->pShm; pShmNode = p->pShmNode; - sqlite3_mutex_enter(pShmNode->mutex); + tdsqlite3_mutex_enter(pShmNode->pShmMutex); + if( pShmNode->isUnlocked ){ + rc = unixLockSharedMemory(pDbFd, pShmNode); + if( rc!=SQLITE_OK ) goto shmpage_out; + pShmNode->isUnlocked = 0; + } assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); assert( pShmNode->pInode==pDbFd->pInode ); - assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 ); - assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); + assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 ); + assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 ); /* Minimum number of regions required to be mapped. */ nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap; @@ -37562,12 +42283,12 @@ static int unixShmMap( pShmNode->szRegion = szRegion; - if( pShmNode->h>=0 ){ + if( pShmNode->hShm>=0 ){ /* The requested region is not mapped into this processes address space. ** Check to see if it has been allocated (i.e. if the wal-index file is ** large enough to contain the requested region). */ - if( osFstat(pShmNode->h, &sStat) ){ + if( osFstat(pShmNode->hShm, &sStat) ){ rc = SQLITE_IOERR_SHMSIZE; goto shmpage_out; } @@ -37595,7 +42316,7 @@ static int unixShmMap( assert( (nByte % pgsz)==0 ); for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){ int x = 0; - if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){ + if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){ const char *zFile = pShmNode->zFilename; rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile); goto shmpage_out; @@ -37606,7 +42327,7 @@ static int unixShmMap( } /* Map the requested memory region into this processes address space. */ - apNew = (char **)sqlite3_realloc( + apNew = (char **)tdsqlite3_realloc( pShmNode->apRegion, nReqRegion*sizeof(char *) ); if( !apNew ){ @@ -37618,22 +42339,22 @@ static int unixShmMap( int nMap = szRegion*nShmPerMap; int i; void *pMem; - if( pShmNode->h>=0 ){ + if( pShmNode->hShm>=0 ){ pMem = osMmap(0, nMap, pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, - MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion + MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion ); if( pMem==MAP_FAILED ){ rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename); goto shmpage_out; } }else{ - pMem = sqlite3_malloc64(szRegion); + pMem = tdsqlite3_malloc64(nMap); if( pMem==0 ){ rc = SQLITE_NOMEM_BKPT; goto shmpage_out; } - memset(pMem, 0, szRegion); + memset(pMem, 0, nMap); } for(i=0; i<nShmPerMap; i++){ @@ -37650,7 +42371,7 @@ shmpage_out: *pp = 0; } if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY; - sqlite3_mutex_leave(pShmNode->mutex); + tdsqlite3_mutex_leave(pShmNode->pShmMutex); return rc; } @@ -37663,7 +42384,7 @@ shmpage_out: ** not go from shared to exclusive or from exclusive to shared. */ static int unixShmLock( - sqlite3_file *fd, /* Database file holding the shared memory */ + tdsqlite3_file *fd, /* Database file holding the shared memory */ int ofst, /* First lock to acquire or release */ int n, /* Number of locks to acquire or release */ int flags /* What to do with the lock */ @@ -37684,12 +42405,12 @@ static int unixShmLock( || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED) || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); - assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 ); - assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); + assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 ); + assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 ); mask = (1<<(ofst+n)) - (1<<ofst); assert( n>1 || mask==(1<<ofst) ); - sqlite3_mutex_enter(pShmNode->mutex); + tdsqlite3_mutex_enter(pShmNode->pShmMutex); if( flags & SQLITE_SHM_UNLOCK ){ u16 allMask = 0; /* Mask of locks held by siblings */ @@ -37762,7 +42483,7 @@ static int unixShmLock( } } } - sqlite3_mutex_leave(pShmNode->mutex); + tdsqlite3_mutex_leave(pShmNode->pShmMutex); OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n", p->id, osGetpid(0), p->sharedMask, p->exclMask)); return rc; @@ -37775,10 +42496,13 @@ static int unixShmLock( ** any load or store begun after the barrier. */ static void unixShmBarrier( - sqlite3_file *fd /* Database file holding the shared memory */ + tdsqlite3_file *fd /* Database file holding the shared memory */ ){ UNUSED_PARAMETER(fd); - sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ + tdsqlite3MemoryBarrier(); /* compiler-defined memory barrier */ + assert( fd->pMethods->xLock==nolockLock + || unixFileMutexNotheld((unixFile*)fd) + ); unixEnterMutex(); /* Also mutex, for redundancy */ unixLeaveMutex(); } @@ -37791,7 +42515,7 @@ static void unixShmBarrier( ** routine is a harmless no-op. */ static int unixShmUnmap( - sqlite3_file *fd, /* The underlying database file */ + tdsqlite3_file *fd, /* The underlying database file */ int deleteFlag /* Delete shared-memory if true */ ){ unixShm *p; /* The connection to be closed */ @@ -37809,22 +42533,23 @@ static int unixShmUnmap( /* Remove connection p from the set of connections associated ** with pShmNode */ - sqlite3_mutex_enter(pShmNode->mutex); + tdsqlite3_mutex_enter(pShmNode->pShmMutex); for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} *pp = p->pNext; /* Free the connection p */ - sqlite3_free(p); + tdsqlite3_free(p); pDbFd->pShm = 0; - sqlite3_mutex_leave(pShmNode->mutex); + tdsqlite3_mutex_leave(pShmNode->pShmMutex); /* If pShmNode->nRef has reached 0, then close the underlying ** shared-memory file, too */ + assert( unixFileMutexNotheld(pDbFd) ); unixEnterMutex(); assert( pShmNode->nRef>0 ); pShmNode->nRef--; if( pShmNode->nRef==0 ){ - if( deleteFlag && pShmNode->h>=0 ){ + if( deleteFlag && pShmNode->hShm>=0 ){ osUnlink(pShmNode->zFilename); } unixShmPurge(pDbFd); @@ -37866,7 +42591,7 @@ static void unixUnmapfile(unixFile *pFd){ ** unixFile.mmapSize ** unixFile.mmapSizeActual ** -** If unsuccessful, an error message is logged via sqlite3_log() and +** If unsuccessful, an error message is logged via tdsqlite3_log() and ** the three variables above are zeroed. In this case SQLite should ** continue accessing the database using the xRead() and xWrite() ** methods. @@ -38000,7 +42725,7 @@ static int unixMapfile(unixFile *pFd, i64 nMap){ ** If this function does return a pointer, the caller must eventually ** release the reference by calling unixUnfetch(). */ -static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ +static int unixFetch(tdsqlite3_file *fd, i64 iOff, int nAmt, void **pp){ #if SQLITE_MAX_MMAP_SIZE>0 unixFile *pFd = (unixFile *)fd; /* The underlying database file */ #endif @@ -38031,7 +42756,7 @@ static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ ** to inform the VFS layer that, according to POSIX, any existing mapping ** may now be invalid and should be unmapped. */ -static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){ +static int unixUnfetch(tdsqlite3_file *fd, i64 iOff, void *p){ #if SQLITE_MAX_MMAP_SIZE>0 unixFile *pFd = (unixFile *)fd; /* The underlying database file */ UNUSED_PARAMETER(iOff); @@ -38060,20 +42785,20 @@ static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){ } /* -** Here ends the implementation of all sqlite3_file methods. +** Here ends the implementation of all tdsqlite3_file methods. ** -********************** End sqlite3_file Methods ******************************* +********************** End tdsqlite3_file Methods ******************************* ******************************************************************************/ /* -** This division contains definitions of sqlite3_io_methods objects that +** This division contains definitions of tdsqlite3_io_methods objects that ** implement various file locking strategies. It also contains definitions ** of "finder" functions. A finder-function is used to locate the appropriate -** sqlite3_io_methods object for a particular database file. The pAppData -** field of the sqlite3_vfs VFS objects are initialized to be pointers to +** tdsqlite3_io_methods object for a particular database file. The pAppData +** field of the tdsqlite3_vfs VFS objects are initialized to be pointers to ** the correct finder-function for that VFS. ** -** Most finder functions return a pointer to a fixed sqlite3_io_methods +** Most finder functions return a pointer to a fixed tdsqlite3_io_methods ** object. The only interesting finder-function is autolockIoFinder, which ** looks at the filesystem type and tries to guess the best locking ** strategy from that. @@ -38093,14 +42818,14 @@ static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){ ** ** Each instance of this macro generates two objects: ** -** * A constant sqlite3_io_methods object call METHOD that has locking +** * A constant tdsqlite3_io_methods object call METHOD that has locking ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK. ** ** * An I/O method finder function called FINDER that returns a pointer ** to the METHOD object in the previous bullet. */ #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \ -static const sqlite3_io_methods METHOD = { \ +static const tdsqlite3_io_methods METHOD = { \ VERSION, /* iVersion */ \ CLOSE, /* xClose */ \ unixRead, /* xRead */ \ @@ -38121,21 +42846,21 @@ static const sqlite3_io_methods METHOD = { \ unixFetch, /* xFetch */ \ unixUnfetch, /* xUnfetch */ \ }; \ -static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \ +static const tdsqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \ UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \ return &METHOD; \ } \ -static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \ +static const tdsqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \ = FINDER##Impl; /* -** Here are all of the sqlite3_io_methods objects for each of the +** Here are all of the tdsqlite3_io_methods objects for each of the ** locking strategies. Functions that return pointers to these methods ** are also created. */ IOMETHODS( posixIoFinder, /* Finder function name */ - posixIoMethods, /* sqlite3_io_methods object name */ + posixIoMethods, /* tdsqlite3_io_methods object name */ 3, /* shared memory and mmap are enabled */ unixClose, /* xClose method */ unixLock, /* xLock method */ @@ -38145,8 +42870,8 @@ IOMETHODS( ) IOMETHODS( nolockIoFinder, /* Finder function name */ - nolockIoMethods, /* sqlite3_io_methods object name */ - 3, /* shared memory is disabled */ + nolockIoMethods, /* tdsqlite3_io_methods object name */ + 3, /* shared memory and mmap are enabled */ nolockClose, /* xClose method */ nolockLock, /* xLock method */ nolockUnlock, /* xUnlock method */ @@ -38155,7 +42880,7 @@ IOMETHODS( ) IOMETHODS( dotlockIoFinder, /* Finder function name */ - dotlockIoMethods, /* sqlite3_io_methods object name */ + dotlockIoMethods, /* tdsqlite3_io_methods object name */ 1, /* shared memory is disabled */ dotlockClose, /* xClose method */ dotlockLock, /* xLock method */ @@ -38167,7 +42892,7 @@ IOMETHODS( #if SQLITE_ENABLE_LOCKING_STYLE IOMETHODS( flockIoFinder, /* Finder function name */ - flockIoMethods, /* sqlite3_io_methods object name */ + flockIoMethods, /* tdsqlite3_io_methods object name */ 1, /* shared memory is disabled */ flockClose, /* xClose method */ flockLock, /* xLock method */ @@ -38180,7 +42905,7 @@ IOMETHODS( #if OS_VXWORKS IOMETHODS( semIoFinder, /* Finder function name */ - semIoMethods, /* sqlite3_io_methods object name */ + semIoMethods, /* tdsqlite3_io_methods object name */ 1, /* shared memory is disabled */ semXClose, /* xClose method */ semXLock, /* xLock method */ @@ -38193,7 +42918,7 @@ IOMETHODS( #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE IOMETHODS( afpIoFinder, /* Finder function name */ - afpIoMethods, /* sqlite3_io_methods object name */ + afpIoMethods, /* tdsqlite3_io_methods object name */ 1, /* shared memory is disabled */ afpClose, /* xClose method */ afpLock, /* xLock method */ @@ -38209,17 +42934,17 @@ IOMETHODS( ** it uses proxy, dot-file, AFP, and flock() locking methods on those ** secondary files. For this reason, the division that implements ** proxy locking is located much further down in the file. But we need -** to go ahead and define the sqlite3_io_methods and finder function +** to go ahead and define the tdsqlite3_io_methods and finder function ** for proxy locking here. So we forward declare the I/O methods. */ #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE -static int proxyClose(sqlite3_file*); -static int proxyLock(sqlite3_file*, int); -static int proxyUnlock(sqlite3_file*, int); -static int proxyCheckReservedLock(sqlite3_file*, int*); +static int proxyClose(tdsqlite3_file*); +static int proxyLock(tdsqlite3_file*, int); +static int proxyUnlock(tdsqlite3_file*, int); +static int proxyCheckReservedLock(tdsqlite3_file*, int*); IOMETHODS( proxyIoFinder, /* Finder function name */ - proxyIoMethods, /* sqlite3_io_methods object name */ + proxyIoMethods, /* tdsqlite3_io_methods object name */ 1, /* shared memory is disabled */ proxyClose, /* xClose method */ proxyLock, /* xLock method */ @@ -38233,7 +42958,7 @@ IOMETHODS( #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE IOMETHODS( nfsIoFinder, /* Finder function name */ - nfsIoMethods, /* sqlite3_io_methods object name */ + nfsIoMethods, /* tdsqlite3_io_methods object name */ 1, /* shared memory is disabled */ unixClose, /* xClose method */ unixLock, /* xLock method */ @@ -38246,18 +42971,18 @@ IOMETHODS( #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE /* ** This "finder" function attempts to determine the best locking strategy -** for the database file "filePath". It then returns the sqlite3_io_methods +** for the database file "filePath". It then returns the tdsqlite3_io_methods ** object that implements that strategy. ** ** This is for MacOSX only. */ -static const sqlite3_io_methods *autolockIoFinderImpl( +static const tdsqlite3_io_methods *autolockIoFinderImpl( const char *filePath, /* name of the database file */ unixFile *pNew /* open file object for the database file */ ){ static const struct Mapping { const char *zFilesystem; /* Filesystem type name */ - const sqlite3_io_methods *pMethods; /* Appropriate locking method */ + const tdsqlite3_io_methods *pMethods; /* Appropriate locking method */ } aMap[] = { { "hfs", &posixIoMethods }, { "ufs", &posixIoMethods }, @@ -38304,7 +43029,7 @@ static const sqlite3_io_methods *autolockIoFinderImpl( return &dotlockIoMethods; } } -static const sqlite3_io_methods +static const tdsqlite3_io_methods *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ @@ -38315,7 +43040,7 @@ static const sqlite3_io_methods ** locking works. If it does, then that is what is used. If it does not ** work, then fallback to named semaphore locking. */ -static const sqlite3_io_methods *vxworksIoFinderImpl( +static const tdsqlite3_io_methods *vxworksIoFinderImpl( const char *filePath, /* name of the database file */ unixFile *pNew /* the open file object */ ){ @@ -38340,7 +43065,7 @@ static const sqlite3_io_methods *vxworksIoFinderImpl( return &semIoMethods; } } -static const sqlite3_io_methods +static const tdsqlite3_io_methods *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl; #endif /* OS_VXWORKS */ @@ -38348,43 +43073,32 @@ static const sqlite3_io_methods /* ** An abstract type for a pointer to an IO method finder function: */ -typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*); +typedef const tdsqlite3_io_methods *(*finder_type)(const char*,unixFile*); /**************************************************************************** -**************************** sqlite3_vfs methods **************************** +**************************** tdsqlite3_vfs methods **************************** ** ** This division contains the implementation of methods on the -** sqlite3_vfs object. +** tdsqlite3_vfs object. */ /* ** Initialize the contents of the unixFile structure pointed to by pId. */ static int fillInUnixFile( - sqlite3_vfs *pVfs, /* Pointer to vfs object */ + tdsqlite3_vfs *pVfs, /* Pointer to vfs object */ int h, /* Open file descriptor of file being opened */ - sqlite3_file *pId, /* Write to the unixFile structure here */ + tdsqlite3_file *pId, /* Write to the unixFile structure here */ const char *zFilename, /* Name of the file being opened */ int ctrlFlags /* Zero or more UNIXFILE_* values */ ){ - const sqlite3_io_methods *pLockingStyle; + const tdsqlite3_io_methods *pLockingStyle; unixFile *pNew = (unixFile *)pId; int rc = SQLITE_OK; assert( pNew->pInode==NULL ); - /* Usually the path zFilename should not be a relative pathname. The - ** exception is when opening the proxy "conch" file in builds that - ** include the special Apple locking styles. - */ -#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE - assert( zFilename==0 || zFilename[0]=='/' - || pVfs->pAppData==(void*)&autolockIoFinder ); -#else - assert( zFilename==0 || zFilename[0]=='/' ); -#endif - /* No locking occurs in temporary files */ assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 ); @@ -38394,9 +43108,9 @@ static int fillInUnixFile( pNew->zPath = zFilename; pNew->ctrlFlags = (u8)ctrlFlags; #if SQLITE_MAX_MMAP_SIZE>0 - pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap; + pNew->mmapSizeMax = tdsqlite3GlobalConfig.szMmap; #endif - if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0), + if( tdsqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0), "psow", SQLITE_POWERSAFE_OVERWRITE) ){ pNew->ctrlFlags |= UNIXFILE_PSOW; } @@ -38462,7 +43176,7 @@ static int fillInUnixFile( ** the afpLockingContext. */ afpLockingContext *pCtx; - pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) ); + pNew->lockingContext = pCtx = tdsqlite3_malloc64( sizeof(*pCtx) ); if( pCtx==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ @@ -38475,7 +43189,7 @@ static int fillInUnixFile( unixEnterMutex(); rc = findInodeInfo(pNew, &pNew->pInode); if( rc!=SQLITE_OK ){ - sqlite3_free(pNew->lockingContext); + tdsqlite3_free(pNew->lockingContext); robust_close(pNew, h, __LINE__); h = -1; } @@ -38492,11 +43206,11 @@ static int fillInUnixFile( int nFilename; assert( zFilename!=0 ); nFilename = (int)strlen(zFilename) + 6; - zLockFile = (char *)sqlite3_malloc64(nFilename); + zLockFile = (char *)tdsqlite3_malloc64(nFilename); if( zLockFile==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ - sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); + tdsqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); } pNew->lockingContext = zLockFile; } @@ -38511,7 +43225,7 @@ static int fillInUnixFile( if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){ char *zSemName = pNew->pInode->aSemName; int n; - sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem", + tdsqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem", pNew->pId->zCanonicalName); for( n=1; zSemName[n]; n++ ) if( zSemName[n]=='/' ) zSemName[n] = '_'; @@ -38559,7 +43273,7 @@ static const char *unixTempFileDir(void){ }; unsigned int i = 0; struct stat buf; - const char *zDir = sqlite3_temp_directory; + const char *zDir = tdsqlite3_temp_directory; if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR"); if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR"); @@ -38597,10 +43311,10 @@ static int unixGetTempname(int nBuf, char *zBuf){ if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH; do{ u64 r; - sqlite3_randomness(sizeof(r), &r); + tdsqlite3_randomness(sizeof(r), &r); assert( nBuf>2 ); zBuf[nBuf-2] = 0; - sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c", + tdsqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c", zDir, r, 0); if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR; }while( osAccess(zBuf,0)==0 ); @@ -38643,6 +43357,8 @@ static UnixUnusedFd *findReusableFd(const char *zPath, int flags){ #if !OS_VXWORKS struct stat sStat; /* Results of stat() call */ + unixEnterMutex(); + /* A stat() call may fail for various reasons. If this happens, it is ** almost certain that an open() call on the same path will also fail. ** For this reason, if an error occurs in the stat() call here, it is @@ -38651,25 +43367,28 @@ static UnixUnusedFd *findReusableFd(const char *zPath, int flags){ ** ** Even if a subsequent open() call does succeed, the consequences of ** not searching for a reusable file descriptor are not dire. */ - if( 0==osStat(zPath, &sStat) ){ + if( inodeList!=0 && 0==osStat(zPath, &sStat) ){ unixInodeInfo *pInode; - unixEnterMutex(); pInode = inodeList; while( pInode && (pInode->fileId.dev!=sStat.st_dev - || pInode->fileId.ino!=sStat.st_ino) ){ + || pInode->fileId.ino!=(u64)sStat.st_ino) ){ pInode = pInode->pNext; } if( pInode ){ UnixUnusedFd **pp; + assert( tdsqlite3_mutex_notheld(pInode->pLockMutex) ); + tdsqlite3_mutex_enter(pInode->pLockMutex); + flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE); for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext)); pUnused = *pp; if( pUnused ){ *pp = pUnused->pNext; } + tdsqlite3_mutex_leave(pInode->pLockMutex); } - unixLeaveMutex(); } + unixLeaveMutex(); #endif /* if !OS_VXWORKS */ return pUnused; } @@ -38714,7 +43433,7 @@ static int getFileMode( ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the ** original filename is unavailable. But 8_3_NAMES is only used for ** FAT filesystems and permissions do not matter there, so just use -** the default permissions. +** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero. */ static int findCreateFileMode( const char *zPath, /* Path of file (possibly) being created */ @@ -38743,18 +43462,13 @@ static int findCreateFileMode( ** where NN is a decimal number. The NN naming schemes are ** used by the test_multiplex.c module. */ - nDb = sqlite3Strlen30(zPath) - 1; + nDb = tdsqlite3Strlen30(zPath) - 1; while( zPath[nDb]!='-' ){ -#ifndef SQLITE_ENABLE_8_3_NAMES - /* In the normal case (8+3 filenames disabled) the journal filename - ** is guaranteed to contain a '-' character. */ - assert( nDb>0 ); - assert( sqlite3Isalnum(zPath[nDb]) ); -#else - /* If 8+3 names are possible, then the journal file might not contain - ** a '-' character. So check for that case and return early. */ + /* In normal operation, the journal file name will always contain + ** a '-' character. However in 8+3 filename mode, or if a corrupt + ** rollback journal specifies a master journal with a goofy name, then + ** the '-' might be missing. */ if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK; -#endif nDb--; } memcpy(zDb, zPath, nDb); @@ -38768,7 +43482,7 @@ static int findCreateFileMode( ** filename, check for the "modeof" parameter. If present, interpret ** its value as a filename and try to copy the mode, uid and gid from ** that file. */ - const char *z = sqlite3_uri_parameter(zPath, "modeof"); + const char *z = tdsqlite3_uri_parameter(zPath, "modeof"); if( z ){ rc = getFileMode(z, pMode, pUid, pGid); } @@ -38782,9 +43496,9 @@ static int findCreateFileMode( ** Previously, the SQLite OS layer used three functions in place of this ** one: ** -** sqlite3OsOpenReadWrite(); -** sqlite3OsOpenReadOnly(); -** sqlite3OsOpenExclusive(); +** tdsqlite3OsOpenReadWrite(); +** tdsqlite3OsOpenReadOnly(); +** tdsqlite3OsOpenExclusive(); ** ** These calls correspond to the following combinations of flags: ** @@ -38799,16 +43513,16 @@ static int findCreateFileMode( ** OpenExclusive(). */ static int unixOpen( - sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ + tdsqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ const char *zPath, /* Pathname of file to be opened */ - sqlite3_file *pFile, /* The file descriptor to be filled in */ + tdsqlite3_file *pFile, /* The file descriptor to be filled in */ int flags, /* Input flags to control the opening */ int *pOutFlags /* Output flags returned to SQLite core */ ){ unixFile *p = (unixFile *)pFile; int fd = -1; /* File descriptor returned by open() */ int openFlags = 0; /* Flags to pass to open() */ - int eType = flags&0xFFFFFF00; /* Type of file to open */ + int eType = flags&0x0FFF00; /* Type of file to open */ int noLock; /* True to omit locking primitives */ int rc = SQLITE_OK; /* Function Return Code */ int ctrlFlags = 0; /* UNIXFILE_* flags */ @@ -38829,7 +43543,7 @@ static int unixOpen( ** a file-descriptor on the directory too. The first time unixSync() ** is called the directory file descriptor will be fsync()ed and close()d. */ - int syncDir = (isCreate && ( + int isNewJrnl = (isCreate && ( eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_WAL @@ -38874,9 +43588,8 @@ static int unixOpen( */ if( randomnessPid!=osGetpid(0) ){ randomnessPid = osGetpid(0); - sqlite3_randomness(0,0); + tdsqlite3_randomness(0,0); } - memset(p, 0, sizeof(unixFile)); if( eType==SQLITE_OPEN_MAIN_DB ){ @@ -38885,21 +43598,21 @@ static int unixOpen( if( pUnused ){ fd = pUnused->fd; }else{ - pUnused = sqlite3_malloc64(sizeof(*pUnused)); + pUnused = tdsqlite3_malloc64(sizeof(*pUnused)); if( !pUnused ){ return SQLITE_NOMEM_BKPT; } } - p->pUnused = pUnused; + p->pPreallocatedUnused = pUnused; /* Database filenames are double-zero terminated if they are not ** URIs with parameters. Hence, they can always be passed into - ** sqlite3_uri_parameter(). */ + ** tdsqlite3_uri_parameter(). */ assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 ); }else if( !zName ){ /* If zName is NULL, the upper layer is requesting a temp file. */ - assert(isDelete && !syncDir); + assert(isDelete && !isNewJrnl); rc = unixGetTempname(pVfs->mxPathname, zTmpname); if( rc!=SQLITE_OK ){ return rc; @@ -38907,7 +43620,7 @@ static int unixOpen( zName = zTmpname; /* Generated temporary filenames are always double-zero terminated - ** for use by sqlite3_uri_parameter(). */ + ** for use by tdsqlite3_uri_parameter(). */ assert( zName[strlen(zName)+1]==0 ); } @@ -38919,7 +43632,7 @@ static int unixOpen( if( isReadWrite ) openFlags |= O_RDWR; if( isCreate ) openFlags |= O_CREAT; if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW); - openFlags |= (O_LARGEFILE|O_BINARY); + openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW); if( fd<0 ){ mode_t openMode; /* Permissions to create file with */ @@ -38927,32 +43640,47 @@ static int unixOpen( gid_t gid; /* Groupid for the file */ rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid); if( rc!=SQLITE_OK ){ - assert( !p->pUnused ); + assert( !p->pPreallocatedUnused ); assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL ); return rc; } fd = robust_open(zName, openFlags, openMode); OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); assert( !isExclusive || (openFlags & O_CREAT)!=0 ); - if( fd<0 && errno!=EISDIR && isReadWrite ){ - /* Failed to open the file for read/write access. Try read-only. */ - flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); - openFlags &= ~(O_RDWR|O_CREAT); - flags |= SQLITE_OPEN_READONLY; - openFlags |= O_RDONLY; - isReadonly = 1; - fd = robust_open(zName, openFlags, openMode); + if( fd<0 ){ + if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){ + /* If unable to create a journal because the directory is not + ** writable, change the error code to indicate that. */ + rc = SQLITE_READONLY_DIRECTORY; + }else if( errno!=EISDIR && isReadWrite ){ + /* Failed to open the file for read/write access. Try read-only. */ + flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); + openFlags &= ~(O_RDWR|O_CREAT); + flags |= SQLITE_OPEN_READONLY; + openFlags |= O_RDONLY; + isReadonly = 1; + fd = robust_open(zName, openFlags, openMode); + } } if( fd<0 ){ - rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName); + int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName); + if( rc==SQLITE_OK ) rc = rc2; goto open_finished; } - /* If this process is running as root and if creating a new rollback - ** journal or WAL file, set the ownership of the journal or WAL to be - ** the same as the original database. + /* The owner of the rollback journal or WAL file should always be the + ** same as the owner of the database file. Try to ensure that this is + ** the case. The chown() system call will be a no-op if the current + ** process lacks root privileges, be we should at least try. Without + ** this step, if a root process opens a database file, it can leave + ** behinds a journal/WAL that is owned by root and hence make the + ** database inaccessible to unprivileged processes. + ** + ** If openMode==0, then that means uid and gid are not set correctly + ** (probably because SQLite is configured to use 8+3 filename mode) and + ** in that case we do not want to attempt the chown(). */ - if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ + if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){ robustFchown(fd, uid, gid); } } @@ -38961,16 +43689,17 @@ static int unixOpen( *pOutFlags = flags; } - if( p->pUnused ){ - p->pUnused->fd = fd; - p->pUnused->flags = flags; + if( p->pPreallocatedUnused ){ + p->pPreallocatedUnused->fd = fd; + p->pPreallocatedUnused->flags = + flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE); } if( isDelete ){ #if OS_VXWORKS zPath = zName; #elif defined(SQLITE_UNLINK_AFTER_CLOSE) - zPath = sqlite3_mprintf("%s", zName); + zPath = tdsqlite3_mprintf("%s", zName); if( zPath==0 ){ robust_close(p, fd, __LINE__); return SQLITE_NOMEM_BKPT; @@ -39004,7 +43733,7 @@ static int unixOpen( if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY; noLock = eType!=SQLITE_OPEN_MAIN_DB; if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK; - if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC; + if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC; if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI; #if SQLITE_ENABLE_LOCKING_STYLE @@ -39029,7 +43758,7 @@ static int unixOpen( if( rc!=SQLITE_OK ){ /* Use unixClose to clean up the resources added in fillInUnixFile ** and clear all the structure's references. Specifically, - ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op + ** pFile->pMethods will be NULL so tdsqlite3OsClose will be a no-op */ unixClose(pFile); return rc; @@ -39040,11 +43769,14 @@ static int unixOpen( } #endif + assert( zPath==0 || zPath[0]=='/' + || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL + ); rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); open_finished: if( rc!=SQLITE_OK ){ - sqlite3_free(p->pUnused); + tdsqlite3_free(p->pPreallocatedUnused); } return rc; } @@ -39055,7 +43787,7 @@ open_finished: ** the directory after deleting the file. */ static int unixDelete( - sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ + tdsqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ const char *zPath, /* Name of file to be deleted */ int dirSync /* If true, fsync() directory after deleting file */ ){ @@ -39103,7 +43835,7 @@ static int unixDelete( ** Otherwise return 0. */ static int unixAccess( - sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ + tdsqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ const char *zPath, /* Path of the file to examine */ int flags, /* What do we want to learn about the zPath file? */ int *pResOut /* Write result boolean here */ @@ -39118,7 +43850,8 @@ static int unixAccess( if( flags==SQLITE_ACCESS_EXISTS ){ struct stat buf; - *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0); + *pResOut = 0==osStat(zPath, &buf) && + (!S_ISREG(buf.st_mode) || buf.st_size>0); }else{ *pResOut = osAccess(zPath, W_OK|R_OK)==0; } @@ -39133,13 +43866,13 @@ static int mkFullPathname( char *zOut, /* Output buffer */ int nOut /* Allocated size of buffer zOut */ ){ - int nPath = sqlite3Strlen30(zPath); + int nPath = tdsqlite3Strlen30(zPath); int iOff = 0; if( zPath[0]!='/' ){ if( osGetcwd(zOut, nOut-2)==0 ){ return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath); } - iOff = sqlite3Strlen30(zOut); + iOff = tdsqlite3Strlen30(zOut); zOut[iOff++] = '/'; } if( (iOff+nPath+1)>nOut ){ @@ -39148,7 +43881,7 @@ static int mkFullPathname( zOut[iOff] = '\0'; return SQLITE_CANTOPEN_BKPT; } - sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath); + tdsqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath); return SQLITE_OK; } @@ -39157,12 +43890,12 @@ static int mkFullPathname( ** is stored as a nul-terminated string in the buffer pointed to by ** zPath. ** -** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes +** zOut points to a buffer of at least tdsqlite3_vfs.mxPathname bytes ** (in this case, MAX_PATHNAME bytes). The full-path is written to ** this buffer before returning. */ static int unixFullPathname( - sqlite3_vfs *pVfs, /* Pointer to vfs object */ + tdsqlite3_vfs *pVfs, /* Pointer to vfs object */ const char *zPath, /* Possibly relative input path */ int nOut, /* Size of output buffer in bytes */ char *zOut /* Output buffer */ @@ -39172,7 +43905,7 @@ static int unixFullPathname( #else int rc = SQLITE_OK; int nByte; - int nLink = 1; /* Number of symbolic links followed so far */ + int nLink = 0; /* Number of symbolic links followed so far */ const char *zIn = zPath; /* Input path for each iteration of loop */ char *zDel = 0; @@ -39201,10 +43934,11 @@ static int unixFullPathname( } if( bLink ){ + nLink++; if( zDel==0 ){ - zDel = sqlite3_malloc(nOut); + zDel = tdsqlite3_malloc(nOut); if( zDel==0 ) rc = SQLITE_NOMEM_BKPT; - }else if( ++nLink>SQLITE_MAX_SYMLINKS ){ + }else if( nLink>=SQLITE_MAX_SYMLINKS ){ rc = SQLITE_CANTOPEN_BKPT; } @@ -39215,7 +43949,7 @@ static int unixFullPathname( }else{ if( zDel[0]!='/' ){ int n; - for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--); + for(n = tdsqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--); if( nByte+n+1>nOut ){ rc = SQLITE_CANTOPEN_BKPT; }else{ @@ -39239,7 +43973,8 @@ static int unixFullPathname( zIn = zOut; }while( rc==SQLITE_OK ); - sqlite3_free(zDel); + tdsqlite3_free(zDel); + if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK; return rc; #endif /* HAVE_READLINK && HAVE_LSTAT */ } @@ -39251,7 +43986,7 @@ static int unixFullPathname( ** within the shared library, and closing the shared library. */ #include <dlfcn.h> -static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){ +static void *unixDlOpen(tdsqlite3_vfs *NotUsed, const char *zFilename){ UNUSED_PARAMETER(NotUsed); return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL); } @@ -39263,17 +43998,17 @@ static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){ ** is available, zBufOut is left unmodified and SQLite uses a default ** error message. */ -static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){ +static void unixDlError(tdsqlite3_vfs *NotUsed, int nBuf, char *zBufOut){ const char *zErr; UNUSED_PARAMETER(NotUsed); unixEnterMutex(); zErr = dlerror(); if( zErr ){ - sqlite3_snprintf(nBuf, zBufOut, "%s", zErr); + tdsqlite3_snprintf(nBuf, zBufOut, "%s", zErr); } unixLeaveMutex(); } -static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){ +static void (*unixDlSym(tdsqlite3_vfs *NotUsed, void *p, const char*zSym))(void){ /* ** GCC with -pedantic-errors says that C90 does not allow a void* to be ** cast into a pointer to a function. And yet the library dlsym() routine @@ -39296,7 +44031,7 @@ static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){ x = (void(*(*)(void*,const char*))(void))dlsym; return (*x)(p, zSym); } -static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){ +static void unixDlClose(tdsqlite3_vfs *NotUsed, void *pHandle){ UNUSED_PARAMETER(NotUsed); dlclose(pHandle); } @@ -39310,7 +44045,7 @@ static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){ /* ** Write nBuf bytes of random data to the supplied buffer zBuf. */ -static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ +static int unixRandomness(tdsqlite3_vfs *NotUsed, int nBuf, char *zBuf){ UNUSED_PARAMETER(NotUsed); assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int))); @@ -39357,7 +44092,7 @@ static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ ** might be greater than or equal to the argument, but not less ** than the argument. */ -static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){ +static int unixSleep(tdsqlite3_vfs *NotUsed, int microseconds){ #if OS_VXWORKS struct timespec sp; @@ -39381,10 +44116,10 @@ static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){ /* ** The following variable, if set to a non-zero value, is interpreted as ** the number of seconds since 1970 and is used to set the result of -** sqlite3OsCurrentTime() during testing. +** tdsqlite3OsCurrentTime() during testing. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ +SQLITE_API int tdsqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ #endif /* @@ -39397,26 +44132,26 @@ SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date ** cannot be found. */ -static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){ - static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; +static int unixCurrentTimeInt64(tdsqlite3_vfs *NotUsed, tdsqlite3_int64 *piNow){ + static const tdsqlite3_int64 unixEpoch = 24405875*(tdsqlite3_int64)8640000; int rc = SQLITE_OK; #if defined(NO_GETTOD) time_t t; time(&t); - *piNow = ((sqlite3_int64)t)*1000 + unixEpoch; + *piNow = ((tdsqlite3_int64)t)*1000 + unixEpoch; #elif OS_VXWORKS struct timespec sNow; clock_gettime(CLOCK_REALTIME, &sNow); - *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000; + *piNow = unixEpoch + 1000*(tdsqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000; #else struct timeval sNow; (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */ - *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000; + *piNow = unixEpoch + 1000*(tdsqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000; #endif #ifdef SQLITE_TEST - if( sqlite3_current_time ){ - *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; + if( tdsqlite3_current_time ){ + *piNow = 1000*(tdsqlite3_int64)tdsqlite3_current_time + unixEpoch; } #endif UNUSED_PARAMETER(NotUsed); @@ -39429,8 +44164,8 @@ static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){ ** current time and date as a Julian Day number into *prNow and ** return 0. Return 1 if the time and date cannot be found. */ -static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){ - sqlite3_int64 i = 0; +static int unixCurrentTime(tdsqlite3_vfs *NotUsed, double *prNow){ + tdsqlite3_int64 i = 0; int rc; UNUSED_PARAMETER(NotUsed); rc = unixCurrentTimeInt64(0, &i); @@ -39447,7 +44182,7 @@ static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){ ** during SQLite operation. Only the integer return code is currently ** used. */ -static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ +static int unixGetLastError(tdsqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ UNUSED_PARAMETER(NotUsed); UNUSED_PARAMETER(NotUsed2); UNUSED_PARAMETER(NotUsed3); @@ -39456,7 +44191,7 @@ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ /* -************************ End of sqlite3_vfs methods *************************** +************************ End of tdsqlite3_vfs methods *************************** ******************************************************************************/ /****************************************************************************** @@ -39509,9 +44244,9 @@ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ ** ** C APIs ** -** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE, +** tdsqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE, ** <proxy_path> | ":auto:"); -** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE, +** tdsqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE, ** &<proxy_path>); ** ** @@ -39628,7 +44363,7 @@ struct proxyLockingContext { int conchHeld; /* 1 if the conch is held, -1 if lockless */ int nFails; /* Number of conch taking failures */ void *oldLockingContext; /* Original lockingcontext to restore on close */ - sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ + tdsqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ }; /* @@ -39712,7 +44447,7 @@ static int proxyCreateLockPath(const char *lockPath){ /* ** Create a new VFS file descriptor (stored in memory obtained from -** sqlite3_malloc) and open the file named "path" in the file descriptor. +** tdsqlite3_malloc) and open the file named "path" in the file descriptor. ** ** The caller is responsible not only for closing the file descriptor ** but also for freeing the memory associated with the file descriptor. @@ -39725,8 +44460,8 @@ static int proxyCreateUnixFile( int fd = -1; unixFile *pNew; int rc = SQLITE_OK; - int openFlags = O_RDWR | O_CREAT; - sqlite3_vfs dummyVfs; + int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW; + tdsqlite3_vfs dummyVfs; int terrno = 0; UnixUnusedFd *pUnused = NULL; @@ -39740,7 +44475,7 @@ static int proxyCreateUnixFile( if( pUnused ){ fd = pUnused->fd; }else{ - pUnused = sqlite3_malloc64(sizeof(*pUnused)); + pUnused = tdsqlite3_malloc64(sizeof(*pUnused)); if( !pUnused ){ return SQLITE_NOMEM_BKPT; } @@ -39755,7 +44490,7 @@ static int proxyCreateUnixFile( } } if( fd<0 ){ - openFlags = O_RDONLY; + openFlags = O_RDONLY | O_NOFOLLOW; fd = robust_open(path, openFlags, 0); terrno = errno; } @@ -39773,7 +44508,7 @@ static int proxyCreateUnixFile( } } - pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew)); + pNew = (unixFile *)tdsqlite3_malloc64(sizeof(*pNew)); if( pNew==NULL ){ rc = SQLITE_NOMEM_BKPT; goto end_create_proxy; @@ -39785,28 +44520,28 @@ static int proxyCreateUnixFile( dummyVfs.zName = "dummy"; pUnused->fd = fd; pUnused->flags = openFlags; - pNew->pUnused = pUnused; + pNew->pPreallocatedUnused = pUnused; - rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0); + rc = fillInUnixFile(&dummyVfs, fd, (tdsqlite3_file*)pNew, path, 0); if( rc==SQLITE_OK ){ *ppFile = pNew; return SQLITE_OK; } end_create_proxy: robust_close(pNew, fd, __LINE__); - sqlite3_free(pNew); - sqlite3_free(pUnused); + tdsqlite3_free(pNew); + tdsqlite3_free(pUnused); return rc; } #ifdef SQLITE_TEST /* simulate multiple hosts by creating unique hostid file paths */ -SQLITE_API int sqlite3_hostid_num = 0; +SQLITE_API int tdsqlite3_hostid_num = 0; #endif #define PROXY_HOSTIDLEN 16 /* conch file host id length */ -#ifdef HAVE_GETHOSTUUID +#if HAVE_GETHOSTUUID /* Not always defined in the headers as it ought to be */ extern int gethostuuid(uuid_t id, const struct timespec *wait); #endif @@ -39817,7 +44552,7 @@ extern int gethostuuid(uuid_t id, const struct timespec *wait); static int proxyGetHostID(unsigned char *pHostID, int *pError){ assert(PROXY_HOSTIDLEN == sizeof(uuid_t)); memset(pHostID, 0, PROXY_HOSTIDLEN); -#ifdef HAVE_GETHOSTUUID +#if HAVE_GETHOSTUUID { struct timespec timeout = {1, 0}; /* 1 sec timeout */ if( gethostuuid(pHostID, &timeout) ){ @@ -39833,8 +44568,8 @@ static int proxyGetHostID(unsigned char *pHostID, int *pError){ #endif #ifdef SQLITE_TEST /* simulate multiple hosts by creating unique hostid file paths */ - if( sqlite3_hostid_num != 0){ - pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF)); + if( tdsqlite3_hostid_num != 0){ + pHostID[0] = (char)(pHostID[0] + (char)(tdsqlite3_hostid_num & 0xFF)); } #endif @@ -39871,27 +44606,27 @@ static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){ pathLen = strlcpy(tPath, cPath, MAXPATHLEN); if( pathLen>MAXPATHLEN || pathLen<6 || (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){ - sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen); + tdsqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen); goto end_breaklock; } /* read the conch content */ readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0); if( readLen<PROXY_PATHINDEX ){ - sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen); + tdsqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen); goto end_breaklock; } /* write it out to the temporary break file */ - fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0); + fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0); if( fd<0 ){ - sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno); + tdsqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno); goto end_breaklock; } if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){ - sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno); + tdsqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno); goto end_breaklock; } if( rename(tPath, cPath) ){ - sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno); + tdsqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno); goto end_breaklock; } rc = 0; @@ -39923,7 +44658,7 @@ static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){ memset(&conchModTime, 0, sizeof(conchModTime)); do { - rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); + rc = conchFile->pMethod->xLock((tdsqlite3_file*)conchFile, lockType); nTries ++; if( rc==SQLITE_BUSY ){ /* If the lock failed (busy): @@ -39974,10 +44709,10 @@ static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){ if( 0==proxyBreakConchLock(pFile, myHostID) ){ rc = SQLITE_OK; if( lockType==EXCLUSIVE_LOCK ){ - rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); + rc = conchFile->pMethod->xLock((tdsqlite3_file*)conchFile, SHARED_LOCK); } if( !rc ){ - rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); + rc = conchFile->pMethod->xLock((tdsqlite3_file*)conchFile, lockType); } } } @@ -40117,7 +44852,7 @@ static int proxyTakeConch(unixFile *pFile){ } writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]); robust_ftruncate(conchFile->h, writeSize); - rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0); + rc = unixWrite((tdsqlite3_file *)conchFile, writeBuffer, writeSize, 0); full_fsync(conchFile->h,0,0); /* If we created a new conch file (not just updated the contents of a ** valid conch file), try to match the permissions of the database @@ -40150,7 +44885,7 @@ static int proxyTakeConch(unixFile *pFile){ } } } - conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); + conchFile->pMethod->xUnlock((tdsqlite3_file*)conchFile, SHARED_LOCK); end_takeconch: OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h)); @@ -40186,7 +44921,7 @@ static int proxyTakeConch(unixFile *pFile){ ** from the conch file or the path was allocated on the stack */ if( tempLockPath ){ - pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath); + pCtx->lockProxyPath = tdsqlite3DbStrDup(0, tempLockPath); if( !pCtx->lockProxyPath ){ rc = SQLITE_NOMEM_BKPT; } @@ -40201,7 +44936,7 @@ static int proxyTakeConch(unixFile *pFile){ afpCtx->dbPath = pCtx->lockProxyPath; } } else { - conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); + conchFile->pMethod->xUnlock((tdsqlite3_file*)conchFile, NO_LOCK); } OSTRACE(("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed")); @@ -40225,7 +44960,7 @@ static int proxyReleaseConch(unixFile *pFile){ (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), osGetpid(0))); if( pCtx->conchHeld>0 ){ - rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); + rc = conchFile->pMethod->xUnlock((tdsqlite3_file*)conchFile, NO_LOCK); } pCtx->conchHeld = 0; OSTRACE(("RELEASECONCH %d %s\n", conchFile->h, @@ -40235,7 +44970,7 @@ static int proxyReleaseConch(unixFile *pFile){ /* ** Given the name of a database file, compute the name of its conch file. -** Store the conch filename in memory obtained from sqlite3_malloc64(). +** Store the conch filename in memory obtained from tdsqlite3_malloc64(). ** Make *pConchPath point to the new name. Return SQLITE_OK on success ** or SQLITE_NOMEM if unable to obtain memory. ** @@ -40251,7 +44986,7 @@ static int proxyCreateConchPathname(char *dbPath, char **pConchPath){ /* Allocate space for the conch filename and initialize the name to ** the name of the original database file. */ - *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8); + *pConchPath = conchPath = (char *)tdsqlite3_malloc64(len + 8); if( conchPath==0 ){ return SQLITE_NOMEM_BKPT; } @@ -40299,12 +45034,12 @@ static int switchLockProxyPath(unixFile *pFile, const char *path) { pCtx->lockProxy=NULL; pCtx->conchHeld = 0; if( lockProxy!=NULL ){ - rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy); + rc=lockProxy->pMethod->xClose((tdsqlite3_file *)lockProxy); if( rc ) return rc; - sqlite3_free(lockProxy); + tdsqlite3_free(lockProxy); } - sqlite3_free(oldPath); - pCtx->lockProxyPath = sqlite3DbStrDup(0, path); + tdsqlite3_free(oldPath); + pCtx->lockProxyPath = tdsqlite3DbStrDup(0, path); } return rc; @@ -40367,7 +45102,7 @@ static int proxyTransformUnixFile(unixFile *pFile, const char *path) { OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h, (lockPath ? lockPath : ":auto:"), osGetpid(0))); - pCtx = sqlite3_malloc64( sizeof(*pCtx) ); + pCtx = tdsqlite3_malloc64( sizeof(*pCtx) ); if( pCtx==0 ){ return SQLITE_NOMEM_BKPT; } @@ -40399,11 +45134,11 @@ static int proxyTransformUnixFile(unixFile *pFile, const char *path) { } } if( rc==SQLITE_OK && lockPath ){ - pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); + pCtx->lockProxyPath = tdsqlite3DbStrDup(0, lockPath); } if( rc==SQLITE_OK ){ - pCtx->dbPath = sqlite3DbStrDup(0, dbPath); + pCtx->dbPath = tdsqlite3DbStrDup(0, dbPath); if( pCtx->dbPath==NULL ){ rc = SQLITE_NOMEM_BKPT; } @@ -40418,12 +45153,12 @@ static int proxyTransformUnixFile(unixFile *pFile, const char *path) { pFile->pMethod = &proxyIoMethods; }else{ if( pCtx->conchFile ){ - pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); - sqlite3_free(pCtx->conchFile); + pCtx->conchFile->pMethod->xClose((tdsqlite3_file *)pCtx->conchFile); + tdsqlite3_free(pCtx->conchFile); } - sqlite3DbFree(0, pCtx->lockProxyPath); - sqlite3_free(pCtx->conchFilePath); - sqlite3_free(pCtx); + tdsqlite3DbFree(0, pCtx->lockProxyPath); + tdsqlite3_free(pCtx->conchFilePath); + tdsqlite3_free(pCtx); } OSTRACE(("TRANSPROXY %d %s\n", pFile->h, (rc==SQLITE_OK ? "ok" : "failed"))); @@ -40432,10 +45167,10 @@ static int proxyTransformUnixFile(unixFile *pFile, const char *path) { /* -** This routine handles sqlite3_file_control() calls that are specific +** This routine handles tdsqlite3_file_control() calls that are specific ** to proxy locking. */ -static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ +static int proxyFileControl(tdsqlite3_file *id, int op, void *pArg){ switch( op ){ case SQLITE_FCNTL_GET_LOCKPROXYFILE: { unixFile *pFile = (unixFile*)id; @@ -40491,14 +45226,14 @@ static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ assert( 0 ); /* The call assures that only valid opcodes are sent */ } } - /*NOTREACHED*/ + /*NOTREACHED*/ assert(0); return SQLITE_ERROR; } /* ** Within this division (the proxying locking implementation) the procedures ** above this point are all utilities. The lock-related methods of the -** proxy-locking sqlite3_io_method object follow. +** proxy-locking tdsqlite3_io_method object follow. */ @@ -40508,14 +45243,14 @@ static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ ** to a non-zero value otherwise *pResOut is set to zero. The return value ** is set to SQLITE_OK unless an I/O error occurs during lock checking. */ -static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { +static int proxyCheckReservedLock(tdsqlite3_file *id, int *pResOut) { unixFile *pFile = (unixFile*)id; int rc = proxyTakeConch(pFile); if( rc==SQLITE_OK ){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld>0 ){ unixFile *proxy = pCtx->lockProxy; - return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); + return proxy->pMethod->xCheckReservedLock((tdsqlite3_file*)proxy, pResOut); }else{ /* conchHeld < 0 is lockless */ pResOut=0; } @@ -40544,17 +45279,17 @@ static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { ** RESERVED -> (PENDING) -> EXCLUSIVE ** PENDING -> EXCLUSIVE ** -** This routine will only increase a lock. Use the sqlite3OsUnlock() +** This routine will only increase a lock. Use the tdsqlite3OsUnlock() ** routine to lower a locking level. */ -static int proxyLock(sqlite3_file *id, int eFileLock) { +static int proxyLock(tdsqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; int rc = proxyTakeConch(pFile); if( rc==SQLITE_OK ){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld>0 ){ unixFile *proxy = pCtx->lockProxy; - rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock); + rc = proxy->pMethod->xLock((tdsqlite3_file*)proxy, eFileLock); pFile->eFileLock = proxy->eFileLock; }else{ /* conchHeld < 0 is lockless */ @@ -40571,14 +45306,14 @@ static int proxyLock(sqlite3_file *id, int eFileLock) { ** If the locking level of the file descriptor is already at or below ** the requested locking level, this routine is a no-op. */ -static int proxyUnlock(sqlite3_file *id, int eFileLock) { +static int proxyUnlock(tdsqlite3_file *id, int eFileLock) { unixFile *pFile = (unixFile*)id; int rc = proxyTakeConch(pFile); if( rc==SQLITE_OK ){ proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; if( pCtx->conchHeld>0 ){ unixFile *proxy = pCtx->lockProxy; - rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock); + rc = proxy->pMethod->xUnlock((tdsqlite3_file*)proxy, eFileLock); pFile->eFileLock = proxy->eFileLock; }else{ /* conchHeld < 0 is lockless */ @@ -40590,7 +45325,7 @@ static int proxyUnlock(sqlite3_file *id, int eFileLock) { /* ** Close a file that uses proxy locks. */ -static int proxyClose(sqlite3_file *id) { +static int proxyClose(tdsqlite3_file *id) { if( ALWAYS(id) ){ unixFile *pFile = (unixFile*)id; proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; @@ -40599,11 +45334,11 @@ static int proxyClose(sqlite3_file *id) { int rc = SQLITE_OK; if( lockProxy ){ - rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK); + rc = lockProxy->pMethod->xUnlock((tdsqlite3_file*)lockProxy, NO_LOCK); if( rc ) return rc; - rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy); + rc = lockProxy->pMethod->xClose((tdsqlite3_file*)lockProxy); if( rc ) return rc; - sqlite3_free(lockProxy); + tdsqlite3_free(lockProxy); pCtx->lockProxy = 0; } if( conchFile ){ @@ -40611,17 +45346,17 @@ static int proxyClose(sqlite3_file *id) { rc = proxyReleaseConch(pFile); if( rc ) return rc; } - rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile); + rc = conchFile->pMethod->xClose((tdsqlite3_file*)conchFile); if( rc ) return rc; - sqlite3_free(conchFile); + tdsqlite3_free(conchFile); } - sqlite3DbFree(0, pCtx->lockProxyPath); - sqlite3_free(pCtx->conchFilePath); - sqlite3DbFree(0, pCtx->dbPath); + tdsqlite3DbFree(0, pCtx->lockProxyPath); + tdsqlite3_free(pCtx->conchFilePath); + tdsqlite3DbFree(0, pCtx->dbPath); /* restore the original locking context and pMethod then close it */ pFile->lockingContext = pCtx->oldLockingContext; pFile->pMethod = pCtx->pOldMethod; - sqlite3_free(pCtx); + tdsqlite3_free(pCtx); return pFile->pMethod->xClose(id); } return SQLITE_OK; @@ -40643,7 +45378,7 @@ static int proxyClose(sqlite3_file *id) { ** Initialize the operating system interface. ** ** This routine registers all VFS implementations for unix-like operating -** systems. This routine, and the sqlite3_os_end() routine that follows, +** systems. This routine, and the tdsqlite3_os_end() routine that follows, ** should be the only routines in this file that are visible from other ** files. ** @@ -40652,9 +45387,9 @@ static int proxyClose(sqlite3_file *id) { ** necessarily been initialized when this routine is called, and so they ** should not be used. */ -SQLITE_API int sqlite3_os_init(void){ +SQLITE_API int tdsqlite3_os_init(void){ /* - ** The following macro defines an initializer for an sqlite3_vfs object. + ** The following macro defines an initializer for an tdsqlite3_vfs object. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer ** to the "finder" function. (pAppData is a pointer to a pointer because ** silly C90 rules prohibit a void* from being cast to a function pointer @@ -40667,7 +45402,7 @@ SQLITE_API int sqlite3_os_init(void){ ** behaviors. See the division above that contains the IOMETHODS ** macro for addition information on finder-functions. ** - ** Most finders simply return a pointer to a fixed sqlite3_io_methods + ** Most finders simply return a pointer to a fixed tdsqlite3_io_methods ** object. But the "autolockIoFinder" available on MacOSX does a little ** more than that; it looks at the filesystem type that hosts the ** database file and tries to choose an locking method appropriate for @@ -40701,11 +45436,11 @@ SQLITE_API int sqlite3_os_init(void){ /* ** All default VFSes for unix are contained in the following array. ** - ** Note that the sqlite3_vfs.pNext field of the VFS object is modified + ** Note that the tdsqlite3_vfs.pNext field of the VFS object is modified ** by the SQLite core when the VFS is registered. So the following ** array cannot be const. */ - static sqlite3_vfs aVfs[] = { + static tdsqlite3_vfs aVfs[] = { #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) UNIXVFS("unix", autolockIoFinder ), #elif OS_VXWORKS @@ -40735,12 +45470,13 @@ SQLITE_API int sqlite3_os_init(void){ /* Double-check that the aSyscall[] array has been constructed ** correctly. See ticket [bb3a86e890c8e96ab] */ - assert( ArraySize(aSyscall)==28 ); + assert( ArraySize(aSyscall)==29 ); /* Register all VFSes defined in the aVfs[] array */ - for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ - sqlite3_vfs_register(&aVfs[i], i==0); + for(i=0; i<(sizeof(aVfs)/sizeof(tdsqlite3_vfs)); i++){ + tdsqlite3_vfs_register(&aVfs[i], i==0); } + unixBigLock = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1); return SQLITE_OK; } @@ -40751,7 +45487,8 @@ SQLITE_API int sqlite3_os_init(void){ ** to release dynamically allocated objects. But not on unix. ** This routine is a no-op for unix. */ -SQLITE_API int sqlite3_os_end(void){ +SQLITE_API int tdsqlite3_os_end(void){ + unixBigLock = 0; return SQLITE_OK; } @@ -40837,7 +45574,7 @@ SQLITE_API int sqlite3_os_end(void){ ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" -** counters for x86 class CPUs. +** counters for x86 and x86_64 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H @@ -40848,12 +45585,13 @@ SQLITE_API int sqlite3_os_end(void){ ** processor and returns that value. This can be used for high-res ** profiling. */ -#if (defined(__GNUC__) || defined(_MSC_VER)) && \ - (defined(i386) || defined(__i386__) || defined(_M_IX86)) +#if !defined(__STRICT_ANSI__) && \ + (defined(__GNUC__) || defined(_MSC_VER)) && \ + (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; @@ -40861,7 +45599,7 @@ SQLITE_API int sqlite3_os_end(void){ #elif defined(_MSC_VER) - __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ + __declspec(naked) __inline sqlite_uint64 __cdecl tdsqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX @@ -40870,17 +45608,17 @@ SQLITE_API int sqlite3_os_end(void){ #endif -#elif (defined(__GNUC__) && defined(__x86_64__)) +#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__)) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } -#elif (defined(__GNUC__) && defined(__ppc__)) +#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__)) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ @@ -40895,16 +45633,15 @@ SQLITE_API int sqlite3_os_end(void){ #else - #error Need implementation of sqlite3Hwtime() for your platform. - /* - ** To compile without implementing sqlite3Hwtime() for your platform, - ** you can remove the above #error and use the following - ** stub function. You will lose timing support for many - ** of the debugging and testing utilities, but it should at - ** least compile and run. + ** asm() is needed for hardware timing support. Without asm(), + ** disable the tdsqlite3Hwtime() routine. + ** + ** tdsqlite3Hwtime() is only used for some obscure debugging + ** and analysis configurations, not in any deliverable, so this + ** should not be a great loss. */ -SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } +SQLITE_PRIVATE sqlite_uint64 tdsqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif @@ -40915,8 +45652,8 @@ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } static sqlite_uint64 g_start; static sqlite_uint64 g_elapsed; -#define TIMER_START g_start=sqlite3Hwtime() -#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start +#define TIMER_START g_start=tdsqlite3Hwtime() +#define TIMER_END g_elapsed=tdsqlite3Hwtime()-g_start #define TIMER_ELAPSED g_elapsed #else #define TIMER_START @@ -40930,32 +45667,32 @@ static sqlite_uint64 g_elapsed; ** is used for testing the I/O recovery logic. */ #if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_io_error_hit; -SQLITE_API extern int sqlite3_io_error_hardhit; -SQLITE_API extern int sqlite3_io_error_pending; -SQLITE_API extern int sqlite3_io_error_persist; -SQLITE_API extern int sqlite3_io_error_benign; -SQLITE_API extern int sqlite3_diskfull_pending; -SQLITE_API extern int sqlite3_diskfull; -#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) +SQLITE_API extern int tdsqlite3_io_error_hit; +SQLITE_API extern int tdsqlite3_io_error_hardhit; +SQLITE_API extern int tdsqlite3_io_error_pending; +SQLITE_API extern int tdsqlite3_io_error_persist; +SQLITE_API extern int tdsqlite3_io_error_benign; +SQLITE_API extern int tdsqlite3_diskfull_pending; +SQLITE_API extern int tdsqlite3_diskfull; +#define SimulateIOErrorBenign(X) tdsqlite3_io_error_benign=(X) #define SimulateIOError(CODE) \ - if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ - || sqlite3_io_error_pending-- == 1 ) \ + if( (tdsqlite3_io_error_persist && tdsqlite3_io_error_hit) \ + || tdsqlite3_io_error_pending-- == 1 ) \ { local_ioerr(); CODE; } static void local_ioerr(){ IOTRACE(("IOERR\n")); - sqlite3_io_error_hit++; - if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; + tdsqlite3_io_error_hit++; + if( !tdsqlite3_io_error_benign ) tdsqlite3_io_error_hardhit++; } #define SimulateDiskfullError(CODE) \ - if( sqlite3_diskfull_pending ){ \ - if( sqlite3_diskfull_pending == 1 ){ \ + if( tdsqlite3_diskfull_pending ){ \ + if( tdsqlite3_diskfull_pending == 1 ){ \ local_ioerr(); \ - sqlite3_diskfull = 1; \ - sqlite3_io_error_hit = 1; \ + tdsqlite3_diskfull = 1; \ + tdsqlite3_io_error_hit = 1; \ CODE; \ }else{ \ - sqlite3_diskfull_pending--; \ + tdsqlite3_diskfull_pending--; \ } \ } #else @@ -40968,8 +45705,8 @@ static void local_ioerr(){ ** When testing, keep a count of the number of open files. */ #if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_open_file_count; -#define OpenCounter(X) sqlite3_open_file_count+=(X) +SQLITE_API extern int tdsqlite3_open_file_count; +#define OpenCounter(X) tdsqlite3_open_file_count+=(X) #else #define OpenCounter(X) #endif /* defined(SQLITE_TEST) */ @@ -41215,13 +45952,13 @@ typedef struct winceLock { #endif /* -** The winFile structure is a subclass of sqlite3_file* specific to the win32 +** The winFile structure is a subclass of tdsqlite3_file* specific to the win32 ** portability layer. */ typedef struct winFile winFile; struct winFile { - const sqlite3_io_methods *pMethod; /*** Must be first ***/ - sqlite3_vfs *pVfs; /* The VFS used to open this file */ + const tdsqlite3_io_methods *pMethod; /*** Must be first ***/ + tdsqlite3_vfs *pVfs; /* The VFS used to open this file */ HANDLE h; /* Handle for accessing the file */ u8 locktype; /* Type of lock currently held on this file */ short sharedLockByte; /* Randomly chosen byte used as a shared lock */ @@ -41243,9 +45980,8 @@ struct winFile { int nFetchOut; /* Number of outstanding xFetch references */ HANDLE hMap; /* Handle for accessing memory mapping */ void *pMapRegion; /* Area memory mapped */ - sqlite3_int64 mmapSize; /* Usable size of mapped region */ - sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */ - sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ + tdsqlite3_int64 mmapSize; /* Size of mapped region */ + tdsqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ #endif }; @@ -41255,7 +45991,7 @@ struct winFile { */ typedef struct winVfsAppData winVfsAppData; struct winVfsAppData { - const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */ + const tdsqlite3_io_methods *pMethod; /* The file I/O methods to use. */ void *pAppData; /* The extra pAppData, if any. */ BOOL bNoLock; /* Non-zero if locking is disabled. */ }; @@ -41268,29 +46004,13 @@ struct winVfsAppData { #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ /* - * The size of the buffer used by sqlite3_win32_write_debug(). + * The size of the buffer used by tdsqlite3_win32_write_debug(). */ #ifndef SQLITE_WIN32_DBG_BUF_SIZE # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD))) #endif /* - * The value used with sqlite3_win32_set_directory() to specify that - * the data directory should be changed. - */ -#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE -# define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1) -#endif - -/* - * The value used with sqlite3_win32_set_directory() to specify that - * the temporary directory should be changed. - */ -#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE -# define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2) -#endif - -/* * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the * various Win32 API heap functions instead of our own. */ @@ -41304,14 +46024,41 @@ struct winVfsAppData { * ****************************************************************************** * WARNING: It is important to note that when this setting is non-zero and the - * winMemShutdown function is called (e.g. by the sqlite3_shutdown + * winMemShutdown function is called (e.g. by the tdsqlite3_shutdown * function), all data that was allocated using the isolated heap will * be freed immediately and any attempt to access any of that freed * data will almost certainly result in an immediate access violation. ****************************************************************************** */ #ifndef SQLITE_WIN32_HEAP_CREATE -# define SQLITE_WIN32_HEAP_CREATE (TRUE) +# define SQLITE_WIN32_HEAP_CREATE (TRUE) +#endif + +/* + * This is the maximum possible initial size of the Win32-specific heap, in + * bytes. + */ +#ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE +# define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U) +#endif + +/* + * This is the extra space for the initial size of the Win32-specific heap, + * in bytes. This value may be zero. + */ +#ifndef SQLITE_WIN32_HEAP_INIT_EXTRA +# define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304) +#endif + +/* + * Calculate the maximum legal cache size, in pages, based on the maximum + * possible initial heap size and the default page size, setting aside the + * needed extra space. + */ +#ifndef SQLITE_WIN32_MAX_CACHE_SIZE +# define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \ + (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \ + (SQLITE_DEFAULT_PAGE_SIZE)) #endif /* @@ -41320,25 +46067,36 @@ struct winVfsAppData { */ #ifndef SQLITE_WIN32_CACHE_SIZE # if SQLITE_DEFAULT_CACHE_SIZE>=0 -# define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE) +# define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE) # else -# define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE)) +# define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE)) # endif #endif /* + * Make sure that the calculated cache size, in pages, cannot cause the + * initial size of the Win32-specific heap to exceed the maximum amount + * of memory that can be specified in the call to HeapCreate. + */ +#if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE +# undef SQLITE_WIN32_CACHE_SIZE +# define SQLITE_WIN32_CACHE_SIZE (2000) +#endif + +/* * The initial size of the Win32-specific heap. This value may be zero. */ #ifndef SQLITE_WIN32_HEAP_INIT_SIZE -# define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \ - (SQLITE_DEFAULT_PAGE_SIZE) + 4194304) +# define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \ + (SQLITE_DEFAULT_PAGE_SIZE) + \ + (SQLITE_WIN32_HEAP_INIT_EXTRA)) #endif /* * The maximum size of the Win32-specific heap. This value may be zero. */ #ifndef SQLITE_WIN32_HEAP_MAX_SIZE -# define SQLITE_WIN32_HEAP_MAX_SIZE (0) +# define SQLITE_WIN32_HEAP_MAX_SIZE (0) #endif /* @@ -41346,13 +46104,13 @@ struct winVfsAppData { * zero for the default behavior. */ #ifndef SQLITE_WIN32_HEAP_FLAGS -# define SQLITE_WIN32_HEAP_FLAGS (0) +# define SQLITE_WIN32_HEAP_FLAGS (0) #endif /* ** The winMemData structure stores information required by the Win32-specific -** sqlite3_mem_methods implementation. +** tdsqlite3_mem_methods implementation. */ typedef struct winMemData winMemData; struct winMemData { @@ -41401,7 +46159,7 @@ static int winMemRoundup(int n); static int winMemInit(void *pAppData); static void winMemShutdown(void *pAppData); -SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void); +SQLITE_PRIVATE const tdsqlite3_mem_methods *tdsqlite3MemGetWin32(void); #endif /* SQLITE_WIN32_MALLOC */ /* @@ -41417,13 +46175,13 @@ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void); ** can manually set this value to 1 to emulate Win98 behavior. */ #ifdef SQLITE_TEST -SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; +SQLITE_API LONG SQLITE_WIN32_VOLATILE tdsqlite3_os_type = 0; #else -static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; +static LONG SQLITE_WIN32_VOLATILE tdsqlite3_os_type = 0; #endif #ifndef SYSCALL -# define SYSCALL sqlite3_syscall_ptr +# define SYSCALL tdsqlite3_syscall_ptr #endif /* @@ -41442,8 +46200,8 @@ static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; */ static struct win_syscall { const char *zName; /* Name of the system call */ - sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ - sqlite3_syscall_ptr pDefault; /* Default value */ + tdsqlite3_syscall_ptr pCurrent; /* Current value of the system call */ + tdsqlite3_syscall_ptr pDefault; /* Default value */ } aSyscall[] = { #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 }, @@ -42096,15 +46854,15 @@ static struct win_syscall { }; /* End of the overrideable system calls */ /* -** This is the xSetSystemCall() method of sqlite3_vfs for all of the +** This is the xSetSystemCall() method of tdsqlite3_vfs for all of the ** "win32" VFSes. Return SQLITE_OK opon successfully updating the ** system call pointer, or SQLITE_NOTFOUND if there is no configurable ** system call named zName. */ static int winSetSystemCall( - sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ + tdsqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ const char *zName, /* Name of system call to override */ - sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ + tdsqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ ){ unsigned int i; int rc = SQLITE_NOTFOUND; @@ -42144,8 +46902,8 @@ static int winSetSystemCall( ** recognized system call name. NULL is also returned if the system call ** is currently undefined. */ -static sqlite3_syscall_ptr winGetSystemCall( - sqlite3_vfs *pNotUsed, +static tdsqlite3_syscall_ptr winGetSystemCall( + tdsqlite3_vfs *pNotUsed, const char *zName ){ unsigned int i; @@ -42163,7 +46921,7 @@ static sqlite3_syscall_ptr winGetSystemCall( ** is the last system call or if zName is not the name of a valid ** system call. */ -static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){ +static const char *winNextSystemCall(tdsqlite3_vfs *p, const char *zName){ int i = -1; UNUSED_PARAMETER(p); @@ -42186,7 +46944,7 @@ static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){ ** "pnLargest" argument, if non-zero, will be used to return the size of the ** largest committed free block in the heap, in bytes. */ -SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){ +SQLITE_API int tdsqlite3_win32_compact_heap(LPUINT pnLargest){ int rc = SQLITE_OK; UINT nLargest = 0; HANDLE hHeap; @@ -42202,17 +46960,17 @@ SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){ if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){ DWORD lastErrno = osGetLastError(); if( lastErrno==NO_ERROR ){ - sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p", + tdsqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p", (void*)hHeap); rc = SQLITE_NOMEM_BKPT; }else{ - sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p", + tdsqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p", osGetLastError(), (void*)hHeap); rc = SQLITE_ERROR; } } #else - sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p", + tdsqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p", (void*)hHeap); rc = SQLITE_NOTFOUND; #endif @@ -42223,19 +46981,19 @@ SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){ /* ** If a Win32 native heap has been configured, this function will attempt to ** destroy and recreate it. If the Win32 native heap is not isolated and/or -** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will +** the tdsqlite3_memory_used() function does not return zero, SQLITE_BUSY will ** be returned and no changes will be made to the Win32 native heap. */ -SQLITE_API int sqlite3_win32_reset_heap(){ +SQLITE_API int tdsqlite3_win32_reset_heap(){ int rc; - MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ - MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */ - MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) - MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); ) - sqlite3_mutex_enter(pMaster); - sqlite3_mutex_enter(pMem); + MUTEX_LOGIC( tdsqlite3_mutex *pMaster; ) /* The main static mutex */ + MUTEX_LOGIC( tdsqlite3_mutex *pMem; ) /* The memsys static mutex */ + MUTEX_LOGIC( pMaster = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + MUTEX_LOGIC( pMem = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); ) + tdsqlite3_mutex_enter(pMaster); + tdsqlite3_mutex_enter(pMem); winMemAssertMagic(); - if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){ + if( winMemGetHeap()!=NULL && winMemGetOwned() && tdsqlite3_memory_used()==0 ){ /* ** At this point, there should be no outstanding memory allocations on ** the heap. Also, since both the master and memsys locks are currently @@ -42245,23 +47003,23 @@ SQLITE_API int sqlite3_win32_reset_heap(){ */ assert( winMemGetHeap()!=NULL ); assert( winMemGetOwned() ); - assert( sqlite3_memory_used()==0 ); + assert( tdsqlite3_memory_used()==0 ); winMemShutdown(winMemGetDataPtr()); assert( winMemGetHeap()==NULL ); assert( !winMemGetOwned() ); - assert( sqlite3_memory_used()==0 ); + assert( tdsqlite3_memory_used()==0 ); rc = winMemInit(winMemGetDataPtr()); assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL ); assert( rc!=SQLITE_OK || winMemGetOwned() ); - assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 ); + assert( rc!=SQLITE_OK || tdsqlite3_memory_used()==0 ); }else{ /* ** The Win32 native heap cannot be modified because it may be in use. */ rc = SQLITE_BUSY; } - sqlite3_mutex_leave(pMem); - sqlite3_mutex_leave(pMaster); + tdsqlite3_mutex_leave(pMem); + tdsqlite3_mutex_leave(pMaster); return rc; } #endif /* SQLITE_WIN32_MALLOC */ @@ -42271,7 +47029,7 @@ SQLITE_API int sqlite3_win32_reset_heap(){ ** (if available). */ -SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){ +SQLITE_API void tdsqlite3_win32_write_debug(const char *zBuf, int nBuf){ char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE]; int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */ if( nMin<-1 ) nMin = -1; /* all negative values become -1. */ @@ -42317,7 +47075,7 @@ SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){ static HANDLE sleepObj = NULL; #endif -SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){ +SQLITE_API void tdsqlite3_win32_sleep(DWORD milliseconds){ #if SQLITE_OS_WINRT if ( sleepObj==NULL ){ sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET, @@ -42332,7 +47090,7 @@ SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){ #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ SQLITE_THREADSAFE>0 -SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){ +SQLITE_PRIVATE DWORD tdsqlite3Win32Wait(HANDLE hObject){ DWORD rc; while( (rc = osWaitForSingleObjectEx(hObject, INFINITE, TRUE))==WAIT_IO_COMPLETION ){} @@ -42359,14 +47117,14 @@ SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){ #elif !defined(SQLITE_WIN32_HAS_WIDE) # define osIsNT() (0) #else -# define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt()) +# define osIsNT() ((tdsqlite3_os_type==2) || tdsqlite3_win32_is_nt()) #endif /* ** This function determines if the machine is running a version of Windows ** based on the NT kernel. */ -SQLITE_API int sqlite3_win32_is_nt(void){ +SQLITE_API int tdsqlite3_win32_is_nt(void){ #if SQLITE_OS_WINRT /* ** NOTE: The WinRT sub-platform is always assumed to be based on the NT @@ -42374,24 +47132,24 @@ SQLITE_API int sqlite3_win32_is_nt(void){ */ return 1; #elif SQLITE_WIN32_GETVERSIONEX - if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){ + if( osInterlockedCompareExchange(&tdsqlite3_os_type, 0, 0)==0 ){ #if defined(SQLITE_WIN32_HAS_ANSI) OSVERSIONINFOA sInfo; sInfo.dwOSVersionInfoSize = sizeof(sInfo); osGetVersionExA(&sInfo); - osInterlockedCompareExchange(&sqlite3_os_type, + osInterlockedCompareExchange(&tdsqlite3_os_type, (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); #elif defined(SQLITE_WIN32_HAS_WIDE) OSVERSIONINFOW sInfo; sInfo.dwOSVersionInfoSize = sizeof(sInfo); osGetVersionExW(&sInfo); - osInterlockedCompareExchange(&sqlite3_os_type, + osInterlockedCompareExchange(&tdsqlite3_os_type, (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); #endif } - return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2; + return osInterlockedCompareExchange(&tdsqlite3_os_type, 2, 2)==2; #elif SQLITE_TEST - return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2; + return osInterlockedCompareExchange(&tdsqlite3_os_type, 2, 2)==2; #else /* ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are @@ -42419,7 +47177,7 @@ static void *winMemMalloc(int nBytes){ assert( nBytes>=0 ); p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); if( !p ){ - sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p", + tdsqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p", nBytes, osGetLastError(), (void*)hHeap); } return p; @@ -42440,7 +47198,7 @@ static void winMemFree(void *pPrior){ #endif if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */ if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){ - sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p", + tdsqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p", pPrior, osGetLastError(), (void*)hHeap); } } @@ -42466,7 +47224,7 @@ static void *winMemRealloc(void *pPrior, int nBytes){ p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes); } if( !p ){ - sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p", + tdsqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p", pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(), (void*)hHeap); } @@ -42490,7 +47248,7 @@ static int winMemSize(void *p){ if( !p ) return 0; n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p); if( n==(SIZE_T)-1 ){ - sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p", + tdsqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p", p, osGetLastError(), (void*)hHeap); return 0; } @@ -42517,7 +47275,7 @@ static int winMemInit(void *pAppData){ #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE if( !pWinMemData->hHeap ){ DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE; - DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap; + DWORD dwMaximumSize = (DWORD)tdsqlite3GlobalConfig.nHeap; if( dwMaximumSize==0 ){ dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE; }else if( dwInitialSize>dwMaximumSize ){ @@ -42526,7 +47284,7 @@ static int winMemInit(void *pAppData){ pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS, dwInitialSize, dwMaximumSize); if( !pWinMemData->hHeap ){ - sqlite3_log(SQLITE_NOMEM, + tdsqlite3_log(SQLITE_NOMEM, "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu", osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize, dwMaximumSize); @@ -42538,7 +47296,7 @@ static int winMemInit(void *pAppData){ #else pWinMemData->hHeap = osGetProcessHeap(); if( !pWinMemData->hHeap ){ - sqlite3_log(SQLITE_NOMEM, + tdsqlite3_log(SQLITE_NOMEM, "failed to GetProcessHeap (%lu)", osGetLastError()); return SQLITE_NOMEM_BKPT; } @@ -42570,7 +47328,7 @@ static void winMemShutdown(void *pAppData){ #endif if( pWinMemData->bOwned ){ if( !osHeapDestroy(pWinMemData->hHeap) ){ - sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p", + tdsqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p", osGetLastError(), (void*)pWinMemData->hHeap); } pWinMemData->bOwned = FALSE; @@ -42581,14 +47339,14 @@ static void winMemShutdown(void *pAppData){ /* ** Populate the low-level memory allocation function pointers in -** sqlite3GlobalConfig.m with pointers to the routines in this file. The +** tdsqlite3GlobalConfig.m with pointers to the routines in this file. The ** arguments specify the block of memory to manage. ** -** This routine is only called by sqlite3_config(), and therefore +** This routine is only called by tdsqlite3_config(), and therefore ** is not required to be threadsafe (it is not). */ -SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){ - static const sqlite3_mem_methods winMemMethods = { +SQLITE_PRIVATE const tdsqlite3_mem_methods *tdsqlite3MemGetWin32(void){ + static const tdsqlite3_mem_methods winMemMethods = { winMemMalloc, winMemFree, winMemRealloc, @@ -42601,15 +47359,15 @@ SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){ return &winMemMethods; } -SQLITE_PRIVATE void sqlite3MemSetDefault(void){ - sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32()); +SQLITE_PRIVATE void tdsqlite3MemSetDefault(void){ + tdsqlite3_config(SQLITE_CONFIG_MALLOC, tdsqlite3MemGetWin32()); } #endif /* SQLITE_WIN32_MALLOC */ /* ** Convert a UTF-8 string to Microsoft Unicode. ** -** Space to hold the returned string is obtained from sqlite3_malloc(). +** Space to hold the returned string is obtained from tdsqlite3_malloc(). */ static LPWSTR winUtf8ToUnicode(const char *zText){ int nChar; @@ -42619,14 +47377,14 @@ static LPWSTR winUtf8ToUnicode(const char *zText){ if( nChar==0 ){ return 0; } - zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) ); + zWideText = tdsqlite3MallocZero( nChar*sizeof(WCHAR) ); if( zWideText==0 ){ return 0; } nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText, nChar); if( nChar==0 ){ - sqlite3_free(zWideText); + tdsqlite3_free(zWideText); zWideText = 0; } return zWideText; @@ -42635,7 +47393,7 @@ static LPWSTR winUtf8ToUnicode(const char *zText){ /* ** Convert a Microsoft Unicode string to UTF-8. ** -** Space to hold the returned string is obtained from sqlite3_malloc(). +** Space to hold the returned string is obtained from tdsqlite3_malloc(). */ static char *winUnicodeToUtf8(LPCWSTR zWideText){ int nByte; @@ -42645,14 +47403,14 @@ static char *winUnicodeToUtf8(LPCWSTR zWideText){ if( nByte == 0 ){ return 0; } - zText = sqlite3MallocZero( nByte ); + zText = tdsqlite3MallocZero( nByte ); if( zText==0 ){ return 0; } nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte, 0, 0); if( nByte == 0 ){ - sqlite3_free(zText); + tdsqlite3_free(zText); zText = 0; } return zText; @@ -42662,7 +47420,7 @@ static char *winUnicodeToUtf8(LPCWSTR zWideText){ ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM ** code page. ** -** Space to hold the returned string is obtained from sqlite3_malloc(). +** Space to hold the returned string is obtained from tdsqlite3_malloc(). */ static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){ int nByte; @@ -42674,14 +47432,14 @@ static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){ if( nByte==0 ){ return 0; } - zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) ); + zMbcsText = tdsqlite3MallocZero( nByte*sizeof(WCHAR) ); if( zMbcsText==0 ){ return 0; } nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText, nByte); if( nByte==0 ){ - sqlite3_free(zMbcsText); + tdsqlite3_free(zMbcsText); zMbcsText = 0; } return zMbcsText; @@ -42691,7 +47449,7 @@ static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){ ** Convert a Microsoft Unicode string to a multi-byte character string, ** using the ANSI or OEM code page. ** -** Space to hold the returned string is obtained from sqlite3_malloc(). +** Space to hold the returned string is obtained from tdsqlite3_malloc(). */ static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){ int nByte; @@ -42702,14 +47460,14 @@ static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){ if( nByte == 0 ){ return 0; } - zText = sqlite3MallocZero( nByte ); + zText = tdsqlite3MallocZero( nByte ); if( zText==0 ){ return 0; } nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText, nByte, 0, 0); if( nByte == 0 ){ - sqlite3_free(zText); + tdsqlite3_free(zText); zText = 0; } return zText; @@ -42718,7 +47476,7 @@ static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){ /* ** Convert a multi-byte character string to UTF-8. ** -** Space to hold the returned string is obtained from sqlite3_malloc(). +** Space to hold the returned string is obtained from tdsqlite3_malloc(). */ static char *winMbcsToUtf8(const char *zText, int useAnsi){ char *zTextUtf8; @@ -42729,14 +47487,14 @@ static char *winMbcsToUtf8(const char *zText, int useAnsi){ return 0; } zTextUtf8 = winUnicodeToUtf8(zTmpWide); - sqlite3_free(zTmpWide); + tdsqlite3_free(zTmpWide); return zTextUtf8; } /* ** Convert a UTF-8 string to a multi-byte character string. ** -** Space to hold the returned string is obtained from sqlite3_malloc(). +** Space to hold the returned string is obtained from tdsqlite3_malloc(). */ static char *winUtf8ToMbcs(const char *zText, int useAnsi){ char *zTextMbcs; @@ -42747,14 +47505,14 @@ static char *winUtf8ToMbcs(const char *zText, int useAnsi){ return 0; } zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi); - sqlite3_free(zTmpWide); + tdsqlite3_free(zTmpWide); return zTextMbcs; } /* ** This is a public wrapper for the winUtf8ToUnicode() function. */ -SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){ +SQLITE_API LPWSTR tdsqlite3_win32_utf8_to_unicode(const char *zText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; @@ -42762,7 +47520,7 @@ SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){ } #endif #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif return winUtf8ToUnicode(zText); } @@ -42770,7 +47528,7 @@ SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){ /* ** This is a public wrapper for the winUnicodeToUtf8() function. */ -SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){ +SQLITE_API char *tdsqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zWideText ){ (void)SQLITE_MISUSE_BKPT; @@ -42778,7 +47536,7 @@ SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){ } #endif #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif return winUnicodeToUtf8(zWideText); } @@ -42786,7 +47544,7 @@ SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){ /* ** This is a public wrapper for the winMbcsToUtf8() function. */ -SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){ +SQLITE_API char *tdsqlite3_win32_mbcs_to_utf8(const char *zText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; @@ -42794,7 +47552,7 @@ SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){ } #endif #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif return winMbcsToUtf8(zText, osAreFileApisANSI()); } @@ -42802,7 +47560,7 @@ SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){ /* ** This is a public wrapper for the winMbcsToUtf8() function. */ -SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){ +SQLITE_API char *tdsqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; @@ -42810,7 +47568,7 @@ SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){ } #endif #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif return winMbcsToUtf8(zText, useAnsi); } @@ -42818,7 +47576,7 @@ SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){ /* ** This is a public wrapper for the winUtf8ToMbcs() function. */ -SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){ +SQLITE_API char *tdsqlite3_win32_utf8_to_mbcs(const char *zText){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; @@ -42826,7 +47584,7 @@ SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){ } #endif #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif return winUtf8ToMbcs(zText, osAreFileApisANSI()); } @@ -42834,7 +47592,7 @@ SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){ /* ** This is a public wrapper for the winUtf8ToMbcs() function. */ -SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){ +SQLITE_API char *tdsqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){ #ifdef SQLITE_ENABLE_API_ARMOR if( !zText ){ (void)SQLITE_MISUSE_BKPT; @@ -42842,49 +47600,82 @@ SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){ } #endif #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; + if( tdsqlite3_initialize() ) return 0; #endif return winUtf8ToMbcs(zText, useAnsi); } /* -** This function sets the data directory or the temporary directory based on -** the provided arguments. The type argument must be 1 in order to set the -** data directory or 2 in order to set the temporary directory. The zValue -** argument is the name of the directory to use. The return value will be -** SQLITE_OK if successful. +** This function is the same as tdsqlite3_win32_set_directory (below); however, +** it accepts a UTF-8 string. */ -SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){ +SQLITE_API int tdsqlite3_win32_set_directory8( + unsigned long type, /* Identifier for directory being set or reset */ + const char *zValue /* New value for directory being set or reset */ +){ char **ppDirectory = 0; #ifndef SQLITE_OMIT_AUTOINIT - int rc = sqlite3_initialize(); + int rc = tdsqlite3_initialize(); if( rc ) return rc; #endif if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){ - ppDirectory = &sqlite3_data_directory; + ppDirectory = &tdsqlite3_data_directory; }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){ - ppDirectory = &sqlite3_temp_directory; + ppDirectory = &tdsqlite3_temp_directory; } assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ); - assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) ); + assert( !ppDirectory || tdsqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) ); if( ppDirectory ){ - char *zValueUtf8 = 0; + char *zCopy = 0; if( zValue && zValue[0] ){ - zValueUtf8 = winUnicodeToUtf8(zValue); - if ( zValueUtf8==0 ){ + zCopy = tdsqlite3_mprintf("%s", zValue); + if ( zCopy==0 ){ return SQLITE_NOMEM_BKPT; } } - sqlite3_free(*ppDirectory); - *ppDirectory = zValueUtf8; + tdsqlite3_free(*ppDirectory); + *ppDirectory = zCopy; return SQLITE_OK; } return SQLITE_ERROR; } /* +** This function is the same as tdsqlite3_win32_set_directory (below); however, +** it accepts a UTF-16 string. +*/ +SQLITE_API int tdsqlite3_win32_set_directory16( + unsigned long type, /* Identifier for directory being set or reset */ + const void *zValue /* New value for directory being set or reset */ +){ + int rc; + char *zUtf8 = 0; + if( zValue ){ + zUtf8 = tdsqlite3_win32_unicode_to_utf8(zValue); + if( zUtf8==0 ) return SQLITE_NOMEM_BKPT; + } + rc = tdsqlite3_win32_set_directory8(type, zUtf8); + if( zUtf8 ) tdsqlite3_free(zUtf8); + return rc; +} + +/* +** This function sets the data directory or the temporary directory based on +** the provided arguments. The type argument must be 1 in order to set the +** data directory or 2 in order to set the temporary directory. The zValue +** argument is the name of the directory to use. The return value will be +** SQLITE_OK if successful. +*/ +SQLITE_API int tdsqlite3_win32_set_directory( + unsigned long type, /* Identifier for directory being set or reset */ + void *zValue /* New value for directory being set or reset */ +){ + return tdsqlite3_win32_set_directory16(type, zValue); +} + +/* ** The return value of winGetLastErrorMsg ** is zero if the error message fits in the buffer, or non-zero ** otherwise (if the message was truncated). @@ -42922,9 +47713,9 @@ static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){ #endif if( dwLen > 0 ){ /* allocate a buffer and convert to UTF8 */ - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); zOut = winUnicodeToUtf8(zTempWide); - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); #if !SQLITE_OS_WINRT /* free the system buffer allocated by FormatMessage */ osLocalFree(zTempWide); @@ -42945,21 +47736,21 @@ static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){ 0); if( dwLen > 0 ){ /* allocate a buffer and convert to UTF8 */ - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); /* free the system buffer allocated by FormatMessage */ osLocalFree(zTemp); } } #endif if( 0 == dwLen ){ - sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno); + tdsqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno); }else{ /* copy a maximum of nBuf chars to output buffer */ - sqlite3_snprintf(nBuf, zBuf, "%s", zOut); + tdsqlite3_snprintf(nBuf, zBuf, "%s", zOut); /* free the UTF8 buffer */ - sqlite3_free(zOut); + tdsqlite3_free(zOut); } return 0; } @@ -42970,7 +47761,7 @@ static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){ ** winLogError(). ** ** This routine is invoked after an error occurs in an OS function. -** It logs a message using sqlite3_log() containing the current value of +** It logs a message using tdsqlite3_log() containing the current value of ** error code and, if possible, the human-readable equivalent from ** FormatMessage. ** @@ -42996,7 +47787,7 @@ static int winLogErrorAtLine( if( zPath==0 ) zPath = ""; for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){} zMsg[i] = 0; - sqlite3_log(errcode, + tdsqlite3_log(errcode, "os_win.c:%d: (%lu) %s(%s) - %s", iLine, lastErrno, zFunc, zPath, zMsg ); @@ -43059,13 +47850,13 @@ static int winRetryIoerr(int *pnRetry, DWORD *pError){ return 0; } if( winIoerrCanRetry1(e) ){ - sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); + tdsqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); ++*pnRetry; return 1; } #if defined(winIoerrCanRetry2) else if( winIoerrCanRetry2(e) ){ - sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); + tdsqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); ++*pnRetry; return 1; } @@ -43081,7 +47872,7 @@ static int winRetryIoerr(int *pnRetry, DWORD *pError){ */ static void winLogIoerr(int nRetry, int lineno){ if( nRetry ){ - sqlite3_log(SQLITE_NOTICE, + tdsqlite3_log(SQLITE_NOTICE, "delayed %dms for lock/sharing conflict at line %d", winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno ); @@ -43104,7 +47895,7 @@ struct tm *__cdecl localtime(const time_t *t) static struct tm y; FILETIME uTm, lTm; SYSTEMTIME pTm; - sqlite3_int64 t64; + tdsqlite3_int64 t64; t64 = *t; t64 = (t64 + 11644473600)*10000000; uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF); @@ -43173,7 +47964,7 @@ static int winceCreateLock(const char *zFilename, winFile *pFile){ pFile->hMutex = osCreateMutexW(NULL, FALSE, zName); if (!pFile->hMutex){ pFile->lastErrno = osGetLastError(); - sqlite3_free(zName); + tdsqlite3_free(zName); return winLogError(SQLITE_IOERR, pFile->lastErrno, "winceCreateLock1", zFilename); } @@ -43197,7 +47988,7 @@ static int winceCreateLock(const char *zFilename, winFile *pFile){ bInit = FALSE; } - sqlite3_free(zName); + tdsqlite3_free(zName); /* If we succeeded in making the shared memory handle, map it. */ if( pFile->hShared ){ @@ -43471,7 +48262,7 @@ static BOOL winUnlockFile( /***************************************************************************** ** The next group of routines implement the I/O methods specified -** by the sqlite3_io_methods object. +** by the tdsqlite3_io_methods object. ******************************************************************************/ /* @@ -43486,7 +48277,7 @@ static BOOL winUnlockFile( ** argument to offset iOffset within the file. If successful, return 0. ** Otherwise, set pFile->lastErrno and return non-zero. */ -static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){ +static int winSeekFile(winFile *pFile, tdsqlite3_int64 iOffset){ #if !SQLITE_OS_WINRT LONG upperBits; /* Most sig. 32 bits of new offset */ LONG lowerBits; /* Least sig. 32 bits of new offset */ @@ -43544,7 +48335,7 @@ static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){ #if SQLITE_MAX_MMAP_SIZE>0 /* Forward references to VFS helper methods used for memory mapped files */ -static int winMapfile(winFile*, sqlite3_int64); +static int winMapfile(winFile*, tdsqlite3_int64); static int winUnmapfile(winFile*); #endif @@ -43559,7 +48350,7 @@ static int winUnmapfile(winFile*); ** giving up and returning an error. */ #define MX_CLOSE_ATTEMPT 3 -static int winClose(sqlite3_file *id){ +static int winClose(tdsqlite3_file *id){ int rc, cnt = 0; winFile *pFile = (winFile*)id; @@ -43578,7 +48369,7 @@ static int winClose(sqlite3_file *id){ do{ rc = osCloseHandle(pFile->h); /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */ - }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) ); + }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (tdsqlite3_win32_sleep(100), 1) ); #if SQLITE_OS_WINCE #define WINCE_DELETION_ATTEMPTS 3 { @@ -43594,9 +48385,9 @@ static int winClose(sqlite3_file *id){ && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff && cnt++ < WINCE_DELETION_ATTEMPTS ){ - sqlite3_win32_sleep(100); /* Wait a little before trying again */ + tdsqlite3_win32_sleep(100); /* Wait a little before trying again */ } - sqlite3_free(pFile->zDeleteOnClose); + tdsqlite3_free(pFile->zDeleteOnClose); } #endif if( rc ){ @@ -43616,10 +48407,10 @@ static int winClose(sqlite3_file *id){ ** wrong. */ static int winRead( - sqlite3_file *id, /* File to read from */ + tdsqlite3_file *id, /* File to read from */ void *pBuf, /* Write content into this buffer */ int amt, /* Number of bytes to read */ - sqlite3_int64 offset /* Begin reading at this offset */ + tdsqlite3_int64 offset /* Begin reading at this offset */ ){ #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) OVERLAPPED overlapped; /* The offset for ReadFile. */ @@ -43696,10 +48487,10 @@ static int winRead( ** or some other error code on failure. */ static int winWrite( - sqlite3_file *id, /* File to write into */ + tdsqlite3_file *id, /* File to write into */ const void *pBuf, /* The bytes to be written */ int amt, /* Number of bytes to write */ - sqlite3_int64 offset /* Offset into the file to begin writing at */ + tdsqlite3_int64 offset /* Offset into the file to begin writing at */ ){ int rc = 0; /* True if error has occurred, else false */ winFile *pFile = (winFile*)id; /* File handle */ @@ -43804,10 +48595,33 @@ static int winWrite( /* ** Truncate an open file to a specified size */ -static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){ +static int winTruncate(tdsqlite3_file *id, tdsqlite3_int64 nByte){ winFile *pFile = (winFile*)id; /* File handle object */ int rc = SQLITE_OK; /* Return code for this function */ DWORD lastErrno; +#if SQLITE_MAX_MMAP_SIZE>0 + tdsqlite3_int64 oldMmapSize; + if( pFile->nFetchOut>0 ){ + /* File truncation is a no-op if there are outstanding memory mapped + ** pages. This is because truncating the file means temporarily unmapping + ** the file, and that might delete memory out from under existing cursors. + ** + ** This can result in incremental vacuum not truncating the file, + ** if there is an active read cursor when the incremental vacuum occurs. + ** No real harm comes of this - the database file is not corrupted, + ** though some folks might complain that the file is bigger than it + ** needs to be. + ** + ** The only feasible work-around is to defer the truncation until after + ** all references to memory-mapped content are closed. That is doable, + ** but involves adding a few branches in the common write code path which + ** could slow down normal operations slightly. Hence, we have decided for + ** now to simply make trancations a no-op if there are pending reads. We + ** can maybe revisit this decision in the future. + */ + return SQLITE_OK; + } +#endif assert( pFile ); SimulateIOError(return SQLITE_IOERR_TRUNCATE); @@ -43823,6 +48637,15 @@ static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){ nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; } +#if SQLITE_MAX_MMAP_SIZE>0 + if( pFile->pMapRegion ){ + oldMmapSize = pFile->mmapSize; + }else{ + oldMmapSize = 0; + } + winUnmapfile(pFile); +#endif + /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */ if( winSeekFile(pFile, nByte) ){ rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno, @@ -43835,17 +48658,17 @@ static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){ } #if SQLITE_MAX_MMAP_SIZE>0 - /* If the file was truncated to a size smaller than the currently - ** mapped region, reduce the effective mapping size as well. SQLite will - ** use read() and write() to access data beyond this point from now on. - */ - if( pFile->pMapRegion && nByte<pFile->mmapSize ){ - pFile->mmapSize = nByte; + if( rc==SQLITE_OK && oldMmapSize>0 ){ + if( oldMmapSize>nByte ){ + winMapfile(pFile, -1); + }else{ + winMapfile(pFile, oldMmapSize); + } } #endif OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n", - osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc))); + osGetCurrentProcessId(), pFile, pFile->h, tdsqlite3ErrName(rc))); return rc; } @@ -43854,14 +48677,14 @@ static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){ ** Count the number of fullsyncs and normal syncs. This is used to test ** that syncs and fullsyncs are occuring at the right times. */ -SQLITE_API int sqlite3_sync_count = 0; -SQLITE_API int sqlite3_fullsync_count = 0; +SQLITE_API int tdsqlite3_sync_count = 0; +SQLITE_API int tdsqlite3_fullsync_count = 0; #endif /* ** Make sure all writes to a particular file are committed to disk. */ -static int winSync(sqlite3_file *id, int flags){ +static int winSync(tdsqlite3_file *id, int flags){ #ifndef SQLITE_NO_SYNC /* ** Used only when SQLITE_NO_SYNC is not defined. @@ -43898,9 +48721,9 @@ static int winSync(sqlite3_file *id, int flags){ UNUSED_PARAMETER(flags); #else if( (flags&0x0F)==SQLITE_SYNC_FULL ){ - sqlite3_fullsync_count++; + tdsqlite3_fullsync_count++; } - sqlite3_sync_count++; + tdsqlite3_sync_count++; #endif /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a @@ -43946,7 +48769,7 @@ static int winSync(sqlite3_file *id, int flags){ /* ** Determine the current size of a file in bytes */ -static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ +static int winFileSize(tdsqlite3_file *id, tdsqlite3_int64 *pSize){ winFile *pFile = (winFile*)id; int rc = SQLITE_OK; @@ -43974,7 +48797,7 @@ static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ DWORD lastErrno; lowerBits = osGetFileSize(pFile->h, &upperBits); - *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; + *pSize = (((tdsqlite3_int64)upperBits)<<32) + lowerBits; if( (lowerBits == INVALID_FILE_SIZE) && ((lastErrno = osGetLastError())!=NO_ERROR) ){ pFile->lastErrno = lastErrno; @@ -43984,7 +48807,7 @@ static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ } #endif OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n", - pFile->h, pSize, *pSize, sqlite3ErrName(rc))); + pFile->h, pSize, *pSize, tdsqlite3ErrName(rc))); return rc; } @@ -44042,7 +48865,7 @@ static int winGetReadLock(winFile *pFile){ #ifdef SQLITE_WIN32_HAS_ANSI else{ int lk; - sqlite3_randomness(sizeof(lk), &lk); + tdsqlite3_randomness(sizeof(lk), &lk); pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1)); res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); @@ -44106,7 +48929,7 @@ static int winUnlockReadLock(winFile *pFile){ ** It is not possible to lower the locking level one step at a time. You ** must go straight to locking level 0. */ -static int winLock(sqlite3_file *id, int locktype){ +static int winLock(tdsqlite3_file *id, int locktype){ int rc = SQLITE_OK; /* Return code from subroutines */ int res = 1; /* Result of a Windows lock call */ int newLocktype; /* Set pFile->locktype to this value before exiting */ @@ -44120,7 +48943,7 @@ static int winLock(sqlite3_file *id, int locktype){ /* If there is already a lock of this type or more restrictive on the ** OsFile, do nothing. Don't use the end_lock: exit path, as - ** sqlite3OsEnterMutex() hasn't been called yet. + ** tdsqlite3OsEnterMutex() hasn't been called yet. */ if( pFile->locktype>=locktype ){ OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h)); @@ -44163,10 +48986,10 @@ static int winLock(sqlite3_file *id, int locktype){ pFile->lastErrno = lastErrno; rc = SQLITE_IOERR_LOCK; OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n", - pFile->h, cnt, sqlite3ErrName(rc))); + pFile->h, cnt, tdsqlite3ErrName(rc))); return rc; } - if( cnt ) sqlite3_win32_sleep(1); + if( cnt ) tdsqlite3_win32_sleep(1); } gotPendingLock = res; if( !res ){ @@ -44240,7 +49063,7 @@ static int winLock(sqlite3_file *id, int locktype){ } pFile->locktype = (u8)newLocktype; OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n", - pFile->h, pFile->locktype, sqlite3ErrName(rc))); + pFile->h, pFile->locktype, tdsqlite3ErrName(rc))); return rc; } @@ -44249,7 +49072,7 @@ static int winLock(sqlite3_file *id, int locktype){ ** file by this or any other process. If such a lock is held, return ** non-zero, otherwise zero. */ -static int winCheckReservedLock(sqlite3_file *id, int *pResOut){ +static int winCheckReservedLock(tdsqlite3_file *id, int *pResOut){ int res; winFile *pFile = (winFile*)id; @@ -44285,7 +49108,7 @@ static int winCheckReservedLock(sqlite3_file *id, int *pResOut){ ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine ** might return SQLITE_IOERR; */ -static int winUnlock(sqlite3_file *id, int locktype){ +static int winUnlock(tdsqlite3_file *id, int locktype){ int type; winFile *pFile = (winFile*)id; int rc = SQLITE_OK; @@ -44314,7 +49137,7 @@ static int winUnlock(sqlite3_file *id, int locktype){ } pFile->locktype = (u8)locktype; OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n", - pFile->h, pFile->locktype, sqlite3ErrName(rc))); + pFile->h, pFile->locktype, tdsqlite3ErrName(rc))); return rc; } @@ -44335,19 +49158,19 @@ static int winUnlock(sqlite3_file *id, int locktype){ ** time and one or more of those connections are writing. */ -static int winNolockLock(sqlite3_file *id, int locktype){ +static int winNolockLock(tdsqlite3_file *id, int locktype){ UNUSED_PARAMETER(id); UNUSED_PARAMETER(locktype); return SQLITE_OK; } -static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){ +static int winNolockCheckReservedLock(tdsqlite3_file *id, int *pResOut){ UNUSED_PARAMETER(id); UNUSED_PARAMETER(pResOut); return SQLITE_OK; } -static int winNolockUnlock(sqlite3_file *id, int locktype){ +static int winNolockUnlock(tdsqlite3_file *id, int locktype){ UNUSED_PARAMETER(id); UNUSED_PARAMETER(locktype); return SQLITE_OK; @@ -44373,14 +49196,14 @@ static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){ } /* Forward references to VFS helper methods used for temporary files */ -static int winGetTempname(sqlite3_vfs *, char **); +static int winGetTempname(tdsqlite3_vfs *, char **); static int winIsDir(const void *); static BOOL winIsDriveLetterAndColon(const char *); /* ** Control and query of the open file handle. */ -static int winFileControl(sqlite3_file *id, int op, void *pArg){ +static int winFileControl(tdsqlite3_file *id, int op, void *pArg){ winFile *pFile = (winFile*)id; OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg)); switch( op ){ @@ -44401,17 +49224,17 @@ static int winFileControl(sqlite3_file *id, int op, void *pArg){ } case SQLITE_FCNTL_SIZE_HINT: { if( pFile->szChunk>0 ){ - sqlite3_int64 oldSz; + tdsqlite3_int64 oldSz; int rc = winFileSize(id, &oldSz); if( rc==SQLITE_OK ){ - sqlite3_int64 newSz = *(sqlite3_int64*)pArg; + tdsqlite3_int64 newSz = *(tdsqlite3_int64*)pArg; if( newSz>oldSz ){ SimulateIOErrorBenign(1); rc = winTruncate(id, newSz); SimulateIOErrorBenign(0); } } - OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); + OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, tdsqlite3ErrName(rc))); return rc; } OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); @@ -44428,7 +49251,7 @@ static int winFileControl(sqlite3_file *id, int op, void *pArg){ return SQLITE_OK; } case SQLITE_FCNTL_VFSNAME: { - *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); + *(char**)pArg = tdsqlite3_mprintf("%s", pFile->pVfs->zName); OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); return SQLITE_OK; } @@ -44470,16 +49293,24 @@ static int winFileControl(sqlite3_file *id, int op, void *pArg){ if( rc==SQLITE_OK ){ *(char**)pArg = zTFile; } - OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); + OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, tdsqlite3ErrName(rc))); return rc; } #if SQLITE_MAX_MMAP_SIZE>0 case SQLITE_FCNTL_MMAP_SIZE: { i64 newLimit = *(i64*)pArg; int rc = SQLITE_OK; - if( newLimit>sqlite3GlobalConfig.mxMmap ){ - newLimit = sqlite3GlobalConfig.mxMmap; + if( newLimit>tdsqlite3GlobalConfig.mxMmap ){ + newLimit = tdsqlite3GlobalConfig.mxMmap; } + + /* The value of newLimit may be eventually cast to (SIZE_T) and passed + ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at + ** least a 64-bit type. */ + if( newLimit>0 && sizeof(SIZE_T)<8 ){ + newLimit = (newLimit & 0x7FFFFFFF); + } + *(i64*)pArg = pFile->mmapSizeMax; if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ pFile->mmapSizeMax = newLimit; @@ -44488,7 +49319,7 @@ static int winFileControl(sqlite3_file *id, int op, void *pArg){ rc = winMapfile(pFile, -1); } } - OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); + OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, tdsqlite3ErrName(rc))); return rc; } #endif @@ -44507,7 +49338,7 @@ static int winFileControl(sqlite3_file *id, int op, void *pArg){ ** a database and its journal file) that the sector size will be the ** same for both. */ -static int winSectorSize(sqlite3_file *id){ +static int winSectorSize(tdsqlite3_file *id){ (void)id; return SQLITE_DEFAULT_SECTOR_SIZE; } @@ -44515,7 +49346,7 @@ static int winSectorSize(sqlite3_file *id){ /* ** Return a vector of device characteristics. */ -static int winDeviceCharacteristics(sqlite3_file *id){ +static int winDeviceCharacteristics(tdsqlite3_file *id){ winFile *p = (winFile*)id; return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0); @@ -44524,7 +49355,7 @@ static int winDeviceCharacteristics(sqlite3_file *id){ /* ** Windows will only let you create file view mappings ** on allocation size granularity boundaries. -** During sqlite3_os_init() we do a GetSystemInfo() +** During tdsqlite3_os_init() we do a GetSystemInfo() ** to get the granularity size. */ static SYSTEM_INFO winSysInfo; @@ -44544,15 +49375,16 @@ static SYSTEM_INFO winSysInfo; ** assert( winShmMutexHeld() ); ** winShmLeaveMutex() */ +static tdsqlite3_mutex *winBigLock = 0; static void winShmEnterMutex(void){ - sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); + tdsqlite3_mutex_enter(winBigLock); } static void winShmLeaveMutex(void){ - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); + tdsqlite3_mutex_leave(winBigLock); } #ifndef NDEBUG static int winShmMutexHeld(void) { - return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); + return tdsqlite3_mutex_held(winBigLock); } #endif @@ -44580,12 +49412,15 @@ static int winShmMutexHeld(void) { ** */ struct winShmNode { - sqlite3_mutex *mutex; /* Mutex to access this object */ + tdsqlite3_mutex *mutex; /* Mutex to access this object */ char *zFilename; /* Name of the file */ winFile hFile; /* File handle from winOpen */ int szRegion; /* Size of shared-memory regions */ int nRegion; /* Size of array apRegion */ + u8 isReadonly; /* True if read-only */ + u8 isUnlocked; /* True if no DMS lock held */ + struct ShmRegion { HANDLE hMap; /* File handle from CreateFileMapping */ void *pMap; @@ -44652,7 +49487,7 @@ static int winShmSystemLock( int rc = 0; /* Result code form Lock/UnlockFileEx() */ /* Access to the winShmNode object is serialized by the caller */ - assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 ); + assert( pFile->nRef==0 || tdsqlite3_mutex_held(pFile->mutex) ); OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n", pFile->hFile.h, lockType, ofst, nByte)); @@ -44676,14 +49511,14 @@ static int winShmSystemLock( OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n", pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" : - "winLockFile", pFile->lastErrno, sqlite3ErrName(rc))); + "winLockFile", pFile->lastErrno, tdsqlite3ErrName(rc))); return rc; } /* Forward references to VFS methods */ -static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*); -static int winDelete(sqlite3_vfs *,const char*,int); +static int winOpen(tdsqlite3_vfs*,const char*,tdsqlite3_file*,int,int*); +static int winDelete(tdsqlite3_vfs *,const char*,int); /* ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0. @@ -44691,7 +49526,7 @@ static int winDelete(sqlite3_vfs *,const char*,int); ** This is not a VFS shared-memory method; it is a utility function called ** by VFS shared-memory methods. */ -static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ +static void winShmPurge(tdsqlite3_vfs *pVfs, int deleteFlag){ winShmNode **pp; winShmNode *p; assert( winShmMutexHeld() ); @@ -44701,7 +49536,7 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ while( (p = *pp)!=0 ){ if( p->nRef==0 ){ int i; - if( p->mutex ){ sqlite3_mutex_free(p->mutex); } + if( p->mutex ){ tdsqlite3_mutex_free(p->mutex); } for(i=0; i<p->nRegion; i++){ BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap); OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n", @@ -44714,19 +49549,19 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ } if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){ SimulateIOErrorBenign(1); - winClose((sqlite3_file *)&p->hFile); + winClose((tdsqlite3_file *)&p->hFile); SimulateIOErrorBenign(0); } if( deleteFlag ){ SimulateIOErrorBenign(1); - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); winDelete(pVfs, p->zFilename, 0); - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); SimulateIOErrorBenign(0); } *pp = p->pNext; - sqlite3_free(p->aRegion); - sqlite3_free(p); + tdsqlite3_free(p->aRegion); + tdsqlite3_free(p); }else{ pp = &p->pNext; } @@ -44734,6 +49569,37 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ } /* +** The DMS lock has not yet been taken on shm file pShmNode. Attempt to +** take it now. Return SQLITE_OK if successful, or an SQLite error +** code otherwise. +** +** If the DMS cannot be locked because this is a readonly_shm=1 +** connection and no other process already holds a lock, return +** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1. +*/ +static int winLockSharedMemory(winShmNode *pShmNode){ + int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1); + + if( rc==SQLITE_OK ){ + if( pShmNode->isReadonly ){ + pShmNode->isUnlocked = 1; + winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); + return SQLITE_READONLY_CANTINIT; + }else if( winTruncate((tdsqlite3_file*)&pShmNode->hFile, 0) ){ + winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); + return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(), + "winLockSharedMemory", pShmNode->zFilename); + } + } + + if( rc==SQLITE_OK ){ + winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); + } + + return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1); +} + +/* ** Open the shared-memory area associated with database file pDbFd. ** ** When opening a new shared-memory file, if no other instances of that @@ -44742,27 +49608,27 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ */ static int winOpenSharedMemory(winFile *pDbFd){ struct winShm *p; /* The connection to be opened */ - struct winShmNode *pShmNode = 0; /* The underlying mmapped file */ - int rc; /* Result code */ - struct winShmNode *pNew; /* Newly allocated winShmNode */ + winShmNode *pShmNode = 0; /* The underlying mmapped file */ + int rc = SQLITE_OK; /* Result code */ + winShmNode *pNew; /* Newly allocated winShmNode */ int nName; /* Size of zName in bytes */ assert( pDbFd->pShm==0 ); /* Not previously opened */ - /* Allocate space for the new sqlite3_shm object. Also speculatively + /* Allocate space for the new tdsqlite3_shm object. Also speculatively ** allocate space for a new winShmNode and filename. */ - p = sqlite3MallocZero( sizeof(*p) ); + p = tdsqlite3MallocZero( sizeof(*p) ); if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT; - nName = sqlite3Strlen30(pDbFd->zPath); - pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 ); + nName = tdsqlite3Strlen30(pDbFd->zPath); + pNew = tdsqlite3MallocZero( sizeof(*pShmNode) + nName + 17 ); if( pNew==0 ){ - sqlite3_free(p); + tdsqlite3_free(p); return SQLITE_IOERR_NOMEM_BKPT; } pNew->zFilename = (char*)&pNew[1]; - sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath); - sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); + tdsqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath); + tdsqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); /* Look to see if there is an existing winShmNode that can be used. ** If no matching winShmNode currently exists, create a new one. @@ -44772,49 +49638,45 @@ static int winOpenSharedMemory(winFile *pDbFd){ /* TBD need to come up with better match here. Perhaps ** use FILE_ID_BOTH_DIR_INFO Structure. */ - if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break; + if( tdsqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break; } if( pShmNode ){ - sqlite3_free(pNew); + tdsqlite3_free(pNew); }else{ + int inFlags = SQLITE_OPEN_WAL; + int outFlags = 0; + pShmNode = pNew; pNew = 0; ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE; pShmNode->pNext = winShmNodeList; winShmNodeList = pShmNode; - if( sqlite3GlobalConfig.bCoreMutex ){ - pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); + if( tdsqlite3GlobalConfig.bCoreMutex ){ + pShmNode->mutex = tdsqlite3_mutex_alloc(SQLITE_MUTEX_FAST); if( pShmNode->mutex==0 ){ rc = SQLITE_IOERR_NOMEM_BKPT; goto shm_open_err; } } - rc = winOpen(pDbFd->pVfs, - pShmNode->zFilename, /* Name of the file (UTF-8) */ - (sqlite3_file*)&pShmNode->hFile, /* File handle here */ - SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, - 0); - if( SQLITE_OK!=rc ){ + if( 0==tdsqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ + inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; + }else{ + inFlags |= SQLITE_OPEN_READONLY; + } + rc = winOpen(pDbFd->pVfs, pShmNode->zFilename, + (tdsqlite3_file*)&pShmNode->hFile, + inFlags, &outFlags); + if( rc!=SQLITE_OK ){ + rc = winLogError(rc, osGetLastError(), "winOpenShm", + pShmNode->zFilename); goto shm_open_err; } + if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1; - /* Check to see if another process is holding the dead-man switch. - ** If not, truncate the file to zero length. - */ - if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){ - rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0); - if( rc!=SQLITE_OK ){ - rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(), - "winOpenShm", pDbFd->zPath); - } - } - if( rc==SQLITE_OK ){ - winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); - rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1); - } - if( rc ) goto shm_open_err; + rc = winLockSharedMemory(pShmNode); + if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err; } /* Make the new connection a child of the winShmNode */ @@ -44833,18 +49695,18 @@ static int winOpenSharedMemory(winFile *pDbFd){ ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex ** mutex. */ - sqlite3_mutex_enter(pShmNode->mutex); + tdsqlite3_mutex_enter(pShmNode->mutex); p->pNext = pShmNode->pFirst; pShmNode->pFirst = p; - sqlite3_mutex_leave(pShmNode->mutex); - return SQLITE_OK; + tdsqlite3_mutex_leave(pShmNode->mutex); + return rc; /* Jump here on any error */ shm_open_err: winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */ - sqlite3_free(p); - sqlite3_free(pNew); + tdsqlite3_free(p); + tdsqlite3_free(pNew); winShmLeaveMutex(); return rc; } @@ -44854,7 +49716,7 @@ shm_open_err: ** storage if deleteFlag is true. */ static int winShmUnmap( - sqlite3_file *fd, /* Database holding shared memory */ + tdsqlite3_file *fd, /* Database holding shared memory */ int deleteFlag /* Delete after closing if true */ ){ winFile *pDbFd; /* Database holding shared-memory */ @@ -44869,14 +49731,14 @@ static int winShmUnmap( /* Remove connection p from the set of connections associated ** with pShmNode */ - sqlite3_mutex_enter(pShmNode->mutex); + tdsqlite3_mutex_enter(pShmNode->mutex); for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} *pp = p->pNext; /* Free the connection p */ - sqlite3_free(p); + tdsqlite3_free(p); pDbFd->pShm = 0; - sqlite3_mutex_leave(pShmNode->mutex); + tdsqlite3_mutex_leave(pShmNode->mutex); /* If pShmNode->nRef has reached 0, then close the underlying ** shared-memory file, too */ @@ -44895,7 +49757,7 @@ static int winShmUnmap( ** Change the lock state for a shared-memory segment. */ static int winShmLock( - sqlite3_file *fd, /* Database file holding the shared memory */ + tdsqlite3_file *fd, /* Database file holding the shared memory */ int ofst, /* First lock to acquire or release */ int n, /* Number of locks to acquire or release */ int flags /* What to do with the lock */ @@ -44917,7 +49779,7 @@ static int winShmLock( mask = (u16)((1U<<(ofst+n)) - (1U<<ofst)); assert( n>1 || mask==(1<<ofst) ); - sqlite3_mutex_enter(pShmNode->mutex); + tdsqlite3_mutex_enter(pShmNode->mutex); if( flags & SQLITE_SHM_UNLOCK ){ u16 allMask = 0; /* Mask of locks held by siblings */ @@ -44990,10 +49852,10 @@ static int winShmLock( } } } - sqlite3_mutex_leave(pShmNode->mutex); + tdsqlite3_mutex_leave(pShmNode->mutex); OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n", osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask, - sqlite3ErrName(rc))); + tdsqlite3ErrName(rc))); return rc; } @@ -45004,10 +49866,10 @@ static int winShmLock( ** any load or store begun after the barrier. */ static void winShmBarrier( - sqlite3_file *fd /* Database holding the shared memory */ + tdsqlite3_file *fd /* Database holding the shared memory */ ){ UNUSED_PARAMETER(fd); - sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ + tdsqlite3MemoryBarrier(); /* compiler-defined memory barrier */ winShmEnterMutex(); /* Also mutex, for redundancy */ winShmLeaveMutex(); } @@ -45032,7 +49894,7 @@ static void winShmBarrier( ** memory and SQLITE_OK returned. */ static int winShmMap( - sqlite3_file *fd, /* Handle open on database file */ + tdsqlite3_file *fd, /* Handle open on database file */ int iRegion, /* Region to retrieve */ int szRegion, /* Size of regions */ int isWrite, /* True to extend file if necessary */ @@ -45041,22 +49903,30 @@ static int winShmMap( winFile *pDbFd = (winFile*)fd; winShm *pShm = pDbFd->pShm; winShmNode *pShmNode; + DWORD protect = PAGE_READWRITE; + DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ; int rc = SQLITE_OK; if( !pShm ){ rc = winOpenSharedMemory(pDbFd); if( rc!=SQLITE_OK ) return rc; pShm = pDbFd->pShm; + assert( pShm!=0 ); } pShmNode = pShm->pShmNode; - sqlite3_mutex_enter(pShmNode->mutex); + tdsqlite3_mutex_enter(pShmNode->mutex); + if( pShmNode->isUnlocked ){ + rc = winLockSharedMemory(pShmNode); + if( rc!=SQLITE_OK ) goto shmpage_out; + pShmNode->isUnlocked = 0; + } assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); if( pShmNode->nRegion<=iRegion ){ struct ShmRegion *apNew; /* New aRegion[] array */ int nByte = (iRegion+1)*szRegion; /* Minimum required file size */ - sqlite3_int64 sz; /* Current size of wal-index file */ + tdsqlite3_int64 sz; /* Current size of wal-index file */ pShmNode->szRegion = szRegion; @@ -45064,7 +49934,7 @@ static int winShmMap( ** Check to see if it has been allocated (i.e. if the wal-index file is ** large enough to contain the requested region). */ - rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz); + rc = winFileSize((tdsqlite3_file *)&pShmNode->hFile, &sz); if( rc!=SQLITE_OK ){ rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), "winShmMap1", pDbFd->zPath); @@ -45079,7 +49949,7 @@ static int winShmMap( ** the requested memory region. */ if( !isWrite ) goto shmpage_out; - rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte); + rc = winTruncate((tdsqlite3_file *)&pShmNode->hFile, nByte); if( rc!=SQLITE_OK ){ rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), "winShmMap2", pDbFd->zPath); @@ -45088,7 +49958,7 @@ static int winShmMap( } /* Map the requested memory region into this processes address space. */ - apNew = (struct ShmRegion *)sqlite3_realloc64( + apNew = (struct ShmRegion *)tdsqlite3_realloc64( pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0]) ); if( !apNew ){ @@ -45097,21 +49967,26 @@ static int winShmMap( } pShmNode->aRegion = apNew; + if( pShmNode->isReadonly ){ + protect = PAGE_READONLY; + flags = FILE_MAP_READ; + } + while( pShmNode->nRegion<=iRegion ){ HANDLE hMap = NULL; /* file-mapping handle */ void *pMap = 0; /* Mapped memory region */ #if SQLITE_OS_WINRT hMap = osCreateFileMappingFromApp(pShmNode->hFile.h, - NULL, PAGE_READWRITE, nByte, NULL + NULL, protect, nByte, NULL ); #elif defined(SQLITE_WIN32_HAS_WIDE) hMap = osCreateFileMappingW(pShmNode->hFile.h, - NULL, PAGE_READWRITE, 0, nByte, NULL + NULL, protect, 0, nByte, NULL ); #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA hMap = osCreateFileMappingA(pShmNode->hFile.h, - NULL, PAGE_READWRITE, 0, nByte, NULL + NULL, protect, 0, nByte, NULL ); #endif OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n", @@ -45121,11 +49996,11 @@ static int winShmMap( int iOffset = pShmNode->nRegion*szRegion; int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; #if SQLITE_OS_WINRT - pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ, + pMap = osMapViewOfFileFromApp(hMap, flags, iOffset - iOffsetShift, szRegion + iOffsetShift ); #else - pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, + pMap = osMapViewOfFile(hMap, flags, 0, iOffset - iOffsetShift, szRegion + iOffsetShift ); #endif @@ -45156,7 +50031,8 @@ shmpage_out: }else{ *pp = 0; } - sqlite3_mutex_leave(pShmNode->mutex); + if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY; + tdsqlite3_mutex_leave(pShmNode->mutex); return rc; } @@ -45174,9 +50050,9 @@ shmpage_out: static int winUnmapfile(winFile *pFile){ assert( pFile!=0 ); OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, " - "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n", + "mmapSize=%lld, mmapSizeMax=%lld\n", osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion, - pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax)); + pFile->mmapSize, pFile->mmapSizeMax)); if( pFile->pMapRegion ){ if( !osUnmapViewOfFile(pFile->pMapRegion) ){ pFile->lastErrno = osGetLastError(); @@ -45188,7 +50064,6 @@ static int winUnmapfile(winFile *pFile){ } pFile->pMapRegion = 0; pFile->mmapSize = 0; - pFile->mmapSizeActual = 0; } if( pFile->hMap!=NULL ){ if( !osCloseHandle(pFile->hMap) ){ @@ -45221,8 +50096,8 @@ static int winUnmapfile(winFile *pFile){ ** recreated as a result of outstanding references) or an SQLite error ** code otherwise. */ -static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ - sqlite3_int64 nMap = nByte; +static int winMapfile(winFile *pFd, tdsqlite3_int64 nByte){ + tdsqlite3_int64 nMap = nByte; int rc; assert( nMap>=0 || pFd->nFetchOut==0 ); @@ -45232,7 +50107,7 @@ static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ if( pFd->nFetchOut>0 ) return SQLITE_OK; if( nMap<0 ){ - rc = winFileSize((sqlite3_file*)pFd, &nMap); + rc = winFileSize((tdsqlite3_file*)pFd, &nMap); if( rc ){ OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n", osGetCurrentProcessId(), pFd)); @@ -45242,7 +50117,7 @@ static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ if( nMap>pFd->mmapSizeMax ){ nMap = pFd->mmapSizeMax; } - nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1); + nMap &= ~(tdsqlite3_int64)(winSysInfo.dwPageSize - 1); if( nMap==0 && pFd->mmapSize>0 ){ winUnmapfile(pFd); @@ -45276,11 +50151,11 @@ static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ "winMapfile1", pFd->zPath); /* Log the error, but continue normal operation using xRead/xWrite */ OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n", - osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); + osGetCurrentProcessId(), pFd, tdsqlite3ErrName(rc))); return SQLITE_OK; } assert( (nMap % winSysInfo.dwPageSize)==0 ); - assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff ); + assert( sizeof(SIZE_T)==sizeof(tdsqlite3_int64) || nMap<=0xffffffff ); #if SQLITE_OS_WINRT pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap); #else @@ -45294,12 +50169,11 @@ static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ "winMapfile2", pFd->zPath); /* Log the error, but continue normal operation using xRead/xWrite */ OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n", - osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); + osGetCurrentProcessId(), pFd, tdsqlite3ErrName(rc))); return SQLITE_OK; } pFd->pMapRegion = pNew; pFd->mmapSize = nMap; - pFd->mmapSizeActual = nMap; } OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", @@ -45320,7 +50194,7 @@ static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ ** If this function does return a pointer, the caller must eventually ** release the reference by calling winUnfetch(). */ -static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ +static int winFetch(tdsqlite3_file *fd, i64 iOff, int nAmt, void **pp){ #if SQLITE_MAX_MMAP_SIZE>0 winFile *pFd = (winFile*)fd; /* The underlying database file */ #endif @@ -45335,11 +50209,12 @@ static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ int rc = winMapfile(pFd, -1); if( rc!=SQLITE_OK ){ OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n", - osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); + osGetCurrentProcessId(), pFd, tdsqlite3ErrName(rc))); return rc; } } if( pFd->mmapSize >= iOff+nAmt ){ + assert( pFd->pMapRegion!=0 ); *pp = &((u8 *)pFd->pMapRegion)[iOff]; pFd->nFetchOut++; } @@ -45361,7 +50236,7 @@ static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ ** to inform the VFS layer that, according to POSIX, any existing mapping ** may now be invalid and should be unmapped. */ -static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){ +static int winUnfetch(tdsqlite3_file *fd, i64 iOff, void *p){ #if SQLITE_MAX_MMAP_SIZE>0 winFile *pFd = (winFile*)fd; /* The underlying database file */ @@ -45395,16 +50270,16 @@ static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){ } /* -** Here ends the implementation of all sqlite3_file methods. +** Here ends the implementation of all tdsqlite3_file methods. ** -********************** End sqlite3_file Methods ******************************* +********************** End tdsqlite3_file Methods ******************************* ******************************************************************************/ /* ** This vector defines all the methods that can operate on an -** sqlite3_file for win32. +** tdsqlite3_file for win32. */ -static const sqlite3_io_methods winIoMethod = { +static const tdsqlite3_io_methods winIoMethod = { 3, /* iVersion */ winClose, /* xClose */ winRead, /* xRead */ @@ -45428,9 +50303,9 @@ static const sqlite3_io_methods winIoMethod = { /* ** This vector defines all the methods that can operate on an -** sqlite3_file for win32 without performing any locking. +** tdsqlite3_file for win32 without performing any locking. */ -static const sqlite3_io_methods winIoNolockMethod = { +static const tdsqlite3_io_methods winIoNolockMethod = { 3, /* iVersion */ winClose, /* xClose */ winRead, /* xRead */ @@ -45465,10 +50340,10 @@ static winVfsAppData winNolockAppData = { }; /**************************************************************************** -**************************** sqlite3_vfs methods **************************** +**************************** tdsqlite3_vfs methods **************************** ** ** This division contains the implementation of methods on the -** sqlite3_vfs object. +** tdsqlite3_vfs object. */ #if defined(__CYGWIN__) @@ -45519,7 +50394,7 @@ static void *winConvertFromUtf8Filename(const char *zFilename){ */ static int winMakeEndInDirSep(int nBuf, char *zBuf){ if( zBuf ){ - int nLen = sqlite3Strlen30(zBuf); + int nLen = tdsqlite3Strlen30(zBuf); if( nLen>0 ){ if( winIsDirSep(zBuf[nLen-1]) ){ return 1; @@ -45535,15 +50410,15 @@ static int winMakeEndInDirSep(int nBuf, char *zBuf){ /* ** Create a temporary file name and store the resulting pointer into pzBuf. -** The pointer returned in pzBuf must be freed via sqlite3_free(). +** The pointer returned in pzBuf must be freed via tdsqlite3_free(). */ -static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ +static int winGetTempname(tdsqlite3_vfs *pVfs, char **pzBuf){ static char zChars[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789"; size_t i, j; - int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX); + int nPre = tdsqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX); int nMax, nBuf, nDir, nLen; char *zBuf; @@ -45557,7 +50432,7 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ ** name for the temporary file. If this fails, we cannot continue. */ nMax = pVfs->mxPathname; nBuf = nMax + 2; - zBuf = sqlite3MallocZero( nBuf ); + zBuf = tdsqlite3MallocZero( nBuf ); if( !zBuf ){ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; @@ -45569,18 +50444,18 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ */ nDir = nMax - (nPre + 15); assert( nDir>0 ); - if( sqlite3_temp_directory ){ - int nDirLen = sqlite3Strlen30(sqlite3_temp_directory); + if( tdsqlite3_temp_directory ){ + int nDirLen = tdsqlite3Strlen30(tdsqlite3_temp_directory); if( nDirLen>0 ){ - if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){ + if( !winIsDirSep(tdsqlite3_temp_directory[nDirLen-1]) ){ nDirLen++; } if( nDirLen>nDir ){ - sqlite3_free(zBuf); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0); } - sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory); + tdsqlite3_snprintf(nMax, zBuf, "%s", tdsqlite3_temp_directory); } } #if defined(__CYGWIN__) @@ -45616,28 +50491,28 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ if( winIsDriveLetterAndColon(zDir) ){ zConverted = winConvertFromUtf8Filename(zDir); if( !zConverted ){ - sqlite3_free(zBuf); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } if( winIsDir(zConverted) ){ - sqlite3_snprintf(nMax, zBuf, "%s", zDir); - sqlite3_free(zConverted); + tdsqlite3_snprintf(nMax, zBuf, "%s", zDir); + tdsqlite3_free(zConverted); break; } - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); }else{ - zConverted = sqlite3MallocZero( nMax+1 ); + zConverted = tdsqlite3MallocZero( nMax+1 ); if( !zConverted ){ - sqlite3_free(zBuf); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } if( cygwin_conv_path( osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir, zConverted, nMax+1)<0 ){ - sqlite3_free(zConverted); - sqlite3_free(zBuf); + tdsqlite3_free(zConverted); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n")); return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno, "winGetTempname2", zDir); @@ -45649,44 +50524,44 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ */ char *zUtf8 = winConvertToUtf8Filename(zConverted); if( !zUtf8 ){ - sqlite3_free(zConverted); - sqlite3_free(zBuf); + tdsqlite3_free(zConverted); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } - sqlite3_snprintf(nMax, zBuf, "%s", zUtf8); - sqlite3_free(zUtf8); - sqlite3_free(zConverted); + tdsqlite3_snprintf(nMax, zBuf, "%s", zUtf8); + tdsqlite3_free(zUtf8); + tdsqlite3_free(zConverted); break; } - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); } } } #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__) else if( osIsNT() ){ char *zMulti; - LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) ); + LPWSTR zWidePath = tdsqlite3MallocZero( nMax*sizeof(WCHAR) ); if( !zWidePath ){ - sqlite3_free(zBuf); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } if( osGetTempPathW(nMax, zWidePath)==0 ){ - sqlite3_free(zWidePath); - sqlite3_free(zBuf); + tdsqlite3_free(zWidePath); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(), "winGetTempname2", 0); } zMulti = winUnicodeToUtf8(zWidePath); if( zMulti ){ - sqlite3_snprintf(nMax, zBuf, "%s", zMulti); - sqlite3_free(zMulti); - sqlite3_free(zWidePath); + tdsqlite3_snprintf(nMax, zBuf, "%s", zMulti); + tdsqlite3_free(zMulti); + tdsqlite3_free(zWidePath); }else{ - sqlite3_free(zWidePath); - sqlite3_free(zBuf); + tdsqlite3_free(zWidePath); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } @@ -45694,24 +50569,24 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ #ifdef SQLITE_WIN32_HAS_ANSI else{ char *zUtf8; - char *zMbcsPath = sqlite3MallocZero( nMax ); + char *zMbcsPath = tdsqlite3MallocZero( nMax ); if( !zMbcsPath ){ - sqlite3_free(zBuf); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } if( osGetTempPathA(nMax, zMbcsPath)==0 ){ - sqlite3_free(zBuf); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(), "winGetTempname3", 0); } zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI()); if( zUtf8 ){ - sqlite3_snprintf(nMax, zBuf, "%s", zUtf8); - sqlite3_free(zUtf8); + tdsqlite3_snprintf(nMax, zBuf, "%s", zUtf8); + tdsqlite3_free(zUtf8); }else{ - sqlite3_free(zBuf); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } @@ -45725,7 +50600,7 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ ** one, fail. */ if( !winMakeEndInDirSep(nDir+1, zBuf) ){ - sqlite3_free(zBuf); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0); } @@ -45741,17 +50616,17 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ ** two trailing NUL characters. The final directory separator character ** has already added if it was not already present. */ - nLen = sqlite3Strlen30(zBuf); + nLen = tdsqlite3Strlen30(zBuf); if( (nLen + nPre + 17) > nBuf ){ - sqlite3_free(zBuf); + tdsqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0); } - sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX); + tdsqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX); - j = sqlite3Strlen30(zBuf); - sqlite3_randomness(15, &zBuf[j]); + j = tdsqlite3Strlen30(zBuf); + tdsqlite3_randomness(15, &zBuf[j]); for(i=0; i<15; i++, j++){ zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; } @@ -45792,13 +50667,21 @@ static int winIsDir(const void *zConverted){ return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY); } +/* forward reference */ +static int winAccess( + tdsqlite3_vfs *pVfs, /* Not used on win32 */ + const char *zFilename, /* Name of file to check */ + int flags, /* Type of test to make on this file */ + int *pResOut /* OUT: Result */ +); + /* ** Open a file. */ static int winOpen( - sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */ + tdsqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */ const char *zName, /* Name of the file (UTF-8) */ - sqlite3_file *id, /* Write the SQLite file handle here */ + tdsqlite3_file *id, /* Write the SQLite file handle here */ int flags, /* Open mode flags */ int *pOutFlags /* Status return flags */ ){ @@ -45875,9 +50758,9 @@ static int winOpen( pFile->h = INVALID_HANDLE_VALUE; #if SQLITE_OS_WINRT - if( !zUtf8Name && !sqlite3_temp_directory ){ - sqlite3_log(SQLITE_ERROR, - "sqlite3_temp_directory variable should be set for WinRT"); + if( !zUtf8Name && !tdsqlite3_temp_directory ){ + tdsqlite3_log(SQLITE_ERROR, + "tdsqlite3_temp_directory variable should be set for WinRT"); } #endif @@ -45888,7 +50771,7 @@ static int winOpen( assert( isDelete && !isOpenJournal ); rc = winGetTempname(pVfs, &zTmpname); if( rc!=SQLITE_OK ){ - OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc))); + OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, tdsqlite3ErrName(rc))); return rc; } zUtf8Name = zTmpname; @@ -45896,22 +50779,22 @@ static int winOpen( /* Database filenames are double-zero terminated if they are not ** URIs with parameters. Hence, they can always be passed into - ** sqlite3_uri_parameter(). + ** tdsqlite3_uri_parameter(). */ assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) || - zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 ); + zUtf8Name[tdsqlite3Strlen30(zUtf8Name)+1]==0 ); /* Convert the filename to the system encoding. */ zConverted = winConvertFromUtf8Filename(zUtf8Name); if( zConverted==0 ){ - sqlite3_free(zTmpname); + tdsqlite3_free(zTmpname); OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name)); return SQLITE_IOERR_NOMEM_BKPT; } if( winIsDir(zConverted) ){ - sqlite3_free(zConverted); - sqlite3_free(zTmpname); + tdsqlite3_free(zConverted); + tdsqlite3_free(zTmpname); OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name)); return SQLITE_CANTOPEN_ISDIR; } @@ -45971,37 +50854,58 @@ static int winOpen( extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS; extendedParameters.lpSecurityAttributes = NULL; extendedParameters.hTemplateFile = NULL; - while( (h = osCreateFile2((LPCWSTR)zConverted, - dwDesiredAccess, - dwShareMode, - dwCreationDisposition, - &extendedParameters))==INVALID_HANDLE_VALUE && - winRetryIoerr(&cnt, &lastErrno) ){ - /* Noop */ - } + do{ + h = osCreateFile2((LPCWSTR)zConverted, + dwDesiredAccess, + dwShareMode, + dwCreationDisposition, + &extendedParameters); + if( h!=INVALID_HANDLE_VALUE ) break; + if( isReadWrite ){ + int rc2, isRO = 0; + tdsqlite3BeginBenignMalloc(); + rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO); + tdsqlite3EndBenignMalloc(); + if( rc2==SQLITE_OK && isRO ) break; + } + }while( winRetryIoerr(&cnt, &lastErrno) ); #else - while( (h = osCreateFileW((LPCWSTR)zConverted, - dwDesiredAccess, - dwShareMode, NULL, - dwCreationDisposition, - dwFlagsAndAttributes, - NULL))==INVALID_HANDLE_VALUE && - winRetryIoerr(&cnt, &lastErrno) ){ - /* Noop */ - } + do{ + h = osCreateFileW((LPCWSTR)zConverted, + dwDesiredAccess, + dwShareMode, NULL, + dwCreationDisposition, + dwFlagsAndAttributes, + NULL); + if( h!=INVALID_HANDLE_VALUE ) break; + if( isReadWrite ){ + int rc2, isRO = 0; + tdsqlite3BeginBenignMalloc(); + rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO); + tdsqlite3EndBenignMalloc(); + if( rc2==SQLITE_OK && isRO ) break; + } + }while( winRetryIoerr(&cnt, &lastErrno) ); #endif } #ifdef SQLITE_WIN32_HAS_ANSI else{ - while( (h = osCreateFileA((LPCSTR)zConverted, - dwDesiredAccess, - dwShareMode, NULL, - dwCreationDisposition, - dwFlagsAndAttributes, - NULL))==INVALID_HANDLE_VALUE && - winRetryIoerr(&cnt, &lastErrno) ){ - /* Noop */ - } + do{ + h = osCreateFileA((LPCSTR)zConverted, + dwDesiredAccess, + dwShareMode, NULL, + dwCreationDisposition, + dwFlagsAndAttributes, + NULL); + if( h!=INVALID_HANDLE_VALUE ) break; + if( isReadWrite ){ + int rc2, isRO = 0; + tdsqlite3BeginBenignMalloc(); + rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO); + tdsqlite3EndBenignMalloc(); + if( rc2==SQLITE_OK && isRO ) break; + } + }while( winRetryIoerr(&cnt, &lastErrno) ); } #endif winLogIoerr(cnt, __LINE__); @@ -46010,16 +50914,16 @@ static int winOpen( dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); if( h==INVALID_HANDLE_VALUE ){ - pFile->lastErrno = lastErrno; - winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name); - sqlite3_free(zConverted); - sqlite3_free(zTmpname); + tdsqlite3_free(zConverted); + tdsqlite3_free(zTmpname); if( isReadWrite && !isExclusive ){ return winOpen(pVfs, zName, id, ((flags|SQLITE_OPEN_READONLY) & ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags); }else{ + pFile->lastErrno = lastErrno; + winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name); return SQLITE_CANTOPEN_BKPT; } } @@ -46045,9 +50949,9 @@ static int winOpen( && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK ){ osCloseHandle(h); - sqlite3_free(zConverted); - sqlite3_free(zTmpname); - OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc))); + tdsqlite3_free(zConverted); + tdsqlite3_free(zTmpname); + OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, tdsqlite3ErrName(rc))); return rc; } } @@ -46056,17 +50960,17 @@ static int winOpen( }else #endif { - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); } - sqlite3_free(zTmpname); + tdsqlite3_free(zTmpname); pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod; pFile->pVfs = pVfs; pFile->h = h; if( isReadonly ){ pFile->ctrlFlags |= WINFILE_RDONLY; } - if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){ + if( tdsqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){ pFile->ctrlFlags |= WINFILE_PSOW; } pFile->lastErrno = NO_ERROR; @@ -46075,8 +50979,7 @@ static int winOpen( pFile->hMap = NULL; pFile->pMapRegion = 0; pFile->mmapSize = 0; - pFile->mmapSizeActual = 0; - pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap; + pFile->mmapSizeMax = tdsqlite3GlobalConfig.szMmap; #endif OpenCounter(+1); @@ -46096,7 +50999,7 @@ static int winOpen( ** up and returning an error. */ static int winDelete( - sqlite3_vfs *pVfs, /* Not used on win32 */ + tdsqlite3_vfs *pVfs, /* Not used on win32 */ const char *zFilename, /* Name of file to delete */ int syncDir /* Not used on win32 */ ){ @@ -46195,8 +51098,8 @@ static int winDelete( }else{ winLogIoerr(cnt, __LINE__); } - sqlite3_free(zConverted); - OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc))); + tdsqlite3_free(zConverted); + OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, tdsqlite3ErrName(rc))); return rc; } @@ -46204,7 +51107,7 @@ static int winDelete( ** Check the existence and status of a file. */ static int winAccess( - sqlite3_vfs *pVfs, /* Not used on win32 */ + tdsqlite3_vfs *pVfs, /* Not used on win32 */ const char *zFilename, /* Name of file to check */ int flags, /* Type of test to make on this file */ int *pResOut /* OUT: Result */ @@ -46245,7 +51148,7 @@ static int winAccess( }else{ winLogIoerr(cnt, __LINE__); if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){ - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename); }else{ @@ -46258,7 +51161,7 @@ static int winAccess( attr = osGetFileAttributesA((char*)zConverted); } #endif - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); switch( flags ){ case SQLITE_ACCESS_READ: case SQLITE_ACCESS_EXISTS: @@ -46284,7 +51187,7 @@ static int winAccess( static BOOL winIsDriveLetterAndColon( const char *zPathname ){ - return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ); + return ( tdsqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ); } /* @@ -46330,7 +51233,7 @@ static BOOL winIsVerbatimPathname( ** bytes in size. */ static int winFullPathname( - sqlite3_vfs *pVfs, /* Pointer to vfs object */ + tdsqlite3_vfs *pVfs, /* Pointer to vfs object */ const char *zRelative, /* Possibly relative input path */ int nFull, /* Size of output buffer in bytes */ char *zFull /* Output buffer */ @@ -46352,54 +51255,54 @@ static int winFullPathname( SimulateIOError( return SQLITE_ERROR ); UNUSED_PARAMETER(nFull); assert( nFull>=pVfs->mxPathname ); - if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ + if ( tdsqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ /* ** NOTE: We are dealing with a relative path name and the data ** directory has been set. Therefore, use it as the basis ** for converting the relative path name to an absolute ** one by prepending the data directory and a slash. */ - char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); + char *zOut = tdsqlite3MallocZero( pVfs->mxPathname+1 ); if( !zOut ){ return SQLITE_IOERR_NOMEM_BKPT; } if( cygwin_conv_path( (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) | CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){ - sqlite3_free(zOut); + tdsqlite3_free(zOut); return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, "winFullPathname1", zRelative); }else{ char *zUtf8 = winConvertToUtf8Filename(zOut); if( !zUtf8 ){ - sqlite3_free(zOut); + tdsqlite3_free(zOut); return SQLITE_IOERR_NOMEM_BKPT; } - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", - sqlite3_data_directory, winGetDirSep(), zUtf8); - sqlite3_free(zUtf8); - sqlite3_free(zOut); + tdsqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", + tdsqlite3_data_directory, winGetDirSep(), zUtf8); + tdsqlite3_free(zUtf8); + tdsqlite3_free(zOut); } }else{ - char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); + char *zOut = tdsqlite3MallocZero( pVfs->mxPathname+1 ); if( !zOut ){ return SQLITE_IOERR_NOMEM_BKPT; } if( cygwin_conv_path( (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A), zRelative, zOut, pVfs->mxPathname+1)<0 ){ - sqlite3_free(zOut); + tdsqlite3_free(zOut); return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, "winFullPathname2", zRelative); }else{ char *zUtf8 = winConvertToUtf8Filename(zOut); if( !zUtf8 ){ - sqlite3_free(zOut); + tdsqlite3_free(zOut); return SQLITE_IOERR_NOMEM_BKPT; } - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8); - sqlite3_free(zUtf8); - sqlite3_free(zOut); + tdsqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8); + tdsqlite3_free(zUtf8); + tdsqlite3_free(zOut); } } return SQLITE_OK; @@ -46409,17 +51312,17 @@ static int winFullPathname( SimulateIOError( return SQLITE_ERROR ); /* WinCE has no concept of a relative pathname, or so I am told. */ /* WinRT has no way to convert a relative path to an absolute one. */ - if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ + if ( tdsqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ /* ** NOTE: We are dealing with a relative path name and the data ** directory has been set. Therefore, use it as the basis ** for converting the relative path name to an absolute ** one by prepending the data directory and a backslash. */ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", - sqlite3_data_directory, winGetDirSep(), zRelative); + tdsqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", + tdsqlite3_data_directory, winGetDirSep(), zRelative); }else{ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative); + tdsqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative); } return SQLITE_OK; #endif @@ -46431,15 +51334,15 @@ static int winFullPathname( ** current working directory has been unlinked. */ SimulateIOError( return SQLITE_ERROR ); - if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ + if ( tdsqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ /* ** NOTE: We are dealing with a relative path name and the data ** directory has been set. Therefore, use it as the basis ** for converting the relative path name to an absolute ** one by prepending the data directory and a backslash. */ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", - sqlite3_data_directory, winGetDirSep(), zRelative); + tdsqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", + tdsqlite3_data_directory, winGetDirSep(), zRelative); return SQLITE_OK; } zConverted = winConvertFromUtf8Filename(zRelative); @@ -46450,57 +51353,57 @@ static int winFullPathname( LPWSTR zTemp; nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0); if( nByte==0 ){ - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname1", zRelative); } nByte += 3; - zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); + zTemp = tdsqlite3MallocZero( nByte*sizeof(zTemp[0]) ); if( zTemp==0 ){ - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); return SQLITE_IOERR_NOMEM_BKPT; } nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0); if( nByte==0 ){ - sqlite3_free(zConverted); - sqlite3_free(zTemp); + tdsqlite3_free(zConverted); + tdsqlite3_free(zTemp); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname2", zRelative); } - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); zOut = winUnicodeToUtf8(zTemp); - sqlite3_free(zTemp); + tdsqlite3_free(zTemp); } #ifdef SQLITE_WIN32_HAS_ANSI else{ char *zTemp; nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0); if( nByte==0 ){ - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname3", zRelative); } nByte += 3; - zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); + zTemp = tdsqlite3MallocZero( nByte*sizeof(zTemp[0]) ); if( zTemp==0 ){ - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); return SQLITE_IOERR_NOMEM_BKPT; } nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0); if( nByte==0 ){ - sqlite3_free(zConverted); - sqlite3_free(zTemp); + tdsqlite3_free(zConverted); + tdsqlite3_free(zTemp); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname4", zRelative); } - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); - sqlite3_free(zTemp); + tdsqlite3_free(zTemp); } #endif if( zOut ){ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); - sqlite3_free(zOut); + tdsqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); + tdsqlite3_free(zOut); return SQLITE_OK; }else{ return SQLITE_IOERR_NOMEM_BKPT; @@ -46513,23 +51416,23 @@ static int winFullPathname( ** Interfaces for opening a shared library, finding entry points ** within the shared library, and closing the shared library. */ -static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){ +static void *winDlOpen(tdsqlite3_vfs *pVfs, const char *zFilename){ HANDLE h; #if defined(__CYGWIN__) int nFull = pVfs->mxPathname+1; - char *zFull = sqlite3MallocZero( nFull ); + char *zFull = tdsqlite3MallocZero( nFull ); void *zConverted = 0; if( zFull==0 ){ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); return 0; } if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){ - sqlite3_free(zFull); + tdsqlite3_free(zFull); OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); return 0; } zConverted = winConvertFromUtf8Filename(zFull); - sqlite3_free(zFull); + tdsqlite3_free(zFull); #else void *zConverted = winConvertFromUtf8Filename(zFilename); UNUSED_PARAMETER(pVfs); @@ -46551,14 +51454,14 @@ static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){ } #endif OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h)); - sqlite3_free(zConverted); + tdsqlite3_free(zConverted); return (void*)h; } -static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){ +static void winDlError(tdsqlite3_vfs *pVfs, int nBuf, char *zBufOut){ UNUSED_PARAMETER(pVfs); winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut); } -static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ +static void (*winDlSym(tdsqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ FARPROC proc; UNUSED_PARAMETER(pVfs); proc = osGetProcAddressA((HANDLE)pH, zSym); @@ -46566,7 +51469,7 @@ static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ (void*)pH, zSym, (void*)proc)); return (void(*)(void))proc; } -static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){ +static void winDlClose(tdsqlite3_vfs *pVfs, void *pHandle){ UNUSED_PARAMETER(pVfs); osFreeLibrary((HANDLE)pHandle); OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle)); @@ -46603,7 +51506,7 @@ static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){ /* ** Write up to nBuf bytes of randomness into zBuf. */ -static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ +static int winRandomness(tdsqlite3_vfs *pVfs, int nBuf, char *zBuf){ #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) UNUSED_PARAMETER(pVfs); memset(zBuf, 0, nBuf); @@ -46612,9 +51515,6 @@ static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ EntropyGatherer e; UNUSED_PARAMETER(pVfs); memset(zBuf, 0, nBuf); -#if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE - rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */ -#endif /* defined(_MSC_VER) && _MSC_VER>=1400 */ e.a = (unsigned char*)zBuf; e.na = nBuf; e.nXor = 0; @@ -46663,8 +51563,8 @@ static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ /* ** Sleep for a little while. Return the amount of time slept. */ -static int winSleep(sqlite3_vfs *pVfs, int microsec){ - sqlite3_win32_sleep((microsec+999)/1000); +static int winSleep(tdsqlite3_vfs *pVfs, int microsec){ + tdsqlite3_win32_sleep((microsec+999)/1000); UNUSED_PARAMETER(pVfs); return ((microsec+999)/1000)*1000; } @@ -46672,10 +51572,10 @@ static int winSleep(sqlite3_vfs *pVfs, int microsec){ /* ** The following variable, if set to a non-zero value, is interpreted as ** the number of seconds since 1970 and is used to set the result of -** sqlite3OsCurrentTime() during testing. +** tdsqlite3OsCurrentTime() during testing. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ +SQLITE_API int tdsqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ #endif /* @@ -46688,19 +51588,19 @@ SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date ** cannot be found. */ -static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ +static int winCurrentTimeInt64(tdsqlite3_vfs *pVfs, tdsqlite3_int64 *piNow){ /* FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). */ FILETIME ft; - static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000; + static const tdsqlite3_int64 winFiletimeEpoch = 23058135*(tdsqlite3_int64)8640000; #ifdef SQLITE_TEST - static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; + static const tdsqlite3_int64 unixEpoch = 24405875*(tdsqlite3_int64)8640000; #endif /* 2^32 - to avoid use of LL and warnings in gcc */ - static const sqlite3_int64 max32BitValue = - (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + - (sqlite3_int64)294967296; + static const tdsqlite3_int64 max32BitValue = + (tdsqlite3_int64)2000000000 + (tdsqlite3_int64)2000000000 + + (tdsqlite3_int64)294967296; #if SQLITE_OS_WINCE SYSTEMTIME time; @@ -46714,12 +51614,12 @@ static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ #endif *piNow = winFiletimeEpoch + - ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + - (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000; + ((((tdsqlite3_int64)ft.dwHighDateTime)*max32BitValue) + + (tdsqlite3_int64)ft.dwLowDateTime)/(tdsqlite3_int64)10000; #ifdef SQLITE_TEST - if( sqlite3_current_time ){ - *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; + if( tdsqlite3_current_time ){ + *piNow = 1000*(tdsqlite3_int64)tdsqlite3_current_time + unixEpoch; } #endif UNUSED_PARAMETER(pVfs); @@ -46731,9 +51631,9 @@ static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ ** current time and date as a Julian Day number into *prNow and ** return 0. Return 1 if the time and date cannot be found. */ -static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){ +static int winCurrentTime(tdsqlite3_vfs *pVfs, double *prNow){ int rc; - sqlite3_int64 i; + tdsqlite3_int64 i; rc = winCurrentTimeInt64(pVfs, &i); if( !rc ){ *prNow = i/86400000.0; @@ -46762,16 +51662,16 @@ static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){ ** on SQLite. It is fine to have an implementation that never ** returns an error message: ** -** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ +** int xGetLastError(tdsqlite3_vfs *pVfs, int nBuf, char *zBuf){ ** assert(zBuf[0]=='\0'); ** return 0; ** } ** ** However if an error message is supplied, it will be incorporated ** by sqlite into the error message available to the user using -** sqlite3_errmsg(), possibly making IO errors easier to debug. +** tdsqlite3_errmsg(), possibly making IO errors easier to debug. */ -static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ +static int winGetLastError(tdsqlite3_vfs *pVfs, int nBuf, char *zBuf){ DWORD e = osGetLastError(); UNUSED_PARAMETER(pVfs); if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf); @@ -46781,8 +51681,8 @@ static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ /* ** Initialize and deinitialize the operating system interface. */ -SQLITE_API int sqlite3_os_init(void){ - static sqlite3_vfs winVfs = { +SQLITE_API int tdsqlite3_os_init(void){ + static tdsqlite3_vfs winVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ @@ -46807,7 +51707,7 @@ SQLITE_API int sqlite3_os_init(void){ winNextSystemCall, /* xNextSystemCall */ }; #if defined(SQLITE_WIN32_HAS_WIDE) - static sqlite3_vfs winLongPathVfs = { + static tdsqlite3_vfs winLongPathVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ @@ -46832,7 +51732,7 @@ SQLITE_API int sqlite3_os_init(void){ winNextSystemCall, /* xNextSystemCall */ }; #endif - static sqlite3_vfs winNolockVfs = { + static tdsqlite3_vfs winNolockVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ @@ -46857,7 +51757,7 @@ SQLITE_API int sqlite3_os_init(void){ winNextSystemCall, /* xNextSystemCall */ }; #if defined(SQLITE_WIN32_HAS_WIDE) - static sqlite3_vfs winLongPathNolockVfs = { + static tdsqlite3_vfs winLongPathNolockVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ @@ -46897,34 +51797,669 @@ SQLITE_API int sqlite3_os_init(void){ assert( winSysInfo.dwAllocationGranularity>0 ); assert( winSysInfo.dwPageSize>0 ); - sqlite3_vfs_register(&winVfs, 1); + tdsqlite3_vfs_register(&winVfs, 1); #if defined(SQLITE_WIN32_HAS_WIDE) - sqlite3_vfs_register(&winLongPathVfs, 0); + tdsqlite3_vfs_register(&winLongPathVfs, 0); #endif - sqlite3_vfs_register(&winNolockVfs, 0); + tdsqlite3_vfs_register(&winNolockVfs, 0); #if defined(SQLITE_WIN32_HAS_WIDE) - sqlite3_vfs_register(&winLongPathNolockVfs, 0); + tdsqlite3_vfs_register(&winLongPathNolockVfs, 0); +#endif + +#ifndef SQLITE_OMIT_WAL + winBigLock = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1); #endif return SQLITE_OK; } -SQLITE_API int sqlite3_os_end(void){ +SQLITE_API int tdsqlite3_os_end(void){ #if SQLITE_OS_WINRT if( sleepObj!=NULL ){ osCloseHandle(sleepObj); sleepObj = NULL; } #endif + +#ifndef SQLITE_OMIT_WAL + winBigLock = 0; +#endif + return SQLITE_OK; } #endif /* SQLITE_OS_WIN */ /************** End of os_win.c **********************************************/ +/************** Begin file memdb.c *******************************************/ +/* +** 2016-09-07 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file implements an in-memory VFS. A database is held as a contiguous +** block of memory. +** +** This file also implements interface tdsqlite3_serialize() and +** tdsqlite3_deserialize(). +*/ +/* #include "sqliteInt.h" */ +#ifdef SQLITE_ENABLE_DESERIALIZE + +/* +** Forward declaration of objects used by this utility +*/ +typedef struct tdsqlite3_vfs MemVfs; +typedef struct MemFile MemFile; + +/* Access to a lower-level VFS that (might) implement dynamic loading, +** access to randomness, etc. +*/ +#define ORIGVFS(p) ((tdsqlite3_vfs*)((p)->pAppData)) + +/* An open file */ +struct MemFile { + tdsqlite3_file base; /* IO methods */ + tdsqlite3_int64 sz; /* Size of the file */ + tdsqlite3_int64 szAlloc; /* Space allocated to aData */ + tdsqlite3_int64 szMax; /* Maximum allowed size of the file */ + unsigned char *aData; /* content of the file */ + int nMmap; /* Number of memory mapped pages */ + unsigned mFlags; /* Flags */ + int eLock; /* Most recent lock against this file */ +}; + +/* +** Methods for MemFile +*/ +static int memdbClose(tdsqlite3_file*); +static int memdbRead(tdsqlite3_file*, void*, int iAmt, tdsqlite3_int64 iOfst); +static int memdbWrite(tdsqlite3_file*,const void*,int iAmt, tdsqlite3_int64 iOfst); +static int memdbTruncate(tdsqlite3_file*, tdsqlite3_int64 size); +static int memdbSync(tdsqlite3_file*, int flags); +static int memdbFileSize(tdsqlite3_file*, tdsqlite3_int64 *pSize); +static int memdbLock(tdsqlite3_file*, int); +/* static int memdbCheckReservedLock(tdsqlite3_file*, int *pResOut);// not used */ +static int memdbFileControl(tdsqlite3_file*, int op, void *pArg); +/* static int memdbSectorSize(tdsqlite3_file*); // not used */ +static int memdbDeviceCharacteristics(tdsqlite3_file*); +static int memdbFetch(tdsqlite3_file*, tdsqlite3_int64 iOfst, int iAmt, void **pp); +static int memdbUnfetch(tdsqlite3_file*, tdsqlite3_int64 iOfst, void *p); + +/* +** Methods for MemVfs +*/ +static int memdbOpen(tdsqlite3_vfs*, const char *, tdsqlite3_file*, int , int *); +/* static int memdbDelete(tdsqlite3_vfs*, const char *zName, int syncDir); */ +static int memdbAccess(tdsqlite3_vfs*, const char *zName, int flags, int *); +static int memdbFullPathname(tdsqlite3_vfs*, const char *zName, int, char *zOut); +static void *memdbDlOpen(tdsqlite3_vfs*, const char *zFilename); +static void memdbDlError(tdsqlite3_vfs*, int nByte, char *zErrMsg); +static void (*memdbDlSym(tdsqlite3_vfs *pVfs, void *p, const char*zSym))(void); +static void memdbDlClose(tdsqlite3_vfs*, void*); +static int memdbRandomness(tdsqlite3_vfs*, int nByte, char *zOut); +static int memdbSleep(tdsqlite3_vfs*, int microseconds); +/* static int memdbCurrentTime(tdsqlite3_vfs*, double*); */ +static int memdbGetLastError(tdsqlite3_vfs*, int, char *); +static int memdbCurrentTimeInt64(tdsqlite3_vfs*, tdsqlite3_int64*); + +static tdsqlite3_vfs memdb_vfs = { + 2, /* iVersion */ + 0, /* szOsFile (set when registered) */ + 1024, /* mxPathname */ + 0, /* pNext */ + "memdb", /* zName */ + 0, /* pAppData (set when registered) */ + memdbOpen, /* xOpen */ + 0, /* memdbDelete, */ /* xDelete */ + memdbAccess, /* xAccess */ + memdbFullPathname, /* xFullPathname */ + memdbDlOpen, /* xDlOpen */ + memdbDlError, /* xDlError */ + memdbDlSym, /* xDlSym */ + memdbDlClose, /* xDlClose */ + memdbRandomness, /* xRandomness */ + memdbSleep, /* xSleep */ + 0, /* memdbCurrentTime, */ /* xCurrentTime */ + memdbGetLastError, /* xGetLastError */ + memdbCurrentTimeInt64 /* xCurrentTimeInt64 */ +}; + +static const tdsqlite3_io_methods memdb_io_methods = { + 3, /* iVersion */ + memdbClose, /* xClose */ + memdbRead, /* xRead */ + memdbWrite, /* xWrite */ + memdbTruncate, /* xTruncate */ + memdbSync, /* xSync */ + memdbFileSize, /* xFileSize */ + memdbLock, /* xLock */ + memdbLock, /* xUnlock - same as xLock in this case */ + 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */ + memdbFileControl, /* xFileControl */ + 0, /* memdbSectorSize,*/ /* xSectorSize */ + memdbDeviceCharacteristics, /* xDeviceCharacteristics */ + 0, /* xShmMap */ + 0, /* xShmLock */ + 0, /* xShmBarrier */ + 0, /* xShmUnmap */ + memdbFetch, /* xFetch */ + memdbUnfetch /* xUnfetch */ +}; + + + +/* +** Close an memdb-file. +** +** The pData pointer is owned by the application, so there is nothing +** to free. +*/ +static int memdbClose(tdsqlite3_file *pFile){ + MemFile *p = (MemFile *)pFile; + if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) tdsqlite3_free(p->aData); + return SQLITE_OK; +} + +/* +** Read data from an memdb-file. +*/ +static int memdbRead( + tdsqlite3_file *pFile, + void *zBuf, + int iAmt, + sqlite_int64 iOfst +){ + MemFile *p = (MemFile *)pFile; + if( iOfst+iAmt>p->sz ){ + memset(zBuf, 0, iAmt); + if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst); + return SQLITE_IOERR_SHORT_READ; + } + memcpy(zBuf, p->aData+iOfst, iAmt); + return SQLITE_OK; +} + +/* +** Try to enlarge the memory allocation to hold at least sz bytes +*/ +static int memdbEnlarge(MemFile *p, tdsqlite3_int64 newSz){ + unsigned char *pNew; + if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){ + return SQLITE_FULL; + } + if( newSz>p->szMax ){ + return SQLITE_FULL; + } + newSz *= 2; + if( newSz>p->szMax ) newSz = p->szMax; + pNew = tdsqlite3_realloc64(p->aData, newSz); + if( pNew==0 ) return SQLITE_NOMEM; + p->aData = pNew; + p->szAlloc = newSz; + return SQLITE_OK; +} + +/* +** Write data to an memdb-file. +*/ +static int memdbWrite( + tdsqlite3_file *pFile, + const void *z, + int iAmt, + sqlite_int64 iOfst +){ + MemFile *p = (MemFile *)pFile; + if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ) return SQLITE_READONLY; + if( iOfst+iAmt>p->sz ){ + int rc; + if( iOfst+iAmt>p->szAlloc + && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK + ){ + return rc; + } + if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz); + p->sz = iOfst+iAmt; + } + memcpy(p->aData+iOfst, z, iAmt); + return SQLITE_OK; +} + +/* +** Truncate an memdb-file. +** +** In rollback mode (which is always the case for memdb, as it does not +** support WAL mode) the truncate() method is only used to reduce +** the size of a file, never to increase the size. +*/ +static int memdbTruncate(tdsqlite3_file *pFile, sqlite_int64 size){ + MemFile *p = (MemFile *)pFile; + if( NEVER(size>p->sz) ) return SQLITE_FULL; + p->sz = size; + return SQLITE_OK; +} + +/* +** Sync an memdb-file. +*/ +static int memdbSync(tdsqlite3_file *pFile, int flags){ + return SQLITE_OK; +} + +/* +** Return the current file-size of an memdb-file. +*/ +static int memdbFileSize(tdsqlite3_file *pFile, sqlite_int64 *pSize){ + MemFile *p = (MemFile *)pFile; + *pSize = p->sz; + return SQLITE_OK; +} + +/* +** Lock an memdb-file. +*/ +static int memdbLock(tdsqlite3_file *pFile, int eLock){ + MemFile *p = (MemFile *)pFile; + if( eLock>SQLITE_LOCK_SHARED + && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0 + ){ + return SQLITE_READONLY; + } + p->eLock = eLock; + return SQLITE_OK; +} + +#if 0 /* Never used because memdbAccess() always returns false */ +/* +** Check if another file-handle holds a RESERVED lock on an memdb-file. +*/ +static int memdbCheckReservedLock(tdsqlite3_file *pFile, int *pResOut){ + *pResOut = 0; + return SQLITE_OK; +} +#endif + +/* +** File control method. For custom operations on an memdb-file. +*/ +static int memdbFileControl(tdsqlite3_file *pFile, int op, void *pArg){ + MemFile *p = (MemFile *)pFile; + int rc = SQLITE_NOTFOUND; + if( op==SQLITE_FCNTL_VFSNAME ){ + *(char**)pArg = tdsqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz); + rc = SQLITE_OK; + } + if( op==SQLITE_FCNTL_SIZE_LIMIT ){ + tdsqlite3_int64 iLimit = *(tdsqlite3_int64*)pArg; + if( iLimit<p->sz ){ + if( iLimit<0 ){ + iLimit = p->szMax; + }else{ + iLimit = p->sz; + } + } + p->szMax = iLimit; + *(tdsqlite3_int64*)pArg = iLimit; + rc = SQLITE_OK; + } + return rc; +} + +#if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */ +/* +** Return the sector-size in bytes for an memdb-file. +*/ +static int memdbSectorSize(tdsqlite3_file *pFile){ + return 1024; +} +#endif + +/* +** Return the device characteristic flags supported by an memdb-file. +*/ +static int memdbDeviceCharacteristics(tdsqlite3_file *pFile){ + return SQLITE_IOCAP_ATOMIC | + SQLITE_IOCAP_POWERSAFE_OVERWRITE | + SQLITE_IOCAP_SAFE_APPEND | + SQLITE_IOCAP_SEQUENTIAL; +} + +/* Fetch a page of a memory-mapped file */ +static int memdbFetch( + tdsqlite3_file *pFile, + tdsqlite3_int64 iOfst, + int iAmt, + void **pp +){ + MemFile *p = (MemFile *)pFile; + if( iOfst+iAmt>p->sz ){ + *pp = 0; + }else{ + p->nMmap++; + *pp = (void*)(p->aData + iOfst); + } + return SQLITE_OK; +} + +/* Release a memory-mapped page */ +static int memdbUnfetch(tdsqlite3_file *pFile, tdsqlite3_int64 iOfst, void *pPage){ + MemFile *p = (MemFile *)pFile; + p->nMmap--; + return SQLITE_OK; +} + +/* +** Open an mem file handle. +*/ +static int memdbOpen( + tdsqlite3_vfs *pVfs, + const char *zName, + tdsqlite3_file *pFile, + int flags, + int *pOutFlags +){ + MemFile *p = (MemFile*)pFile; + if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){ + return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags); + } + memset(p, 0, sizeof(*p)); + p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE; + assert( pOutFlags!=0 ); /* True because flags==SQLITE_OPEN_MAIN_DB */ + *pOutFlags = flags | SQLITE_OPEN_MEMORY; + p->base.pMethods = &memdb_io_methods; + p->szMax = tdsqlite3GlobalConfig.mxMemdbSize; + return SQLITE_OK; +} + +#if 0 /* Only used to delete rollback journals, master journals, and WAL + ** files, none of which exist in memdb. So this routine is never used */ +/* +** Delete the file located at zPath. If the dirSync argument is true, +** ensure the file-system modifications are synced to disk before +** returning. +*/ +static int memdbDelete(tdsqlite3_vfs *pVfs, const char *zPath, int dirSync){ + return SQLITE_IOERR_DELETE; +} +#endif + +/* +** Test for access permissions. Return true if the requested permission +** is available, or false otherwise. +** +** With memdb, no files ever exist on disk. So always return false. +*/ +static int memdbAccess( + tdsqlite3_vfs *pVfs, + const char *zPath, + int flags, + int *pResOut +){ + *pResOut = 0; + return SQLITE_OK; +} + +/* +** Populate buffer zOut with the full canonical pathname corresponding +** to the pathname in zPath. zOut is guaranteed to point to a buffer +** of at least (INST_MAX_PATHNAME+1) bytes. +*/ +static int memdbFullPathname( + tdsqlite3_vfs *pVfs, + const char *zPath, + int nOut, + char *zOut +){ + tdsqlite3_snprintf(nOut, zOut, "%s", zPath); + return SQLITE_OK; +} + +/* +** Open the dynamic library located at zPath and return a handle. +*/ +static void *memdbDlOpen(tdsqlite3_vfs *pVfs, const char *zPath){ + return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath); +} + +/* +** Populate the buffer zErrMsg (size nByte bytes) with a human readable +** utf-8 string describing the most recent error encountered associated +** with dynamic libraries. +*/ +static void memdbDlError(tdsqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg); +} + +/* +** Return a pointer to the symbol zSymbol in the dynamic library pHandle. +*/ +static void (*memdbDlSym(tdsqlite3_vfs *pVfs, void *p, const char *zSym))(void){ + return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym); +} + +/* +** Close the dynamic library handle pHandle. +*/ +static void memdbDlClose(tdsqlite3_vfs *pVfs, void *pHandle){ + ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle); +} + +/* +** Populate the buffer pointed to by zBufOut with nByte bytes of +** random data. +*/ +static int memdbRandomness(tdsqlite3_vfs *pVfs, int nByte, char *zBufOut){ + return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut); +} + +/* +** Sleep for nMicro microseconds. Return the number of microseconds +** actually slept. +*/ +static int memdbSleep(tdsqlite3_vfs *pVfs, int nMicro){ + return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro); +} + +#if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */ +/* +** Return the current time as a Julian Day number in *pTimeOut. +*/ +static int memdbCurrentTime(tdsqlite3_vfs *pVfs, double *pTimeOut){ + return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut); +} +#endif + +static int memdbGetLastError(tdsqlite3_vfs *pVfs, int a, char *b){ + return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b); +} +static int memdbCurrentTimeInt64(tdsqlite3_vfs *pVfs, tdsqlite3_int64 *p){ + return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p); +} + +/* +** Translate a database connection pointer and schema name into a +** MemFile pointer. +*/ +static MemFile *memdbFromDbSchema(tdsqlite3 *db, const char *zSchema){ + MemFile *p = 0; + int rc = tdsqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p); + if( rc ) return 0; + if( p->base.pMethods!=&memdb_io_methods ) return 0; + return p; +} + +/* +** Return the serialization of a database +*/ +SQLITE_API unsigned char *tdsqlite3_serialize( + tdsqlite3 *db, /* The database connection */ + const char *zSchema, /* Which database within the connection */ + tdsqlite3_int64 *piSize, /* Write size here, if not NULL */ + unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */ +){ + MemFile *p; + int iDb; + Btree *pBt; + tdsqlite3_int64 sz; + int szPage = 0; + tdsqlite3_stmt *pStmt = 0; + unsigned char *pOut; + char *zSql; + int rc; + +#ifdef SQLITE_ENABLE_API_ARMOR + if( !tdsqlite3SafetyCheckOk(db) ){ + (void)SQLITE_MISUSE_BKPT; + return 0; + } +#endif + + if( zSchema==0 ) zSchema = db->aDb[0].zDbSName; + p = memdbFromDbSchema(db, zSchema); + iDb = tdsqlite3FindDbName(db, zSchema); + if( piSize ) *piSize = -1; + if( iDb<0 ) return 0; + if( p ){ + if( piSize ) *piSize = p->sz; + if( mFlags & SQLITE_SERIALIZE_NOCOPY ){ + pOut = p->aData; + }else{ + pOut = tdsqlite3_malloc64( p->sz ); + if( pOut ) memcpy(pOut, p->aData, p->sz); + } + return pOut; + } + pBt = db->aDb[iDb].pBt; + if( pBt==0 ) return 0; + szPage = tdsqlite3BtreeGetPageSize(pBt); + zSql = tdsqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema); + rc = zSql ? tdsqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM; + tdsqlite3_free(zSql); + if( rc ) return 0; + rc = tdsqlite3_step(pStmt); + if( rc!=SQLITE_ROW ){ + pOut = 0; + }else{ + sz = tdsqlite3_column_int64(pStmt, 0)*szPage; + if( piSize ) *piSize = sz; + if( mFlags & SQLITE_SERIALIZE_NOCOPY ){ + pOut = 0; + }else{ + pOut = tdsqlite3_malloc64( sz ); + if( pOut ){ + int nPage = tdsqlite3_column_int(pStmt, 0); + Pager *pPager = tdsqlite3BtreePager(pBt); + int pgno; + for(pgno=1; pgno<=nPage; pgno++){ + DbPage *pPage = 0; + unsigned char *pTo = pOut + szPage*(tdsqlite3_int64)(pgno-1); + rc = tdsqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0); + if( rc==SQLITE_OK ){ + memcpy(pTo, tdsqlite3PagerGetData(pPage), szPage); + }else{ + memset(pTo, 0, szPage); + } + tdsqlite3PagerUnref(pPage); + } + } + } + } + tdsqlite3_finalize(pStmt); + return pOut; +} + +/* Convert zSchema to a MemDB and initialize its content. +*/ +SQLITE_API int tdsqlite3_deserialize( + tdsqlite3 *db, /* The database connection */ + const char *zSchema, /* Which DB to reopen with the deserialization */ + unsigned char *pData, /* The serialized database content */ + tdsqlite3_int64 szDb, /* Number bytes in the deserialization */ + tdsqlite3_int64 szBuf, /* Total size of buffer pData[] */ + unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */ +){ + MemFile *p; + char *zSql; + tdsqlite3_stmt *pStmt = 0; + int rc; + int iDb; + +#ifdef SQLITE_ENABLE_API_ARMOR + if( !tdsqlite3SafetyCheckOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + if( szDb<0 ) return SQLITE_MISUSE_BKPT; + if( szBuf<0 ) return SQLITE_MISUSE_BKPT; +#endif + + tdsqlite3_mutex_enter(db->mutex); + if( zSchema==0 ) zSchema = db->aDb[0].zDbSName; + iDb = tdsqlite3FindDbName(db, zSchema); + if( iDb<0 ){ + rc = SQLITE_ERROR; + goto end_deserialize; + } + zSql = tdsqlite3_mprintf("ATTACH x AS %Q", zSchema); + rc = tdsqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + tdsqlite3_free(zSql); + if( rc ) goto end_deserialize; + db->init.iDb = (u8)iDb; + db->init.reopenMemdb = 1; + rc = tdsqlite3_step(pStmt); + db->init.reopenMemdb = 0; + if( rc!=SQLITE_DONE ){ + rc = SQLITE_ERROR; + goto end_deserialize; + } + p = memdbFromDbSchema(db, zSchema); + if( p==0 ){ + rc = SQLITE_ERROR; + }else{ + p->aData = pData; + p->sz = szDb; + p->szAlloc = szBuf; + p->szMax = szBuf; + if( p->szMax<tdsqlite3GlobalConfig.mxMemdbSize ){ + p->szMax = tdsqlite3GlobalConfig.mxMemdbSize; + } + p->mFlags = mFlags; + rc = SQLITE_OK; + } + +end_deserialize: + tdsqlite3_finalize(pStmt); + tdsqlite3_mutex_leave(db->mutex); + return rc; +} + +/* +** This routine is called when the extension is loaded. +** Register the new VFS. +*/ +SQLITE_PRIVATE int tdsqlite3MemdbInit(void){ + tdsqlite3_vfs *pLower = tdsqlite3_vfs_find(0); + int sz = pLower->szOsFile; + memdb_vfs.pAppData = pLower; + /* In all known configurations of SQLite, the size of a default + ** tdsqlite3_file is greater than the size of a memdb tdsqlite3_file. + ** Should that ever change, remove the following NEVER() */ + if( NEVER(sz<sizeof(MemFile)) ) sz = sizeof(MemFile); + memdb_vfs.szOsFile = sz; + return tdsqlite3_vfs_register(&memdb_vfs, 0); +} +#endif /* SQLITE_ENABLE_DESERIALIZE */ + +/************** End of memdb.c ***********************************************/ /************** Begin file bitvec.c ******************************************/ /* ** 2008 February 16 @@ -47040,10 +52575,10 @@ struct Bitvec { ** inclusive. Return a pointer to the new object. Return NULL if ** malloc fails. */ -SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){ +SQLITE_PRIVATE Bitvec *tdsqlite3BitvecCreate(u32 iSize){ Bitvec *p; assert( sizeof(*p)==BITVEC_SZ ); - p = sqlite3MallocZero( sizeof(*p) ); + p = tdsqlite3MallocZero( sizeof(*p) ); if( p ){ p->iSize = iSize; } @@ -47055,7 +52590,7 @@ SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){ ** If p is NULL (if the bitmap has not been created) or if ** i is out of range, then return false. */ -SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){ +SQLITE_PRIVATE int tdsqlite3BitvecTestNotNull(Bitvec *p, u32 i){ assert( p!=0 ); i--; if( i>=p->iSize ) return 0; @@ -47078,8 +52613,8 @@ SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){ return 0; } } -SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){ - return p!=0 && sqlite3BitvecTestNotNull(p,i); +SQLITE_PRIVATE int tdsqlite3BitvecTest(Bitvec *p, u32 i){ + return p!=0 && tdsqlite3BitvecTestNotNull(p,i); } /* @@ -47094,7 +52629,7 @@ SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){ ** and that the value for "i" is within range of the Bitvec object. ** Otherwise the behavior is undefined. */ -SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){ +SQLITE_PRIVATE int tdsqlite3BitvecSet(Bitvec *p, u32 i){ u32 h; if( p==0 ) return SQLITE_OK; assert( i>0 ); @@ -47104,7 +52639,7 @@ SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){ u32 bin = i/p->iDivisor; i = i%p->iDivisor; if( p->u.apSub[bin]==0 ){ - p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor ); + p->u.apSub[bin] = tdsqlite3BitvecCreate( p->iDivisor ); if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT; } p = p->u.apSub[bin]; @@ -47138,18 +52673,18 @@ bitvec_set_rehash: if( p->nSet>=BITVEC_MXHASH ){ unsigned int j; int rc; - u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash)); + u32 *aiValues = tdsqlite3StackAllocRaw(0, sizeof(p->u.aHash)); if( aiValues==0 ){ return SQLITE_NOMEM_BKPT; }else{ memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); memset(p->u.apSub, 0, sizeof(p->u.apSub)); p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR; - rc = sqlite3BitvecSet(p, i); + rc = tdsqlite3BitvecSet(p, i); for(j=0; j<BITVEC_NINT; j++){ - if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]); + if( aiValues[j] ) rc |= tdsqlite3BitvecSet(p, aiValues[j]); } - sqlite3StackFree(0, aiValues); + tdsqlite3StackFree(0, aiValues); return rc; } } @@ -47165,7 +52700,7 @@ bitvec_set_end: ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage ** that BitvecClear can use to rebuilt its hash table. */ -SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ +SQLITE_PRIVATE void tdsqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ if( p==0 ) return; assert( i>0 ); i--; @@ -47202,26 +52737,26 @@ SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ /* ** Destroy a bitmap object. Reclaim all memory used. */ -SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){ +SQLITE_PRIVATE void tdsqlite3BitvecDestroy(Bitvec *p){ if( p==0 ) return; if( p->iDivisor ){ unsigned int i; for(i=0; i<BITVEC_NPTR; i++){ - sqlite3BitvecDestroy(p->u.apSub[i]); + tdsqlite3BitvecDestroy(p->u.apSub[i]); } } - sqlite3_free(p); + tdsqlite3_free(p); } /* ** Return the value of the iSize parameter specified when Bitvec *p ** was created. */ -SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){ +SQLITE_PRIVATE u32 tdsqlite3BitvecSize(Bitvec *p){ return p->iSize; } -#ifndef SQLITE_OMIT_BUILTIN_TEST +#ifndef SQLITE_UNTESTABLE /* ** Let V[] be an array of unsigned characters sufficient to hold ** up to N bits. Let I be an integer between 0 and N. 0<=I<N. @@ -47262,7 +52797,7 @@ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){ ** ** If a memory allocation error occurs, return -1. */ -SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ +SQLITE_PRIVATE int tdsqlite3BitvecBuiltinTest(int sz, int *aOp){ Bitvec *pBitvec = 0; unsigned char *pV = 0; int rc = -1; @@ -47271,14 +52806,14 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ /* Allocate the Bitvec to be tested and a linear array of ** bits to act as the reference */ - pBitvec = sqlite3BitvecCreate( sz ); - pV = sqlite3MallocZero( (sz+7)/8 + 1 ); - pTmpSpace = sqlite3_malloc64(BITVEC_SZ); + pBitvec = tdsqlite3BitvecCreate( sz ); + pV = tdsqlite3MallocZero( (sz+7)/8 + 1 ); + pTmpSpace = tdsqlite3_malloc64(BITVEC_SZ); if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end; /* NULL pBitvec tests */ - sqlite3BitvecSet(0, 1); - sqlite3BitvecClear(0, 1, pTmpSpace); + tdsqlite3BitvecSet(0, 1); + tdsqlite3BitvecClear(0, 1, pTmpSpace); /* Run the program */ pc = 0; @@ -47296,7 +52831,7 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ case 4: default: { nx = 2; - sqlite3_randomness(sizeof(i), &i); + tdsqlite3_randomness(sizeof(i), &i); break; } } @@ -47306,11 +52841,11 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ if( (op & 1)!=0 ){ SETBIT(pV, (i+1)); if( op!=5 ){ - if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end; + if( tdsqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end; } }else{ CLEARBIT(pV, (i+1)); - sqlite3BitvecClear(pBitvec, i+1, pTmpSpace); + tdsqlite3BitvecClear(pBitvec, i+1, pTmpSpace); } } @@ -47319,11 +52854,11 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ ** match (rc==0). Change rc to non-zero if a discrepancy ** is found. */ - rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1) - + sqlite3BitvecTest(pBitvec, 0) - + (sqlite3BitvecSize(pBitvec) - sz); + rc = tdsqlite3BitvecTest(0,0) + tdsqlite3BitvecTest(pBitvec, sz+1) + + tdsqlite3BitvecTest(pBitvec, 0) + + (tdsqlite3BitvecSize(pBitvec) - sz); for(i=1; i<=sz; i++){ - if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){ + if( (TESTBIT(pV,i))!=tdsqlite3BitvecTest(pBitvec,i) ){ rc = i; break; } @@ -47331,12 +52866,12 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ /* Free allocated structure */ bitvec_end: - sqlite3_free(pTmpSpace); - sqlite3_free(pV); - sqlite3BitvecDestroy(pBitvec); + tdsqlite3_free(pTmpSpace); + tdsqlite3_free(pV); + tdsqlite3BitvecDestroy(pBitvec); return rc; } -#endif /* SQLITE_OMIT_BUILTIN_TEST */ +#endif /* SQLITE_UNTESTABLE */ /************** End of bitvec.c **********************************************/ /************** Begin file pcache.c ******************************************/ @@ -47374,7 +52909,7 @@ bitvec_end: ** The PCache.pSynced variable is used to optimize searching for a dirty ** page to eject from the cache mid-transaction. It is better to eject ** a page that does not require a journal sync than one that does. -** Therefore, pSynced is maintained to that it *almost* always points +** Therefore, pSynced is maintained so that it *almost* always points ** to either the oldest page in the pDirty/pDirtyTail list that has a ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one ** (so that the right page to eject can be found by following pDirtyPrev @@ -47392,7 +52927,7 @@ struct PCache { u8 eCreate; /* eCreate value for for xFetch() */ int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */ void *pStress; /* Argument to xStress */ - sqlite3_pcache *pCache; /* Pluggable cache module */ + tdsqlite3_pcache *pCache; /* Pluggable cache module */ }; /********************************** Test and Debug Logic **********************/ @@ -47400,27 +52935,27 @@ struct PCache { ** Debug tracing macros. Enable by by changing the "0" to "1" and ** recompiling. ** -** When sqlite3PcacheTrace is 1, single line trace messages are issued. -** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries +** When tdsqlite3PcacheTrace is 1, single line trace messages are issued. +** When tdsqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries ** is displayed for many operations, resulting in a lot of output. */ #if defined(SQLITE_DEBUG) && 0 - int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */ - int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */ -# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;} + int tdsqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */ + int tdsqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */ +# define pcacheTrace(X) if(tdsqlite3PcacheTrace){tdsqlite3DebugPrintf X;} void pcacheDump(PCache *pCache){ int N; int i, j; - sqlite3_pcache_page *pLower; + tdsqlite3_pcache_page *pLower; PgHdr *pPg; unsigned char *a; - if( sqlite3PcacheTrace<2 ) return; + if( tdsqlite3PcacheTrace<2 ) return; if( pCache->pCache==0 ) return; - N = sqlite3PcachePagecount(pCache); - if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump; + N = tdsqlite3PcachePagecount(pCache); + if( N>tdsqlite3PcacheMxDump ) N = tdsqlite3PcacheMxDump; for(i=1; i<=N; i++){ - pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0); + pLower = tdsqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0); if( pLower==0 ) continue; pPg = (PgHdr*)pLower->pExtra; printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags); @@ -47428,7 +52963,7 @@ struct PCache { for(j=0; j<12; j++) printf("%02x", a[j]); printf("\n"); if( pPg->pPage==0 ){ - sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0); + tdsqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0); } } } @@ -47444,13 +52979,13 @@ struct PCache { ** This routine is for use inside of assert() statements only. For ** example: ** -** assert( sqlite3PcachePageSanity(pPg) ); +** assert( tdsqlite3PcachePageSanity(pPg) ); */ -#if SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){ +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int tdsqlite3PcachePageSanity(PgHdr *pPg){ PCache *pCache; assert( pPg!=0 ); - assert( pPg->pgno>0 ); /* Page number is 1 or more */ + assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */ pCache = pPg->pCache; assert( pCache!=0 ); /* Every page has an associated PCache */ if( pPg->flags & PGHDR_CLEAN ){ @@ -47463,7 +52998,7 @@ SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){ assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */ } /* NEED_SYNC can be set independently of WRITEABLE. This can happen, - ** for example, when using the sqlite3PagerDontWrite() optimization: + ** for example, when using the tdsqlite3PagerDontWrite() optimization: ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK. ** (2) Page X moved to freelist, WRITEABLE is cleared ** (3) Page X reused, WRITEABLE is set again @@ -47522,7 +53057,7 @@ static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){ pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext; }else{ /* If there are now no dirty pages in the cache, set eCreate to 2. - ** This is an optimization that allows sqlite3PcacheFetch() to skip + ** This is an optimization that allows tdsqlite3PcacheFetch() to skip ** searching for a dirty page to eject from the cache when it might ** otherwise have to. */ assert( pPage==p->pDirty ); @@ -47533,12 +53068,9 @@ static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){ p->eCreate = 2; } } - pPage->pDirtyNext = 0; - pPage->pDirtyPrev = 0; } if( addRemove & PCACHE_DIRTYLIST_ADD ){ - assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage ); - + pPage->pDirtyPrev = 0; pPage->pDirtyNext = p->pDirty; if( pPage->pDirtyNext ){ assert( pPage->pDirtyNext->pDirtyPrev==0 ); @@ -47555,7 +53087,7 @@ static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){ /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set ** pSynced to point to it. Checking the NEED_SYNC flag is an ** optimization, as if pSynced points to a page with the NEED_SYNC - ** flag set sqlite3PcacheFetchStress() searches through all newer + ** flag set tdsqlite3PcacheFetchStress() searches through all newer ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */ if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/ @@ -47573,7 +53105,7 @@ static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){ static void pcacheUnpin(PgHdr *p){ if( p->pCache->bPurgeable ){ pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno)); - sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0); + tdsqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0); pcacheDump(p->pCache); } } @@ -47588,9 +53120,10 @@ static int numberOfCachePages(PCache *p){ ** suggested cache size is set to N. */ return p->szCache; }else{ - /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then - ** the number of cache pages is adjusted to use approximately abs(N*1024) - ** bytes of memory. */ + /* IMPLEMANTATION-OF: R-59858-46238 If the argument N is negative, then the + ** number of cache pages is adjusted to be a number of pages that would + ** use approximately abs(N*1024) bytes of memory based on the current + ** page size. */ return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra)); } } @@ -47600,34 +53133,41 @@ static int numberOfCachePages(PCache *p){ ** Initialize and shutdown the page cache subsystem. Neither of these ** functions are threadsafe. */ -SQLITE_PRIVATE int sqlite3PcacheInitialize(void){ - if( sqlite3GlobalConfig.pcache2.xInit==0 ){ +SQLITE_PRIVATE int tdsqlite3PcacheInitialize(void){ + if( tdsqlite3GlobalConfig.pcache2.xInit==0 ){ /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the ** built-in default page cache is used instead of the application defined ** page cache. */ - sqlite3PCacheSetDefault(); + tdsqlite3PCacheSetDefault(); + assert( tdsqlite3GlobalConfig.pcache2.xInit!=0 ); } - return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg); + return tdsqlite3GlobalConfig.pcache2.xInit(tdsqlite3GlobalConfig.pcache2.pArg); } -SQLITE_PRIVATE void sqlite3PcacheShutdown(void){ - if( sqlite3GlobalConfig.pcache2.xShutdown ){ +SQLITE_PRIVATE void tdsqlite3PcacheShutdown(void){ + if( tdsqlite3GlobalConfig.pcache2.xShutdown ){ /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */ - sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg); + tdsqlite3GlobalConfig.pcache2.xShutdown(tdsqlite3GlobalConfig.pcache2.pArg); } } /* ** Return the size in bytes of a PCache object. */ -SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); } +SQLITE_PRIVATE int tdsqlite3PcacheSize(void){ return sizeof(PCache); } /* ** Create a new PCache object. Storage space to hold the object ** has already been allocated and is passed in as the p pointer. ** The caller discovers how much space needs to be allocated by -** calling sqlite3PcacheSize(). +** calling tdsqlite3PcacheSize(). +** +** szExtra is some extra space allocated for each page. The first +** 8 bytes of the extra space will be zeroed as the page is allocated, +** but remaining content will be uninitialized. Though it is opaque +** to this module, the extra space really ends up being the MemPage +** structure in the pager. */ -SQLITE_PRIVATE int sqlite3PcacheOpen( +SQLITE_PRIVATE int tdsqlite3PcacheOpen( int szPage, /* Size of every page */ int szExtra, /* Extra space associated with each page */ int bPurgeable, /* True if pages are on backing store */ @@ -47638,6 +53178,7 @@ SQLITE_PRIVATE int sqlite3PcacheOpen( memset(p, 0, sizeof(PCache)); p->szPage = 1; p->szExtra = szExtra; + assert( szExtra>=8 ); /* First 8 bytes will be zeroed */ p->bPurgeable = bPurgeable; p->eCreate = 2; p->xStress = xStress; @@ -47645,25 +53186,25 @@ SQLITE_PRIVATE int sqlite3PcacheOpen( p->szCache = 100; p->szSpill = 1; pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable)); - return sqlite3PcacheSetPageSize(p, szPage); + return tdsqlite3PcacheSetPageSize(p, szPage); } /* ** Change the page size for PCache object. The caller must ensure that there ** are no outstanding page references when this function is called. */ -SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ +SQLITE_PRIVATE int tdsqlite3PcacheSetPageSize(PCache *pCache, int szPage){ assert( pCache->nRefSum==0 && pCache->pDirty==0 ); if( pCache->szPage ){ - sqlite3_pcache *pNew; - pNew = sqlite3GlobalConfig.pcache2.xCreate( + tdsqlite3_pcache *pNew; + pNew = tdsqlite3GlobalConfig.pcache2.xCreate( szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)), pCache->bPurgeable ); if( pNew==0 ) return SQLITE_NOMEM_BKPT; - sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache)); + tdsqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache)); if( pCache->pCache ){ - sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); + tdsqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); } pCache->pCache = pNew; pCache->szPage = szPage; @@ -47675,7 +53216,7 @@ SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ /* ** Try to obtain a page from the cache. ** -** This routine returns a pointer to an sqlite3_pcache_page object if +** This routine returns a pointer to an tdsqlite3_pcache_page object if ** such an object is already in cache, or if a new one is created. ** This routine returns a NULL pointer if the object was not in cache ** and could not be created. @@ -47688,26 +53229,25 @@ SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ ** is created only if that can be done without spilling dirty pages ** and without exceeding the cache size limit. ** -** The caller needs to invoke sqlite3PcacheFetchFinish() to properly -** initialize the sqlite3_pcache_page object and convert it into a -** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish() +** The caller needs to invoke tdsqlite3PcacheFetchFinish() to properly +** initialize the tdsqlite3_pcache_page object and convert it into a +** PgHdr object. The tdsqlite3PcacheFetch() and tdsqlite3PcacheFetchFinish() ** routines are split this way for performance reasons. When separated ** they can both (usually) operate without having to push values to ** the stack on entry and pop them back off on exit, which saves a ** lot of pushing and popping. */ -SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch( +SQLITE_PRIVATE tdsqlite3_pcache_page *tdsqlite3PcacheFetch( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number to obtain */ int createFlag /* If true, create page if it does not exist already */ ){ int eCreate; - sqlite3_pcache_page *pRes; + tdsqlite3_pcache_page *pRes; assert( pCache!=0 ); assert( pCache->pCache!=0 ); assert( createFlag==3 || createFlag==0 ); - assert( pgno>0 ); assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) ); /* eCreate defines what to do if the page does not exist. @@ -47721,14 +53261,14 @@ SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch( assert( eCreate==0 || eCreate==1 || eCreate==2 ); assert( createFlag==0 || pCache->eCreate==eCreate ); assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) ); - pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate); + pRes = tdsqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate); pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno, createFlag?" create":"",pRes)); return pRes; } /* -** If the sqlite3PcacheFetch() routine is unable to allocate a new +** If the tdsqlite3PcacheFetch() routine is unable to allocate a new ** page because no clean pages are available for reuse and the cache ** size limit has been reached, then this routine can be invoked to ** try harder to allocate a page. This routine might invoke the stress @@ -47736,17 +53276,17 @@ SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch( ** allocate the new page and will only fail to allocate a new page on ** an OOM error. ** -** This routine should be invoked only after sqlite3PcacheFetch() fails. +** This routine should be invoked only after tdsqlite3PcacheFetch() fails. */ -SQLITE_PRIVATE int sqlite3PcacheFetchStress( +SQLITE_PRIVATE int tdsqlite3PcacheFetchStress( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number to obtain */ - sqlite3_pcache_page **ppPage /* Write result here */ + tdsqlite3_pcache_page **ppPage /* Write result here */ ){ PgHdr *pPg; if( pCache->eCreate==2 ) return 0; - if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){ + if( tdsqlite3PcachePagecount(pCache)>pCache->szSpill ){ /* Find a dirty page to write-out and recycle. First try to find a ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC ** cleared), but if that is not possible settle for any other @@ -47767,10 +53307,10 @@ SQLITE_PRIVATE int sqlite3PcacheFetchStress( if( pPg ){ int rc; #ifdef SQLITE_LOG_CACHE_SPILL - sqlite3_log(SQLITE_FULL, + tdsqlite3_log(SQLITE_FULL, "spill page %d making room for %d - cache used: %d/%d", pPg->pgno, pgno, - sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache), + tdsqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache), numberOfCachePages(pCache)); #endif pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno)); @@ -47781,12 +53321,12 @@ SQLITE_PRIVATE int sqlite3PcacheFetchStress( } } } - *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2); + *ppPage = tdsqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2); return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK; } /* -** This is a helper routine for sqlite3PcacheFetchFinish() +** This is a helper routine for tdsqlite3PcacheFetchFinish() ** ** In the uncommon case where the page being fetched has not been ** initialized, this routine is invoked to do the initialization. @@ -47797,7 +53337,7 @@ SQLITE_PRIVATE int sqlite3PcacheFetchStress( static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number obtained */ - sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ + tdsqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ ){ PgHdr *pPgHdr; assert( pPage!=0 ); @@ -47807,23 +53347,23 @@ static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit( pPgHdr->pPage = pPage; pPgHdr->pData = pPage->pBuf; pPgHdr->pExtra = (void *)&pPgHdr[1]; - memset(pPgHdr->pExtra, 0, pCache->szExtra); + memset(pPgHdr->pExtra, 0, 8); pPgHdr->pCache = pCache; pPgHdr->pgno = pgno; pPgHdr->flags = PGHDR_CLEAN; - return sqlite3PcacheFetchFinish(pCache,pgno,pPage); + return tdsqlite3PcacheFetchFinish(pCache,pgno,pPage); } /* -** This routine converts the sqlite3_pcache_page object returned by -** sqlite3PcacheFetch() into an initialized PgHdr object. This routine -** must be called after sqlite3PcacheFetch() in order to get a usable +** This routine converts the tdsqlite3_pcache_page object returned by +** tdsqlite3PcacheFetch() into an initialized PgHdr object. This routine +** must be called after tdsqlite3PcacheFetch() in order to get a usable ** result. */ -SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish( +SQLITE_PRIVATE PgHdr *tdsqlite3PcacheFetchFinish( PCache *pCache, /* Obtain the page from this cache */ Pgno pgno, /* Page number obtained */ - sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ + tdsqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ ){ PgHdr *pPgHdr; @@ -47835,7 +53375,7 @@ SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish( } pCache->nRefSum++; pPgHdr->nRef++; - assert( sqlite3PcachePageSanity(pPgHdr) ); + assert( tdsqlite3PcachePageSanity(pPgHdr) ); return pPgHdr; } @@ -47843,17 +53383,13 @@ SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish( ** Decrement the reference count on a page. If the page is clean and the ** reference count drops to 0, then it is made eligible for recycling. */ -SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){ +SQLITE_PRIVATE void SQLITE_NOINLINE tdsqlite3PcacheRelease(PgHdr *p){ assert( p->nRef>0 ); p->pCache->nRefSum--; if( (--p->nRef)==0 ){ if( p->flags&PGHDR_CLEAN ){ pcacheUnpin(p); - }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/ - /* Move the page to the head of the dirty list. If p->pDirtyPrev==0, - ** then page p is already at the head of the dirty list and the - ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE - ** tag above. */ + }else{ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT); } } @@ -47862,9 +53398,9 @@ SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){ /* ** Increase the reference count of a supplied page by 1. */ -SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){ +SQLITE_PRIVATE void tdsqlite3PcacheRef(PgHdr *p){ assert(p->nRef>0); - assert( sqlite3PcachePageSanity(p) ); + assert( tdsqlite3PcachePageSanity(p) ); p->nRef++; p->pCache->nRefSum++; } @@ -47874,23 +53410,23 @@ SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){ ** page. This function deletes that reference, so after it returns the ** page pointed to by p is invalid. */ -SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){ +SQLITE_PRIVATE void tdsqlite3PcacheDrop(PgHdr *p){ assert( p->nRef==1 ); - assert( sqlite3PcachePageSanity(p) ); + assert( tdsqlite3PcachePageSanity(p) ); if( p->flags&PGHDR_DIRTY ){ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE); } p->pCache->nRefSum--; - sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1); + tdsqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1); } /* ** Make sure the page is marked as dirty. If it isn't dirty already, ** make it so. */ -SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){ +SQLITE_PRIVATE void tdsqlite3PcacheMakeDirty(PgHdr *p){ assert( p->nRef>0 ); - assert( sqlite3PcachePageSanity(p) ); + assert( tdsqlite3PcachePageSanity(p) ); if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/ p->flags &= ~PGHDR_DONT_WRITE; if( p->flags & PGHDR_CLEAN ){ @@ -47899,7 +53435,7 @@ SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){ assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY ); pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD); } - assert( sqlite3PcachePageSanity(p) ); + assert( tdsqlite3PcachePageSanity(p) ); } } @@ -47907,36 +53443,35 @@ SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){ ** Make sure the page is marked as clean. If it isn't clean already, ** make it so. */ -SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){ - assert( sqlite3PcachePageSanity(p) ); - if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){ - assert( (p->flags & PGHDR_CLEAN)==0 ); - pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE); - p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE); - p->flags |= PGHDR_CLEAN; - pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno)); - assert( sqlite3PcachePageSanity(p) ); - if( p->nRef==0 ){ - pcacheUnpin(p); - } +SQLITE_PRIVATE void tdsqlite3PcacheMakeClean(PgHdr *p){ + assert( tdsqlite3PcachePageSanity(p) ); + assert( (p->flags & PGHDR_DIRTY)!=0 ); + assert( (p->flags & PGHDR_CLEAN)==0 ); + pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE); + p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE); + p->flags |= PGHDR_CLEAN; + pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno)); + assert( tdsqlite3PcachePageSanity(p) ); + if( p->nRef==0 ){ + pcacheUnpin(p); } } /* ** Make every page in the cache clean. */ -SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){ +SQLITE_PRIVATE void tdsqlite3PcacheCleanAll(PCache *pCache){ PgHdr *p; pcacheTrace(("%p.CLEAN-ALL\n",pCache)); while( (p = pCache->pDirty)!=0 ){ - sqlite3PcacheMakeClean(p); + tdsqlite3PcacheMakeClean(p); } } /* ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages. */ -SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){ +SQLITE_PRIVATE void tdsqlite3PcacheClearWritable(PCache *pCache){ PgHdr *p; pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache)); for(p=pCache->pDirty; p; p=p->pDirtyNext){ @@ -47948,7 +53483,7 @@ SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){ /* ** Clear the PGHDR_NEED_SYNC flag from all dirty pages. */ -SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){ +SQLITE_PRIVATE void tdsqlite3PcacheClearSyncFlags(PCache *pCache){ PgHdr *p; for(p=pCache->pDirty; p; p=p->pDirtyNext){ p->flags &= ~PGHDR_NEED_SYNC; @@ -47959,13 +53494,13 @@ SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){ /* ** Change the page number of page p to newPgno. */ -SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){ +SQLITE_PRIVATE void tdsqlite3PcacheMove(PgHdr *p, Pgno newPgno){ PCache *pCache = p->pCache; assert( p->nRef>0 ); assert( newPgno>0 ); - assert( sqlite3PcachePageSanity(p) ); + assert( tdsqlite3PcachePageSanity(p) ); pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno)); - sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno); + tdsqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno); p->pgno = newPgno; if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){ pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT); @@ -47981,7 +53516,7 @@ SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){ ** function is 0, then the data area associated with page 1 is zeroed, but ** the page object is not dropped. */ -SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){ +SQLITE_PRIVATE void tdsqlite3PcacheTruncate(PCache *pCache, Pgno pgno){ if( pCache->pCache ){ PgHdr *p; PgHdr *pNext; @@ -47989,42 +53524,42 @@ SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){ for(p=pCache->pDirty; p; p=pNext){ pNext = p->pDirtyNext; /* This routine never gets call with a positive pgno except right - ** after sqlite3PcacheCleanAll(). So if there are dirty pages, + ** after tdsqlite3PcacheCleanAll(). So if there are dirty pages, ** it must be that pgno==0. */ assert( p->pgno>0 ); if( p->pgno>pgno ){ assert( p->flags&PGHDR_DIRTY ); - sqlite3PcacheMakeClean(p); + tdsqlite3PcacheMakeClean(p); } } if( pgno==0 && pCache->nRefSum ){ - sqlite3_pcache_page *pPage1; - pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0); + tdsqlite3_pcache_page *pPage1; + pPage1 = tdsqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0); if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because ** pCache->nRefSum>0 */ memset(pPage1->pBuf, 0, pCache->szPage); pgno = 1; } } - sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1); + tdsqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1); } } /* ** Close a cache. */ -SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){ +SQLITE_PRIVATE void tdsqlite3PcacheClose(PCache *pCache){ assert( pCache->pCache!=0 ); pcacheTrace(("%p.CLOSE\n",pCache)); - sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); + tdsqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); } /* ** Discard the contents of the cache. */ -SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){ - sqlite3PcacheTruncate(pCache, 0); +SQLITE_PRIVATE void tdsqlite3PcacheClear(PCache *pCache){ + tdsqlite3PcacheTruncate(pCache, 0); } /* @@ -48103,7 +53638,7 @@ static PgHdr *pcacheSortDirtyList(PgHdr *pIn){ /* ** Return a list of all dirty pages in the cache, sorted by page number. */ -SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){ +SQLITE_PRIVATE PgHdr *tdsqlite3PcacheDirtyList(PCache *pCache){ PgHdr *p; for(p=pCache->pDirty; p; p=p->pDirtyNext){ p->pDirty = p->pDirtyNext; @@ -48117,30 +53652,30 @@ SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){ ** This is not the total number of pages referenced, but the sum of the ** reference count for all pages. */ -SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){ +SQLITE_PRIVATE int tdsqlite3PcacheRefCount(PCache *pCache){ return pCache->nRefSum; } /* ** Return the number of references to the page supplied as an argument. */ -SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){ +SQLITE_PRIVATE int tdsqlite3PcachePageRefcount(PgHdr *p){ return p->nRef; } /* ** Return the total number of pages in the cache. */ -SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){ +SQLITE_PRIVATE int tdsqlite3PcachePagecount(PCache *pCache){ assert( pCache->pCache!=0 ); - return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache); + return tdsqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache); } #ifdef SQLITE_TEST /* ** Get the suggested cache-size value. */ -SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){ +SQLITE_PRIVATE int tdsqlite3PcacheGetCachesize(PCache *pCache){ return numberOfCachePages(pCache); } #endif @@ -48148,10 +53683,10 @@ SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){ /* ** Set the suggested cache-size value. */ -SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){ +SQLITE_PRIVATE void tdsqlite3PcacheSetCachesize(PCache *pCache, int mxPage){ assert( pCache->pCache!=0 ); pCache->szCache = mxPage; - sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache, + tdsqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache, numberOfCachePages(pCache)); } @@ -48160,7 +53695,7 @@ SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){ ** argument is zero. Return the effective cache-spill size, which will ** be the larger of the szSpill and szCache. */ -SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){ +SQLITE_PRIVATE int tdsqlite3PcacheSetSpillsize(PCache *p, int mxPage){ int res; assert( p->pCache!=0 ); if( mxPage ){ @@ -48177,22 +53712,22 @@ SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){ /* ** Free up as much memory as possible from the page cache. */ -SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){ +SQLITE_PRIVATE void tdsqlite3PcacheShrink(PCache *pCache){ assert( pCache->pCache!=0 ); - sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache); + tdsqlite3GlobalConfig.pcache2.xShrink(pCache->pCache); } /* ** Return the size of the header added by this middleware layer ** in the page-cache hierarchy. */ -SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); } +SQLITE_PRIVATE int tdsqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); } /* ** Return the number of dirty pages currently in the cache, as a percentage ** of the configured cache size. */ -SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){ +SQLITE_PRIVATE int tdsqlite3PCachePercentDirty(PCache *pCache){ PgHdr *pDirty; int nDirty = 0; int nCache = numberOfCachePages(pCache); @@ -48200,13 +53735,22 @@ SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){ return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0; } +#ifdef SQLITE_DIRECT_OVERFLOW_READ +/* +** Return true if there are one or more dirty pages in the cache. Else false. +*/ +SQLITE_PRIVATE int tdsqlite3PCacheIsDirty(PCache *pCache){ + return (pCache->pDirty!=0); +} +#endif + #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) /* ** For all dirty pages currently in the cache, invoke the specified ** callback. This is only used if the SQLITE_CHECK_PAGES macro is ** defined. */ -SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){ +SQLITE_PRIVATE void tdsqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){ PgHdr *pDirty; for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){ xIter(pDirty); @@ -48229,8 +53773,8 @@ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHd ************************************************************************* ** ** This file implements the default page cache implementation (the -** sqlite3_pcache interface). It also contains part of the implementation -** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features. +** tdsqlite3_pcache interface). It also contains part of the implementation +** of the SQLITE_CONFIG_PAGECACHE and tdsqlite3_release_memory() features. ** If the default page cache implementation is overridden, then neither of ** these two features are available. ** @@ -48246,13 +53790,13 @@ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHd ** as the database page number and how that database page is used. PgHdr ** is added by the pcache.c layer and contains information used to keep track ** of which pages are "dirty". PgHdr1 is an extension added by this -** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page. +** module (pcache1.c). The PgHdr1 header is a subclass of tdsqlite3_pcache_page. ** PgHdr1 contains information needed to look up a page by its page number. -** The superclass sqlite3_pcache_page.pBuf points to the start of the -** database page content and sqlite3_pcache_page.pExtra points to PgHdr. +** The superclass tdsqlite3_pcache_page.pBuf points to the start of the +** database page content and tdsqlite3_pcache_page.pExtra points to PgHdr. ** ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at -** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The +** runtime using tdsqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this ** size can vary according to architecture, compile-time options, and ** SQLite library version number. @@ -48274,8 +53818,8 @@ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHd ** ** Memory for a page might come from any of three sources: ** -** (1) The general-purpose memory allocator - sqlite3Malloc() -** (2) Global page-cache memory provided using sqlite3_config() with +** (1) The general-purpose memory allocator - tdsqlite3Malloc() +** (2) Global page-cache memory provided using tdsqlite3_config() with ** SQLITE_CONFIG_PAGECACHE. ** (3) PCache-local bulk allocation. ** @@ -48283,10 +53827,10 @@ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHd ** that is allocated when the page cache is created. The size of the local ** bulk allocation can be adjusted using ** -** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N). +** tdsqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N). ** ** If N is positive, then N pages worth of memory are allocated using a single -** sqlite3Malloc() call and that memory is used for the first N pages allocated. +** tdsqlite3Malloc() call and that memory is used for the first N pages allocated. ** Or if N is negative, then -1024*N bytes of memory are allocated and used ** for as many pages as can be accomodated. ** @@ -48310,19 +53854,36 @@ typedef struct PGroup PGroup; ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of ** PgHdr1.pCache->szPage bytes is allocated directly before this structure ** in memory. +** +** Note: Variables isBulkLocal and isAnchor were once type "u8". That works, +** but causes a 2-byte gap in the structure for most architectures (since +** pointers must be either 4 or 8-byte aligned). As this structure is located +** in memory directly after the associated page data, if the database is +** corrupt, code at the b-tree layer may overread the page buffer and +** read part of this structure before the corruption is detected. This +** can cause a valgrind error if the unitialized gap is accessed. Using u16 +** ensures there is no such gap, and therefore no bytes of unitialized memory +** in the structure. */ struct PgHdr1 { - sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */ + tdsqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */ unsigned int iKey; /* Key value (page number) */ - u8 isPinned; /* Page in use, not on the LRU list */ - u8 isBulkLocal; /* This page from bulk local storage */ - u8 isAnchor; /* This is the PGroup.lru element */ + u16 isBulkLocal; /* This page from bulk local storage */ + u16 isAnchor; /* This is the PGroup.lru element */ PgHdr1 *pNext; /* Next in hash table chain */ PCache1 *pCache; /* Cache that currently owns this page */ PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */ PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */ + /* NB: pLruPrev is only valid if pLruNext!=0 */ }; +/* +** A page is pinned if it is not on the LRU list. To be "pinned" means +** that the page is in active use and must not be deallocated. +*/ +#define PAGE_IS_PINNED(p) ((p)->pLruNext==0) +#define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0) + /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set ** of one or more PCaches that are able to recycle each other's unpinned ** pages when they are under memory pressure. A PGroup is an instance of @@ -48346,11 +53907,11 @@ struct PgHdr1 { ** SQLITE_MUTEX_STATIC_LRU. */ struct PGroup { - sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */ + tdsqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */ unsigned int nMaxPage; /* Sum of nMax for purgeable caches */ unsigned int nMinPage; /* Sum of nMin for purgeable caches */ unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */ - unsigned int nCurrentPage; /* Number of purgeable pages allocated */ + unsigned int nPurgeable; /* Number of purgeable pages allocated */ PgHdr1 lru; /* The beginning and end of the LRU list */ }; @@ -48360,15 +53921,17 @@ struct PGroup { ** is an instance of this object. ** ** Pointers to structures of this type are cast and returned as -** opaque sqlite3_pcache* handles. +** opaque tdsqlite3_pcache* handles. */ struct PCache1 { /* Cache configuration parameters. Page size (szPage) and the purgeable - ** flag (bPurgeable) are set when the cache is created. nMax may be + ** flag (bPurgeable) and the pnPurgeable pointer are all set when the + ** cache is created and are never changed thereafter. nMax may be ** modified at any time by a call to the pcache1Cachesize() method. ** The PGroup mutex must be held when accessing nMax. */ PGroup *pGroup; /* PGroup this cache belongs to */ + unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */ int szPage; /* Size of database content section */ int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */ int szAlloc; /* Total size of one pcache line */ @@ -48377,6 +53940,7 @@ struct PCache1 { unsigned int nMax; /* Configured "cache_size" value */ unsigned int n90pct; /* nMax*9/10 */ unsigned int iMaxKey; /* Largest key seen since xTruncate() */ + unsigned int nPurgeableDummy; /* pnPurgeable points here when not used*/ /* Hash table of all pages. The following variables may only be accessed ** when the accessor is holding the PGroup mutex. @@ -48405,7 +53969,7 @@ static SQLITE_WSD struct PCacheGlobal { /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all - ** fixed at sqlite3_initialize() time and do not require mutex protection. + ** fixed at tdsqlite3_initialize() time and do not require mutex protection. ** The nFreeSlot and pFree values do require mutex protection. */ int isInit; /* True if initialized */ @@ -48416,7 +53980,7 @@ static SQLITE_WSD struct PCacheGlobal { int nReserve; /* Try to keep nFreeSlot above this */ void *pStart, *pEnd; /* Bounds of global page cache memory */ /* Above requires no mutex. Use mutex below for variable that follow. */ - sqlite3_mutex *mutex; /* Mutex for accessing the following: */ + tdsqlite3_mutex *mutex; /* Mutex for accessing the following: */ PgFreeslot *pFree; /* Free page blocks */ int nFreeSlot; /* Number of unused pcache slots */ /* The following value requires a mutex to change. We skip the mutex on @@ -48441,8 +54005,8 @@ static SQLITE_WSD struct PCacheGlobal { # define pcache1LeaveMutex(X) assert((X)->mutex==0) # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0 #else -# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex) -# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex) +# define pcache1EnterMutex(X) tdsqlite3_mutex_enter((X)->mutex) +# define pcache1LeaveMutex(X) tdsqlite3_mutex_leave((X)->mutex) # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1 #endif @@ -48453,16 +54017,17 @@ static SQLITE_WSD struct PCacheGlobal { /* ** This function is called during initialization if a static buffer is ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE -** verb to sqlite3_config(). Parameter pBuf points to an allocation large +** verb to tdsqlite3_config(). Parameter pBuf points to an allocation large ** enough to contain 'n' buffers of 'sz' bytes each. ** -** This routine is called from sqlite3_initialize() and so it is guaranteed +** This routine is called from tdsqlite3_initialize() and so it is guaranteed ** to be serialized already. There is no need for further mutexing. */ -SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){ +SQLITE_PRIVATE void tdsqlite3PCacheBufferSetup(void *pBuf, int sz, int n){ if( pcache1.isInit ){ PgFreeslot *p; if( pBuf==0 ) sz = n = 0; + if( n==0 ) sz = 0; sz = ROUNDDOWN8(sz); pcache1.szSlot = sz; pcache1.nSlot = pcache1.nFreeSlot = n; @@ -48490,7 +54055,7 @@ static int pcache1InitBulk(PCache1 *pCache){ if( pcache1.nInitPage==0 ) return 0; /* Do not bother with a bulk allocation if the cache size very small */ if( pCache->nMax<3 ) return 0; - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); if( pcache1.nInitPage>0 ){ szBulk = pCache->szAlloc * (i64)pcache1.nInitPage; }else{ @@ -48499,65 +54064,65 @@ static int pcache1InitBulk(PCache1 *pCache){ if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){ szBulk = pCache->szAlloc*(i64)pCache->nMax; } - zBulk = pCache->pBulk = sqlite3Malloc( szBulk ); - sqlite3EndBenignMalloc(); + zBulk = pCache->pBulk = tdsqlite3Malloc( szBulk ); + tdsqlite3EndBenignMalloc(); if( zBulk ){ - int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc; - int i; - for(i=0; i<nBulk; i++){ + int nBulk = tdsqlite3MallocSize(zBulk)/pCache->szAlloc; + do{ PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage]; pX->page.pBuf = zBulk; pX->page.pExtra = &pX[1]; pX->isBulkLocal = 1; pX->isAnchor = 0; pX->pNext = pCache->pFree; + pX->pLruPrev = 0; /* Initializing this saves a valgrind error */ pCache->pFree = pX; zBulk += pCache->szAlloc; - } + }while( --nBulk ); } return pCache->pFree!=0; } /* ** Malloc function used within this file to allocate space from the buffer -** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no +** configured using tdsqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no ** such buffer exists or there is no space left in it, this function falls -** back to sqlite3Malloc(). +** back to tdsqlite3Malloc(). ** ** Multiple threads can run this routine at the same time. Global variables ** in pcache1 need to be protected via mutex. */ static void *pcache1Alloc(int nByte){ void *p = 0; - assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); + assert( tdsqlite3_mutex_notheld(pcache1.grp.mutex) ); if( nByte<=pcache1.szSlot ){ - sqlite3_mutex_enter(pcache1.mutex); + tdsqlite3_mutex_enter(pcache1.mutex); p = (PgHdr1 *)pcache1.pFree; if( p ){ pcache1.pFree = pcache1.pFree->pNext; pcache1.nFreeSlot--; pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve; assert( pcache1.nFreeSlot>=0 ); - sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); - sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1); + tdsqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); + tdsqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1); } - sqlite3_mutex_leave(pcache1.mutex); + tdsqlite3_mutex_leave(pcache1.mutex); } if( p==0 ){ /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get - ** it from sqlite3Malloc instead. + ** it from tdsqlite3Malloc instead. */ - p = sqlite3Malloc(nByte); + p = tdsqlite3Malloc(nByte); #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS if( p ){ - int sz = sqlite3MallocSize(p); - sqlite3_mutex_enter(pcache1.mutex); - sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); - sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz); - sqlite3_mutex_leave(pcache1.mutex); + int sz = tdsqlite3MallocSize(p); + tdsqlite3_mutex_enter(pcache1.mutex); + tdsqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); + tdsqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz); + tdsqlite3_mutex_leave(pcache1.mutex); } #endif - sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); + tdsqlite3MemdebugSetType(p, MEMTYPE_PCACHE); } return p; } @@ -48569,28 +54134,28 @@ static void pcache1Free(void *p){ if( p==0 ) return; if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){ PgFreeslot *pSlot; - sqlite3_mutex_enter(pcache1.mutex); - sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1); + tdsqlite3_mutex_enter(pcache1.mutex); + tdsqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1); pSlot = (PgFreeslot*)p; pSlot->pNext = pcache1.pFree; pcache1.pFree = pSlot; pcache1.nFreeSlot++; pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve; assert( pcache1.nFreeSlot<=pcache1.nSlot ); - sqlite3_mutex_leave(pcache1.mutex); + tdsqlite3_mutex_leave(pcache1.mutex); }else{ - assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) ); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); + assert( tdsqlite3MemdebugHasType(p, MEMTYPE_PCACHE) ); + tdsqlite3MemdebugSetType(p, MEMTYPE_HEAP); #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS { int nFreed = 0; - nFreed = sqlite3MallocSize(p); - sqlite3_mutex_enter(pcache1.mutex); - sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed); - sqlite3_mutex_leave(pcache1.mutex); + nFreed = tdsqlite3MallocSize(p); + tdsqlite3_mutex_enter(pcache1.mutex); + tdsqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed); + tdsqlite3_mutex_leave(pcache1.mutex); } #endif - sqlite3_free(p); + tdsqlite3_free(p); } } @@ -48603,10 +54168,10 @@ static int pcache1MemSize(void *p){ return pcache1.szSlot; }else{ int iSize; - assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) ); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); - iSize = sqlite3MallocSize(p); - sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); + assert( tdsqlite3MemdebugHasType(p, MEMTYPE_PCACHE) ); + tdsqlite3MemdebugSetType(p, MEMTYPE_HEAP); + iSize = tdsqlite3MallocSize(p); + tdsqlite3MemdebugSetType(p, MEMTYPE_PCACHE); return iSize; } } @@ -48619,46 +54184,47 @@ static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){ PgHdr1 *p = 0; void *pPg; - assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); + assert( tdsqlite3_mutex_held(pCache->pGroup->mutex) ); if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){ + assert( pCache->pFree!=0 ); p = pCache->pFree; pCache->pFree = p->pNext; p->pNext = 0; }else{ #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* The group mutex must be released before pcache1Alloc() is called. This - ** is because it might call sqlite3_release_memory(), which assumes that + ** is because it might call tdsqlite3_release_memory(), which assumes that ** this mutex is not held. */ assert( pcache1.separateCache==0 ); assert( pCache->pGroup==&pcache1.grp ); pcache1LeaveMutex(pCache->pGroup); #endif - if( benignMalloc ){ sqlite3BeginBenignMalloc(); } + if( benignMalloc ){ tdsqlite3BeginBenignMalloc(); } #ifdef SQLITE_PCACHE_SEPARATE_HEADER pPg = pcache1Alloc(pCache->szPage); - p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra); + p = tdsqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra); if( !pPg || !p ){ pcache1Free(pPg); - sqlite3_free(p); + tdsqlite3_free(p); pPg = 0; } #else pPg = pcache1Alloc(pCache->szAlloc); - p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage]; #endif - if( benignMalloc ){ sqlite3EndBenignMalloc(); } + if( benignMalloc ){ tdsqlite3EndBenignMalloc(); } #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT pcache1EnterMutex(pCache->pGroup); #endif if( pPg==0 ) return 0; +#ifndef SQLITE_PCACHE_SEPARATE_HEADER + p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage]; +#endif p->page.pBuf = pPg; p->page.pExtra = &p[1]; p->isBulkLocal = 0; p->isAnchor = 0; } - if( pCache->bPurgeable ){ - pCache->pGroup->nCurrentPage++; - } + (*pCache->pnPurgeable)++; return p; } @@ -48669,34 +54235,33 @@ static void pcache1FreePage(PgHdr1 *p){ PCache1 *pCache; assert( p!=0 ); pCache = p->pCache; - assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) ); + assert( tdsqlite3_mutex_held(p->pCache->pGroup->mutex) ); if( p->isBulkLocal ){ p->pNext = pCache->pFree; pCache->pFree = p; }else{ pcache1Free(p->page.pBuf); #ifdef SQLITE_PCACHE_SEPARATE_HEADER - sqlite3_free(p); + tdsqlite3_free(p); #endif } - if( pCache->bPurgeable ){ - pCache->pGroup->nCurrentPage--; - } + (*pCache->pnPurgeable)--; } /* ** Malloc function used by SQLite to obtain space from the buffer configured -** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer -** exists, this function falls back to sqlite3Malloc(). +** using tdsqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer +** exists, this function falls back to tdsqlite3Malloc(). */ -SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){ +SQLITE_PRIVATE void *tdsqlite3PageMalloc(int sz){ + assert( sz<=65536+8 ); /* These allocations are never very large */ return pcache1Alloc(sz); } /* -** Free an allocated buffer obtained from sqlite3PageMalloc(). +** Free an allocated buffer obtained from tdsqlite3PageMalloc(). */ -SQLITE_PRIVATE void sqlite3PageFree(void *p){ +SQLITE_PRIVATE void tdsqlite3PageFree(void *p){ pcache1Free(p); } @@ -48721,7 +54286,7 @@ static int pcache1UnderMemoryPressure(PCache1 *pCache){ if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){ return pcache1.bUnderPressure; }else{ - return sqlite3HeapNearlyFull(); + return tdsqlite3HeapNearlyFull(); } } @@ -48739,7 +54304,7 @@ static void pcache1ResizeHash(PCache1 *p){ unsigned int nNew; unsigned int i; - assert( sqlite3_mutex_held(p->pGroup->mutex) ); + assert( tdsqlite3_mutex_held(p->pGroup->mutex) ); nNew = p->nHash*2; if( nNew<256 ){ @@ -48747,9 +54312,9 @@ static void pcache1ResizeHash(PCache1 *p){ } pcache1LeaveMutex(p->pGroup); - if( p->nHash ){ sqlite3BeginBenignMalloc(); } - apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew); - if( p->nHash ){ sqlite3EndBenignMalloc(); } + if( p->nHash ){ tdsqlite3BeginBenignMalloc(); } + apNew = (PgHdr1 **)tdsqlite3MallocZero(sizeof(PgHdr1 *)*nNew); + if( p->nHash ){ tdsqlite3EndBenignMalloc(); } pcache1EnterMutex(p->pGroup); if( apNew ){ for(i=0; i<p->nHash; i++){ @@ -48762,7 +54327,7 @@ static void pcache1ResizeHash(PCache1 *p){ apNew[h] = pPage; } } - sqlite3_free(p->apHash); + tdsqlite3_free(p->apHash); p->apHash = apNew; p->nHash = nNew; } @@ -48776,22 +54341,19 @@ static void pcache1ResizeHash(PCache1 *p){ ** The PGroup mutex must be held when this function is called. */ static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){ - PCache1 *pCache; - assert( pPage!=0 ); - assert( pPage->isPinned==0 ); - pCache = pPage->pCache; + assert( PAGE_IS_UNPINNED(pPage) ); assert( pPage->pLruNext ); assert( pPage->pLruPrev ); - assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pCache->pGroup->mutex) ); pPage->pLruPrev->pLruNext = pPage->pLruNext; pPage->pLruNext->pLruPrev = pPage->pLruPrev; pPage->pLruNext = 0; - pPage->pLruPrev = 0; - pPage->isPinned = 1; + /* pPage->pLruPrev = 0; + ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */ assert( pPage->isAnchor==0 ); - assert( pCache->pGroup->lru.isAnchor==1 ); - pCache->nRecyclable--; + assert( pPage->pCache->pGroup->lru.isAnchor==1 ); + pPage->pCache->nRecyclable--; return pPage; } @@ -48808,7 +54370,7 @@ static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){ PCache1 *pCache = pPage->pCache; PgHdr1 **pp; - assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); + assert( tdsqlite3_mutex_held(pCache->pGroup->mutex) ); h = pPage->iKey % pCache->nHash; for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext); *pp = (*pp)->pNext; @@ -48824,17 +54386,17 @@ static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){ static void pcache1EnforceMaxPage(PCache1 *pCache){ PGroup *pGroup = pCache->pGroup; PgHdr1 *p; - assert( sqlite3_mutex_held(pGroup->mutex) ); - while( pGroup->nCurrentPage>pGroup->nMaxPage + assert( tdsqlite3_mutex_held(pGroup->mutex) ); + while( pGroup->nPurgeable>pGroup->nMaxPage && (p=pGroup->lru.pLruPrev)->isAnchor==0 ){ assert( p->pCache->pGroup==pGroup ); - assert( p->isPinned==0 ); + assert( PAGE_IS_UNPINNED(p) ); pcache1PinPage(p); pcache1RemoveFromHash(p, 1); } if( pCache->nPage==0 && pCache->pBulk ){ - sqlite3_free(pCache->pBulk); + tdsqlite3_free(pCache->pBulk); pCache->pBulk = pCache->pFree = 0; } } @@ -48852,7 +54414,7 @@ static void pcache1TruncateUnsafe( ){ TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */ unsigned int h, iStop; - assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); + assert( tdsqlite3_mutex_held(pCache->pGroup->mutex) ); assert( pCache->iMaxKey >= iLimit ); assert( pCache->nHash > 0 ); if( pCache->iMaxKey - iLimit < pCache->nHash ){ @@ -48878,7 +54440,7 @@ static void pcache1TruncateUnsafe( if( pPage->iKey>=iLimit ){ pCache->nPage--; *pp = pPage->pNext; - if( !pPage->isPinned ) pcache1PinPage(pPage); + if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage); pcache1FreePage(pPage); }else{ pp = &pPage->pNext; @@ -48892,10 +54454,10 @@ static void pcache1TruncateUnsafe( } /******************************************************************************/ -/******** sqlite3_pcache Methods **********************************************/ +/******** tdsqlite3_pcache Methods **********************************************/ /* -** Implementation of the sqlite3_pcache.xInit method. +** Implementation of the tdsqlite3_pcache.xInit method. */ static int pcache1Init(void *NotUsed){ UNUSED_PARAMETER(NotUsed); @@ -48912,7 +54474,7 @@ static int pcache1Init(void *NotUsed){ ** ** * Use a unified cache in single-threaded applications that have ** configured a start-time buffer for use as page-cache memory using - ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL + ** tdsqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL ** pBuf argument. ** ** * Otherwise use separate caches (mode-1) @@ -48920,23 +54482,23 @@ static int pcache1Init(void *NotUsed){ #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) pcache1.separateCache = 0; #elif SQLITE_THREADSAFE - pcache1.separateCache = sqlite3GlobalConfig.pPage==0 - || sqlite3GlobalConfig.bCoreMutex>0; + pcache1.separateCache = tdsqlite3GlobalConfig.pPage==0 + || tdsqlite3GlobalConfig.bCoreMutex>0; #else - pcache1.separateCache = sqlite3GlobalConfig.pPage==0; + pcache1.separateCache = tdsqlite3GlobalConfig.pPage==0; #endif #if SQLITE_THREADSAFE - if( sqlite3GlobalConfig.bCoreMutex ){ - pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU); - pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM); + if( tdsqlite3GlobalConfig.bCoreMutex ){ + pcache1.grp.mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU); + pcache1.mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM); } #endif if( pcache1.separateCache - && sqlite3GlobalConfig.nPage!=0 - && sqlite3GlobalConfig.pPage==0 + && tdsqlite3GlobalConfig.nPage!=0 + && tdsqlite3GlobalConfig.pPage==0 ){ - pcache1.nInitPage = sqlite3GlobalConfig.nPage; + pcache1.nInitPage = tdsqlite3GlobalConfig.nPage; }else{ pcache1.nInitPage = 0; } @@ -48946,7 +54508,7 @@ static int pcache1Init(void *NotUsed){ } /* -** Implementation of the sqlite3_pcache.xShutdown method. +** Implementation of the tdsqlite3_pcache.xShutdown method. ** Note that the static mutex allocated in xInit does ** not need to be freed. */ @@ -48957,14 +54519,14 @@ static void pcache1Shutdown(void *NotUsed){ } /* forward declaration */ -static void pcache1Destroy(sqlite3_pcache *p); +static void pcache1Destroy(tdsqlite3_pcache *p); /* -** Implementation of the sqlite3_pcache.xCreate method. +** Implementation of the tdsqlite3_pcache.xCreate method. ** ** Allocate a new cache. */ -static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ +static tdsqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ PCache1 *pCache; /* The newly created page cache */ PGroup *pGroup; /* The group the new page cache will belong to */ int sz; /* Bytes of memory required to allocate the new cache */ @@ -48973,7 +54535,7 @@ static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ assert( szExtra < 300 ); sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache; - pCache = (PCache1 *)sqlite3MallocZero(sz); + pCache = (PCache1 *)tdsqlite3MallocZero(sz); if( pCache ){ if( pcache1.separateCache ){ pGroup = (PGroup*)&pCache[1]; @@ -48981,6 +54543,7 @@ static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ }else{ pGroup = &pcache1.grp; } + pcache1EnterMutex(pGroup); if( pGroup->lru.isAnchor==0 ){ pGroup->lru.isAnchor = 1; pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru; @@ -48990,28 +54553,30 @@ static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ pCache->szExtra = szExtra; pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1)); pCache->bPurgeable = (bPurgeable ? 1 : 0); - pcache1EnterMutex(pGroup); pcache1ResizeHash(pCache); if( bPurgeable ){ pCache->nMin = 10; pGroup->nMinPage += pCache->nMin; pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; + pCache->pnPurgeable = &pGroup->nPurgeable; + }else{ + pCache->pnPurgeable = &pCache->nPurgeableDummy; } pcache1LeaveMutex(pGroup); if( pCache->nHash==0 ){ - pcache1Destroy((sqlite3_pcache*)pCache); + pcache1Destroy((tdsqlite3_pcache*)pCache); pCache = 0; } } - return (sqlite3_pcache *)pCache; + return (tdsqlite3_pcache *)pCache; } /* -** Implementation of the sqlite3_pcache.xCachesize method. +** Implementation of the tdsqlite3_pcache.xCachesize method. ** ** Configure the cache_size limit for a cache. */ -static void pcache1Cachesize(sqlite3_pcache *p, int nMax){ +static void pcache1Cachesize(tdsqlite3_pcache *p, int nMax){ PCache1 *pCache = (PCache1 *)p; if( pCache->bPurgeable ){ PGroup *pGroup = pCache->pGroup; @@ -49026,11 +54591,11 @@ static void pcache1Cachesize(sqlite3_pcache *p, int nMax){ } /* -** Implementation of the sqlite3_pcache.xShrink method. +** Implementation of the tdsqlite3_pcache.xShrink method. ** ** Free up as much memory as possible. */ -static void pcache1Shrink(sqlite3_pcache *p){ +static void pcache1Shrink(tdsqlite3_pcache *p){ PCache1 *pCache = (PCache1*)p; if( pCache->bPurgeable ){ PGroup *pGroup = pCache->pGroup; @@ -49045,9 +54610,9 @@ static void pcache1Shrink(sqlite3_pcache *p){ } /* -** Implementation of the sqlite3_pcache.xPagecount method. +** Implementation of the tdsqlite3_pcache.xPagecount method. */ -static int pcache1Pagecount(sqlite3_pcache *p){ +static int pcache1Pagecount(tdsqlite3_pcache *p){ int n; PCache1 *pCache = (PCache1*)p; pcache1EnterMutex(pCache->pGroup); @@ -49097,7 +54662,7 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2( ){ PCache1 *pOther; pPage = pGroup->lru.pLruPrev; - assert( pPage->isPinned==0 ); + assert( PAGE_IS_UNPINNED(pPage) ); pcache1RemoveFromHash(pPage, 0); pcache1PinPage(pPage); pOther = pPage->pCache; @@ -49105,7 +54670,7 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2( pcache1FreePage(pPage); pPage = 0; }else{ - pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable); + pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable); } } @@ -49122,9 +54687,9 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2( pPage->iKey = iKey; pPage->pNext = pCache->apHash[h]; pPage->pCache = pCache; - pPage->pLruPrev = 0; pPage->pLruNext = 0; - pPage->isPinned = 1; + /* pPage->pLruPrev = 0; + ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */ *(void **)pPage->page.pExtra = 0; pCache->apHash[h] = pPage; if( iKey>pCache->iMaxKey ){ @@ -49135,7 +54700,7 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2( } /* -** Implementation of the sqlite3_pcache.xFetch method. +** Implementation of the tdsqlite3_pcache.xFetch method. ** ** Fetch a page by key value. ** @@ -49194,7 +54759,7 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2( ** invokes the appropriate routine. */ static PgHdr1 *pcache1FetchNoMutex( - sqlite3_pcache *p, + tdsqlite3_pcache *p, unsigned int iKey, int createFlag ){ @@ -49210,7 +54775,7 @@ static PgHdr1 *pcache1FetchNoMutex( ** Otherwise (page not in hash and createFlag!=0) continue with ** subsequent steps to try to create the page. */ if( pPage ){ - if( !pPage->isPinned ){ + if( PAGE_IS_UNPINNED(pPage) ){ return pcache1PinPage(pPage); }else{ return pPage; @@ -49224,7 +54789,7 @@ static PgHdr1 *pcache1FetchNoMutex( } #if PCACHE1_MIGHT_USE_GROUP_MUTEX static PgHdr1 *pcache1FetchWithMutex( - sqlite3_pcache *p, + tdsqlite3_pcache *p, unsigned int iKey, int createFlag ){ @@ -49238,8 +54803,8 @@ static PgHdr1 *pcache1FetchWithMutex( return pPage; } #endif -static sqlite3_pcache_page *pcache1Fetch( - sqlite3_pcache *p, +static tdsqlite3_pcache_page *pcache1Fetch( + tdsqlite3_pcache *p, unsigned int iKey, int createFlag ){ @@ -49255,23 +54820,23 @@ static sqlite3_pcache_page *pcache1Fetch( assert( pCache->nHash>0 ); #if PCACHE1_MIGHT_USE_GROUP_MUTEX if( pCache->pGroup->mutex ){ - return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag); + return (tdsqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag); }else #endif { - return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag); + return (tdsqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag); } } /* -** Implementation of the sqlite3_pcache.xUnpin method. +** Implementation of the tdsqlite3_pcache.xUnpin method. ** ** Mark a page as unpinned (eligible for asynchronous recycling). */ static void pcache1Unpin( - sqlite3_pcache *p, - sqlite3_pcache_page *pPg, + tdsqlite3_pcache *p, + tdsqlite3_pcache_page *pPg, int reuseUnlikely ){ PCache1 *pCache = (PCache1 *)p; @@ -49284,10 +54849,10 @@ static void pcache1Unpin( /* It is an error to call this function if the page is already ** part of the PGroup LRU list. */ - assert( pPage->pLruPrev==0 && pPage->pLruNext==0 ); - assert( pPage->isPinned==1 ); + assert( pPage->pLruNext==0 ); + assert( PAGE_IS_PINNED(pPage) ); - if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){ + if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){ pcache1RemoveFromHash(pPage, 1); }else{ /* Add the page to the PGroup LRU list. */ @@ -49296,18 +54861,17 @@ static void pcache1Unpin( (pPage->pLruNext = *ppFirst)->pLruPrev = pPage; *ppFirst = pPage; pCache->nRecyclable++; - pPage->isPinned = 0; } pcache1LeaveMutex(pCache->pGroup); } /* -** Implementation of the sqlite3_pcache.xRekey method. +** Implementation of the tdsqlite3_pcache.xRekey method. */ static void pcache1Rekey( - sqlite3_pcache *p, - sqlite3_pcache_page *pPg, + tdsqlite3_pcache *p, + tdsqlite3_pcache_page *pPg, unsigned int iOld, unsigned int iNew ){ @@ -49339,13 +54903,13 @@ static void pcache1Rekey( } /* -** Implementation of the sqlite3_pcache.xTruncate method. +** Implementation of the tdsqlite3_pcache.xTruncate method. ** ** Discard all unpinned pages in the cache with a page number equal to ** or greater than parameter iLimit. Any pinned pages with a page number ** equal to or greater than iLimit are implicitly unpinned. */ -static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){ +static void pcache1Truncate(tdsqlite3_pcache *p, unsigned int iLimit){ PCache1 *pCache = (PCache1 *)p; pcache1EnterMutex(pCache->pGroup); if( iLimit<=pCache->iMaxKey ){ @@ -49356,11 +54920,11 @@ static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){ } /* -** Implementation of the sqlite3_pcache.xDestroy method. +** Implementation of the tdsqlite3_pcache.xDestroy method. ** ** Destroy a cache allocated using pcache1Create(). */ -static void pcache1Destroy(sqlite3_pcache *p){ +static void pcache1Destroy(tdsqlite3_pcache *p){ PCache1 *pCache = (PCache1 *)p; PGroup *pGroup = pCache->pGroup; assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) ); @@ -49373,18 +54937,18 @@ static void pcache1Destroy(sqlite3_pcache *p){ pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; pcache1EnforceMaxPage(pCache); pcache1LeaveMutex(pGroup); - sqlite3_free(pCache->pBulk); - sqlite3_free(pCache->apHash); - sqlite3_free(pCache); + tdsqlite3_free(pCache->pBulk); + tdsqlite3_free(pCache->apHash); + tdsqlite3_free(pCache); } /* -** This function is called during initialization (sqlite3_initialize()) to +** This function is called during initialization (tdsqlite3_initialize()) to ** install the default pluggable cache module, assuming the user has not ** already provided an alternative. */ -SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){ - static const sqlite3_pcache_methods2 defaultMethods = { +SQLITE_PRIVATE void tdsqlite3PCacheSetDefault(void){ + static const tdsqlite3_pcache_methods2 defaultMethods = { 1, /* iVersion */ 0, /* pArg */ pcache1Init, /* xInit */ @@ -49399,19 +54963,19 @@ SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){ pcache1Destroy, /* xDestroy */ pcache1Shrink /* xShrink */ }; - sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods); + tdsqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods); } /* ** Return the size of the header on each page of this PCACHE implementation. */ -SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); } +SQLITE_PRIVATE int tdsqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); } /* ** Return the global mutex used by this PCACHE implementation. The -** sqlite3_status() routine needs access to this mutex. +** tdsqlite3_status() routine needs access to this mutex. */ -SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){ +SQLITE_PRIVATE tdsqlite3_mutex *tdsqlite3Pcache1Mutex(void){ return pcache1.mutex; } @@ -49419,17 +54983,17 @@ SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){ /* ** This function is called to free superfluous dynamically allocated memory ** held by the pager system. Memory in use by any SQLite pager allocated -** by the current thread may be sqlite3_free()ed. +** by the current thread may be tdsqlite3_free()ed. ** ** nReq is the number of bytes of memory required. Once this much has ** been released, the function returns. The return value is the total number ** of bytes of memory released. */ -SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){ +SQLITE_PRIVATE int tdsqlite3PcacheReleaseMemory(int nReq){ int nFree = 0; - assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); - assert( sqlite3_mutex_notheld(pcache1.mutex) ); - if( sqlite3GlobalConfig.nPage==0 ){ + assert( tdsqlite3_mutex_notheld(pcache1.grp.mutex) ); + assert( tdsqlite3_mutex_notheld(pcache1.mutex) ); + if( tdsqlite3GlobalConfig.pPage==0 ){ PgHdr1 *p; pcache1EnterMutex(&pcache1.grp); while( (nReq<0 || nFree<nReq) @@ -49438,9 +55002,9 @@ SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){ ){ nFree += pcache1MemSize(p->page.pBuf); #ifdef SQLITE_PCACHE_SEPARATE_HEADER - nFree += sqlite3MemSize(p); + nFree += tdsqlite3MemSize(p); #endif - assert( p->isPinned==0 ); + assert( PAGE_IS_UNPINNED(p) ); pcache1PinPage(p); pcache1RemoveFromHash(p, 1); } @@ -49455,7 +55019,7 @@ SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){ ** This function is used by test procedures to inspect the internal state ** of the global cache. */ -SQLITE_PRIVATE void sqlite3PcacheStats( +SQLITE_PRIVATE void tdsqlite3PcacheStats( int *pnCurrent, /* OUT: Total number of pages cached */ int *pnMax, /* OUT: Global maximum cache size */ int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */ @@ -49464,10 +55028,10 @@ SQLITE_PRIVATE void sqlite3PcacheStats( PgHdr1 *p; int nRecyclable = 0; for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){ - assert( p->isPinned==0 ); + assert( PAGE_IS_UNPINNED(p) ); nRecyclable++; } - *pnCurrent = pcache1.grp.nCurrentPage; + *pnCurrent = pcache1.grp.nPurgeable; *pnMax = (int)pcache1.grp.nMaxPage; *pnMin = (int)pcache1.grp.nMinPage; *pnRecyclable = nRecyclable; @@ -49585,7 +55149,7 @@ struct RowSetChunk { */ struct RowSet { struct RowSetChunk *pChunk; /* List of all chunk allocations */ - sqlite3 *db; /* The database connection */ + tdsqlite3 *db; /* The database connection */ struct RowSetEntry *pEntry; /* List of entries using pRight */ struct RowSetEntry *pLast; /* Last entry on the pEntry list */ struct RowSetEntry *pFresh; /* Source of new entry objects */ @@ -49599,33 +55163,26 @@ struct RowSet { ** Allowed values for RowSet.rsFlags */ #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */ -#define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */ +#define ROWSET_NEXT 0x02 /* True if tdsqlite3RowSetNext() has been called */ /* -** Turn bulk memory into a RowSet object. N bytes of memory -** are available at pSpace. The db pointer is used as a memory context -** for any subsequent allocations that need to occur. -** Return a pointer to the new RowSet object. -** -** It must be the case that N is sufficient to make a Rowset. If not -** an assertion fault occurs. -** -** If N is larger than the minimum, use the surplus as an initial -** allocation of entries available to be filled. +** Allocate a RowSet object. Return NULL if a memory allocation +** error occurs. */ -SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){ - RowSet *p; - assert( N >= ROUND8(sizeof(*p)) ); - p = pSpace; - p->pChunk = 0; - p->db = db; - p->pEntry = 0; - p->pLast = 0; - p->pForest = 0; - p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); - p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); - p->rsFlags = ROWSET_SORTED; - p->iBatch = 0; +SQLITE_PRIVATE RowSet *tdsqlite3RowSetInit(tdsqlite3 *db){ + RowSet *p = tdsqlite3DbMallocRawNN(db, sizeof(*p)); + if( p ){ + int N = tdsqlite3DbMallocSize(db, p); + p->pChunk = 0; + p->db = db; + p->pEntry = 0; + p->pLast = 0; + p->pForest = 0; + p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); + p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); + p->rsFlags = ROWSET_SORTED; + p->iBatch = 0; + } return p; } @@ -49634,11 +55191,12 @@ SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int ** the RowSet has allocated over its lifetime. This routine is ** the destructor for the RowSet. */ -SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){ +SQLITE_PRIVATE void tdsqlite3RowSetClear(void *pArg){ + RowSet *p = (RowSet*)pArg; struct RowSetChunk *pChunk, *pNextChunk; for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){ pNextChunk = pChunk->pNextChunk; - sqlite3DbFree(p->db, pChunk); + tdsqlite3DbFree(p->db, pChunk); } p->pChunk = 0; p->nFresh = 0; @@ -49649,6 +55207,16 @@ SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){ } /* +** Deallocate all chunks from a RowSet. This frees all memory that +** the RowSet has allocated over its lifetime. This routine is +** the destructor for the RowSet. +*/ +SQLITE_PRIVATE void tdsqlite3RowSetDelete(void *pArg){ + tdsqlite3RowSetClear(pArg); + tdsqlite3DbFree(((RowSet*)pArg)->db, pArg); +} + +/* ** Allocate a new RowSetEntry object that is associated with the ** given RowSet. Return a pointer to the new and completely uninitialized ** objected. @@ -49662,7 +55230,7 @@ static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){ /* We could allocate a fresh RowSetEntry each time one is needed, but it ** is more efficient to pull a preallocated entry from the pool */ struct RowSetChunk *pNew; - pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew)); + pNew = tdsqlite3DbMallocRawNN(p->db, sizeof(*pNew)); if( pNew==0 ){ return 0; } @@ -49681,11 +55249,11 @@ static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){ ** The mallocFailed flag of the database connection is set if a ** memory allocation fails. */ -SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){ +SQLITE_PRIVATE void tdsqlite3RowSetInsert(RowSet *p, i64 rowid){ struct RowSetEntry *pEntry; /* The new entry */ struct RowSetEntry *pLast; /* The last prior entry */ - /* This routine is never called after sqlite3RowSetNext() */ + /* This routine is never called after tdsqlite3RowSetNext() */ assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); pEntry = rowSetEntryAlloc(p); @@ -49871,17 +55439,17 @@ static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){ ** Write the element into *pRowid. Return 1 on success. Return ** 0 if the RowSet is already empty. ** -** After this routine has been called, the sqlite3RowSetInsert() +** After this routine has been called, the tdsqlite3RowSetInsert() ** routine may not be called again. ** -** This routine may not be called after sqlite3RowSetTest() has +** This routine may not be called after tdsqlite3RowSetTest() has ** been used. Older versions of RowSet allowed that, but as the ** capability was not used by the code generator, it was removed ** for code economy. */ -SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ +SQLITE_PRIVATE int tdsqlite3RowSetNext(RowSet *p, i64 *pRowid){ assert( p!=0 ); - assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */ + assert( p->pForest==0 ); /* Cannot be used with tdsqlite3RowSetText() */ /* Merge the forest into a single sorted list on first call */ if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/ @@ -49896,8 +55464,8 @@ SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ *pRowid = p->pEntry->v; p->pEntry = p->pEntry->pRight; if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/ - /* Free memory immediately, rather than waiting on sqlite3_finalize() */ - sqlite3RowSetClear(p); + /* Free memory immediately, rather than waiting on tdsqlite3_finalize() */ + tdsqlite3RowSetClear(p); } return 1; }else{ @@ -49913,10 +55481,10 @@ SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ ** on pRowSet->pEntry, then sort those entries into the forest at ** pRowSet->pForest so that they can be tested. */ -SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){ +SQLITE_PRIVATE int tdsqlite3RowSetTest(RowSet *pRowSet, int iBatch, tdsqlite3_int64 iRowid){ struct RowSetEntry *p, *pTree; - /* This routine is never called after sqlite3RowSetNext() */ + /* This routine is never called after tdsqlite3RowSetNext() */ assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 ); /* Sort entries into the forest on the first test of a new batch. @@ -50022,32 +55590,32 @@ SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 /* #include "sqliteInt.h" */ -/* Additional values that can be added to the sync_flags argument of -** sqlite3WalFrames(): +/* Macros for extracting appropriate sync flags for either transaction +** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)): */ -#define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */ -#define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */ +#define WAL_SYNC_FLAGS(X) ((X)&0x03) +#define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03) #ifdef SQLITE_OMIT_WAL -# define sqlite3WalOpen(x,y,z) 0 -# define sqlite3WalLimit(x,y) -# define sqlite3WalClose(w,x,y,z) 0 -# define sqlite3WalBeginReadTransaction(y,z) 0 -# define sqlite3WalEndReadTransaction(z) -# define sqlite3WalDbsize(y) 0 -# define sqlite3WalBeginWriteTransaction(y) 0 -# define sqlite3WalEndWriteTransaction(x) 0 -# define sqlite3WalUndo(x,y,z) 0 -# define sqlite3WalSavepoint(y,z) -# define sqlite3WalSavepointUndo(y,z) 0 -# define sqlite3WalFrames(u,v,w,x,y,z) 0 -# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0 -# define sqlite3WalCallback(z) 0 -# define sqlite3WalExclusiveMode(y,z) 0 -# define sqlite3WalHeapMemory(z) 0 -# define sqlite3WalFramesize(z) 0 -# define sqlite3WalFindFrame(x,y,z) 0 -# define sqlite3WalFile(x) 0 +# define tdsqlite3WalOpen(x,y,z) 0 +# define tdsqlite3WalLimit(x,y) +# define tdsqlite3WalClose(v,w,x,y,z) 0 +# define tdsqlite3WalBeginReadTransaction(y,z) 0 +# define tdsqlite3WalEndReadTransaction(z) +# define tdsqlite3WalDbsize(y) 0 +# define tdsqlite3WalBeginWriteTransaction(y) 0 +# define tdsqlite3WalEndWriteTransaction(x) 0 +# define tdsqlite3WalUndo(x,y,z) 0 +# define tdsqlite3WalSavepoint(y,z) +# define tdsqlite3WalSavepointUndo(y,z) 0 +# define tdsqlite3WalFrames(u,v,w,x,y,z) 0 +# define tdsqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0 +# define tdsqlite3WalCallback(z) 0 +# define tdsqlite3WalExclusiveMode(y,z) 0 +# define tdsqlite3WalHeapMemory(z) 0 +# define tdsqlite3WalFramesize(z) 0 +# define tdsqlite3WalFindFrame(x,y,z) 0 +# define tdsqlite3WalFile(x) 0 #else #define WAL_SAVEPOINT_NDATA 4 @@ -50058,50 +55626,51 @@ SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 typedef struct Wal Wal; /* Open and close a connection to a write-ahead log. */ -SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**); -SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *); +SQLITE_PRIVATE int tdsqlite3WalOpen(tdsqlite3_vfs*, tdsqlite3_file*, const char *, int, i64, Wal**); +SQLITE_PRIVATE int tdsqlite3WalClose(Wal *pWal, tdsqlite3*, int sync_flags, int, u8 *); /* Set the limiting size of a WAL file. */ -SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64); +SQLITE_PRIVATE void tdsqlite3WalLimit(Wal*, i64); /* Used by readers to open (lock) and close (unlock) a snapshot. A ** snapshot is like a read-transaction. It is the state of the database -** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and +** at an instant in time. tdsqlite3WalOpenSnapshot gets a read lock and ** preserves the current state even if the other threads or processes -** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the +** write to or checkpoint the WAL. tdsqlite3WalCloseSnapshot() closes the ** transaction and releases the lock. */ -SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *); -SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal); +SQLITE_PRIVATE int tdsqlite3WalBeginReadTransaction(Wal *pWal, int *); +SQLITE_PRIVATE void tdsqlite3WalEndReadTransaction(Wal *pWal); /* Read a page from the write-ahead log, if it is present. */ -SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *); -SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *); +SQLITE_PRIVATE int tdsqlite3WalFindFrame(Wal *, Pgno, u32 *); +SQLITE_PRIVATE int tdsqlite3WalReadFrame(Wal *, u32, int, u8 *); /* If the WAL is not empty, return the size of the database. */ -SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal); +SQLITE_PRIVATE Pgno tdsqlite3WalDbsize(Wal *pWal); /* Obtain or release the WRITER lock. */ -SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal); -SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal); +SQLITE_PRIVATE int tdsqlite3WalBeginWriteTransaction(Wal *pWal); +SQLITE_PRIVATE int tdsqlite3WalEndWriteTransaction(Wal *pWal); /* Undo any frames written (but not committed) to the log */ -SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx); +SQLITE_PRIVATE int tdsqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx); /* Return an integer that records the current (uncommitted) write ** position in the WAL */ -SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData); +SQLITE_PRIVATE void tdsqlite3WalSavepoint(Wal *pWal, u32 *aWalData); /* Move the write position of the WAL back to iFrame. Called in ** response to a ROLLBACK TO command. */ -SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData); +SQLITE_PRIVATE int tdsqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData); /* Write a frame or frames to the log. */ -SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int); +SQLITE_PRIVATE int tdsqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int); /* Copy pages from the log to the database file */ -SQLITE_PRIVATE int sqlite3WalCheckpoint( +SQLITE_PRIVATE int tdsqlite3WalCheckpoint( Wal *pWal, /* Write-ahead log connection */ + tdsqlite3 *db, /* Check this handle's interrupt flag */ int eMode, /* One of PASSIVE, FULL and RESTART */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ @@ -50112,38 +55681,41 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint( int *pnCkpt /* OUT: Number of backfilled frames in WAL */ ); -/* Return the value to pass to a sqlite3_wal_hook callback, the +/* Return the value to pass to a tdsqlite3_wal_hook callback, the ** number of frames in the WAL at the point of the last commit since -** sqlite3WalCallback() was called. If no commits have occurred since +** tdsqlite3WalCallback() was called. If no commits have occurred since ** the last call, then return 0. */ -SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal); +SQLITE_PRIVATE int tdsqlite3WalCallback(Wal *pWal); /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released) ** by the pager layer on the database file. */ -SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op); +SQLITE_PRIVATE int tdsqlite3WalExclusiveMode(Wal *pWal, int op); /* Return true if the argument is non-NULL and the WAL module is using ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the ** WAL module is using shared-memory, return false. */ -SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal); +SQLITE_PRIVATE int tdsqlite3WalHeapMemory(Wal *pWal); #ifdef SQLITE_ENABLE_SNAPSHOT -SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot); -SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot); +SQLITE_PRIVATE int tdsqlite3WalSnapshotGet(Wal *pWal, tdsqlite3_snapshot **ppSnapshot); +SQLITE_PRIVATE void tdsqlite3WalSnapshotOpen(Wal *pWal, tdsqlite3_snapshot *pSnapshot); +SQLITE_PRIVATE int tdsqlite3WalSnapshotRecover(Wal *pWal); +SQLITE_PRIVATE int tdsqlite3WalSnapshotCheck(Wal *pWal, tdsqlite3_snapshot *pSnapshot); +SQLITE_PRIVATE void tdsqlite3WalSnapshotUnlock(Wal *pWal); #endif #ifdef SQLITE_ENABLE_ZIPVFS /* If the WAL file is not empty, return the number of bytes of content ** stored in each frame (i.e. the db page-size when the WAL was created). */ -SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal); +SQLITE_PRIVATE int tdsqlite3WalFramesize(Wal *pWal); #endif -/* Return the sqlite3_file object for the WAL file */ -SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal); +/* Return the tdsqlite3_file object for the WAL file */ +SQLITE_PRIVATE tdsqlite3_file *tdsqlite3WalFile(Wal *pWal); #endif /* ifndef SQLITE_OMIT_WAL */ #endif /* SQLITE_WAL_H */ @@ -50242,9 +55814,9 @@ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal); ** Macros for troubleshooting. Normally turned off */ #if 0 -int sqlite3PagerTrace=1; /* True to enable tracing */ -#define sqlite3DebugPrintf printf -#define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; } +int tdsqlite3PagerTrace=1; /* True to enable tracing */ +#define tdsqlite3DebugPrintf printf +#define PAGERTRACE(X) if( tdsqlite3PagerTrace ){ tdsqlite3DebugPrintf X; } #else #define PAGERTRACE(X) #endif @@ -50254,11 +55826,11 @@ int sqlite3PagerTrace=1; /* True to enable tracing */ ** to print out file-descriptors. ** ** PAGERID() takes a pointer to a Pager struct as its argument. The -** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file +** associated file-descriptor is returned. FILEHANDLEID() takes an tdsqlite3_file ** struct as its argument. */ -#define PAGERID(p) ((int)(p->fd)) -#define FILEHANDLEID(fd) ((int)fd) +#define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd)) +#define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd)) /* ** The Pager.eState variable stores the current 'state' of a pager. A @@ -50285,13 +55857,13 @@ int sqlite3PagerTrace=1; /* True to enable tracing */ ** ** List of state transitions and the C [function] that performs each: ** -** OPEN -> READER [sqlite3PagerSharedLock] +** OPEN -> READER [tdsqlite3PagerSharedLock] ** READER -> OPEN [pager_unlock] ** -** READER -> WRITER_LOCKED [sqlite3PagerBegin] +** READER -> WRITER_LOCKED [tdsqlite3PagerBegin] ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal] ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal] -** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne] +** WRITER_DBMOD -> WRITER_FINISHED [tdsqlite3PagerCommitPhaseOne] ** WRITER_*** -> READER [pager_end_transaction] ** ** WRITER_*** -> ERROR [pager_error] @@ -50354,7 +55926,7 @@ int sqlite3PagerTrace=1; /* True to enable tracing */ ** * If the connection is open in rollback-mode, a RESERVED or greater ** lock is held on the database file. ** * If the connection is open in WAL-mode, a WAL write transaction -** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully +** is open (i.e. tdsqlite3WalBeginWriteTransaction() has been successfully ** called). ** * The dbSize, dbOrigSize and dbFileSize variables are all valid. ** * The contents of the pager cache have not been modified. @@ -50438,10 +56010,10 @@ int sqlite3PagerTrace=1; /* True to enable tracing */ ** Specifically, the pager jumps into the ERROR state if: ** ** 1. An error occurs while attempting a rollback. This happens in -** function sqlite3PagerRollback(). +** function tdsqlite3PagerRollback(). ** ** 2. An error occurs while attempting to finalize a journal file -** following a commit in function sqlite3PagerCommitPhaseTwo(). +** following a commit in function tdsqlite3PagerCommitPhaseTwo(). ** ** 3. An error occurs while attempting to write to the journal or ** database file in function pagerStress() in order to free up @@ -50562,7 +56134,7 @@ int sqlite3PagerTrace=1; /* True to enable tracing */ ** An instance of the following structure is allocated for each active ** savepoint and statement transaction in the system. All such structures ** are stored in the Pager.aSavepoint[] array, which is allocated and -** resized using sqlite3Realloc(). +** resized using tdsqlite3Realloc(). ** ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is ** set to 0. If a journal-header is written into the main journal while @@ -50672,7 +56244,7 @@ struct PagerSavepoint { ** ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from ** pagerStress() is permitted, but syncing the journal file is not. -** This flag is set by sqlite3PagerWrite() when the file-system sector-size +** This flag is set by tdsqlite3PagerWrite() when the file-system sector-size ** is larger than the database page-size in order to prevent a journal sync ** from happening in between the journalling of two pages on the same sector. ** @@ -50745,18 +56317,29 @@ struct PagerSavepoint { ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX ** sub-codes. +** +** syncFlags, walSyncFlags +** +** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03). +** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode +** and contains the flags used to sync the checkpoint operations in the +** lower two bits, and sync flags used for transaction commits in the WAL +** file in bits 0x04 and 0x08. In other words, to get the correct sync flags +** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct +** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note +** that with synchronous=NORMAL in WAL mode, transaction commit is not synced +** meaning that the 0x04 and 0x08 bits are both zero. */ struct Pager { - sqlite3_vfs *pVfs; /* OS functions to use for IO */ + tdsqlite3_vfs *pVfs; /* OS functions to use for IO */ u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */ u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */ u8 useJournal; /* Use a rollback journal on this file */ u8 noSync; /* Do not sync the journal if true */ u8 fullSync; /* Do extra syncs of the journal for robustness */ u8 extraSync; /* sync directory after journal delete */ - u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */ - u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */ u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */ + u8 walSyncFlags; /* See description above */ u8 tempFile; /* zFilename is a temporary or immutable file */ u8 noLock; /* Do not lock (except in WAL mode) */ u8 readOnly; /* True for a read-only database */ @@ -50788,19 +56371,19 @@ struct Pager { u32 cksumInit; /* Quasi-random value added to every checksum */ u32 nSubRec; /* Number of records written to sub-journal */ Bitvec *pInJournal; /* One bit for each page in the database file */ - sqlite3_file *fd; /* File descriptor for database */ - sqlite3_file *jfd; /* File descriptor for main journal */ - sqlite3_file *sjfd; /* File descriptor for sub-journal */ + tdsqlite3_file *fd; /* File descriptor for database */ + tdsqlite3_file *jfd; /* File descriptor for main journal */ + tdsqlite3_file *sjfd; /* File descriptor for sub-journal */ i64 journalOff; /* Current write offset in the journal file */ i64 journalHdr; /* Byte offset to previous journal header */ - sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */ + tdsqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */ PagerSavepoint *aSavepoint; /* Array of active savepoints */ int nSavepoint; /* Number of elements in aSavepoint[] */ u32 iDataVersion; /* Changes whenever database content changes */ char dbFileVers[16]; /* Changes whenever database file changes */ int nMmapOut; /* Number of mmap pages currently outstanding */ - sqlite3_int64 szMmap; /* Desired maximum mmap size */ + tdsqlite3_int64 szMmap; /* Desired maximum mmap size */ PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */ /* ** End of the routinely-changing class members @@ -50808,7 +56391,7 @@ struct Pager { u16 nExtra; /* Add this many bytes to each in-memory page */ i16 nReserve; /* Number of unused bytes at end of each page */ - u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */ + u32 vfsFlags; /* Flags for tdsqlite3_vfs.xOpen() */ u32 sectorSize; /* Assumed sector size during rollback */ int pageSize; /* Number of bytes in a page */ Pgno mxPgno; /* Maximum allowed size of the database */ @@ -50817,11 +56400,12 @@ struct Pager { char *zJournal; /* Name of the journal file */ int (*xBusyHandler)(void*); /* Function to call when busy */ void *pBusyHandlerArg; /* Context argument for xBusyHandler */ - int aStat[3]; /* Total cache hits, misses and writes */ + int aStat[4]; /* Total cache hits, misses, writes, spills */ #ifdef SQLITE_TEST int nRead; /* Database pages read */ #endif void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */ + int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */ #ifdef SQLITE_HAS_CODEC void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ @@ -50839,11 +56423,12 @@ struct Pager { /* ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS -** or CACHE_WRITE to sqlite3_db_status(). +** or CACHE_WRITE to tdsqlite3_db_status(). */ #define PAGER_STAT_HIT 0 #define PAGER_STAT_MISS 1 #define PAGER_STAT_WRITE 2 +#define PAGER_STAT_SPILL 3 /* ** The following global variables hold counters used for @@ -50851,9 +56436,9 @@ struct Pager { ** a non-testing build. These variables are not thread-safe. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ -SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ -SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */ +SQLITE_API int tdsqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ +SQLITE_API int tdsqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ +SQLITE_API int tdsqlite3_pager_writej_count = 0; /* Number of pages written to journal */ # define PAGER_INCR(v) v++ #else # define PAGER_INCR(v) @@ -50928,7 +56513,7 @@ static const unsigned char aJournalMagic[] = { #define PAGER_MAX_PGNO 2147483647 /* -** The argument to this macro is a file descriptor (type sqlite3_file*). +** The argument to this macro is a file descriptor (type tdsqlite3_file*). ** Return 0 if it is not open, or non-zero (but not 1) if it is. ** ** This is so that expressions can be written as: @@ -50941,15 +56526,35 @@ static const unsigned char aJournalMagic[] = { */ #define isOpen(pFd) ((pFd)->pMethods!=0) +#ifdef SQLITE_DIRECT_OVERFLOW_READ /* -** Return true if this pager uses a write-ahead log instead of the usual -** rollback journal. Otherwise false. +** Return true if page pgno can be read directly from the database file +** by the b-tree layer. This is the case if: +** +** * the database file is open, +** * there are no dirty pages in the cache, and +** * the desired page is not currently in the wal file. */ +SQLITE_PRIVATE int tdsqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){ + if( pPager->fd->pMethods==0 ) return 0; + if( tdsqlite3PCacheIsDirty(pPager->pPCache) ) return 0; +#ifdef SQLITE_HAS_CODEC + if( pPager->xCodec!=0 ) return 0; +#endif #ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager){ - return (pPager->pWal!=0); + if( pPager->pWal ){ + u32 iRead = 0; + int rc; + rc = tdsqlite3WalFindFrame(pPager->pWal, pgno, &iRead); + return (rc==SQLITE_OK && iRead==0); + } +#endif + return 1; } -# define pagerUseWal(x) sqlite3PagerUseWal(x) +#endif + +#ifndef SQLITE_OMIT_WAL +# define pagerUseWal(x) ((x)->pWal!=0) #else # define pagerUseWal(x) 0 # define pagerRollbackWal(x) 0 @@ -51021,7 +56626,7 @@ static int assert_pager_state(Pager *p){ case PAGER_OPEN: assert( !MEMDB ); assert( pPager->errCode==SQLITE_OK ); - assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile ); + assert( tdsqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile ); break; case PAGER_READER: @@ -51069,6 +56674,7 @@ static int assert_pager_state(Pager *p){ assert( isOpen(p->jfd) || p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_WAL + || (tdsqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC) ); assert( pPager->dbOrigSize<=pPager->dbHintSize ); break; @@ -51080,6 +56686,7 @@ static int assert_pager_state(Pager *p){ assert( isOpen(p->jfd) || p->journalMode==PAGER_JOURNALMODE_OFF || p->journalMode==PAGER_JOURNALMODE_WAL + || (tdsqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC) ); break; @@ -51089,7 +56696,7 @@ static int assert_pager_state(Pager *p){ ** back to OPEN state. */ assert( pPager->errCode!=SQLITE_OK ); - assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile ); + assert( tdsqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile ); break; } @@ -51105,11 +56712,15 @@ static int assert_pager_state(Pager *p){ ** to "print *pPager" in gdb: ** ** (gdb) printf "%s", print_pager_state(pPager) +** +** This routine has external linkage in order to suppress compiler warnings +** about an unused function. It is enclosed within SQLITE_DEBUG and so does +** not appear in normal builds. */ -static char *print_pager_state(Pager *p){ +char *print_pager_state(Pager *p){ static char zRet[1024]; - sqlite3_snprintf(1024, zRet, + tdsqlite3_snprintf(1024, zRet, "Filename: %s\n" "State: %s errCode=%d\n" "Lock: %s\n" @@ -51148,6 +56759,33 @@ static char *print_pager_state(Pager *p){ } #endif +/* Forward references to the various page getters */ +static int getPageNormal(Pager*,Pgno,DbPage**,int); +static int getPageError(Pager*,Pgno,DbPage**,int); +#if SQLITE_MAX_MMAP_SIZE>0 +static int getPageMMap(Pager*,Pgno,DbPage**,int); +#endif + +/* +** Set the Pager.xGet method for the appropriate routine used to fetch +** content from the pager. +*/ +static void setGetterMethod(Pager *pPager){ + if( pPager->errCode ){ + pPager->xGet = getPageError; +#if SQLITE_MAX_MMAP_SIZE>0 + }else if( USEFETCH(pPager) +#ifdef SQLITE_HAS_CODEC + && pPager->xCodec==0 +#endif + ){ + pPager->xGet = getPageMMap; +#endif /* SQLITE_MAX_MMAP_SIZE>0 */ + }else{ + pPager->xGet = getPageNormal; + } +} + /* ** Return true if it is necessary to write page *pPg into the sub-journal. ** A page needs to be written into the sub-journal if there exists one @@ -51164,7 +56802,7 @@ static int subjRequiresPage(PgHdr *pPg){ int i; for(i=0; i<pPager->nSavepoint; i++){ p = &pPager->aSavepoint[i]; - if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){ + if( p->nOrig>=pgno && 0==tdsqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){ return 1; } } @@ -51176,7 +56814,7 @@ static int subjRequiresPage(PgHdr *pPg){ ** Return true if the page is already in the journal file. */ static int pageInJournal(Pager *pPager, PgHdr *pPg){ - return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno); + return tdsqlite3BitvecTest(pPager->pInJournal, pPg->pgno); } #endif @@ -51187,11 +56825,11 @@ static int pageInJournal(Pager *pPager, PgHdr *pPg){ ** ** All values are stored on disk as big-endian. */ -static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){ +static int read32bits(tdsqlite3_file *fd, i64 offset, u32 *pRes){ unsigned char ac[4]; - int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset); + int rc = tdsqlite3OsRead(fd, ac, sizeof(ac), offset); if( rc==SQLITE_OK ){ - *pRes = sqlite3Get4byte(ac); + *pRes = tdsqlite3Get4byte(ac); } return rc; } @@ -51199,17 +56837,17 @@ static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){ /* ** Write a 32-bit integer into a string buffer in big-endian byte order. */ -#define put32bits(A,B) sqlite3Put4byte((u8*)A,B) +#define put32bits(A,B) tdsqlite3Put4byte((u8*)A,B) /* ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK ** on success or an error code is something goes wrong. */ -static int write32bits(sqlite3_file *fd, i64 offset, u32 val){ +static int write32bits(tdsqlite3_file *fd, i64 offset, u32 val){ char ac[4]; put32bits(ac, val); - return sqlite3OsWrite(fd, ac, 4, offset); + return tdsqlite3OsWrite(fd, ac, 4, offset); } /* @@ -51229,12 +56867,13 @@ static int pagerUnlockDb(Pager *pPager, int eLock){ assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 ); if( isOpen(pPager->fd) ){ assert( pPager->eLock>=eLock ); - rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock); + rc = pPager->noLock ? SQLITE_OK : tdsqlite3OsUnlock(pPager->fd, eLock); if( pPager->eLock!=UNKNOWN_LOCK ){ pPager->eLock = (u8)eLock; } IOTRACE(("UNLOCK %p %d\n", pPager, eLock)) } + pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */ return rc; } @@ -51253,7 +56892,7 @@ static int pagerLockDb(Pager *pPager, int eLock){ assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK ); if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){ - rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock); + rc = pPager->noLock ? SQLITE_OK : tdsqlite3OsLock(pPager->fd, eLock); if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){ pPager->eLock = (u8)eLock; IOTRACE(("LOCK %p %d\n", pPager, eLock)) @@ -51263,34 +56902,47 @@ static int pagerLockDb(Pager *pPager, int eLock){ } /* -** This function determines whether or not the atomic-write optimization -** can be used with this pager. The optimization can be used if: +** This function determines whether or not the atomic-write or +** atomic-batch-write optimizations can be used with this pager. The +** atomic-write optimization can be used if: ** ** (a) the value returned by OsDeviceCharacteristics() indicates that ** a database page may be written atomically, and ** (b) the value returned by OsSectorSize() is less than or equal ** to the page size. ** -** The optimization is also always enabled for temporary files. It is -** an error to call this function if pPager is opened on an in-memory -** database. +** If it can be used, then the value returned is the size of the journal +** file when it contains rollback data for exactly one page. ** -** If the optimization cannot be used, 0 is returned. If it can be used, -** then the value returned is the size of the journal file when it -** contains rollback data for exactly one page. +** The atomic-batch-write optimization can be used if OsDeviceCharacteristics() +** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is +** returned in this case. +** +** If neither optimization can be used, 0 is returned. */ -#ifdef SQLITE_ENABLE_ATOMIC_WRITE static int jrnlBufferSize(Pager *pPager){ assert( !MEMDB ); - if( !pPager->tempFile ){ - int dc; /* Device characteristics */ - int nSector; /* Sector size */ - int szPage; /* Page size */ - assert( isOpen(pPager->fd) ); - dc = sqlite3OsDeviceCharacteristics(pPager->fd); - nSector = pPager->sectorSize; - szPage = pPager->pageSize; +#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \ + || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) + int dc; /* Device characteristics */ + + assert( isOpen(pPager->fd) ); + dc = tdsqlite3OsDeviceCharacteristics(pPager->fd); +#else + UNUSED_PARAMETER(pPager); +#endif + +#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE + if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){ + return -1; + } +#endif + +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + { + int nSector = pPager->sectorSize; + int szPage = pPager->pageSize; assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); @@ -51300,11 +56952,11 @@ static int jrnlBufferSize(Pager *pPager){ } return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager); -} -#else -# define jrnlBufferSize(x) 0 #endif + return 0; +} + /* ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking ** on the cache using a hash function. This is used for testing @@ -51356,7 +57008,7 @@ static void checkPage(PgHdr *pPg){ ** used to store a master journal file name at the end of a journal file. ** ** zMaster must point to a buffer of at least nMaster bytes allocated by -** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is +** the caller. This should be tdsqlite3_vfs.mxPathname+1 (to ensure there is ** enough space to write the master journal name). If the master journal ** name in the journal is longer than nMaster bytes (including a ** nul-terminator), then this is handled as if no master journal name @@ -51373,7 +57025,7 @@ static void checkPage(PgHdr *pPg){ ** If an error occurs while reading from the journal file, an SQLite ** error code is returned. */ -static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){ +static int readMasterJournal(tdsqlite3_file *pJrnl, char *zMaster, u32 nMaster){ int rc; /* Return code */ u32 len; /* Length in bytes of master journal name */ i64 szJ; /* Total size in bytes of journal file pJrnl */ @@ -51382,15 +57034,16 @@ static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){ unsigned char aMagic[8]; /* A buffer to hold the magic header */ zMaster[0] = '\0'; - if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ)) + if( SQLITE_OK!=(rc = tdsqlite3OsFileSize(pJrnl, &szJ)) || szJ<16 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len)) || len>=nMaster + || len>szJ-16 || len==0 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum)) - || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8)) + || SQLITE_OK!=(rc = tdsqlite3OsRead(pJrnl, aMagic, 8, szJ-8)) || memcmp(aMagic, aJournalMagic, 8) - || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len)) + || SQLITE_OK!=(rc = tdsqlite3OsRead(pJrnl, zMaster, len, szJ-16-len)) ){ return rc; } @@ -51408,6 +57061,7 @@ static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){ len = 0; } zMaster[len] = '\0'; + zMaster[len+1] = '\0'; return SQLITE_OK; } @@ -51463,19 +57117,19 @@ static i64 journalHdrOffset(Pager *pPager){ static int zeroJournalHdr(Pager *pPager, int doTruncate){ int rc = SQLITE_OK; /* Return code */ assert( isOpen(pPager->jfd) ); - assert( !sqlite3JournalIsInMemory(pPager->jfd) ); + assert( !tdsqlite3JournalIsInMemory(pPager->jfd) ); if( pPager->journalOff ){ const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */ IOTRACE(("JZEROHDR %p\n", pPager)) if( doTruncate || iLimit==0 ){ - rc = sqlite3OsTruncate(pPager->jfd, 0); + rc = tdsqlite3OsTruncate(pPager->jfd, 0); }else{ static const char zeroHdr[28] = {0}; - rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0); + rc = tdsqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0); } if( rc==SQLITE_OK && !pPager->noSync ){ - rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags); + rc = tdsqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags); } /* At this point the transaction is committed but the write lock @@ -51486,9 +57140,9 @@ static int zeroJournalHdr(Pager *pPager, int doTruncate){ */ if( rc==SQLITE_OK && iLimit>0 ){ i64 sz; - rc = sqlite3OsFileSize(pPager->jfd, &sz); + rc = tdsqlite3OsFileSize(pPager->jfd, &sz); if( rc==SQLITE_OK && sz>iLimit ){ - rc = sqlite3OsTruncate(pPager->jfd, iLimit); + rc = tdsqlite3OsTruncate(pPager->jfd, iLimit); } } } @@ -51557,7 +57211,7 @@ static int writeJournalHdr(Pager *pPager){ */ assert( isOpen(pPager->fd) || pPager->noSync ); if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY) - || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) + || (tdsqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) ){ memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff); @@ -51566,7 +57220,7 @@ static int writeJournalHdr(Pager *pPager){ } /* The random check-hash initializer */ - sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit); + tdsqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit); put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit); /* The initial database size */ put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize); @@ -51598,12 +57252,12 @@ static int writeJournalHdr(Pager *pPager){ ** ** The loop is required here in case the sector-size is larger than the ** database page size. Since the zHeader buffer is only Pager.pageSize - ** bytes in size, more than one call to sqlite3OsWrite() may be required + ** bytes in size, more than one call to tdsqlite3OsWrite() may be required ** to populate the entire journal header sector. */ for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){ IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader)) - rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff); + rc = tdsqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff); assert( pPager->journalHdr <= pPager->journalOff ); pPager->journalOff += nHeader; } @@ -51657,7 +57311,7 @@ static int readJournalHdr( ** proceed. */ if( isHot || iHdrOff!=pPager->journalHdr ){ - rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff); + rc = tdsqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff); if( rc ){ return rc; } @@ -51717,7 +57371,7 @@ static int readJournalHdr( ** Use a testcase() macro to make sure that malloc failure within ** PagerSetPagesize() is tested. */ - rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1); + rc = tdsqlite3PagerSetPagesize(pPager, &iPageSize, -1); testcase( rc!=SQLITE_OK ); /* Update the assumed sector-size to match the value used by @@ -51790,10 +57444,10 @@ static int writeMasterJournal(Pager *pPager, const char *zMaster){ ** an error occurs, return the error code to the caller. */ if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager)))) - || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4))) + || (0 != (rc = tdsqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4))) || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster))) || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum))) - || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, + || (0 != (rc = tdsqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8))) ){ return rc; @@ -51810,10 +57464,10 @@ static int writeMasterJournal(Pager *pPager, const char *zMaster){ ** Easiest thing to do in this scenario is to truncate the journal ** file to the required size. */ - if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize)) + if( SQLITE_OK==(rc = tdsqlite3OsFileSize(pPager->jfd, &jrnlSize)) && jrnlSize>pPager->journalOff ){ - rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff); + rc = tdsqlite3OsTruncate(pPager->jfd, pPager->journalOff); } return rc; } @@ -51823,15 +57477,14 @@ static int writeMasterJournal(Pager *pPager, const char *zMaster){ */ static void pager_reset(Pager *pPager){ pPager->iDataVersion++; - sqlite3BackupRestart(pPager->pBackup); - sqlite3PcacheClear(pPager->pPCache); + tdsqlite3BackupRestart(pPager->pBackup); + tdsqlite3PcacheClear(pPager->pPCache); } /* ** Return the pPager->iDataVersion value */ -SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){ - assert( pPager->eState>PAGER_OPEN ); +SQLITE_PRIVATE u32 tdsqlite3PagerDataVersion(Pager *pPager){ return pPager->iDataVersion; } @@ -51843,12 +57496,12 @@ SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){ static void releaseAllSavepoints(Pager *pPager){ int ii; /* Iterator for looping through Pager.aSavepoint */ for(ii=0; ii<pPager->nSavepoint; ii++){ - sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); + tdsqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); } - if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){ - sqlite3OsClose(pPager->sjfd); + if( !pPager->exclusiveMode || tdsqlite3JournalIsInMemory(pPager->sjfd) ){ + tdsqlite3OsClose(pPager->sjfd); } - sqlite3_free(pPager->aSavepoint); + tdsqlite3_free(pPager->aSavepoint); pPager->aSavepoint = 0; pPager->nSavepoint = 0; pPager->nSubRec = 0; @@ -51866,7 +57519,7 @@ static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){ for(ii=0; ii<pPager->nSavepoint; ii++){ PagerSavepoint *p = &pPager->aSavepoint[ii]; if( pgno<=p->nOrig ){ - rc |= sqlite3BitvecSet(p->pInSavepoint, pgno); + rc |= tdsqlite3BitvecSet(p->pInSavepoint, pgno); testcase( rc==SQLITE_NOMEM ); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); } @@ -51898,17 +57551,17 @@ static void pager_unlock(Pager *pPager){ || pPager->eState==PAGER_ERROR ); - sqlite3BitvecDestroy(pPager->pInJournal); + tdsqlite3BitvecDestroy(pPager->pInJournal); pPager->pInJournal = 0; releaseAllSavepoints(pPager); if( pagerUseWal(pPager) ){ assert( !isOpen(pPager->jfd) ); - sqlite3WalEndReadTransaction(pPager->pWal); + tdsqlite3WalEndReadTransaction(pPager->pWal); pPager->eState = PAGER_OPEN; }else if( !pPager->exclusiveMode ){ int rc; /* Error code returned by pagerUnlockDb() */ - int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0; + int iDc = isOpen(pPager->fd)?tdsqlite3OsDeviceCharacteristics(pPager->fd):0; /* If the operating system support deletion of open files, then ** close the journal file when dropping the database lock. Otherwise @@ -51924,7 +57577,7 @@ static void pager_unlock(Pager *pPager){ if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN) || 1!=(pPager->journalMode & 5) ){ - sqlite3OsClose(pPager->jfd); + tdsqlite3OsClose(pPager->jfd); } /* If the pager is in the ERROR state and the call to unlock the database @@ -51942,7 +57595,6 @@ static void pager_unlock(Pager *pPager){ ** code is cleared and the cache reset in the block below. */ assert( pPager->errCode || pPager->eState!=PAGER_ERROR ); - pPager->changeCountDone = 0; pPager->eState = PAGER_OPEN; } @@ -51960,8 +57612,9 @@ static void pager_unlock(Pager *pPager){ }else{ pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER); } - if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); + if( USEFETCH(pPager) ) tdsqlite3OsUnfetch(pPager->fd, 0, 0); pPager->errCode = SQLITE_OK; + setGetterMethod(pPager); } pPager->journalOff = 0; @@ -51999,6 +57652,7 @@ static int pager_error(Pager *pPager, int rc){ if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){ pPager->errCode = rc; pPager->eState = PAGER_ERROR; + setGetterMethod(pPager); } return rc; } @@ -52025,7 +57679,7 @@ static int pagerFlushOnCommit(Pager *pPager, int bCommit){ if( pPager->tempFile==0 ) return 1; if( !bCommit ) return 0; if( !isOpen(pPager->fd) ) return 0; - return (sqlite3PCachePercentDirty(pPager->pPCache)>=25); + return (tdsqlite3PCachePercentDirty(pPager->pPCache)>=25); } /* @@ -52061,7 +57715,7 @@ static int pagerFlushOnCommit(Pager *pPager, int bCommit){ ** file. An invalid journal file cannot be rolled back. ** ** journalMode==DELETE -** The journal file is closed and deleted using sqlite3OsDelete(). +** The journal file is closed and deleted using tdsqlite3OsDelete(). ** ** If the pager is running in exclusive mode, this method of finalizing ** the journal file is never used. Instead, if the journalMode is @@ -52105,26 +57759,28 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){ } releaseAllSavepoints(pPager); - assert( isOpen(pPager->jfd) || pPager->pInJournal==0 ); + assert( isOpen(pPager->jfd) || pPager->pInJournal==0 + || (tdsqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC) + ); if( isOpen(pPager->jfd) ){ assert( !pagerUseWal(pPager) ); /* Finalize the journal file. */ - if( sqlite3JournalIsInMemory(pPager->jfd) ){ + if( tdsqlite3JournalIsInMemory(pPager->jfd) ){ /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */ - sqlite3OsClose(pPager->jfd); + tdsqlite3OsClose(pPager->jfd); }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){ if( pPager->journalOff==0 ){ rc = SQLITE_OK; }else{ - rc = sqlite3OsTruncate(pPager->jfd, 0); + rc = tdsqlite3OsTruncate(pPager->jfd, 0); if( rc==SQLITE_OK && pPager->fullSync ){ /* Make sure the new file size is written into the inode right away. ** Otherwise the journal might resurrect following a power loss and ** cause the last transaction to roll back. See ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773 */ - rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); + rc = tdsqlite3OsSync(pPager->jfd, pPager->syncFlags); } } pPager->journalOff = 0; @@ -52140,39 +57796,39 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){ ** the database file, it will do so using an in-memory journal. */ int bDelete = !pPager->tempFile; - assert( sqlite3JournalIsInMemory(pPager->jfd)==0 ); + assert( tdsqlite3JournalIsInMemory(pPager->jfd)==0 ); assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->journalMode==PAGER_JOURNALMODE_WAL ); - sqlite3OsClose(pPager->jfd); + tdsqlite3OsClose(pPager->jfd); if( bDelete ){ - rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync); + rc = tdsqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync); } } } #ifdef SQLITE_CHECK_PAGES - sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash); - if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){ - PgHdr *p = sqlite3PagerLookup(pPager, 1); + tdsqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash); + if( pPager->dbSize==0 && tdsqlite3PcacheRefCount(pPager->pPCache)>0 ){ + PgHdr *p = tdsqlite3PagerLookup(pPager, 1); if( p ){ p->pageHash = 0; - sqlite3PagerUnrefNotNull(p); + tdsqlite3PagerUnrefNotNull(p); } } #endif - sqlite3BitvecDestroy(pPager->pInJournal); + tdsqlite3BitvecDestroy(pPager->pInJournal); pPager->pInJournal = 0; pPager->nRec = 0; if( rc==SQLITE_OK ){ - if( pagerFlushOnCommit(pPager, bCommit) ){ - sqlite3PcacheCleanAll(pPager->pPCache); + if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){ + tdsqlite3PcacheCleanAll(pPager->pPCache); }else{ - sqlite3PcacheClearWritable(pPager->pPCache); + tdsqlite3PcacheClearWritable(pPager->pPCache); } - sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize); + tdsqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize); } if( pagerUseWal(pPager) ){ @@ -52180,7 +57836,7 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){ ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE ** lock held on the database file. */ - rc2 = sqlite3WalEndWriteTransaction(pPager->pWal); + rc2 = tdsqlite3WalEndWriteTransaction(pPager->pWal); assert( rc2==SQLITE_OK ); }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){ /* This branch is taken when committing a transaction in rollback-journal @@ -52193,16 +57849,15 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){ rc = pager_truncate(pPager, pPager->dbSize); } - if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){ - rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0); + if( rc==SQLITE_OK && bCommit ){ + rc = tdsqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0); if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; } if( !pPager->exclusiveMode - && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0)) + && (!pagerUseWal(pPager) || tdsqlite3WalExclusiveMode(pPager->pWal, 0)) ){ rc2 = pagerUnlockDb(pPager, SHARED_LOCK); - pPager->changeCountDone = 0; } pPager->eState = PAGER_READER; pPager->setMaster = 0; @@ -52231,9 +57886,9 @@ static void pagerUnlockAndRollback(Pager *pPager){ if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){ assert( assert_pager_state(pPager) ); if( pPager->eState>=PAGER_WRITER_LOCKED ){ - sqlite3BeginBenignMalloc(); - sqlite3PagerRollback(pPager); - sqlite3EndBenignMalloc(); + tdsqlite3BeginBenignMalloc(); + tdsqlite3PagerRollback(pPager); + tdsqlite3EndBenignMalloc(); }else if( !pPager->exclusiveMode ){ assert( pPager->eState==PAGER_READER ); pager_end_transaction(pPager, 0, 0); @@ -52292,7 +57947,7 @@ static void pagerReportSize(Pager *pPager){ ** pager as it is in the source. This comes up when a VACUUM changes the ** number of reserved bits to the "optimal" amount. */ -SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){ +SQLITE_PRIVATE void tdsqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){ if( pDest->nReserve!=pSrc->nReserve ){ pDest->nReserve = pSrc->nReserve; pagerReportSize(pDest); @@ -52349,8 +58004,13 @@ static int pager_playback_one_page( Pgno pgno; /* The page number of a page in journal */ u32 cksum; /* Checksum used for sanity checking */ char *aData; /* Temporary storage for the page */ - sqlite3_file *jfd; /* The file descriptor for the journal file */ + tdsqlite3_file *jfd; /* The file descriptor for the journal file */ int isSynced; /* True if journal page is synced */ +#ifdef SQLITE_HAS_CODEC + /* The jrnlEnc flag is true if Journal pages should be passed through + ** the codec. It is false for pure in-memory journals. */ + const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0); +#endif assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */ assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */ @@ -52378,7 +58038,7 @@ static int pager_playback_one_page( jfd = isMainJrnl ? pPager->jfd : pPager->sjfd; rc = read32bits(jfd, *pOffset, &pgno); if( rc!=SQLITE_OK ) return rc; - rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4); + rc = tdsqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4); if( rc!=SQLITE_OK ) return rc; *pOffset += pPager->pageSize + 4 + isMainJrnl*4; @@ -52391,7 +58051,7 @@ static int pager_playback_one_page( assert( !isSavepnt ); return SQLITE_DONE; } - if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){ + if( pgno>(Pgno)pPager->dbSize || tdsqlite3BitvecTest(pDone, pgno) ){ return SQLITE_OK; } if( isMainJrnl ){ @@ -52405,7 +58065,7 @@ static int pager_playback_one_page( /* If this page has already been played back before during the current ** rollback, then don't bother to play it back again. */ - if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){ + if( pDone && (rc = tdsqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){ return rc; } @@ -52454,7 +58114,7 @@ static int pager_playback_one_page( if( pagerUseWal(pPager) ){ pPg = 0; }else{ - pPg = sqlite3PagerLookup(pPager, pgno); + pPg = tdsqlite3PagerLookup(pPager, pgno); } assert( pPg || !MEMDB ); assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile ); @@ -52474,14 +58134,34 @@ static int pager_playback_one_page( i64 ofst = (pgno-1)*(i64)pPager->pageSize; testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 ); assert( !pagerUseWal(pPager) ); - rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); + + /* Write the data read from the journal back into the database file. + ** This is usually safe even for an encrypted database - as the data + ** was encrypted before it was written to the journal file. The exception + ** is if the data was just read from an in-memory sub-journal. In that + ** case it must be encrypted here before it is copied into the database + ** file. */ +#ifdef SQLITE_HAS_CODEC + if( !jrnlEnc ){ + CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData); + rc = tdsqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); + CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT); + }else +#endif + rc = tdsqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); + if( pgno>pPager->dbFileSize ){ pPager->dbFileSize = pgno; } if( pPager->pBackup ){ - CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT); - sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); - CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData); +#ifdef SQLITE_HAS_CODEC + if( jrnlEnc ){ + CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT); + tdsqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); + CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData); + }else +#endif + tdsqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); } }else if( !isMainJrnl && pPg==0 ){ /* If this is a rollback of a savepoint and data was not written to @@ -52493,7 +58173,7 @@ static int pager_playback_one_page( ** There are a couple of different ways this can happen. All are quite ** obscure. When running in synchronous mode, this can only happen ** if the page is on the free-list at the start of the transaction, then - ** populated, then moved using sqlite3PagerMovepage(). + ** populated, then moved using tdsqlite3PagerMovepage(). ** ** The solution is to add an in-memory page to the cache containing ** the data just read from the sub-journal. Mark the page as dirty @@ -52503,26 +58183,26 @@ static int pager_playback_one_page( assert( isSavepnt ); assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 ); pPager->doNotSpill |= SPILLFLAG_ROLLBACK; - rc = sqlite3PagerGet(pPager, pgno, &pPg, 1); + rc = tdsqlite3PagerGet(pPager, pgno, &pPg, 1); assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 ); pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK; if( rc!=SQLITE_OK ) return rc; - sqlite3PcacheMakeDirty(pPg); + tdsqlite3PcacheMakeDirty(pPg); } if( pPg ){ /* No page should ever be explicitly rolled back that is in use, except ** for page 1 which is held in use in order to keep the lock on the ** database active. However such a page may be rolled back as a result ** of an internal error resulting in an automatic call to - ** sqlite3PagerRollback(). + ** tdsqlite3PagerRollback(). */ void *pData; pData = pPg->pData; memcpy(pData, (u8*)aData, pPager->pageSize); pPager->xReiniter(pPg); - /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But + /* It used to be that tdsqlite3PcacheMakeClean(pPg) was called here. But ** that call was dangerous and had no detectable benefit since the cache - ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so + ** is normally cleaned by tdsqlite3PcacheCleanAll() after rollback and so ** has been removed. */ pager_set_pagehash(pPg); @@ -52533,8 +58213,10 @@ static int pager_playback_one_page( } /* Decode the page just read from disk */ - CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); - sqlite3PcacheRelease(pPg); +#if SQLITE_HAS_CODEC + if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); } +#endif + tdsqlite3PcacheRelease(pPg); } return rc; } @@ -52570,10 +58252,10 @@ static int pager_playback_one_page( ** If a child journal can be found that matches both of the criteria ** above, this function returns without doing anything. Otherwise, if ** no such child journal can be found, file zMaster is deleted from -** the file-system using sqlite3OsDelete(). +** the file-system using tdsqlite3OsDelete(). ** ** If an IO error within this function, an error code is returned. This -** function allocates memory by calling sqlite3Malloc(). If an allocation +** function allocates memory by calling tdsqlite3Malloc(). If an allocation ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors ** occur, SQLITE_OK is returned. ** @@ -52583,10 +58265,10 @@ static int pager_playback_one_page( ** size. */ static int pager_delmaster(Pager *pPager, const char *zMaster){ - sqlite3_vfs *pVfs = pPager->pVfs; + tdsqlite3_vfs *pVfs = pPager->pVfs; int rc; /* Return code */ - sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */ - sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */ + tdsqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */ + tdsqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */ char *zMasterJournal = 0; /* Contents of master journal file */ i64 nMasterJournal; /* Size of master journal file */ char *zJournal; /* Pointer to one journal within MJ file */ @@ -52596,38 +58278,39 @@ static int pager_delmaster(Pager *pPager, const char *zMaster){ /* Allocate space for both the pJournal and pMaster file descriptors. ** If successful, open the master journal file for reading. */ - pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2); - pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile); + pMaster = (tdsqlite3_file *)tdsqlite3MallocZero(pVfs->szOsFile * 2); + pJournal = (tdsqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile); if( !pMaster ){ rc = SQLITE_NOMEM_BKPT; }else{ const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL); - rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0); + rc = tdsqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0); } if( rc!=SQLITE_OK ) goto delmaster_out; /* Load the entire master journal file into space obtained from - ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain + ** tdsqlite3_malloc() and pointed to by zMasterJournal. Also obtain ** sufficient space (in zMasterPtr) to hold the names of master ** journal files extracted from regular rollback-journals. */ - rc = sqlite3OsFileSize(pMaster, &nMasterJournal); + rc = tdsqlite3OsFileSize(pMaster, &nMasterJournal); if( rc!=SQLITE_OK ) goto delmaster_out; nMasterPtr = pVfs->mxPathname+1; - zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1); + zMasterJournal = tdsqlite3Malloc(nMasterJournal + nMasterPtr + 2); if( !zMasterJournal ){ rc = SQLITE_NOMEM_BKPT; goto delmaster_out; } - zMasterPtr = &zMasterJournal[nMasterJournal+1]; - rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0); + zMasterPtr = &zMasterJournal[nMasterJournal+2]; + rc = tdsqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0); if( rc!=SQLITE_OK ) goto delmaster_out; zMasterJournal[nMasterJournal] = 0; + zMasterJournal[nMasterJournal+1] = 0; zJournal = zMasterJournal; while( (zJournal-zMasterJournal)<nMasterJournal ){ int exists; - rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists); + rc = tdsqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists); if( rc!=SQLITE_OK ){ goto delmaster_out; } @@ -52638,13 +58321,13 @@ static int pager_delmaster(Pager *pPager, const char *zMaster){ */ int c; int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL); - rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0); + rc = tdsqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0); if( rc!=SQLITE_OK ){ goto delmaster_out; } rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr); - sqlite3OsClose(pJournal); + tdsqlite3OsClose(pJournal); if( rc!=SQLITE_OK ){ goto delmaster_out; } @@ -52655,18 +58338,18 @@ static int pager_delmaster(Pager *pPager, const char *zMaster){ goto delmaster_out; } } - zJournal += (sqlite3Strlen30(zJournal)+1); + zJournal += (tdsqlite3Strlen30(zJournal)+1); } - sqlite3OsClose(pMaster); - rc = sqlite3OsDelete(pVfs, zMaster, 0); + tdsqlite3OsClose(pMaster); + rc = tdsqlite3OsDelete(pVfs, zMaster, 0); delmaster_out: - sqlite3_free(zMasterJournal); + tdsqlite3_free(zMasterJournal); if( pMaster ){ - sqlite3OsClose(pMaster); + tdsqlite3OsClose(pMaster); assert( !isOpen(pJournal) ); - sqlite3_free(pMaster); + tdsqlite3_free(pMaster); } return rc; } @@ -52704,17 +58387,17 @@ static int pager_truncate(Pager *pPager, Pgno nPage){ int szPage = pPager->pageSize; assert( pPager->eLock==EXCLUSIVE_LOCK ); /* TODO: Is it safe to use Pager.dbFileSize here? */ - rc = sqlite3OsFileSize(pPager->fd, ¤tSize); + rc = tdsqlite3OsFileSize(pPager->fd, ¤tSize); newSize = szPage*(i64)nPage; if( rc==SQLITE_OK && currentSize!=newSize ){ if( currentSize>newSize ){ - rc = sqlite3OsTruncate(pPager->fd, newSize); + rc = tdsqlite3OsTruncate(pPager->fd, newSize); }else if( (currentSize+szPage)<=newSize ){ char *pTmp = pPager->pTmpSpace; memset(pTmp, 0, szPage); testcase( (newSize-szPage) == currentSize ); testcase( (newSize-szPage) > currentSize ); - rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage); + rc = tdsqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage); } if( rc==SQLITE_OK ){ pPager->dbFileSize = nPage; @@ -52728,8 +58411,8 @@ static int pager_truncate(Pager *pPager, Pgno nPage){ ** Return a sanitized version of the sector-size of OS file pFile. The ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE. */ -SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){ - int iRet = sqlite3OsSectorSize(pFile); +SQLITE_PRIVATE int tdsqlite3SectorSize(tdsqlite3_file *pFile){ + int iRet = tdsqlite3OsSectorSize(pFile); if( iRet<32 ){ iRet = 512; }else if( iRet>MAX_SECTOR_SIZE ){ @@ -52766,7 +58449,7 @@ static void setSectorSize(Pager *pPager){ assert( isOpen(pPager->fd) || pPager->tempFile ); if( pPager->tempFile - || (sqlite3OsDeviceCharacteristics(pPager->fd) & + || (tdsqlite3OsDeviceCharacteristics(pPager->fd) & SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0 ){ /* Sector size doesn't matter for temporary files. Also, the file @@ -52774,7 +58457,7 @@ static void setSectorSize(Pager *pPager){ ** call will segfault. */ pPager->sectorSize = 512; }else{ - pPager->sectorSize = sqlite3SectorSize(pPager->fd); + pPager->sectorSize = tdsqlite3SectorSize(pPager->fd); } } @@ -52836,22 +58519,23 @@ static void setSectorSize(Pager *pPager){ ** needed. */ static int pager_playback(Pager *pPager, int isHot){ - sqlite3_vfs *pVfs = pPager->pVfs; + tdsqlite3_vfs *pVfs = pPager->pVfs; i64 szJ; /* Size of the journal file in bytes */ u32 nRec; /* Number of Records in the journal */ u32 u; /* Unsigned loop counter */ Pgno mxPg = 0; /* Size of the original file in pages */ int rc; /* Result code of a subroutine */ - int res = 1; /* Value returned by sqlite3OsAccess() */ + int res = 1; /* Value returned by tdsqlite3OsAccess() */ char *zMaster = 0; /* Name of master journal file if any */ int needPagerReset; /* True to reset page prior to first page rollback */ int nPlayback = 0; /* Total number of pages restored from journal */ + u32 savedPageSize = pPager->pageSize; /* Figure out how many records are in the journal. Abort early if ** the journal is empty. */ assert( isOpen(pPager->jfd) ); - rc = sqlite3OsFileSize(pPager->jfd, &szJ); + rc = tdsqlite3OsFileSize(pPager->jfd, &szJ); if( rc!=SQLITE_OK ){ goto end_playback; } @@ -52870,7 +58554,7 @@ static int pager_playback(Pager *pPager, int isHot){ zMaster = pPager->pTmpSpace; rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); if( rc==SQLITE_OK && zMaster[0] ){ - rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); + rc = tdsqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); } zMaster = 0; if( rc!=SQLITE_OK || !res ){ @@ -52975,15 +58659,16 @@ static int pager_playback(Pager *pPager, int isHot){ assert( 0 ); end_playback: + if( rc==SQLITE_OK ){ + rc = tdsqlite3PagerSetPagesize(pPager, &savedPageSize, -1); + } /* Following a rollback, the database file should be back in its original ** state prior to the start of the transaction, so invoke the ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the ** assertion that the transaction counter was modified. */ #ifdef SQLITE_DEBUG - if( pPager->fd->pMethods ){ - sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0); - } + tdsqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0); #endif /* If this playback is happening automatically as a result of an IO or @@ -53005,7 +58690,7 @@ end_playback: if( rc==SQLITE_OK && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) ){ - rc = sqlite3PagerSync(pPager, 0); + rc = tdsqlite3PagerSync(pPager, 0); } if( rc==SQLITE_OK ){ rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0); @@ -53019,7 +58704,7 @@ end_playback: testcase( rc!=SQLITE_OK ); } if( isHot && nPlayback ){ - sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s", + tdsqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s", nPlayback, pPager->zJournal); } @@ -53033,7 +58718,8 @@ end_playback: /* -** Read the content for page pPg out of the database file and into +** Read the content for page pPg out of the database file (or out of +** the WAL if that is where the most recent copy if found) into ** pPg->pData. A shared lock or greater must be held on the database ** file before this function is called. ** @@ -53043,30 +58729,33 @@ end_playback: ** If an IO error occurs, then the IO error is returned to the caller. ** Otherwise, SQLITE_OK is returned. */ -static int readDbPage(PgHdr *pPg, u32 iFrame){ +static int readDbPage(PgHdr *pPg){ Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */ - Pgno pgno = pPg->pgno; /* Page number to read */ int rc = SQLITE_OK; /* Return code */ - int pgsz = pPager->pageSize; /* Number of bytes to read */ + +#ifndef SQLITE_OMIT_WAL + u32 iFrame = 0; /* Frame of WAL containing pgno */ assert( pPager->eState>=PAGER_READER && !MEMDB ); assert( isOpen(pPager->fd) ); -#ifndef SQLITE_OMIT_WAL + if( pagerUseWal(pPager) ){ + rc = tdsqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame); + if( rc ) return rc; + } if( iFrame ){ - /* Try to pull the page from the write-ahead log. */ - rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData); + rc = tdsqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData); }else #endif { - i64 iOffset = (pgno-1)*(i64)pPager->pageSize; - rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset); + i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize; + rc = tdsqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset); if( rc==SQLITE_IOERR_SHORT_READ ){ rc = SQLITE_OK; } } - if( pgno==1 ){ + if( pPg->pgno==1 ){ if( rc ){ /* If the read is unsuccessful, set the dbFileVers[] to something ** that will never be a valid file version. dbFileVers[] is a copy @@ -53086,13 +58775,13 @@ static int readDbPage(PgHdr *pPg, u32 iFrame){ memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); } } - CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT); + CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT); - PAGER_INCR(sqlite3_pager_readdb_count); + PAGER_INCR(tdsqlite3_pager_readdb_count); PAGER_INCR(pPager->nRead); - IOTRACE(("PGIN %p %d\n", pPager, pgno)); + IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno)); PAGERTRACE(("FETCH %d page %d hash(%08x)\n", - PAGERID(pPager), pgno, pager_pagehash(pPg))); + PAGERID(pPager), pPg->pgno, pager_pagehash(pPg))); return rc; } @@ -53109,7 +58798,7 @@ static void pager_write_changecounter(PgHdr *pPg){ u32 change_counter; /* Increment the value just read and write it back to byte 24. */ - change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1; + change_counter = tdsqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1; put32bits(((char*)pPg->pData)+24, change_counter); /* Also store the SQLite version number in bytes 96..99 and in @@ -53138,20 +58827,16 @@ static int pagerUndoCallback(void *pCtx, Pgno iPg){ PgHdr *pPg; assert( pagerUseWal(pPager) ); - pPg = sqlite3PagerLookup(pPager, iPg); + pPg = tdsqlite3PagerLookup(pPager, iPg); if( pPg ){ - if( sqlite3PcachePageRefcount(pPg)==1 ){ - sqlite3PcacheDrop(pPg); + if( tdsqlite3PcachePageRefcount(pPg)==1 ){ + tdsqlite3PcacheDrop(pPg); }else{ - u32 iFrame = 0; - rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame); - if( rc==SQLITE_OK ){ - rc = readDbPage(pPg, iFrame); - } + rc = readDbPage(pPg); if( rc==SQLITE_OK ){ pPager->xReiniter(pPg); } - sqlite3PagerUnrefNotNull(pPg); + tdsqlite3PagerUnrefNotNull(pPg); } } @@ -53163,7 +58848,7 @@ static int pagerUndoCallback(void *pCtx, Pgno iPg){ ** also copied into the backup databases) as part of this transaction, ** the backups must be restarted. */ - sqlite3BackupRestart(pPager->pBackup); + tdsqlite3BackupRestart(pPager->pBackup); return rc; } @@ -53183,8 +58868,8 @@ static int pagerRollbackWal(Pager *pPager){ ** + Reload page content from the database (if refcount>0). */ pPager->dbSize = pPager->dbOrigSize; - rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager); - pList = sqlite3PcacheDirtyList(pPager->pPCache); + rc = tdsqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager); + pList = tdsqlite3PcacheDirtyList(pPager->pPCache); while( pList && rc==SQLITE_OK ){ PgHdr *pNext = pList->pDirty; rc = pagerUndoCallback((void *)pPager, pList->pgno); @@ -53195,7 +58880,7 @@ static int pagerRollbackWal(Pager *pPager){ } /* -** This function is a wrapper around sqlite3WalFrames(). As well as logging +** This function is a wrapper around tdsqlite3WalFrames(). As well as logging ** the contents of the list of pages headed by pList (connected by pDirty), ** this function notifies any active backup processes that the pages have ** changed. @@ -53243,17 +58928,17 @@ static int pagerWalFrames( pPager->aStat[PAGER_STAT_WRITE] += nList; if( pList->pgno==1 ) pager_write_changecounter(pList); - rc = sqlite3WalFrames(pPager->pWal, + rc = tdsqlite3WalFrames(pPager->pWal, pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags ); if( rc==SQLITE_OK && pPager->pBackup ){ for(p=pList; p; p=p->pDirty){ - sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData); + tdsqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData); } } #ifdef SQLITE_CHECK_PAGES - pList = sqlite3PcacheDirtyList(pPager->pPCache); + pList = tdsqlite3PcacheDirtyList(pPager->pPCache); for(p=pList; p; p=p->pDirty){ pager_set_pagehash(p); } @@ -53277,17 +58962,17 @@ static int pagerBeginReadTransaction(Pager *pPager){ assert( pagerUseWal(pPager) ); assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); - /* sqlite3WalEndReadTransaction() was not called for the previous + /* tdsqlite3WalEndReadTransaction() was not called for the previous ** transaction in locking_mode=EXCLUSIVE. So call it now. If we ** are in locking_mode=NORMAL and EndRead() was previously called, ** the duplicate call is harmless. */ - sqlite3WalEndReadTransaction(pPager->pWal); + tdsqlite3WalEndReadTransaction(pPager->pWal); - rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed); + rc = tdsqlite3WalBeginReadTransaction(pPager->pWal, &changed); if( rc!=SQLITE_OK || changed ){ pager_reset(pPager); - if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); + if( USEFETCH(pPager) ) tdsqlite3OsUnfetch(pPager->fd, 0, 0); } return rc; @@ -53316,16 +59001,16 @@ static int pagerPagecount(Pager *pPager, Pgno *pnPage){ assert( pPager->eLock>=SHARED_LOCK ); assert( isOpen(pPager->fd) ); assert( pPager->tempFile==0 ); - nPage = sqlite3WalDbsize(pPager->pWal); + nPage = tdsqlite3WalDbsize(pPager->pWal); /* If the number of pages in the database is not available from the - ** WAL sub-system, determine the page counte based on the size of + ** WAL sub-system, determine the page count based on the size of ** the database file. If the size of the database file is not an ** integer multiple of the page-size, round up the result. */ if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){ i64 n = 0; /* Size of db file in bytes */ - int rc = sqlite3OsFileSize(pPager->fd, &n); + int rc = tdsqlite3OsFileSize(pPager->fd, &n); if( rc!=SQLITE_OK ){ return rc; } @@ -53370,23 +59055,21 @@ static int pagerOpenWalIfPresent(Pager *pPager){ if( !pPager->tempFile ){ int isWal; /* True if WAL file exists */ - Pgno nPage; /* Size of the database file */ - - rc = pagerPagecount(pPager, &nPage); - if( rc ) return rc; - if( nPage==0 ){ - rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0); - if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK; - isWal = 0; - }else{ - rc = sqlite3OsAccess( - pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal - ); - } + rc = tdsqlite3OsAccess( + pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal + ); if( rc==SQLITE_OK ){ if( isWal ){ - testcase( sqlite3PcachePagecount(pPager->pPCache)==0 ); - rc = sqlite3PagerOpenWal(pPager, 0); + Pgno nPage; /* Size of the database file */ + + rc = pagerPagecount(pPager, &nPage); + if( rc ) return rc; + if( nPage==0 ){ + rc = tdsqlite3OsDelete(pPager->pVfs, pPager->zWal, 0); + }else{ + testcase( tdsqlite3PcachePagecount(pPager->pPCache)==0 ); + rc = tdsqlite3PagerOpenWal(pPager, 0); + } }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){ pPager->journalMode = PAGER_JOURNALMODE_DELETE; } @@ -53443,7 +59126,7 @@ static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ /* Allocate a bitvec to use to store the set of pages rolled back */ if( pSavepoint ){ - pDone = sqlite3BitvecCreate(pSavepoint->nOrig); + pDone = tdsqlite3BitvecCreate(pSavepoint->nOrig); if( !pDone ){ return SQLITE_NOMEM_BKPT; } @@ -53523,7 +59206,7 @@ static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize); if( pagerUseWal(pPager) ){ - rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData); + rc = tdsqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData); } for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){ assert( offset==(i64)ii*(4+pPager->pageSize) ); @@ -53532,7 +59215,7 @@ static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ assert( rc!=SQLITE_DONE ); } - sqlite3BitvecDestroy(pDone); + tdsqlite3BitvecDestroy(pDone); if( rc==SQLITE_OK ){ pPager->journalOff = szJ; } @@ -53544,16 +59227,16 @@ static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ ** Change the maximum number of in-memory pages that are allowed ** before attempting to recycle clean and unused pages. */ -SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){ - sqlite3PcacheSetCachesize(pPager->pPCache, mxPage); +SQLITE_PRIVATE void tdsqlite3PagerSetCachesize(Pager *pPager, int mxPage){ + tdsqlite3PcacheSetCachesize(pPager->pPCache, mxPage); } /* ** Change the maximum number of in-memory pages that are allowed ** before attempting to spill pages to journal. */ -SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){ - return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage); +SQLITE_PRIVATE int tdsqlite3PagerSetSpillsize(Pager *pPager, int mxPage){ + return tdsqlite3PcacheSetSpillsize(pPager->pPCache, mxPage); } /* @@ -53561,12 +59244,13 @@ SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){ */ static void pagerFixMaplimit(Pager *pPager){ #if SQLITE_MAX_MMAP_SIZE>0 - sqlite3_file *fd = pPager->fd; + tdsqlite3_file *fd = pPager->fd; if( isOpen(fd) && fd->pMethods->iVersion>=3 ){ - sqlite3_int64 sz; + tdsqlite3_int64 sz; sz = pPager->szMmap; pPager->bUseFetch = (sz>0); - sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz); + setGetterMethod(pPager); + tdsqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz); } #endif } @@ -53574,7 +59258,7 @@ static void pagerFixMaplimit(Pager *pPager){ /* ** Change the maximum size of any memory mapping made of the database file. */ -SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){ +SQLITE_PRIVATE void tdsqlite3PagerSetMmapLimit(Pager *pPager, tdsqlite3_int64 szMmap){ pPager->szMmap = szMmap; pagerFixMaplimit(pPager); } @@ -53582,8 +59266,8 @@ SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap /* ** Free as much memory as possible from the pager. */ -SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){ - sqlite3PcacheShrink(pPager->pPCache); +SQLITE_PRIVATE void tdsqlite3PagerShrink(Pager *pPager){ + tdsqlite3PcacheShrink(pPager->pPCache); } /* @@ -53594,7 +59278,7 @@ SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){ ** changing the number of syncs()s when writing the journals. ** There are four levels: ** -** OFF sqlite3OsSync() is never called. This is the default +** OFF tdsqlite3OsSync() is never called. This is the default ** for temporary and transient files. ** ** NORMAL The journal is synced once before writes begin on the @@ -53638,7 +59322,7 @@ SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){ ** and FULL=3. */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS -SQLITE_PRIVATE void sqlite3PagerSetFlags( +SQLITE_PRIVATE void tdsqlite3PagerSetFlags( Pager *pPager, /* The pager to set safety level for */ unsigned pgFlags /* Various flags */ ){ @@ -53654,20 +59338,17 @@ SQLITE_PRIVATE void sqlite3PagerSetFlags( } if( pPager->noSync ){ pPager->syncFlags = 0; - pPager->ckptSyncFlags = 0; }else if( pgFlags & PAGER_FULLFSYNC ){ pPager->syncFlags = SQLITE_SYNC_FULL; - pPager->ckptSyncFlags = SQLITE_SYNC_FULL; - }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){ - pPager->syncFlags = SQLITE_SYNC_NORMAL; - pPager->ckptSyncFlags = SQLITE_SYNC_FULL; }else{ pPager->syncFlags = SQLITE_SYNC_NORMAL; - pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; } - pPager->walSyncFlags = pPager->syncFlags; + pPager->walSyncFlags = (pPager->syncFlags<<2); if( pPager->fullSync ){ - pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS; + pPager->walSyncFlags |= pPager->syncFlags; + } + if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){ + pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2); } if( pgFlags & PAGER_CACHESPILL ){ pPager->doNotSpill &= ~SPILLFLAG_OFF; @@ -53683,7 +59364,7 @@ SQLITE_PRIVATE void sqlite3PagerSetFlags( ** testing and analysis only. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_opentemp_count = 0; +SQLITE_API int tdsqlite3_opentemp_count = 0; #endif /* @@ -53703,18 +59384,18 @@ SQLITE_API int sqlite3_opentemp_count = 0; */ static int pagerOpentemp( Pager *pPager, /* The pager object */ - sqlite3_file *pFile, /* Write the file descriptor here */ + tdsqlite3_file *pFile, /* Write the file descriptor here */ int vfsFlags /* Flags passed through to the VFS */ ){ int rc; /* Return code */ #ifdef SQLITE_TEST - sqlite3_opentemp_count++; /* Used for testing and analysis only */ + tdsqlite3_opentemp_count++; /* Used for testing and analysis only */ #endif vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; - rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0); + rc = tdsqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0); assert( rc!=SQLITE_OK || isOpen(pFile) ); return rc; } @@ -53722,7 +59403,7 @@ static int pagerOpentemp( /* ** Set the busy handler function. ** -** The pager invokes the busy-handler if sqlite3OsLock() returns +** The pager invokes the busy-handler if tdsqlite3OsLock() returns ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock, ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE ** lock. It does *not* invoke the busy handler when upgrading from @@ -53740,20 +59421,18 @@ static int pagerOpentemp( ** retried. If it returns zero, then the SQLITE_BUSY error is ** returned to the caller of the pager API function. */ -SQLITE_PRIVATE void sqlite3PagerSetBusyhandler( +SQLITE_PRIVATE void tdsqlite3PagerSetBusyHandler( Pager *pPager, /* Pager object */ int (*xBusyHandler)(void *), /* Pointer to busy-handler function */ void *pBusyHandlerArg /* Argument to pass to xBusyHandler */ ){ + void **ap; pPager->xBusyHandler = xBusyHandler; pPager->pBusyHandlerArg = pBusyHandlerArg; - - if( isOpen(pPager->fd) ){ - void **ap = (void **)&pPager->xBusyHandler; - assert( ((int(*)(void *))(ap[0]))==xBusyHandler ); - assert( ap[1]==pBusyHandlerArg ); - sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap); - } + ap = (void **)&pPager->xBusyHandler; + assert( ((int(*)(void *))(ap[0]))==xBusyHandler ); + assert( ap[1]==pBusyHandlerArg ); + tdsqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap); } /* @@ -53776,7 +59455,7 @@ SQLITE_PRIVATE void sqlite3PagerSetBusyhandler( ** ** then the pager object page size is set to *pPageSize. ** -** If the page size is changed, then this function uses sqlite3PagerMalloc() +** If the page size is changed, then this function uses tdsqlite3PagerMalloc() ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. ** In all other cases, SQLITE_OK is returned. @@ -53786,7 +59465,7 @@ SQLITE_PRIVATE void sqlite3PagerSetBusyhandler( ** function was called, or because the memory allocation attempt failed, ** then *pPageSize is set to the old, retained page size before returning. */ -SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){ +SQLITE_PRIVATE int tdsqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){ int rc = SQLITE_OK; /* It is not possible to do a full assert_pager_state() here, as this @@ -53802,31 +59481,37 @@ SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nR u32 pageSize = *pPageSize; assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) ); if( (pPager->memDb==0 || pPager->dbSize==0) - && sqlite3PcacheRefCount(pPager->pPCache)==0 + && tdsqlite3PcacheRefCount(pPager->pPCache)==0 && pageSize && pageSize!=(u32)pPager->pageSize ){ char *pNew = NULL; /* New temp space */ i64 nByte = 0; if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){ - rc = sqlite3OsFileSize(pPager->fd, &nByte); + rc = tdsqlite3OsFileSize(pPager->fd, &nByte); } if( rc==SQLITE_OK ){ - pNew = (char *)sqlite3PageMalloc(pageSize); - if( !pNew ) rc = SQLITE_NOMEM_BKPT; + /* 8 bytes of zeroed overrun space is sufficient so that the b-tree + * cell header parser will never run off the end of the allocation */ + pNew = (char *)tdsqlite3PageMalloc(pageSize+8); + if( !pNew ){ + rc = SQLITE_NOMEM_BKPT; + }else{ + memset(pNew+pageSize, 0, 8); + } } if( rc==SQLITE_OK ){ pager_reset(pPager); - rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize); + rc = tdsqlite3PcacheSetPageSize(pPager->pPCache, pageSize); } if( rc==SQLITE_OK ){ - sqlite3PageFree(pPager->pTmpSpace); + tdsqlite3PageFree(pPager->pTmpSpace); pPager->pTmpSpace = pNew; pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize); pPager->pageSize = pageSize; }else{ - sqlite3PageFree(pNew); + tdsqlite3PageFree(pNew); } } @@ -53849,7 +59534,7 @@ SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nR ** occurs. But other modules are free to use it too, as long as ** no rollbacks are happening. */ -SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){ +SQLITE_PRIVATE void *tdsqlite3PagerTempSpace(Pager *pPager){ return pPager->pTmpSpace; } @@ -53860,12 +59545,15 @@ SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){ ** ** Regardless of mxPage, return the current maximum page count. */ -SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){ +SQLITE_PRIVATE int tdsqlite3PagerMaxPageCount(Pager *pPager, int mxPage){ if( mxPage>0 ){ pPager->mxPgno = mxPage; } assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */ - assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */ + /* assert( pPager->mxPgno>=pPager->dbSize ); */ + /* OP_MaxPgcnt ensures that the parameter passed to this function is not + ** less than the total number of valid pages in the database. But this + ** may be less than Pager.dbSize, and so the assert() above is not valid */ return pPager->mxPgno; } @@ -53878,15 +59566,15 @@ SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){ ** and generate no code. */ #ifdef SQLITE_TEST -SQLITE_API extern int sqlite3_io_error_pending; -SQLITE_API extern int sqlite3_io_error_hit; +SQLITE_API extern int tdsqlite3_io_error_pending; +SQLITE_API extern int tdsqlite3_io_error_hit; static int saved_cnt; void disable_simulated_io_errors(void){ - saved_cnt = sqlite3_io_error_pending; - sqlite3_io_error_pending = -1; + saved_cnt = tdsqlite3_io_error_pending; + tdsqlite3_io_error_pending = -1; } void enable_simulated_io_errors(void){ - sqlite3_io_error_pending = saved_cnt; + tdsqlite3_io_error_pending = saved_cnt; } #else # define disable_simulated_io_errors() @@ -53907,7 +59595,7 @@ void enable_simulated_io_errors(void){ ** the error code is returned to the caller and the contents of the ** output buffer undefined. */ -SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){ +SQLITE_PRIVATE int tdsqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){ int rc = SQLITE_OK; memset(pDest, 0, N); assert( isOpen(pPager->fd) || pPager->tempFile ); @@ -53920,7 +59608,7 @@ SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned cha if( isOpen(pPager->fd) ){ IOTRACE(("DBHDR %p 0 %d\n", pPager, N)) - rc = sqlite3OsRead(pPager->fd, pDest, N, 0); + rc = tdsqlite3OsRead(pPager->fd, pDest, N, 0); if( rc==SQLITE_IOERR_SHORT_READ ){ rc = SQLITE_OK; } @@ -53935,7 +59623,7 @@ SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned cha ** However, if the file is between 1 and <page-size> bytes in size, then ** this is considered a 1 page file. */ -SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){ +SQLITE_PRIVATE void tdsqlite3PagerPagecount(Pager *pPager, int *pnPage){ assert( pPager->eState>=PAGER_READER ); assert( pPager->eState!=PAGER_WRITER_FINISHED ); *pnPage = (int)pPager->dbSize; @@ -53947,7 +59635,7 @@ SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){ ** a similar or greater lock is already held, this function is a no-op ** (returning SQLITE_OK immediately). ** -** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke +** Otherwise, attempt to obtain the lock using tdsqlite3OsLock(). Invoke ** the busy callback if the lock is currently not available. Repeat ** until the busy callback returns false or until the attempt to ** obtain the lock succeeds. @@ -53962,7 +59650,7 @@ static int pager_wait_on_lock(Pager *pPager, int locktype){ /* Check that this is either a no-op (because the requested lock is ** already held), or one of the transitions that the busy-handler ** may be invoked during, according to the comment above - ** sqlite3PagerSetBusyhandler(). + ** tdsqlite3PagerSetBusyhandler(). */ assert( (pPager->eLock>=locktype) || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK) @@ -54003,7 +59691,7 @@ static void assertTruncateConstraintCb(PgHdr *pPg){ assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize ); } static void assertTruncateConstraint(Pager *pPager){ - sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb); + tdsqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb); } #else # define assertTruncateConstraint(pPager) @@ -54020,7 +59708,7 @@ static void assertTruncateConstraint(Pager *pPager){ ** rolled back or committed. It is not safe to call this function and ** then continue writing to the database. */ -SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){ +SQLITE_PRIVATE void tdsqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){ assert( pPager->dbSize>=nPage ); assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); pPager->dbSize = nPage; @@ -54054,14 +59742,15 @@ SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){ static int pagerSyncHotJournal(Pager *pPager){ int rc = SQLITE_OK; if( !pPager->noSync ){ - rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL); + rc = tdsqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL); } if( rc==SQLITE_OK ){ - rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr); + rc = tdsqlite3OsFileSize(pPager->jfd, &pPager->journalHdr); } return rc; } +#if SQLITE_MAX_MMAP_SIZE>0 /* ** Obtain a reference to a memory mapped page object for page number pgno. ** The new object will use the pointer pData, obtained from xFetch(). @@ -54084,11 +59773,12 @@ static int pagerAcquireMapPage( *ppPage = p = pPager->pMmapFreelist; pPager->pMmapFreelist = p->pDirty; p->pDirty = 0; - memset(p->pExtra, 0, pPager->nExtra); + assert( pPager->nExtra>=8 ); + memset(p->pExtra, 0, 8); }else{ - *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra); + *ppPage = p = (PgHdr *)tdsqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra); if( p==0 ){ - sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData); + tdsqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData); return SQLITE_NOMEM_BKPT; } p->pExtra = (void *)&p[1]; @@ -54109,6 +59799,7 @@ static int pagerAcquireMapPage( return SQLITE_OK; } +#endif /* ** Release a reference to page pPg. pPg must have been returned by an @@ -54121,7 +59812,7 @@ static void pagerReleaseMapPage(PgHdr *pPg){ pPager->pMmapFreelist = pPg; assert( pPager->fd->pMethods->iVersion>=3 ); - sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData); + tdsqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData); } /* @@ -54132,8 +59823,32 @@ static void pagerFreeMapHdrs(Pager *pPager){ PgHdr *pNext; for(p=pPager->pMmapFreelist; p; p=pNext){ pNext = p->pDirty; - sqlite3_free(p); + tdsqlite3_free(p); + } +} + +/* Verify that the database file has not be deleted or renamed out from +** under the pager. Return SQLITE_OK if the database is still where it ought +** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error +** code from tdsqlite3OsAccess()) if the database has gone missing. +*/ +static int databaseIsUnmoved(Pager *pPager){ + int bHasMoved = 0; + int rc; + + if( pPager->tempFile ) return SQLITE_OK; + if( pPager->dbSize==0 ) return SQLITE_OK; + assert( pPager->zFilename && pPager->zFilename[0] ); + rc = tdsqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved); + if( rc==SQLITE_NOTFOUND ){ + /* If the HAS_MOVED file-control is unimplemented, assume that the file + ** has not been moved. That is the historical behavior of SQLite: prior to + ** version 3.8.3, it never checked */ + rc = SQLITE_OK; + }else if( rc==SQLITE_OK && bHasMoved ){ + rc = SQLITE_READONLY_DBMOVED; } + return rc; } @@ -54151,18 +59866,27 @@ static void pagerFreeMapHdrs(Pager *pPager){ ** a hot journal may be left in the filesystem but no error is returned ** to the caller. */ -SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){ - u8 *pTmp = (u8 *)pPager->pTmpSpace; - +SQLITE_PRIVATE int tdsqlite3PagerClose(Pager *pPager, tdsqlite3 *db){ + u8 *pTmp = (u8*)pPager->pTmpSpace; + assert( db || pagerUseWal(pPager)==0 ); assert( assert_pager_state(pPager) ); disable_simulated_io_errors(); - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); pagerFreeMapHdrs(pPager); /* pPager->errCode = 0; */ pPager->exclusiveMode = 0; #ifndef SQLITE_OMIT_WAL - sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp); - pPager->pWal = 0; + { + u8 *a = 0; + assert( db || pPager->pWal==0 ); + if( db && 0==(db->flags & SQLITE_NoCkptOnClose) + && SQLITE_OK==databaseIsUnmoved(pPager) + ){ + a = pTmp; + } + tdsqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a); + pPager->pWal = 0; + } #endif pager_reset(pPager); if( MEMDB ){ @@ -54184,14 +59908,14 @@ SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){ } pagerUnlockAndRollback(pPager); } - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); enable_simulated_io_errors(); PAGERTRACE(("CLOSE %d\n", PAGERID(pPager))); IOTRACE(("CLOSE %p\n", pPager)) - sqlite3OsClose(pPager->jfd); - sqlite3OsClose(pPager->fd); - sqlite3PageFree(pTmp); - sqlite3PcacheClose(pPager->pPCache); + tdsqlite3OsClose(pPager->jfd); + tdsqlite3OsClose(pPager->fd); + tdsqlite3PageFree(pTmp); + tdsqlite3PcacheClose(pPager->pPCache); #ifdef SQLITE_HAS_CODEC if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); @@ -54200,7 +59924,7 @@ SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){ assert( !pPager->aSavepoint && !pPager->pInJournal ); assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ); - sqlite3_free(pPager); + tdsqlite3_free(pPager); return SQLITE_OK; } @@ -54208,7 +59932,7 @@ SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){ /* ** Return the page number for page pPg. */ -SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){ +SQLITE_PRIVATE Pgno tdsqlite3PagerPagenumber(DbPage *pPg){ return pPg->pgno; } #endif @@ -54216,8 +59940,8 @@ SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){ /* ** Increment the reference count for page pPg. */ -SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){ - sqlite3PcacheRef(pPg); +SQLITE_PRIVATE void tdsqlite3PagerRef(DbPage *pPg){ + tdsqlite3PcacheRef(pPg); } /* @@ -54264,13 +59988,13 @@ static int syncJournal(Pager *pPager, int newHdr){ assert( assert_pager_state(pPager) ); assert( !pagerUseWal(pPager) ); - rc = sqlite3PagerExclusiveLock(pPager); + rc = tdsqlite3PagerExclusiveLock(pPager); if( rc!=SQLITE_OK ) return rc; if( !pPager->noSync ){ assert( !pPager->tempFile ); if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){ - const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); + const int iDc = tdsqlite3OsDeviceCharacteristics(pPager->fd); assert( isOpen(pPager->jfd) ); if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ @@ -54304,10 +60028,10 @@ static int syncJournal(Pager *pPager, int newHdr){ put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec); iNextHdrOffset = journalHdrOffset(pPager); - rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset); + rc = tdsqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset); if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){ static const u8 zerobyte = 0; - rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset); + rc = tdsqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset); } if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ return rc; @@ -54327,11 +60051,11 @@ static int syncJournal(Pager *pPager, int newHdr){ if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); IOTRACE(("JSYNC %p\n", pPager)) - rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); + rc = tdsqlite3OsSync(pPager->jfd, pPager->syncFlags); if( rc!=SQLITE_OK ) return rc; } IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr)); - rc = sqlite3OsWrite( + rc = tdsqlite3OsWrite( pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr ); if( rc!=SQLITE_OK ) return rc; @@ -54339,7 +60063,7 @@ static int syncJournal(Pager *pPager, int newHdr){ if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); IOTRACE(("JSYNC %p\n", pPager)) - rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| + rc = tdsqlite3OsSync(pPager->jfd, pPager->syncFlags| (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0) ); if( rc!=SQLITE_OK ) return rc; @@ -54360,7 +60084,7 @@ static int syncJournal(Pager *pPager, int newHdr){ ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on ** all pages. */ - sqlite3PcacheClearSyncFlags(pPager->pPCache); + tdsqlite3PcacheClearSyncFlags(pPager->pPCache); pPager->eState = PAGER_WRITER_DBMOD; assert( assert_pager_state(pPager) ); return SQLITE_OK; @@ -54424,8 +60148,8 @@ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ && pPager->dbHintSize<pPager->dbSize && (pList->pDirty || pList->pgno>pPager->dbHintSize) ){ - sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize; - sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile); + tdsqlite3_int64 szFile = pPager->pageSize * (tdsqlite3_int64)pPager->dbSize; + tdsqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile); pPager->dbHintSize = pPager->dbSize; } @@ -54433,12 +60157,12 @@ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ Pgno pgno = pList->pgno; /* If there are dirty pages in the page cache with page numbers greater - ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to + ** than Pager.dbSize, this means tdsqlite3PagerTruncateImage() was called to ** make the file smaller (presumably by auto-vacuum code). Do not write ** any such pages to the file. ** ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag - ** set (set by sqlite3PagerDontWrite()). + ** set (set by tdsqlite3PagerDontWrite()). */ if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){ i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */ @@ -54451,7 +60175,7 @@ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData); /* Write out the page data. */ - rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset); + rc = tdsqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset); /* If page 1 was just written, update Pager.dbFileVers to match ** the value now stored in the database file. If writing this @@ -54466,12 +60190,12 @@ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ pPager->aStat[PAGER_STAT_WRITE]++; /* Update any backup objects copying the contents of this pager. */ - sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData); + tdsqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData); PAGERTRACE(("STORE %d page %d hash(%08x)\n", PAGERID(pPager), pgno, pager_pagehash(pList))); IOTRACE(("PGOUT %p %d\n", pPager, pgno)); - PAGER_INCR(sqlite3_pager_writedb_count); + PAGER_INCR(tdsqlite3_pager_writedb_count); }else{ PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno)); } @@ -54487,7 +60211,7 @@ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ ** function is a no-op. ** ** SQLITE_OK is returned if everything goes according to plan. An -** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() +** SQLITE_IOERR_XXX error code is returned if a call to tdsqlite3OsOpen() ** fails. */ static int openSubJournal(Pager *pPager){ @@ -54496,11 +60220,11 @@ static int openSubJournal(Pager *pPager){ const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; - int nStmtSpill = sqlite3Config.nStmtSpill; + int nStmtSpill = tdsqlite3Config.nStmtSpill; if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){ nStmtSpill = -1; } - rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill); + rc = tdsqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill); } return rc; } @@ -54537,12 +60261,17 @@ static int subjournalPage(PgHdr *pPg){ void *pData = pPg->pData; i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize); char *pData2; - - CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2); + +#if SQLITE_HAS_CODEC + if( !pPager->subjInMemory ){ + CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2); + }else +#endif + pData2 = pData; PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno)); rc = write32bits(pPager->sjfd, offset, pPg->pgno); if( rc==SQLITE_OK ){ - rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4); + rc = tdsqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4); } } } @@ -54574,11 +60303,11 @@ static int subjournalPageIfRequired(PgHdr *pPg){ ** out to the database file, if possible. This may involve syncing the ** journal file. ** -** If successful, sqlite3PcacheMakeClean() is called on the page and +** If successful, tdsqlite3PcacheMakeClean() is called on the page and ** SQLITE_OK returned. If an IO error occurs while trying to make the ** page clean, the IO error code is returned. If the page cannot be ** made clean for some other reason, but no error occurs, then SQLITE_OK -** is returned by sqlite3PcacheMakeClean() is not called. +** is returned by tdsqlite3PcacheMakeClean() is not called. */ static int pagerStress(void *p, PgHdr *pPg){ Pager *pPager = (Pager *)p; @@ -54589,7 +60318,7 @@ static int pagerStress(void *p, PgHdr *pPg){ /* The doNotSpill NOSYNC bit is set during times when doing a sync of ** journal (and adding a new header) is not allowed. This occurs - ** during calls to sqlite3PagerWrite() while trying to journal multiple + ** during calls to tdsqlite3PagerWrite() while trying to journal multiple ** pages belonging to the same sector. ** ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling @@ -54598,7 +60327,7 @@ static int pagerStress(void *p, PgHdr *pPg){ ** ** Spilling is also prohibited when in an error state since that could ** lead to database corruption. In the current implementation it - ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3 + ** is impossible for tdsqlite3PcacheFetch() to be called with createFlag==3 ** while in the error state, hence it is impossible for this routine to ** be called in the error state. Nevertheless, we include a NEVER() ** test for the error state as a safeguard against future changes. @@ -54614,6 +60343,7 @@ static int pagerStress(void *p, PgHdr *pPg){ return SQLITE_OK; } + pPager->aStat[PAGER_STAT_SPILL]++; pPg->pDirty = 0; if( pagerUseWal(pPager) ){ /* Write a single frame for this page to the log. */ @@ -54622,6 +60352,13 @@ static int pagerStress(void *p, PgHdr *pPg){ rc = pagerWalFrames(pPager, pPg, 0, 0); } }else{ + +#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE + if( pPager->tempFile==0 ){ + rc = tdsqlite3JournalCreate(pPager->jfd); + if( rc!=SQLITE_OK ) return pager_error(pPager, rc); + } +#endif /* Sync the journal file if required. */ if( pPg->flags&PGHDR_NEED_SYNC @@ -54640,7 +60377,7 @@ static int pagerStress(void *p, PgHdr *pPg){ /* Mark the page as clean. */ if( rc==SQLITE_OK ){ PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno)); - sqlite3PcacheMakeClean(pPg); + tdsqlite3PcacheMakeClean(pPg); } return pager_error(pPager, rc); @@ -54649,10 +60386,10 @@ static int pagerStress(void *p, PgHdr *pPg){ /* ** Flush all unreferenced dirty pages to disk. */ -SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerFlush(Pager *pPager){ int rc = pPager->errCode; if( !MEMDB ){ - PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); + PgHdr *pList = tdsqlite3PcacheDirtyList(pPager->pPCache); assert( assert_pager_state(pPager) ); while( rc==SQLITE_OK && pList ){ PgHdr *pNext = pList->pDirty; @@ -54669,7 +60406,7 @@ SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){ /* ** Allocate and initialize a new Pager object and put a pointer to it ** in *ppPager. The pager should eventually be freed by passing it -** to sqlite3PagerClose(). +** to tdsqlite3PagerClose(). ** ** The zFilename argument is the path to the database file to open. ** If zFilename is NULL then a randomly-named temporary file is created @@ -54680,7 +60417,9 @@ SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){ ** ** The nExtra parameter specifies the number of bytes of space allocated ** along with each page reference. This space is available to the user -** via the sqlite3PagerGetExtra() API. +** via the tdsqlite3PagerGetExtra() API. When a new page is allocated, the +** first 8 bytes of this space are zeroed but the remainder is uninitialized. +** (The extra space is used by btree as the MemPage object.) ** ** The flags argument is used to specify properties that affect the ** operation of the pager. It should be passed some bitwise combination @@ -54693,16 +60432,16 @@ SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){ ** successfully, SQLITE_OK is returned and *ppPager set to point to ** the new pager object. If an error occurs, *ppPager is set to NULL ** and error code returned. This function may return SQLITE_NOMEM -** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or +** (tdsqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or ** various SQLITE_IO_XXX errors. */ -SQLITE_PRIVATE int sqlite3PagerOpen( - sqlite3_vfs *pVfs, /* The virtual file system to use */ +SQLITE_PRIVATE int tdsqlite3PagerOpen( + tdsqlite3_vfs *pVfs, /* The virtual file system to use */ Pager **ppPager, /* OUT: Return the Pager structure here */ const char *zFilename, /* Name of the database file to open */ int nExtra, /* Extra bytes append to each in-memory page */ int flags, /* flags controlling this file */ - int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */ + int vfsFlags, /* flags passed through to tdsqlite3_vfs.xOpen() */ void (*xReinit)(DbPage*) /* Function to reinitialize pages */ ){ u8 *pPtr; @@ -54710,19 +60449,25 @@ SQLITE_PRIVATE int sqlite3PagerOpen( int rc = SQLITE_OK; /* Return code */ int tempFile = 0; /* True for temp files (incl. in-memory files) */ int memDb = 0; /* True if this is an in-memory file */ +#ifdef SQLITE_ENABLE_DESERIALIZE + int memJM = 0; /* Memory journal mode */ +#else +# define memJM 0 +#endif int readOnly = 0; /* True if this is a read-only file */ int journalFileSize; /* Bytes to allocate for each journal fd */ char *zPathname = 0; /* Full path to database file */ int nPathname = 0; /* Number of bytes in zPathname */ int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */ - int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */ + int pcacheSize = tdsqlite3PcacheSize(); /* Bytes to allocate for PCache */ u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */ const char *zUri = 0; /* URI args to copy */ - int nUri = 0; /* Number of bytes of URI args at *zUri */ + int nUriByte = 1; /* Number of bytes of URI args at *zUri */ + int nUri = 0; /* Number of URI parameters */ /* Figure out how much space is required for each journal file-handle ** (there are two of them, the main journal and the sub-journal). */ - journalFileSize = ROUND8(sqlite3JournalSize(pVfs)); + journalFileSize = ROUND8(tdsqlite3JournalSize(pVfs)); /* Set the output variable to NULL in case an error occurs. */ *ppPager = 0; @@ -54731,9 +60476,9 @@ SQLITE_PRIVATE int sqlite3PagerOpen( if( flags & PAGER_MEMORY ){ memDb = 1; if( zFilename && zFilename[0] ){ - zPathname = sqlite3DbStrDup(0, zFilename); + zPathname = tdsqlite3DbStrDup(0, zFilename); if( zPathname==0 ) return SQLITE_NOMEM_BKPT; - nPathname = sqlite3Strlen30(zPathname); + nPathname = tdsqlite3Strlen30(zPathname); zFilename = 0; } } @@ -54746,20 +60491,30 @@ SQLITE_PRIVATE int sqlite3PagerOpen( if( zFilename && zFilename[0] ){ const char *z; nPathname = pVfs->mxPathname+1; - zPathname = sqlite3DbMallocRaw(0, nPathname*2); + zPathname = tdsqlite3DbMallocRaw(0, nPathname*2); if( zPathname==0 ){ return SQLITE_NOMEM_BKPT; } zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ - rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname); - nPathname = sqlite3Strlen30(zPathname); - z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1]; + rc = tdsqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_OK_SYMLINK ){ + if( vfsFlags & SQLITE_OPEN_NOFOLLOW ){ + rc = SQLITE_CANTOPEN_SYMLINK; + }else{ + rc = SQLITE_OK; + } + } + } + nPathname = tdsqlite3Strlen30(zPathname); + z = zUri = &zFilename[tdsqlite3Strlen30(zFilename)+1]; while( *z ){ - z += sqlite3Strlen30(z)+1; - z += sqlite3Strlen30(z)+1; + z += strlen(z)+1; + z += strlen(z)+1; + nUri++; } - nUri = (int)(&z[1] - zUri); - assert( nUri>=0 ); + nUriByte = (int)(&z[1] - zUri); + assert( nUriByte>=1 ); if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){ /* This branch is taken when the journal path required by ** the database being opened will be more than pVfs->mxPathname @@ -54770,7 +60525,7 @@ SQLITE_PRIVATE int sqlite3PagerOpen( rc = SQLITE_CANTOPEN_BKPT; } if( rc!=SQLITE_OK ){ - sqlite3DbFree(0, zPathname); + tdsqlite3DbFree(0, zPathname); return rc; } } @@ -54780,54 +60535,92 @@ SQLITE_PRIVATE int sqlite3PagerOpen( ** file name. The layout in memory is as follows: ** ** Pager object (sizeof(Pager) bytes) - ** PCache object (sqlite3PcacheSize() bytes) + ** PCache object (tdsqlite3PcacheSize() bytes) ** Database file handle (pVfs->szOsFile bytes) ** Sub-journal file handle (journalFileSize bytes) ** Main journal file handle (journalFileSize bytes) + ** \0\1\0 journal prefix (3 bytes) + ** Journal filename (nPathname+8+1 bytes) + ** \2\0 WAL prefix (2 bytes) + ** WAL filename (nPathname+4+1 bytes) + ** \3\0 database prefix (2 bytes) ** Database file name (nPathname+1 bytes) - ** Journal file name (nPathname+8+1 bytes) - */ - pPtr = (u8 *)sqlite3MallocZero( - ROUND8(sizeof(*pPager)) + /* Pager structure */ - ROUND8(pcacheSize) + /* PCache object */ - ROUND8(pVfs->szOsFile) + /* The main db file */ - journalFileSize * 2 + /* The two journal files */ - nPathname + 1 + nUri + /* zFilename */ - nPathname + 8 + 2 /* zJournal */ + ** URI query parameters (nUriByte bytes) + ** \0\0 terminator (2 bytes) + */ + pPtr = (u8 *)tdsqlite3MallocZero( + ROUND8(sizeof(*pPager)) + /* Pager structure */ + ROUND8(pcacheSize) + /* PCache object */ + ROUND8(pVfs->szOsFile) + /* The main db file */ + journalFileSize * 2 + /* The two journal files */ + 3 + /* Journal prefix */ + nPathname + 8 + 1 + /* Journal filename */ #ifndef SQLITE_OMIT_WAL - + nPathname + 4 + 2 /* zWal */ + 2 + /* WAL prefix */ + nPathname + 4 + 1 + /* WAL filename */ #endif + 2 + /* Database prefix */ + nPathname + 1 + /* database filename */ + nUriByte + /* query parameters */ + 2 /* Terminator */ ); assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) ); if( !pPtr ){ - sqlite3DbFree(0, zPathname); + tdsqlite3DbFree(0, zPathname); return SQLITE_NOMEM_BKPT; } - pPager = (Pager*)(pPtr); - pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager))); - pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize)); - pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile)); - pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize); - pPager->zFilename = (char*)(pPtr += journalFileSize); + pPager = (Pager*)pPtr; pPtr += ROUND8(sizeof(*pPager)); + pPager->pPCache = (PCache*)pPtr; pPtr += ROUND8(pcacheSize); + pPager->fd = (tdsqlite3_file*)pPtr; pPtr += ROUND8(pVfs->szOsFile); + pPager->sjfd = (tdsqlite3_file*)pPtr; pPtr += journalFileSize; + pPager->jfd = (tdsqlite3_file*)pPtr; pPtr += journalFileSize; assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) ); - /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */ - if( zPathname ){ - assert( nPathname>0 ); - pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri); - memcpy(pPager->zFilename, zPathname, nPathname); - if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri); - memcpy(pPager->zJournal, zPathname, nPathname); - memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2); - sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal); + + /* Fill in Pager.zJournal */ + pPtr[1] = '\001'; pPtr += 3; + if( nPathname>0 ){ + pPager->zJournal = (char*)pPtr; + memcpy(pPtr, zPathname, nPathname); pPtr += nPathname; + memcpy(pPtr, "-journal",8); pPtr += 8 + 1; +#ifdef SQLITE_ENABLE_8_3_NAMES + tdsqlite3FileSuffix3(zFilename,pPager->zJournal); + pPtr = (u8*)(pPager->zJournal + tdsqlite3Strlen30(pPager->zJournal)+1); +#endif + }else{ + pPager->zJournal = 0; + pPtr++; + } + #ifndef SQLITE_OMIT_WAL - pPager->zWal = &pPager->zJournal[nPathname+8+1]; - memcpy(pPager->zWal, zPathname, nPathname); - memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1); - sqlite3FileSuffix3(pPager->zFilename, pPager->zWal); + /* Fill in Pager.zWal */ + pPtr[0] = '\002'; pPtr[1] = 0; pPtr += 2; + if( nPathname>0 ){ + pPager->zWal = (char*)pPtr; + memcpy(pPtr, zPathname, nPathname); pPtr += nPathname; + memcpy(pPtr, "-wal", 4); pPtr += 4 + 1; +#ifdef SQLITE_ENABLE_8_3_NAMES + tdsqlite3FileSuffix3(zFilename, pPager->zWal); + pPtr = (u8*)(pPager->zWal + tdsqlite3Strlen30(pPager->zWal)+1); #endif - sqlite3DbFree(0, zPathname); + }else{ + pPager->zWal = 0; + pPtr++; } +#endif + + /* Fill in the Pager.zFilename and pPager.zQueryParam fields */ + pPtr[0] = '\003'; pPtr[1] = 0; pPtr += 2; + pPager->zFilename = (char*)pPtr; + if( nPathname>0 ){ + memcpy(pPtr, zPathname, nPathname); pPtr += nPathname + 1; + if( zUri ){ + memcpy(pPtr, zUri, nUriByte); /* pPtr += nUriByte; // not needed */ + } + /* Double-zero terminator implied by the tdsqlite3MallocZero */ + } + + if( nPathname ) tdsqlite3DbFree(0, zPathname); pPager->pVfs = pVfs; pPager->vfsFlags = vfsFlags; @@ -54835,20 +60628,23 @@ SQLITE_PRIVATE int sqlite3PagerOpen( */ if( zFilename && zFilename[0] ){ int fout = 0; /* VFS flags returned by xOpen() */ - rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout); + rc = tdsqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout); assert( !memDb ); - readOnly = (fout&SQLITE_OPEN_READONLY); +#ifdef SQLITE_ENABLE_DESERIALIZE + memJM = (fout&SQLITE_OPEN_MEMORY)!=0; +#endif + readOnly = (fout&SQLITE_OPEN_READONLY)!=0; /* If the file was successfully opened for read/write access, ** choose a default page size in case we have to create the ** database file. The default page size is the maximum of: ** ** + SQLITE_DEFAULT_PAGE_SIZE, - ** + The value returned by sqlite3OsSectorSize() + ** + The value returned by tdsqlite3OsSectorSize() ** + The largest page size that can be written atomically. */ if( rc==SQLITE_OK ){ - int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); + int iDc = tdsqlite3OsDeviceCharacteristics(pPager->fd); if( !readOnly ){ setSectorSize(pPager); assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE); @@ -54873,9 +60669,9 @@ SQLITE_PRIVATE int sqlite3PagerOpen( } #endif } - pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0); + pPager->noLock = tdsqlite3_uri_boolean(pPager->zFilename, "nolock", 0); if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0 - || sqlite3_uri_boolean(zFilename, "immutable", 0) ){ + || tdsqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){ vfsFlags |= SQLITE_OPEN_READONLY; goto act_like_temp_file; } @@ -54904,24 +60700,24 @@ act_like_temp_file: */ if( rc==SQLITE_OK ){ assert( pPager->memDb==0 ); - rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1); + rc = tdsqlite3PagerSetPagesize(pPager, &szPageDflt, -1); testcase( rc!=SQLITE_OK ); } /* Initialize the PCache object. */ if( rc==SQLITE_OK ){ - assert( nExtra<1000 ); nExtra = ROUND8(nExtra); - rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb, + assert( nExtra>=8 && nExtra<1000 ); + rc = tdsqlite3PcacheOpen(szPageDflt, nExtra, !memDb, !memDb?pagerStress:0, (void *)pPager, pPager->pPCache); } /* If an error occurred above, free the Pager structure and close the file. */ if( rc!=SQLITE_OK ){ - sqlite3OsClose(pPager->fd); - sqlite3PageFree(pPager->pTmpSpace); - sqlite3_free(pPager); + tdsqlite3OsClose(pPager->fd); + tdsqlite3PageFree(pPager->pTmpSpace); + tdsqlite3_free(pPager); return rc; } @@ -54947,19 +60743,24 @@ act_like_temp_file: pPager->memDb = (u8)memDb; pPager->readOnly = (u8)readOnly; assert( useJournal || pPager->tempFile ); - pPager->noSync = pPager->tempFile; + int level = SQLITE_DEFAULT_SYNCHRONOUS + 1; + pPager->noSync = pPager->tempFile || level==PAGER_SYNCHRONOUS_OFF; if( pPager->noSync ){ assert( pPager->fullSync==0 ); assert( pPager->extraSync==0 ); assert( pPager->syncFlags==0 ); assert( pPager->walSyncFlags==0 ); - assert( pPager->ckptSyncFlags==0 ); }else{ - pPager->fullSync = 1; - pPager->extraSync = 0; + pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0; + pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0; pPager->syncFlags = SQLITE_SYNC_NORMAL; - pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS; - pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL; + pPager->walSyncFlags = (pPager->syncFlags<<2); + if( pPager->fullSync ){ + pPager->walSyncFlags |= pPager->syncFlags; + } +#if SQLITE_DEFAULT_CKPTFULLFSYNC + pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2); +#endif } /* pPager->pFirst = 0; */ /* pPager->pFirstSynced = 0; */ @@ -54970,12 +60771,13 @@ act_like_temp_file: setSectorSize(pPager); if( !useJournal ){ pPager->journalMode = PAGER_JOURNALMODE_OFF; - }else if( memDb ){ + }else if( memDb || memJM ){ pPager->journalMode = PAGER_JOURNALMODE_MEMORY; } /* pPager->xBusyHandler = 0; */ /* pPager->pBusyHandlerArg = 0; */ pPager->xReiniter = xReinit; + setGetterMethod(pPager); /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */ /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */ @@ -54984,30 +60786,6 @@ act_like_temp_file: } -/* Verify that the database file has not be deleted or renamed out from -** under the pager. Return SQLITE_OK if the database is still were it ought -** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error -** code from sqlite3OsAccess()) if the database has gone missing. -*/ -static int databaseIsUnmoved(Pager *pPager){ - int bHasMoved = 0; - int rc; - - if( pPager->tempFile ) return SQLITE_OK; - if( pPager->dbSize==0 ) return SQLITE_OK; - assert( pPager->zFilename && pPager->zFilename[0] ); - rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved); - if( rc==SQLITE_NOTFOUND ){ - /* If the HAS_MOVED file-control is unimplemented, assume that the file - ** has not been moved. That is the historical behavior of SQLite: prior to - ** version 3.8.3, it never checked */ - rc = SQLITE_OK; - }else if( rc==SQLITE_OK && bHasMoved ){ - rc = SQLITE_READONLY_DBMOVED; - } - return rc; -} - /* ** This function is called after transitioning from PAGER_UNLOCK to @@ -55041,7 +60819,7 @@ static int databaseIsUnmoved(Pager *pPager){ ** code is returned and the value of *pExists is undefined. */ static int hasHotJournal(Pager *pPager, int *pExists){ - sqlite3_vfs * const pVfs = pPager->pVfs; + tdsqlite3_vfs * const pVfs = pPager->pVfs; int rc = SQLITE_OK; /* Return code */ int exists = 1; /* True if a journal file is present */ int jrnlOpen = !!isOpen(pPager->jfd); @@ -55050,26 +60828,26 @@ static int hasHotJournal(Pager *pPager, int *pExists){ assert( isOpen(pPager->fd) ); assert( pPager->eState==PAGER_OPEN ); - assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) & + assert( jrnlOpen==0 || ( tdsqlite3OsDeviceCharacteristics(pPager->jfd) & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN )); *pExists = 0; if( !jrnlOpen ){ - rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists); + rc = tdsqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists); } if( rc==SQLITE_OK && exists ){ int locked = 0; /* True if some process holds a RESERVED lock */ /* Race condition here: Another process might have been holding the - ** the RESERVED lock and have a journal open at the sqlite3OsAccess() + ** the RESERVED lock and have a journal open at the tdsqlite3OsAccess() ** call above, but then delete the journal and drop the lock before - ** we get to the following sqlite3OsCheckReservedLock() call. If that + ** we get to the following tdsqlite3OsCheckReservedLock() call. If that ** is the case, this routine might think there is a hot journal when ** in fact there is none. This results in a false-positive which will ** be dealt with by the playback routine. Ticket #3883. */ - rc = sqlite3OsCheckReservedLock(pPager->fd, &locked); + rc = tdsqlite3OsCheckReservedLock(pPager->fd, &locked); if( rc==SQLITE_OK && !locked ){ Pgno nPage; /* Number of pages in database file */ @@ -55085,12 +60863,12 @@ static int hasHotJournal(Pager *pPager, int *pExists){ ** journal_mode=PERSIST. */ if( nPage==0 && !jrnlOpen ){ - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){ - sqlite3OsDelete(pVfs, pPager->zJournal, 0); + tdsqlite3OsDelete(pVfs, pPager->zJournal, 0); if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK); } - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); }else{ /* The journal file exists and no other connection has a reserved ** or greater lock on the database file. Now check that there is @@ -55100,16 +60878,16 @@ static int hasHotJournal(Pager *pPager, int *pExists){ */ if( !jrnlOpen ){ int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL; - rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f); + rc = tdsqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f); } if( rc==SQLITE_OK ){ u8 first = 0; - rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0); + rc = tdsqlite3OsRead(pPager->jfd, (void *)&first, 1, 0); if( rc==SQLITE_IOERR_SHORT_READ ){ rc = SQLITE_OK; } if( !jrnlOpen ){ - sqlite3OsClose(pPager->jfd); + tdsqlite3OsClose(pPager->jfd); } *pExists = (first!=0); }else if( rc==SQLITE_CANTOPEN ){ @@ -55135,7 +60913,7 @@ static int hasHotJournal(Pager *pPager, int *pExists){ /* ** This function is called to obtain a shared lock on the database file. -** It is illegal to call sqlite3PagerGet() until after this function +** It is illegal to call tdsqlite3PagerGet() until after this function ** has been successfully called. If a shared-lock is already held when ** this function is called, it is a no-op. ** @@ -55160,14 +60938,14 @@ static int hasHotJournal(Pager *pPager, int *pExists){ ** occurs while locking the database, checking for a hot-journal file or ** rolling back a journal file, the IO error code is returned. */ -SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerSharedLock(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ /* This routine is only called from b-tree and only when there are no ** outstanding pages. This implies that the pager state should either ** be OPEN or READER. READER is only possible if the pager is or was in ** exclusive access mode. */ - assert( sqlite3PcacheRefCount(pPager->pPCache)==0 ); + assert( tdsqlite3PcacheRefCount(pPager->pPCache)==0 ); assert( assert_pager_state(pPager) ); assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); assert( pPager->errCode==SQLITE_OK ); @@ -55233,19 +61011,19 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ ** function was called and the journal file does not exist. */ if( !isOpen(pPager->jfd) ){ - sqlite3_vfs * const pVfs = pPager->pVfs; + tdsqlite3_vfs * const pVfs = pPager->pVfs; int bExists; /* True if journal file exists */ - rc = sqlite3OsAccess( + rc = tdsqlite3OsAccess( pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists); if( rc==SQLITE_OK && bExists ){ int fout = 0; int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL; assert( !pPager->tempFile ); - rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); + rc = tdsqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){ rc = SQLITE_CANTOPEN_BKPT; - sqlite3OsClose(pPager->jfd); + tdsqlite3OsClose(pPager->jfd); } } } @@ -55301,7 +61079,7 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ ** see if the database has been modified. If the database has changed, ** flush the cache. The hasHeldSharedLock flag prevents this from ** occurring on the very first access to a file, in order to save a - ** single unnecessary sqlite3OsRead() call at the start-up. + ** single unnecessary tdsqlite3OsRead() call at the start-up. ** ** Database changes are detected by looking at 15 bytes beginning ** at offset 24 into the file. The first 4 of these 16 bytes are @@ -55313,19 +61091,14 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ ** detected. The chance of an undetected change is so small that ** it can be neglected. */ - Pgno nPage = 0; char dbFileVers[sizeof(pPager->dbFileVers)]; - rc = pagerPagecount(pPager, &nPage); - if( rc ) goto failed; - - if( nPage>0 ){ - IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers))); - rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24); - if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ + IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers))); + rc = tdsqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24); + if( rc!=SQLITE_OK ){ + if( rc!=SQLITE_IOERR_SHORT_READ ){ goto failed; } - }else{ memset(dbFileVers, 0, sizeof(dbFileVers)); } @@ -55339,7 +61112,7 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ ** to be the right size but is not actually valid. Avoid this ** possibility by unmapping the db here. */ if( USEFETCH(pPager) ){ - sqlite3OsUnfetch(pPager->fd, 0, 0); + tdsqlite3OsUnfetch(pPager->fd, 0, 0); } } } @@ -55383,16 +61156,24 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ ** nothing to rollback, so this routine is a no-op. */ static void pagerUnlockIfUnused(Pager *pPager){ - if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){ + if( tdsqlite3PcacheRefCount(pPager->pPCache)==0 ){ + assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */ pagerUnlockAndRollback(pPager); } } /* -** Acquire a reference to page number pgno in pager pPager (a page -** reference has type DbPage*). If the requested reference is +** The page getter methods each try to acquire a reference to a +** page with page number pgno. If the requested reference is ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned. ** +** There are different implementations of the getter method depending +** on the current state of the pager. +** +** getPageNormal() -- The normal getter +** getPageError() -- Used if the pager is in an error state +** getPageMmap() -- Used if memory-mapped I/O is enabled +** ** If the requested page is already in the cache, it is returned. ** Otherwise, a new page object is allocated and populated with data ** read from the database file. In some cases, the pcache module may @@ -55404,14 +61185,14 @@ static void pagerUnlockIfUnused(Pager *pPager){ ** already in the cache when this function is called, then the extra ** data is left as it was when the page object was last used. ** -** If the database image is smaller than the requested page or if a -** non-zero value is passed as the noContent parameter and the +** If the database image is smaller than the requested page or if +** the flags parameter contains the PAGER_GET_NOCONTENT bit and the ** requested page is not already stored in the cache, then no ** actual disk read occurs. In this case the memory image of the ** page is initialized to all zeros. ** -** If noContent is true, it means that we do not care about the contents -** of the page. This occurs in two scenarios: +** If PAGER_GET_NOCONTENT is true, it means that we do not care about +** the contents of the page. This occurs in two scenarios: ** ** a) When reading a free-list leaf page from the database, and ** @@ -55419,18 +61200,18 @@ static void pagerUnlockIfUnused(Pager *pPager){ ** a new page into the cache to be filled with the data read ** from the savepoint journal. ** -** If noContent is true, then the data returned is zeroed instead of -** being read from the database. Additionally, the bits corresponding +** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead +** of being read from the database. Additionally, the bits corresponding ** to pgno in Pager.pInJournal (bitvec of pages already written to the ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open ** savepoints are set. This means if the page is made writable at any -** point in the future, using a call to sqlite3PagerWrite(), its contents +** point in the future, using a call to tdsqlite3PagerWrite(), its contents ** will not be journaled. This saves IO. ** ** The acquisition might fail for several reasons. In all cases, ** an appropriate error code is returned and *ppPage is set to NULL. ** -** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt +** See also tdsqlite3PagerLookup(). Both this routine and Lookup() attempt ** to find a page in the in-memory cache first. If the page is not already ** in memory, this routine goes to disk to read it in whereas Lookup() ** just returns 0. This routine acquires a read-lock the first time it @@ -55438,106 +61219,39 @@ static void pagerUnlockIfUnused(Pager *pPager){ ** Since Lookup() never goes to disk, it never has to deal with locks ** or journal files. */ -SQLITE_PRIVATE int sqlite3PagerGet( +static int getPageNormal( Pager *pPager, /* The pager open on the database file */ Pgno pgno, /* Page number to fetch */ DbPage **ppPage, /* Write a pointer to the page here */ int flags /* PAGER_GET_XXX flags */ ){ int rc = SQLITE_OK; - PgHdr *pPg = 0; - u32 iFrame = 0; /* Frame to read from WAL file */ - const int noContent = (flags & PAGER_GET_NOCONTENT); - - /* It is acceptable to use a read-only (mmap) page for any page except - ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY - ** flag was specified by the caller. And so long as the db is not a - ** temporary or in-memory database. */ - const int bMmapOk = (pgno>1 && USEFETCH(pPager) - && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY)) -#ifdef SQLITE_HAS_CODEC - && pPager->xCodec==0 -#endif - ); + PgHdr *pPg; + u8 noContent; /* True if PAGER_GET_NOCONTENT is set */ + tdsqlite3_pcache_page *pBase; - /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here - ** allows the compiler optimizer to reuse the results of the "pgno>1" - ** test in the previous statement, and avoid testing pgno==0 in the - ** common case where pgno is large. */ - if( pgno<=1 && pgno==0 ){ - return SQLITE_CORRUPT_BKPT; - } + assert( pPager->errCode==SQLITE_OK ); assert( pPager->eState>=PAGER_READER ); assert( assert_pager_state(pPager) ); - assert( noContent==0 || bMmapOk==0 ); - assert( pPager->hasHeldSharedLock==1 ); - /* If the pager is in the error state, return an error immediately. - ** Otherwise, request the page from the PCache layer. */ - if( pPager->errCode!=SQLITE_OK ){ - rc = pPager->errCode; - }else{ - if( bMmapOk && pagerUseWal(pPager) ){ - rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); - if( rc!=SQLITE_OK ) goto pager_acquire_err; - } - - if( bMmapOk && iFrame==0 ){ - void *pData = 0; - - rc = sqlite3OsFetch(pPager->fd, - (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData - ); - - if( rc==SQLITE_OK && pData ){ - if( pPager->eState>PAGER_READER || pPager->tempFile ){ - pPg = sqlite3PagerLookup(pPager, pgno); - } - if( pPg==0 ){ - rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg); - }else{ - sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData); - } - if( pPg ){ - assert( rc==SQLITE_OK ); - *ppPage = pPg; - return SQLITE_OK; - } - } - if( rc!=SQLITE_OK ){ - goto pager_acquire_err; - } - } - - { - sqlite3_pcache_page *pBase; - pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3); - if( pBase==0 ){ - rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase); - if( rc!=SQLITE_OK ) goto pager_acquire_err; - if( pBase==0 ){ - pPg = *ppPage = 0; - rc = SQLITE_NOMEM_BKPT; - goto pager_acquire_err; - } - } - pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase); - assert( pPg!=0 ); - } - } - - if( rc!=SQLITE_OK ){ - /* Either the call to sqlite3PcacheFetch() returned an error or the - ** pager was already in the error-state when this function was called. - ** Set pPg to 0 and jump to the exception handler. */ + if( pgno==0 ) return SQLITE_CORRUPT_BKPT; + pBase = tdsqlite3PcacheFetch(pPager->pPCache, pgno, 3); + if( pBase==0 ){ pPg = 0; - goto pager_acquire_err; + rc = tdsqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase); + if( rc!=SQLITE_OK ) goto pager_acquire_err; + if( pBase==0 ){ + rc = SQLITE_NOMEM_BKPT; + goto pager_acquire_err; + } } + pPg = *ppPage = tdsqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase); assert( pPg==(*ppPage) ); assert( pPg->pgno==pgno ); assert( pPg->pPager==pPager || pPg->pPager==0 ); + noContent = (flags & PAGER_GET_NOCONTENT)!=0; if( pPg->pPager && !noContent ){ /* In this case the pcache already contains an initialized copy of ** the page. Return without further ado. */ @@ -55547,17 +61261,18 @@ SQLITE_PRIVATE int sqlite3PagerGet( }else{ /* The pager cache has created a new page. Its content needs to - ** be initialized. */ - - pPg->pPager = pPager; - - /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page - ** number greater than this, or the unused locking-page, is requested. */ + ** be initialized. But first some error checks: + ** + ** (1) The maximum page number is 2^31 + ** (2) Never try to fetch the locking page + */ if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){ rc = SQLITE_CORRUPT_BKPT; goto pager_acquire_err; } + pPg->pPager = pPager; + assert( !isOpen(pPager->fd) || !MEMDB ); if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){ if( pgno>pPager->mxPgno ){ @@ -55571,88 +61286,196 @@ SQLITE_PRIVATE int sqlite3PagerGet( ** to test the case where a malloc error occurs while trying to set ** a bit in a bit vector. */ - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); if( pgno<=pPager->dbOrigSize ){ - TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno); + TESTONLY( rc = ) tdsqlite3BitvecSet(pPager->pInJournal, pgno); testcase( rc==SQLITE_NOMEM ); } TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno); testcase( rc==SQLITE_NOMEM ); - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); } memset(pPg->pData, 0, pPager->pageSize); IOTRACE(("ZERO %p %d\n", pPager, pgno)); }else{ - if( pagerUseWal(pPager) && bMmapOk==0 ){ - rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); - if( rc!=SQLITE_OK ) goto pager_acquire_err; - } assert( pPg->pPager==pPager ); pPager->aStat[PAGER_STAT_MISS]++; - rc = readDbPage(pPg, iFrame); + rc = readDbPage(pPg); if( rc!=SQLITE_OK ){ goto pager_acquire_err; } } pager_set_pagehash(pPg); } - return SQLITE_OK; pager_acquire_err: assert( rc!=SQLITE_OK ); if( pPg ){ - sqlite3PcacheDrop(pPg); + tdsqlite3PcacheDrop(pPg); } pagerUnlockIfUnused(pPager); - *ppPage = 0; return rc; } +#if SQLITE_MAX_MMAP_SIZE>0 +/* The page getter for when memory-mapped I/O is enabled */ +static int getPageMMap( + Pager *pPager, /* The pager open on the database file */ + Pgno pgno, /* Page number to fetch */ + DbPage **ppPage, /* Write a pointer to the page here */ + int flags /* PAGER_GET_XXX flags */ +){ + int rc = SQLITE_OK; + PgHdr *pPg = 0; + u32 iFrame = 0; /* Frame to read from WAL file */ + + /* It is acceptable to use a read-only (mmap) page for any page except + ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY + ** flag was specified by the caller. And so long as the db is not a + ** temporary or in-memory database. */ + const int bMmapOk = (pgno>1 + && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY)) + ); + + assert( USEFETCH(pPager) ); +#ifdef SQLITE_HAS_CODEC + assert( pPager->xCodec==0 ); +#endif + + /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here + ** allows the compiler optimizer to reuse the results of the "pgno>1" + ** test in the previous statement, and avoid testing pgno==0 in the + ** common case where pgno is large. */ + if( pgno<=1 && pgno==0 ){ + return SQLITE_CORRUPT_BKPT; + } + assert( pPager->eState>=PAGER_READER ); + assert( assert_pager_state(pPager) ); + assert( pPager->hasHeldSharedLock==1 ); + assert( pPager->errCode==SQLITE_OK ); + + if( bMmapOk && pagerUseWal(pPager) ){ + rc = tdsqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); + if( rc!=SQLITE_OK ){ + *ppPage = 0; + return rc; + } + } + if( bMmapOk && iFrame==0 ){ + void *pData = 0; + rc = tdsqlite3OsFetch(pPager->fd, + (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData + ); + if( rc==SQLITE_OK && pData ){ + if( pPager->eState>PAGER_READER || pPager->tempFile ){ + pPg = tdsqlite3PagerLookup(pPager, pgno); + } + if( pPg==0 ){ + rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg); + }else{ + tdsqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData); + } + if( pPg ){ + assert( rc==SQLITE_OK ); + *ppPage = pPg; + return SQLITE_OK; + } + } + if( rc!=SQLITE_OK ){ + *ppPage = 0; + return rc; + } + } + return getPageNormal(pPager, pgno, ppPage, flags); +} +#endif /* SQLITE_MAX_MMAP_SIZE>0 */ + +/* The page getter method for when the pager is an error state */ +static int getPageError( + Pager *pPager, /* The pager open on the database file */ + Pgno pgno, /* Page number to fetch */ + DbPage **ppPage, /* Write a pointer to the page here */ + int flags /* PAGER_GET_XXX flags */ +){ + UNUSED_PARAMETER(pgno); + UNUSED_PARAMETER(flags); + assert( pPager->errCode!=SQLITE_OK ); + *ppPage = 0; + return pPager->errCode; +} + + +/* Dispatch all page fetch requests to the appropriate getter method. +*/ +SQLITE_PRIVATE int tdsqlite3PagerGet( + Pager *pPager, /* The pager open on the database file */ + Pgno pgno, /* Page number to fetch */ + DbPage **ppPage, /* Write a pointer to the page here */ + int flags /* PAGER_GET_XXX flags */ +){ + return pPager->xGet(pPager, pgno, ppPage, flags); +} + /* ** Acquire a page if it is already in the in-memory cache. Do ** not read the page from disk. Return a pointer to the page, ** or 0 if the page is not in cache. ** -** See also sqlite3PagerGet(). The difference between this routine -** and sqlite3PagerGet() is that _get() will go to the disk and read +** See also tdsqlite3PagerGet(). The difference between this routine +** and tdsqlite3PagerGet() is that _get() will go to the disk and read ** in the page if the page is not already in cache. This routine ** returns NULL if the page is not in cache or if a disk I/O error ** has ever happened. */ -SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){ - sqlite3_pcache_page *pPage; +SQLITE_PRIVATE DbPage *tdsqlite3PagerLookup(Pager *pPager, Pgno pgno){ + tdsqlite3_pcache_page *pPage; assert( pPager!=0 ); assert( pgno!=0 ); assert( pPager->pPCache!=0 ); - pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0); + pPage = tdsqlite3PcacheFetch(pPager->pPCache, pgno, 0); assert( pPage==0 || pPager->hasHeldSharedLock ); if( pPage==0 ) return 0; - return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage); + return tdsqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage); } /* ** Release a page reference. ** -** If the number of references to the page drop to zero, then the -** page is added to the LRU list. When all references to all pages -** are released, a rollback occurs and the lock on the database is -** removed. +** The tdsqlite3PagerUnref() and tdsqlite3PagerUnrefNotNull() may only be +** used if we know that the page being released is not the last page. +** The btree layer always holds page1 open until the end, so these first +** to routines can be used to release any page other than BtShared.pPage1. +** +** Use tdsqlite3PagerUnrefPageOne() to release page1. This latter routine +** checks the total number of outstanding pages and if the number of +** pages reaches zero it drops the database lock. */ -SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){ - Pager *pPager; +SQLITE_PRIVATE void tdsqlite3PagerUnrefNotNull(DbPage *pPg){ + TESTONLY( Pager *pPager = pPg->pPager; ) assert( pPg!=0 ); - pPager = pPg->pPager; if( pPg->flags & PGHDR_MMAP ){ + assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */ pagerReleaseMapPage(pPg); }else{ - sqlite3PcacheRelease(pPg); + tdsqlite3PcacheRelease(pPg); } - pagerUnlockIfUnused(pPager); + /* Do not use this routine to release the last reference to page1 */ + assert( tdsqlite3PcacheRefCount(pPager->pPCache)>0 ); } -SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){ - if( pPg ) sqlite3PagerUnrefNotNull(pPg); +SQLITE_PRIVATE void tdsqlite3PagerUnref(DbPage *pPg){ + if( pPg ) tdsqlite3PagerUnrefNotNull(pPg); +} +SQLITE_PRIVATE void tdsqlite3PagerUnrefPageOne(DbPage *pPg){ + Pager *pPager; + assert( pPg!=0 ); + assert( pPg->pgno==1 ); + assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */ + pPager = pPg->pPager; + tdsqlite3PagerResetLockTimeout(pPager); + tdsqlite3PcacheRelease(pPg); + pagerUnlockIfUnused(pPager); } /* @@ -55679,7 +61502,7 @@ SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){ */ static int pager_open_journal(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ - sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */ + tdsqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */ assert( pPager->eState==PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); @@ -55691,7 +61514,7 @@ static int pager_open_journal(Pager *pPager){ if( NEVER(pPager->errCode) ) return pPager->errCode; if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ - pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize); + pPager->pInJournal = tdsqlite3BitvecCreate(pPager->dbSize); if( pPager->pInJournal==0 ){ return SQLITE_NOMEM_BKPT; } @@ -55699,14 +61522,14 @@ static int pager_open_journal(Pager *pPager){ /* Open the journal file if it is not already open. */ if( !isOpen(pPager->jfd) ){ if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){ - sqlite3MemJournalOpen(pPager->jfd); + tdsqlite3MemJournalOpen(pPager->jfd); }else{ int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; int nSpill; if( pPager->tempFile ){ flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL); - nSpill = sqlite3Config.nStmtSpill; + nSpill = tdsqlite3Config.nStmtSpill; }else{ flags |= SQLITE_OPEN_MAIN_JOURNAL; nSpill = jrnlBufferSize(pPager); @@ -55716,7 +61539,7 @@ static int pager_open_journal(Pager *pPager){ ** it was originally opened. */ rc = databaseIsUnmoved(pPager); if( rc==SQLITE_OK ){ - rc = sqlite3JournalOpen ( + rc = tdsqlite3JournalOpen ( pVfs, pPager->zJournal, pPager->jfd, flags, nSpill ); } @@ -55739,7 +61562,7 @@ static int pager_open_journal(Pager *pPager){ } if( rc!=SQLITE_OK ){ - sqlite3BitvecDestroy(pPager->pInJournal); + tdsqlite3BitvecDestroy(pPager->pInJournal); pPager->pInJournal = 0; }else{ assert( pPager->eState==PAGER_WRITER_LOCKED ); @@ -55766,7 +61589,7 @@ static int pager_open_journal(Pager *pPager){ ** sub-journal is implemented in-memory if pPager is an in-memory database, ** or using a temporary file otherwise. */ -SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){ +SQLITE_PRIVATE int tdsqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){ int rc = SQLITE_OK; if( pPager->errCode ) return pPager->errCode; @@ -55780,12 +61603,12 @@ SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory /* If the pager is configured to use locking_mode=exclusive, and an ** exclusive lock on the database is not already held, obtain it now. */ - if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){ + if( pPager->exclusiveMode && tdsqlite3WalExclusiveMode(pPager->pWal, -1) ){ rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); if( rc!=SQLITE_OK ){ return rc; } - (void)sqlite3WalExclusiveMode(pPager->pWal, 1); + (void)tdsqlite3WalExclusiveMode(pPager->pWal, 1); } /* Grab the write lock on the log file. If successful, upgrade to @@ -55793,7 +61616,7 @@ SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory ** The busy-handler is not invoked if another connection already ** holds the write-lock. If possible, the upper layer will call it. */ - rc = sqlite3WalBeginWriteTransaction(pPager->pWal); + rc = tdsqlite3WalBeginWriteTransaction(pPager->pWal); }else{ /* Obtain a RESERVED lock on the database file. If the exFlag parameter ** is true, then immediately upgrade this to an EXCLUSIVE lock. The @@ -55862,14 +61685,14 @@ static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){ rc = write32bits(pPager->jfd, iOff, pPg->pgno); if( rc!=SQLITE_OK ) return rc; - rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4); + rc = tdsqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4); if( rc!=SQLITE_OK ) return rc; rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum); if( rc!=SQLITE_OK ) return rc; IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, pPager->journalOff, pPager->pageSize)); - PAGER_INCR(sqlite3_pager_writej_count); + PAGER_INCR(tdsqlite3_pager_writej_count); PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n", PAGERID(pPager), pPg->pgno, ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg))); @@ -55877,7 +61700,7 @@ static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){ pPager->journalOff += 8 + pPager->pageSize; pPager->nRec++; assert( pPager->pInJournal!=0 ); - rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno); + rc = tdsqlite3BitvecSet(pPager->pInJournal, pPg->pgno); testcase( rc==SQLITE_NOMEM ); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); rc |= addToSavepointBitvecs(pPager, pPg->pgno); @@ -55913,8 +61736,8 @@ static int pager_write(PgHdr *pPg){ ** obtained the necessary locks to begin the write-transaction, but the ** rollback journal might not yet be open. Open it now if this is the case. ** - ** This is done before calling sqlite3PcacheMakeDirty() on the page. - ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then + ** This is done before calling tdsqlite3PcacheMakeDirty() on the page. + ** Otherwise, if it were done after calling tdsqlite3PcacheMakeDirty(), then ** an error might occur and the pager would end up in WRITER_LOCKED state ** with pages marked as dirty in the cache. */ @@ -55926,7 +61749,7 @@ static int pager_write(PgHdr *pPg){ assert( assert_pager_state(pPager) ); /* Mark the page that is about to be modified as dirty. */ - sqlite3PcacheMakeDirty(pPg); + tdsqlite3PcacheMakeDirty(pPg); /* If a rollback journal is in use, them make sure the page that is about ** to change is in the rollback journal, or if the page is a new page off @@ -55934,7 +61757,7 @@ static int pager_write(PgHdr *pPg){ */ assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) ); if( pPager->pInJournal!=0 - && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0 + && tdsqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0 ){ assert( pagerUseWal(pPager)==0 ); if( pPg->pgno<=pPager->dbOrigSize ){ @@ -55974,7 +61797,7 @@ static int pager_write(PgHdr *pPg){ } /* -** This is a variant of sqlite3PagerWrite() that runs when the sector size +** This is a variant of tdsqlite3PagerWrite() that runs when the sector size ** is larger than the page size. SQLite makes the (reasonable) assumption that ** all bytes of a sector are written together by hardware. Hence, all bytes of ** a sector need to be journalled in case of a power loss in the middle of @@ -56023,22 +61846,22 @@ static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){ for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){ Pgno pg = pg1+ii; PgHdr *pPage; - if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){ + if( pg==pPg->pgno || !tdsqlite3BitvecTest(pPager->pInJournal, pg) ){ if( pg!=PAGER_MJ_PGNO(pPager) ){ - rc = sqlite3PagerGet(pPager, pg, &pPage, 0); + rc = tdsqlite3PagerGet(pPager, pg, &pPage, 0); if( rc==SQLITE_OK ){ rc = pager_write(pPage); if( pPage->flags&PGHDR_NEED_SYNC ){ needSync = 1; } - sqlite3PagerUnrefNotNull(pPage); + tdsqlite3PagerUnrefNotNull(pPage); } } - }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){ + }else if( (pPage = tdsqlite3PagerLookup(pPager, pg))!=0 ){ if( pPage->flags&PGHDR_NEED_SYNC ){ needSync = 1; } - sqlite3PagerUnrefNotNull(pPage); + tdsqlite3PagerUnrefNotNull(pPage); } } @@ -56051,10 +61874,10 @@ static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){ if( rc==SQLITE_OK && needSync ){ assert( !MEMDB ); for(ii=0; ii<nPage; ii++){ - PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii); + PgHdr *pPage = tdsqlite3PagerLookup(pPager, pg1+ii); if( pPage ){ pPage->flags |= PGHDR_NEED_SYNC; - sqlite3PagerUnrefNotNull(pPage); + tdsqlite3PagerUnrefNotNull(pPage); } } } @@ -56078,16 +61901,16 @@ static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){ ** If an error occurs, SQLITE_NOMEM or an IO error code is returned ** as appropriate. Otherwise, SQLITE_OK. */ -SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){ +SQLITE_PRIVATE int tdsqlite3PagerWrite(PgHdr *pPg){ Pager *pPager = pPg->pPager; assert( (pPg->flags & PGHDR_MMAP)==0 ); assert( pPager->eState>=PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); - if( pPager->errCode ){ - return pPager->errCode; - }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){ + if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){ if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg); return SQLITE_OK; + }else if( pPager->errCode ){ + return pPager->errCode; }else if( pPager->sectorSize > (u32)pPager->pageSize ){ assert( pPager->tempFile==0 ); return pagerWriteLargeSector(pPg); @@ -56098,11 +61921,11 @@ SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){ /* ** Return TRUE if the page given in the argument was previously passed -** to sqlite3PagerWrite(). In other words, return TRUE if it is ok +** to tdsqlite3PagerWrite(). In other words, return TRUE if it is ok ** to change the content of the page. */ #ifndef NDEBUG -SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){ +SQLITE_PRIVATE int tdsqlite3PagerIswriteable(DbPage *pPg){ return pPg->flags & PGHDR_WRITEABLE; } #endif @@ -56127,7 +61950,7 @@ SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){ ** to be written out to disk so that it may be read back in if the ** current transaction is rolled back. */ -SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){ +SQLITE_PRIVATE void tdsqlite3PagerDontWrite(PgHdr *pPg){ Pager *pPager = pPg->pPager; if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){ PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager))); @@ -56151,7 +61974,7 @@ SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){ ** unconditional update of the change counters. ** ** If the isDirectMode flag is zero, then this is done by calling -** sqlite3PagerWrite() on page 1, then modifying the contents of the +** tdsqlite3PagerWrite() on page 1, then modifying the contents of the ** page data. In this case the file will be updated when the current ** transaction is committed. ** @@ -56159,7 +61982,7 @@ SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){ ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case, ** if isDirect is non-zero, then the database file is updated directly ** by writing an updated version of page 1 using a call to the -** sqlite3OsWrite() function. +** tdsqlite3OsWrite() function. */ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ int rc = SQLITE_OK; @@ -56193,7 +62016,7 @@ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ assert( !pPager->tempFile && isOpen(pPager->fd) ); /* Open page 1 of the file for writing. */ - rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0); + rc = tdsqlite3PagerGet(pPager, 1, &pPgHdr, 0); assert( pPgHdr==0 || rc==SQLITE_OK ); /* If page one was fetched successfully, and this function is not @@ -56202,7 +62025,7 @@ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ ** above is always successful - hence the ALWAYS on rc==SQLITE_OK. */ if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){ - rc = sqlite3PagerWrite(pPgHdr); + rc = tdsqlite3PagerWrite(pPgHdr); } if( rc==SQLITE_OK ){ @@ -56215,7 +62038,7 @@ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ assert( pPager->dbFileSize>0 ); CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf); if( rc==SQLITE_OK ){ - rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0); + rc = tdsqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0); pPager->aStat[PAGER_STAT_WRITE]++; } if( rc==SQLITE_OK ){ @@ -56232,7 +62055,7 @@ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ } /* Release the page reference. */ - sqlite3PagerUnref(pPgHdr); + tdsqlite3PagerUnref(pPgHdr); } return rc; } @@ -56244,17 +62067,14 @@ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ ** If successful, or if called on a pager for which it is a no-op, this ** function returns SQLITE_OK. Otherwise, an IO error code is returned. */ -SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){ +SQLITE_PRIVATE int tdsqlite3PagerSync(Pager *pPager, const char *zMaster){ int rc = SQLITE_OK; - - if( isOpen(pPager->fd) ){ - void *pArg = (void*)zMaster; - rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg); - if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; - } + void *pArg = (void*)zMaster; + rc = tdsqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg); + if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; if( rc==SQLITE_OK && !pPager->noSync ){ assert( !MEMDB ); - rc = sqlite3OsSync(pPager->fd, pPager->syncFlags); + rc = tdsqlite3OsSync(pPager->fd, pPager->syncFlags); } return rc; } @@ -56270,7 +62090,7 @@ SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){ ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is ** returned. */ -SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerExclusiveLock(Pager *pPager){ int rc = pPager->errCode; assert( assert_pager_state(pPager) ); if( rc==SQLITE_OK ){ @@ -56305,14 +62125,14 @@ SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){ ** delete the master journal file if specified). ** ** Note that if zMaster==NULL, this does not overwrite a previous value -** passed to an sqlite3PagerCommitPhaseOne() call. +** passed to an tdsqlite3PagerCommitPhaseOne() call. ** ** If the final parameter - noSync - is true, then the database file itself -** is not synced. The caller must call sqlite3PagerSync() directly to +** is not synced. The caller must call tdsqlite3PagerSync() directly to ** sync the database file before calling CommitPhaseTwo() to delete the ** journal file in this case. */ -SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( +SQLITE_PRIVATE int tdsqlite3PagerCommitPhaseOne( Pager *pPager, /* Pager object */ const char *zMaster, /* If not NULL, the master journal name */ int noSync /* True to omit the xSync on the db file */ @@ -56330,7 +62150,7 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( if( NEVER(pPager->errCode) ) return pPager->errCode; /* Provide the ability to easily simulate an I/O error during testing */ - if( sqlite3FaultSim(400) ) return SQLITE_IOERR; + if( tdsqlite3FaultSim(400) ) return SQLITE_IOERR; PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", pPager->zFilename, zMaster, pPager->dbSize)); @@ -56344,15 +62164,16 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( /* If this is an in-memory db, or no pages have been written to, or this ** function has already been called, it is mostly a no-op. However, any ** backup in progress needs to be restarted. */ - sqlite3BackupRestart(pPager->pBackup); + tdsqlite3BackupRestart(pPager->pBackup); }else{ + PgHdr *pList; if( pagerUseWal(pPager) ){ - PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); PgHdr *pPageOne = 0; + pList = tdsqlite3PcacheDirtyList(pPager->pPCache); if( pList==0 ){ /* Must have at least one page for the WAL commit flag. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */ - rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0); + rc = tdsqlite3PagerGet(pPager, 1, &pPageOne, 0); pList = pPageOne; pList->pDirty = 0; } @@ -56360,11 +62181,26 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( if( ALWAYS(pList) ){ rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1); } - sqlite3PagerUnref(pPageOne); + tdsqlite3PagerUnref(pPageOne); if( rc==SQLITE_OK ){ - sqlite3PcacheCleanAll(pPager->pPCache); + tdsqlite3PcacheCleanAll(pPager->pPCache); } }else{ + /* The bBatch boolean is true if the batch-atomic-write commit method + ** should be used. No rollback journal is created if batch-atomic-write + ** is enabled. + */ +#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE + tdsqlite3_file *fd = pPager->fd; + int bBatch = zMaster==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */ + && (tdsqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC) + && !pPager->noSync + && tdsqlite3JournalIsInMemory(pPager->jfd); +#else +# define bBatch 0 +#endif + +#ifdef SQLITE_ENABLE_ATOMIC_WRITE /* The following block updates the change-counter. Exactly how it ** does this depends on whether or not the atomic-update optimization ** was enabled at compile time, and if this transaction meets the @@ -56378,7 +62214,7 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( ** If the optimization was not enabled at compile time, then the ** pager_incr_changecounter() function is called to update the change ** counter in 'indirect-mode'. If the optimization is compiled in but - ** is not applicable to this transaction, call sqlite3JournalCreate() + ** is not applicable to this transaction, call tdsqlite3JournalCreate() ** to make sure the journal file has actually been created, then call ** pager_incr_changecounter() to update the change-counter in indirect ** mode. @@ -56388,33 +62224,41 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( ** in 'direct' mode. In this case the journal file will never be ** created for this transaction. */ - #ifdef SQLITE_ENABLE_ATOMIC_WRITE - PgHdr *pPg; - assert( isOpen(pPager->jfd) - || pPager->journalMode==PAGER_JOURNALMODE_OFF - || pPager->journalMode==PAGER_JOURNALMODE_WAL - ); - if( !zMaster && isOpen(pPager->jfd) - && pPager->journalOff==jrnlBufferSize(pPager) - && pPager->dbSize>=pPager->dbOrigSize - && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty) - ){ - /* Update the db file change counter via the direct-write method. The - ** following call will modify the in-memory representation of page 1 - ** to include the updated change counter and then write page 1 - ** directly to the database file. Because of the atomic-write - ** property of the host file-system, this is safe. - */ - rc = pager_incr_changecounter(pPager, 1); - }else{ - rc = sqlite3JournalCreate(pPager->jfd); - if( rc==SQLITE_OK ){ - rc = pager_incr_changecounter(pPager, 0); + if( bBatch==0 ){ + PgHdr *pPg; + assert( isOpen(pPager->jfd) + || pPager->journalMode==PAGER_JOURNALMODE_OFF + || pPager->journalMode==PAGER_JOURNALMODE_WAL + ); + if( !zMaster && isOpen(pPager->jfd) + && pPager->journalOff==jrnlBufferSize(pPager) + && pPager->dbSize>=pPager->dbOrigSize + && (!(pPg = tdsqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty) + ){ + /* Update the db file change counter via the direct-write method. The + ** following call will modify the in-memory representation of page 1 + ** to include the updated change counter and then write page 1 + ** directly to the database file. Because of the atomic-write + ** property of the host file-system, this is safe. + */ + rc = pager_incr_changecounter(pPager, 1); + }else{ + rc = tdsqlite3JournalCreate(pPager->jfd); + if( rc==SQLITE_OK ){ + rc = pager_incr_changecounter(pPager, 0); + } } } - #else +#else /* SQLITE_ENABLE_ATOMIC_WRITE */ +#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE + if( zMaster ){ + rc = tdsqlite3JournalCreate(pPager->jfd); + if( rc!=SQLITE_OK ) goto commit_phase_one_exit; + assert( bBatch==0 ); + } +#endif rc = pager_incr_changecounter(pPager, 0); - #endif +#endif /* !SQLITE_ENABLE_ATOMIC_WRITE */ if( rc!=SQLITE_OK ) goto commit_phase_one_exit; /* Write the master journal name into the journal file. If a master @@ -56437,13 +62281,42 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( */ rc = syncJournal(pPager, 0); if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - - rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache)); + + pList = tdsqlite3PcacheDirtyList(pPager->pPCache); +#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE + if( bBatch ){ + rc = tdsqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0); + if( rc==SQLITE_OK ){ + rc = pager_write_pagelist(pPager, pList); + if( rc==SQLITE_OK ){ + rc = tdsqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0); + } + if( rc!=SQLITE_OK ){ + tdsqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0); + } + } + + if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){ + rc = tdsqlite3JournalCreate(pPager->jfd); + if( rc!=SQLITE_OK ){ + tdsqlite3OsClose(pPager->jfd); + goto commit_phase_one_exit; + } + bBatch = 0; + }else{ + tdsqlite3OsClose(pPager->jfd); + } + } +#endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ + + if( bBatch==0 ){ + rc = pager_write_pagelist(pPager, pList); + } if( rc!=SQLITE_OK ){ assert( rc!=SQLITE_IOERR_BLOCKED ); goto commit_phase_one_exit; } - sqlite3PcacheCleanAll(pPager->pPCache); + tdsqlite3PcacheCleanAll(pPager->pPCache); /* If the file on disk is smaller than the database image, use ** pager_truncate to grow the file here. This can happen if the database @@ -56460,7 +62333,7 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( /* Finally, sync the database file. */ if( !noSync ){ - rc = sqlite3PagerSync(pPager, zMaster); + rc = tdsqlite3PagerSync(pPager, zMaster); } IOTRACE(("DBSYNC %p\n", pPager)) } @@ -56489,13 +62362,14 @@ commit_phase_one_exit: ** If an error occurs, an IO error code is returned and the pager ** moves into the error state. Otherwise, SQLITE_OK is returned. */ -SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerCommitPhaseTwo(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ /* This routine should not be called if a prior error has occurred. ** But if (due to a coding error elsewhere in the system) it does get ** called, just return the same error code without doing anything. */ if( NEVER(pPager->errCode) ) return pPager->errCode; + pPager->iDataVersion++; assert( pPager->eState==PAGER_WRITER_LOCKED || pPager->eState==PAGER_WRITER_FINISHED @@ -56524,7 +62398,6 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){ } PAGERTRACE(("COMMIT %d\n", PAGERID(pPager))); - pPager->iDataVersion++; rc = pager_end_transaction(pPager, pPager->setMaster, 1); return pager_error(pPager, rc); } @@ -56555,7 +62428,7 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){ ** their pre-transaction state by re-reading data from the database or ** WAL files. The WAL transaction is then closed. */ -SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerRollback(Pager *pPager){ int rc = SQLITE_OK; /* Return code */ PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager))); @@ -56569,7 +62442,7 @@ SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){ if( pagerUseWal(pPager) ){ int rc2; - rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1); + rc = tdsqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1); rc2 = pager_end_transaction(pPager, pPager->setMaster, 0); if( rc==SQLITE_OK ) rc = rc2; }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){ @@ -56582,6 +62455,7 @@ SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){ */ pPager->errCode = SQLITE_ABORT; pPager->eState = PAGER_ERROR; + setGetterMethod(pPager); return rc; } }else{ @@ -56604,7 +62478,7 @@ SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){ ** Return TRUE if the database file is opened read-only. Return FALSE ** if the database is (in theory) writable. */ -SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){ +SQLITE_PRIVATE u8 tdsqlite3PagerIsreadonly(Pager *pPager){ return pPager->readOnly; } @@ -56612,8 +62486,8 @@ SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){ /* ** Return the sum of the reference counts for all pages held by pPager. */ -SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){ - return sqlite3PcacheRefCount(pPager->pPCache); +SQLITE_PRIVATE int tdsqlite3PagerRefcount(Pager *pPager){ + return tdsqlite3PcacheRefCount(pPager->pPCache); } #endif @@ -56621,30 +62495,30 @@ SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){ ** Return the approximate number of bytes of memory currently ** used by the pager and its associated cache. */ -SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerMemUsed(Pager *pPager){ int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr) + 5*sizeof(void*); - return perPageSize*sqlite3PcachePagecount(pPager->pPCache) - + sqlite3MallocSize(pPager) + return perPageSize*tdsqlite3PcachePagecount(pPager->pPCache) + + tdsqlite3MallocSize(pPager) + pPager->pageSize; } /* ** Return the number of references to the specified page. */ -SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){ - return sqlite3PcachePageRefcount(pPage); +SQLITE_PRIVATE int tdsqlite3PagerPageRefcount(DbPage *pPage){ + return tdsqlite3PcachePageRefcount(pPage); } #ifdef SQLITE_TEST /* ** This routine is used for testing and analysis only. */ -SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){ +SQLITE_PRIVATE int *tdsqlite3PagerStats(Pager *pPager){ static int a[11]; - a[0] = sqlite3PcacheRefCount(pPager->pPCache); - a[1] = sqlite3PcachePagecount(pPager->pPCache); - a[2] = sqlite3PcacheGetCachesize(pPager->pPCache); + a[0] = tdsqlite3PcacheRefCount(pPager->pPCache); + a[1] = tdsqlite3PcachePagecount(pPager->pPCache); + a[2] = tdsqlite3PcacheGetCachesize(pPager->pPCache); a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize; a[4] = pPager->eState; a[5] = pPager->errCode; @@ -56658,33 +62532,40 @@ SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){ #endif /* -** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or -** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the +** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE, +** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation +** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because +** it was added later. +** +** Before returning, *pnVal is incremented by the ** current cache hit or miss count, according to the value of eStat. If the ** reset parameter is non-zero, the cache hit or miss count is zeroed before ** returning. */ -SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){ +SQLITE_PRIVATE void tdsqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){ assert( eStat==SQLITE_DBSTATUS_CACHE_HIT || eStat==SQLITE_DBSTATUS_CACHE_MISS || eStat==SQLITE_DBSTATUS_CACHE_WRITE + || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1 ); assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS ); assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE ); - assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 ); + assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 + && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 ); - *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT]; + eStat -= SQLITE_DBSTATUS_CACHE_HIT; + *pnVal += pPager->aStat[eStat]; if( reset ){ - pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0; + pPager->aStat[eStat] = 0; } } /* ** Return true if this is an in-memory or temp-file backed pager. */ -SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerIsMemdb(Pager *pPager){ return pPager->tempFile; } @@ -56712,7 +62593,7 @@ static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){ ** if the allocation fails. Otherwise, zero the new portion in case a ** malloc failure occurs while populating it in the for(...) loop below. */ - aNew = (PagerSavepoint *)sqlite3Realloc( + aNew = (PagerSavepoint *)tdsqlite3Realloc( pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint ); if( !aNew ){ @@ -56730,12 +62611,12 @@ static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){ aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager); } aNew[ii].iSubRec = pPager->nSubRec; - aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize); + aNew[ii].pInSavepoint = tdsqlite3BitvecCreate(pPager->dbSize); if( !aNew[ii].pInSavepoint ){ return SQLITE_NOMEM_BKPT; } if( pagerUseWal(pPager) ){ - sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData); + tdsqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData); } pPager->nSavepoint = ii+1; } @@ -56743,7 +62624,7 @@ static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){ assertTruncateConstraint(pPager); return rc; } -SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ +SQLITE_PRIVATE int tdsqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ assert( pPager->eState>=PAGER_WRITER_LOCKED ); assert( assert_pager_state(pPager) ); @@ -56773,7 +62654,7 @@ SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ ** ** If a negative value is passed to this function, then the current ** transaction is rolled back. This is different to calling -** sqlite3PagerRollback() because this function does not terminate +** tdsqlite3PagerRollback() because this function does not terminate ** the transaction or unlock the database, it just restores the ** contents of the database to its original state. ** @@ -56785,7 +62666,7 @@ SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ ** or an IO error code if an IO error occurs while rolling back a ** savepoint. If no errors occur, SQLITE_OK is returned. */ -SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ +SQLITE_PRIVATE int tdsqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ int rc = pPager->errCode; #ifdef SQLITE_ENABLE_ZIPVFS @@ -56805,7 +62686,7 @@ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ */ nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1); for(ii=nNew; ii<pPager->nSavepoint; ii++){ - sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); + tdsqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); } pPager->nSavepoint = nNew; @@ -56814,8 +62695,8 @@ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ if( op==SAVEPOINT_RELEASE ){ if( nNew==0 && isOpen(pPager->sjfd) ){ /* Only truncate if it is an in-memory sub-journal. */ - if( sqlite3JournalIsInMemory(pPager->sjfd) ){ - rc = sqlite3OsTruncate(pPager->sjfd, 0); + if( tdsqlite3JournalIsInMemory(pPager->sjfd) ){ + rc = tdsqlite3OsTruncate(pPager->sjfd, 0); assert( rc==SQLITE_OK ); } pPager->nSubRec = 0; @@ -56843,6 +62724,7 @@ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ ){ pPager->errCode = SQLITE_ABORT; pPager->eState = PAGER_ERROR; + setGetterMethod(pPager); } #endif } @@ -56859,15 +62741,19 @@ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ ** behavior. But when the Btree needs to know the filename for matching to ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can ** participate in shared-cache. +** +** The return value to this routine is always safe to use with +** tdsqlite3_uri_parameter() and tdsqlite3_filename_database() and friends. */ -SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){ - return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename; +SQLITE_PRIVATE const char *tdsqlite3PagerFilename(const Pager *pPager, int nullIfMemDb){ + static const char zFake[] = { 0x00, 0x01, 0x00, 0x00, 0x00 }; + return (nullIfMemDb && pPager->memDb) ? &zFake[3] : pPager->zFilename; } /* ** Return the VFS structure for the pager. */ -SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){ +SQLITE_PRIVATE tdsqlite3_vfs *tdsqlite3PagerVfs(Pager *pPager){ return pPager->pVfs; } @@ -56876,26 +62762,36 @@ SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){ ** with the pager. This might return NULL if the file has ** not yet been opened. */ -SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){ +SQLITE_PRIVATE tdsqlite3_file *tdsqlite3PagerFile(Pager *pPager){ return pPager->fd; } +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT +/* +** Reset the lock timeout for pager. +*/ +SQLITE_PRIVATE void tdsqlite3PagerResetLockTimeout(Pager *pPager){ + int x = 0; + tdsqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_LOCK_TIMEOUT, &x); +} +#endif + /* ** Return the file handle for the journal file (if it exists). ** This will be either the rollback journal or the WAL file. */ -SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){ +SQLITE_PRIVATE tdsqlite3_file *tdsqlite3PagerJrnlFile(Pager *pPager){ #if SQLITE_OMIT_WAL return pPager->jfd; #else - return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd; + return pPager->pWal ? tdsqlite3WalFile(pPager->pWal) : pPager->jfd; #endif } /* ** Return the full pathname of the journal file. */ -SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){ +SQLITE_PRIVATE const char *tdsqlite3PagerJournalname(Pager *pPager){ return pPager->zJournal; } @@ -56903,21 +62799,26 @@ SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){ /* ** Set or retrieve the codec for this pager */ -SQLITE_PRIVATE void sqlite3PagerSetCodec( +SQLITE_PRIVATE void tdsqlite3PagerSetCodec( Pager *pPager, void *(*xCodec)(void*,void*,Pgno,int), void (*xCodecSizeChng)(void*,int,int), void (*xCodecFree)(void*), void *pCodec ){ - if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); + if( pPager->xCodecFree ){ + pPager->xCodecFree(pPager->pCodec); + }else{ + pager_reset(pPager); + } pPager->xCodec = pPager->memDb ? 0 : xCodec; pPager->xCodecSizeChng = xCodecSizeChng; pPager->xCodecFree = xCodecFree; pPager->pCodec = pCodec; + setGetterMethod(pPager); pagerReportSize(pPager); } -SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){ +SQLITE_PRIVATE void *tdsqlite3PagerGetCodec(Pager *pPager){ return pPager->pCodec; } @@ -56928,7 +62829,7 @@ SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){ ** This function returns a pointer to a buffer containing the encrypted ** page content. If a malloc fails, this function may return NULL. */ -SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){ +SQLITE_PRIVATE void *tdsqlite3PagerCodec(PgHdr *pPg){ void *aData = 0; CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData); return aData; @@ -56937,7 +62838,7 @@ SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){ /* ** Return the current pager state */ -SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerState(Pager *pPager){ return pPager->eState; } #endif /* SQLITE_HAS_CODEC */ @@ -56968,7 +62869,7 @@ SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){ ** This function may return SQLITE_NOMEM or an IO error code if an error ** occurs. Otherwise, it returns SQLITE_OK. */ -SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){ +SQLITE_PRIVATE int tdsqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){ PgHdr *pPgOld; /* The page being overwritten. */ Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */ int rc; /* Return code */ @@ -56985,7 +62886,7 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i */ assert( pPager->tempFile || !MEMDB ); if( pPager->tempFile ){ - rc = sqlite3PagerWrite(pPg); + rc = tdsqlite3PagerWrite(pPg); if( rc ) return rc; } @@ -57037,30 +62938,34 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i ** for the page moved there. */ pPg->flags &= ~PGHDR_NEED_SYNC; - pPgOld = sqlite3PagerLookup(pPager, pgno); - assert( !pPgOld || pPgOld->nRef==1 ); + pPgOld = tdsqlite3PagerLookup(pPager, pgno); + assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB ); if( pPgOld ){ + if( pPgOld->nRef>1 ){ + tdsqlite3PagerUnrefNotNull(pPgOld); + return SQLITE_CORRUPT_BKPT; + } pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC); if( pPager->tempFile ){ /* Do not discard pages from an in-memory database since we might ** need to rollback later. Just move the page out of the way. */ - sqlite3PcacheMove(pPgOld, pPager->dbSize+1); + tdsqlite3PcacheMove(pPgOld, pPager->dbSize+1); }else{ - sqlite3PcacheDrop(pPgOld); + tdsqlite3PcacheDrop(pPgOld); } } origPgno = pPg->pgno; - sqlite3PcacheMove(pPg, pgno); - sqlite3PcacheMakeDirty(pPg); + tdsqlite3PcacheMove(pPg, pgno); + tdsqlite3PcacheMakeDirty(pPg); /* For an in-memory database, make sure the original page continues ** to exist, in case the transaction needs to roll back. Use pPgOld ** as the original page since it has already been allocated. */ if( pPager->tempFile && pPgOld ){ - sqlite3PcacheMove(pPgOld, origPgno); - sqlite3PagerUnrefNotNull(pPgOld); + tdsqlite3PcacheMove(pPgOld, origPgno); + tdsqlite3PagerUnrefNotNull(pPgOld); } if( needSyncPgno ){ @@ -57079,17 +62984,17 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i ** the journal file twice, but that is not a problem. */ PgHdr *pPgHdr; - rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0); + rc = tdsqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0); if( rc!=SQLITE_OK ){ if( needSyncPgno<=pPager->dbOrigSize ){ assert( pPager->pTmpSpace!=0 ); - sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace); + tdsqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace); } return rc; } pPgHdr->flags |= PGHDR_NEED_SYNC; - sqlite3PcacheMakeDirty(pPgHdr); - sqlite3PagerUnrefNotNull(pPgHdr); + tdsqlite3PcacheMakeDirty(pPgHdr); + tdsqlite3PagerUnrefNotNull(pPgHdr); } return SQLITE_OK; @@ -57102,16 +63007,16 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i ** page number to iNew and sets the value of the PgHdr.flags field to ** the value passed as the third parameter. */ -SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){ +SQLITE_PRIVATE void tdsqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){ assert( pPg->pgno!=iNew ); pPg->flags = flags; - sqlite3PcacheMove(pPg, iNew); + tdsqlite3PcacheMove(pPg, iNew); } /* ** Return a pointer to the data for the specified page. */ -SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){ +SQLITE_PRIVATE void *tdsqlite3PagerGetData(DbPage *pPg){ assert( pPg->nRef>0 || pPg->pPager->memDb ); return pPg->pData; } @@ -57120,7 +63025,7 @@ SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){ ** Return a pointer to the Pager.nExtra bytes of "extra" space ** allocated along with the specified page. */ -SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){ +SQLITE_PRIVATE void *tdsqlite3PagerGetExtra(DbPage *pPg){ return pPg->pExtra; } @@ -57134,14 +63039,14 @@ SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){ ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated) ** locking-mode. */ -SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){ +SQLITE_PRIVATE int tdsqlite3PagerLockingMode(Pager *pPager, int eMode){ assert( eMode==PAGER_LOCKINGMODE_QUERY || eMode==PAGER_LOCKINGMODE_NORMAL || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); assert( PAGER_LOCKINGMODE_QUERY<0 ); assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 ); - assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) ); - if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){ + assert( pPager->exclusiveMode || 0==tdsqlite3WalHeapMemory(pPager->pWal) ); + if( eMode>=0 && !pPager->tempFile && !tdsqlite3WalHeapMemory(pPager->pWal) ){ pPager->exclusiveMode = (u8)eMode; } return (int)pPager->exclusiveMode; @@ -57167,16 +63072,9 @@ SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){ ** ** The returned indicate the current (possibly updated) journal-mode. */ -SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ +SQLITE_PRIVATE int tdsqlite3PagerSetJournalMode(Pager *pPager, int eMode){ u8 eOld = pPager->journalMode; /* Prior journalmode */ -#ifdef SQLITE_DEBUG - /* The print_pager_state() routine is intended to be used by the debugger - ** only. We invoke it once here to suppress a compiler warning. */ - print_pager_state(pPager); -#endif - - /* The eMode parameter is always valid */ assert( eMode==PAGER_JOURNALMODE_DELETE || eMode==PAGER_JOURNALMODE_TRUNCATE @@ -57229,22 +63127,22 @@ SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ ** database file. This ensures that the journal file is not deleted ** while it is in use by some other client. */ - sqlite3OsClose(pPager->jfd); + tdsqlite3OsClose(pPager->jfd); if( pPager->eLock>=RESERVED_LOCK ){ - sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); + tdsqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); }else{ int rc = SQLITE_OK; int state = pPager->eState; assert( state==PAGER_OPEN || state==PAGER_READER ); if( state==PAGER_OPEN ){ - rc = sqlite3PagerSharedLock(pPager); + rc = tdsqlite3PagerSharedLock(pPager); } if( pPager->eState==PAGER_READER ){ assert( rc==SQLITE_OK ); rc = pagerLockDb(pPager, RESERVED_LOCK); } if( rc==SQLITE_OK ){ - sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); + tdsqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); } if( rc==SQLITE_OK && state==PAGER_READER ){ pagerUnlockDb(pPager, SHARED_LOCK); @@ -57254,7 +63152,7 @@ SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ assert( state==pPager->eState ); } }else if( eMode==PAGER_JOURNALMODE_OFF ){ - sqlite3OsClose(pPager->jfd); + tdsqlite3OsClose(pPager->jfd); } } @@ -57265,7 +63163,7 @@ SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ /* ** Return the current journal mode. */ -SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerGetJournalMode(Pager *pPager){ return (int)pPager->journalMode; } @@ -57274,7 +63172,7 @@ SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){ ** journalmode. Journalmode changes can only happen when the database ** is unmodified. */ -SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerOkToChangeJournalMode(Pager *pPager){ assert( assert_pager_state(pPager) ); if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0; if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0; @@ -57287,10 +63185,10 @@ SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){ ** Setting the size limit to -1 means no limit is enforced. ** An attempt to set a limit smaller than -1 is a no-op. */ -SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){ +SQLITE_PRIVATE i64 tdsqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){ if( iLimit>=-1 ){ pPager->journalSizeLimit = iLimit; - sqlite3WalLimit(pPager->pWal, iLimit); + tdsqlite3WalLimit(pPager->pWal, iLimit); } return pPager->journalSizeLimit; } @@ -57298,10 +63196,10 @@ SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){ /* ** Return a pointer to the pPager->pBackup variable. The backup module ** in backup.c maintains the content of this variable. This module -** uses it opaquely as an argument to sqlite3BackupRestart() and -** sqlite3BackupUpdate() only. +** uses it opaquely as an argument to tdsqlite3BackupRestart() and +** tdsqlite3BackupUpdate() only. */ -SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){ +SQLITE_PRIVATE tdsqlite3_backup **tdsqlite3PagerBackupPtr(Pager *pPager){ return &pPager->pBackup; } @@ -57309,7 +63207,7 @@ SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){ /* ** Unless this is an in-memory or temporary database, clear the pager cache. */ -SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){ +SQLITE_PRIVATE void tdsqlite3PagerClearCache(Pager *pPager){ assert( MEMDB==0 || pPager->tempFile ); if( pPager->tempFile==0 ) pager_reset(pPager); } @@ -57319,34 +63217,41 @@ SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){ #ifndef SQLITE_OMIT_WAL /* ** This function is called when the user invokes "PRAGMA wal_checkpoint", -** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint() +** "PRAGMA wal_blocking_checkpoint" or calls the tdsqlite3_wal_checkpoint() ** or wal_blocking_checkpoint() API functions. ** ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. */ -SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){ +SQLITE_PRIVATE int tdsqlite3PagerCheckpoint( + Pager *pPager, /* Checkpoint on this pager */ + tdsqlite3 *db, /* Db handle used to check for interrupts */ + int eMode, /* Type of checkpoint */ + int *pnLog, /* OUT: Final number of frames in log */ + int *pnCkpt /* OUT: Final number of checkpointed frames */ +){ int rc = SQLITE_OK; if( pPager->pWal ){ - rc = sqlite3WalCheckpoint(pPager->pWal, eMode, + rc = tdsqlite3WalCheckpoint(pPager->pWal, db, eMode, (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler), pPager->pBusyHandlerArg, - pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace, + pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace, pnLog, pnCkpt ); + tdsqlite3PagerResetLockTimeout(pPager); } return rc; } -SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){ - return sqlite3WalCallback(pPager->pWal); +SQLITE_PRIVATE int tdsqlite3PagerWalCallback(Pager *pPager){ + return tdsqlite3WalCallback(pPager->pWal); } /* ** Return true if the underlying VFS for the given pager supports the ** primitives necessary for write-ahead logging. */ -SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){ - const sqlite3_io_methods *pMethods = pPager->fd->pMethods; +SQLITE_PRIVATE int tdsqlite3PagerWalSupported(Pager *pPager){ + const tdsqlite3_io_methods *pMethods = pPager->fd->pMethods; if( pPager->noLock ) return 0; return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap); } @@ -57370,7 +63275,7 @@ static int pagerExclusiveLock(Pager *pPager){ } /* -** Call sqlite3WalOpen() to open the WAL handle. If the pager is in +** Call tdsqlite3WalOpen() to open the WAL handle. If the pager is in ** exclusive-locking mode when this function is called, take an EXCLUSIVE ** lock on the database file and use heap-memory to store the wal-index ** in. Otherwise, use the normal shared-memory. @@ -57394,7 +63299,7 @@ static int pagerOpenWal(Pager *pPager){ ** (e.g. due to malloc() failure), return an error code. */ if( rc==SQLITE_OK ){ - rc = sqlite3WalOpen(pPager->pVfs, + rc = tdsqlite3WalOpen(pPager->pVfs, pPager->fd, pPager->zWal, pPager->exclusiveMode, pPager->journalSizeLimit, &pPager->pWal ); @@ -57420,7 +63325,7 @@ static int pagerOpenWal(Pager *pPager){ ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK ** without doing anything. */ -SQLITE_PRIVATE int sqlite3PagerOpenWal( +SQLITE_PRIVATE int tdsqlite3PagerOpenWal( Pager *pPager, /* Pager object */ int *pbOpen /* OUT: Set to true if call is a no-op */ ){ @@ -57433,10 +63338,10 @@ SQLITE_PRIVATE int sqlite3PagerOpenWal( assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) ); if( !pPager->tempFile && !pPager->pWal ){ - if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN; + if( !tdsqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN; /* Close any rollback journal previously open */ - sqlite3OsClose(pPager->jfd); + tdsqlite3OsClose(pPager->jfd); rc = pagerOpenWal(pPager); if( rc==SQLITE_OK ){ @@ -57459,7 +63364,7 @@ SQLITE_PRIVATE int sqlite3PagerOpenWal( ** error (SQLITE_BUSY) is returned and the log connection is not closed. ** If successful, the EXCLUSIVE lock is not released before returning. */ -SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerCloseWal(Pager *pPager, tdsqlite3 *db){ int rc = SQLITE_OK; assert( pPager->journalMode==PAGER_JOURNALMODE_WAL ); @@ -57472,7 +63377,7 @@ SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){ int logexists = 0; rc = pagerLockDb(pPager, SHARED_LOCK); if( rc==SQLITE_OK ){ - rc = sqlite3OsAccess( + rc = tdsqlite3OsAccess( pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists ); } @@ -57487,7 +63392,7 @@ SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){ if( rc==SQLITE_OK && pPager->pWal ){ rc = pagerExclusiveLock(pPager); if( rc==SQLITE_OK ){ - rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, + rc = tdsqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize, (u8*)pPager->pTmpSpace); pPager->pWal = 0; pagerFixMaplimit(pPager); @@ -57497,15 +63402,17 @@ SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){ return rc; } + + #ifdef SQLITE_ENABLE_SNAPSHOT /* ** If this is a WAL database, obtain a snapshot handle for the snapshot ** currently open. Otherwise, return an error. */ -SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){ +SQLITE_PRIVATE int tdsqlite3PagerSnapshotGet(Pager *pPager, tdsqlite3_snapshot **ppSnapshot){ int rc = SQLITE_ERROR; if( pPager->pWal ){ - rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot); + rc = tdsqlite3WalSnapshotGet(pPager->pWal, ppSnapshot); } return rc; } @@ -57515,15 +63422,61 @@ SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppS ** read transaction is opened, attempt to read from the snapshot it ** identifies. If this is not a WAL database, return an error. */ -SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){ +SQLITE_PRIVATE int tdsqlite3PagerSnapshotOpen(Pager *pPager, tdsqlite3_snapshot *pSnapshot){ int rc = SQLITE_OK; if( pPager->pWal ){ - sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot); + tdsqlite3WalSnapshotOpen(pPager->pWal, pSnapshot); + }else{ + rc = SQLITE_ERROR; + } + return rc; +} + +/* +** If this is a WAL database, call tdsqlite3WalSnapshotRecover(). If this +** is not a WAL database, return an error. +*/ +SQLITE_PRIVATE int tdsqlite3PagerSnapshotRecover(Pager *pPager){ + int rc; + if( pPager->pWal ){ + rc = tdsqlite3WalSnapshotRecover(pPager->pWal); }else{ rc = SQLITE_ERROR; } return rc; } + +/* +** The caller currently has a read transaction open on the database. +** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise, +** this function takes a SHARED lock on the CHECKPOINTER slot and then +** checks if the snapshot passed as the second argument is still +** available. If so, SQLITE_OK is returned. +** +** If the snapshot is not available, SQLITE_ERROR is returned. Or, if +** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error +** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER +** lock is released before returning. +*/ +SQLITE_PRIVATE int tdsqlite3PagerSnapshotCheck(Pager *pPager, tdsqlite3_snapshot *pSnapshot){ + int rc; + if( pPager->pWal ){ + rc = tdsqlite3WalSnapshotCheck(pPager->pWal, pSnapshot); + }else{ + rc = SQLITE_ERROR; + } + return rc; +} + +/* +** Release a lock obtained by an earlier successful call to +** tdsqlite3PagerSnapshotCheck(). +*/ +SQLITE_PRIVATE void tdsqlite3PagerSnapshotUnlock(Pager *pPager){ + assert( pPager->pWal ); + tdsqlite3WalSnapshotUnlock(pPager->pWal); +} + #endif /* SQLITE_ENABLE_SNAPSHOT */ #endif /* !SQLITE_OMIT_WAL */ @@ -57535,9 +63488,9 @@ SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSn ** WAL frames. Otherwise, if this is not a WAL database or the WAL file ** is empty, return 0. */ -SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){ +SQLITE_PRIVATE int tdsqlite3PagerWalFramesize(Pager *pPager){ assert( pPager->eState>=PAGER_READER ); - return sqlite3WalFramesize(pPager->pWal); + return tdsqlite3WalFramesize(pPager->pWal); } #endif @@ -57545,30 +63498,19 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){ /* BEGIN SQLCIPHER */ #ifdef SQLITE_HAS_CODEC -SQLITE_API void sqlite3pager_get_codec(Pager *pPager, void **ctx) { - *ctx = pPager->pCodec; -} -SQLITE_API int sqlite3pager_is_mj_pgno(Pager *pPager, Pgno pgno) { +SQLITE_API int tdsqlite3pager_is_mj_pgno(Pager *pPager, Pgno pgno) { return (PAGER_MJ_PGNO(pPager) == pgno) ? 1 : 0; } -SQLITE_PRIVATE sqlite3_file *sqlite3Pager_get_fd(Pager *pPager) { - return (isOpen(pPager->fd)) ? pPager->fd : NULL; -} - -SQLITE_API void sqlite3pager_sqlite3PagerSetCodec( - Pager *pPager, - void *(*xCodec)(void*,void*,Pgno,int), - void (*xCodecSizeChng)(void*,int,int), - void (*xCodecFree)(void*), - void *pCodec -){ - sqlite3PagerSetCodec(pPager, xCodec, xCodecSizeChng, xCodecFree, pCodec); +SQLITE_API void tdsqlite3pager_error(Pager *pPager, int error) { + pPager->errCode = error; + pPager->eState = PAGER_ERROR; + setGetterMethod(pPager); } -SQLITE_API void sqlite3pager_sqlite3PagerSetError( Pager *pPager, int error) { - pPager->errCode = error; +SQLITE_API void tdsqlite3pager_reset(Pager *pPager){ + pager_reset(pPager); } #endif @@ -57711,6 +63653,10 @@ SQLITE_API void sqlite3pager_sqlite3PagerSetError( Pager *pPager, int error) { ** on a network filesystem. All users of the database must be able to ** share memory. ** +** In the default unix and windows implementation, the wal-index is a mmapped +** file whose name is the database name with a "-shm" suffix added. For that +** reason, the wal-index is sometimes called the "shm" file. +** ** The wal-index is transient. After a crash, the wal-index can (and should ** be) reconstructed from the original WAL file. In fact, the VFS is required ** to either truncate or zero the header of the wal-index when the last @@ -57827,13 +63773,25 @@ SQLITE_API void sqlite3pager_sqlite3PagerSetError( Pager *pPager, int error) { ** Trace output macros */ #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) -SQLITE_PRIVATE int sqlite3WalTrace = 0; -# define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X +SQLITE_PRIVATE int tdsqlite3WalTrace = 0; +# define WALTRACE(X) if(tdsqlite3WalTrace) tdsqlite3DebugPrintf X #else # define WALTRACE(X) #endif /* +** WAL mode depends on atomic aligned 32-bit loads and stores in a few +** places. The following macros try to make this explicit. +*/ +#if GCC_VESRION>=5004000 +# define AtomicLoad(PTR) __atomic_load_n((PTR),__ATOMIC_RELAXED) +# define AtomicStore(PTR,VAL) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED) +#else +# define AtomicLoad(PTR) (*(PTR)) +# define AtomicStore(PTR,VAL) (*(PTR) = (VAL)) +#endif + +/* ** The maximum (and only) versions of the wal and wal-index formats ** that may be interpreted by this version of SQLite. ** @@ -57850,9 +63808,18 @@ SQLITE_PRIVATE int sqlite3WalTrace = 0; #define WALINDEX_MAX_VERSION 3007000 /* -** Indices of various locking bytes. WAL_NREADER is the number +** Index numbers for various locking bytes. WAL_NREADER is the number ** of available reader locks and should be at least 3. The default ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5. +** +** Technically, the various VFSes are free to implement these locks however +** they see fit. However, compatibility is encouraged so that VFSes can +** interoperate. The standard implemention used on both unix and windows +** is for the index number to indicate a byte offset into the +** WalCkptInfo.aLock[] array in the wal-index header. In other words, all +** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which +** should be 120) is the location in the shm file for the first locking +** byte. */ #define WAL_WRITE_LOCK 0 #define WAL_ALL_BUT_WRITE 1 @@ -57976,7 +63943,6 @@ struct WalCkptInfo { #define WAL_FRAME_HDRSIZE 24 /* Size of write ahead log header, including checksum. */ -/* #define WAL_HDRSIZE 24 */ #define WAL_HDRSIZE 32 /* WAL magic value. Either this value, or the same value with the least @@ -58004,9 +63970,9 @@ struct WalCkptInfo { ** following object. */ struct Wal { - sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */ - sqlite3_file *pDbFd; /* File handle for the database file */ - sqlite3_file *pWalFd; /* File handle for WAL file */ + tdsqlite3_vfs *pVfs; /* The VFS used to create pDbFd */ + tdsqlite3_file *pDbFd; /* File handle for the database file */ + tdsqlite3_file *pWalFd; /* File handle for WAL file */ u32 iCallback; /* Value to pass to log callback (or 0) */ i64 mxWalSize; /* Truncate WAL to this size upon reset */ int nWiData; /* Size of array apWiData */ @@ -58022,6 +63988,7 @@ struct Wal { u8 truncateOnCommit; /* True to truncate WAL file on commit */ u8 syncHeader; /* Fsync the WAL header if true */ u8 padToSectorBoundary; /* Pad transactions out to the next sector */ + u8 bShmUnreliable; /* SHM content is read-only and unreliable */ WalIndexHdr hdr; /* Wal-index header for current transaction */ u32 minFrame; /* Ignore wal frames before this one */ u32 iReCksum; /* On commit, recalculate checksums from here */ @@ -58111,18 +64078,27 @@ struct WalIterator { ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are ** numbered from zero. ** +** If the wal-index is currently smaller the iPage pages then the size +** of the wal-index might be increased, but only if it is safe to do +** so. It is safe to enlarge the wal-index if pWal->writeLock is true +** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE. +** ** If this call is successful, *ppPage is set to point to the wal-index ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs, ** then an SQLite error code is returned and *ppPage is set to 0. */ -static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){ +static SQLITE_NOINLINE int walIndexPageRealloc( + Wal *pWal, /* The WAL context */ + int iPage, /* The page we seek */ + volatile u32 **ppPage /* Write the page pointer here */ +){ int rc = SQLITE_OK; /* Enlarge the pWal->apWiData[] array if required */ if( pWal->nWiData<=iPage ){ - int nByte = sizeof(u32*)*(iPage+1); + tdsqlite3_int64 nByte = sizeof(u32*)*(iPage+1); volatile u32 **apNew; - apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte); + apNew = (volatile u32 **)tdsqlite3_realloc64((void *)pWal->apWiData, nByte); if( !apNew ){ *ppPage = 0; return SQLITE_NOMEM_BKPT; @@ -58134,16 +64110,19 @@ static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){ } /* Request a pointer to the required page from the VFS */ - if( pWal->apWiData[iPage]==0 ){ - if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ - pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ); - if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT; - }else{ - rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, - pWal->writeLock, (void volatile **)&pWal->apWiData[iPage] - ); + assert( pWal->apWiData[iPage]==0 ); + if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ + pWal->apWiData[iPage] = (u32 volatile *)tdsqlite3MallocZero(WALINDEX_PGSZ); + if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT; + }else{ + rc = tdsqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, + pWal->writeLock, (void volatile **)&pWal->apWiData[iPage] + ); + assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 ); + testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK ); + if( (rc&0xff)==SQLITE_READONLY ){ + pWal->readOnly |= WAL_SHM_RDONLY; if( rc==SQLITE_READONLY ){ - pWal->readOnly |= WAL_SHM_RDONLY; rc = SQLITE_OK; } } @@ -58153,6 +64132,16 @@ static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){ assert( iPage==0 || *ppPage || rc!=SQLITE_OK ); return rc; } +static int walIndexPage( + Wal *pWal, /* The WAL context */ + int iPage, /* The page we seek */ + volatile u32 **ppPage /* Write the page pointer here */ +){ + if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){ + return walIndexPageRealloc(pWal, iPage, ppPage); + } + return SQLITE_OK; +} /* ** Return a pointer to the WalCkptInfo structure in the wal-index. @@ -58211,6 +64200,7 @@ static void walChecksumBytes( assert( nByte>=8 ); assert( (nByte&0x00000007)==0 ); + assert( nByte<=65536 ); if( nativeCksum ){ do { @@ -58231,7 +64221,7 @@ static void walChecksumBytes( static void walShmBarrier(Wal *pWal){ if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){ - sqlite3OsShmBarrier(pWal->pDbFd); + tdsqlite3OsShmBarrier(pWal->pDbFd); } } @@ -58276,8 +64266,8 @@ static void walEncodeFrame( int nativeCksum; /* True for native byte-order checksums */ u32 *aCksum = pWal->hdr.aFrameCksum; assert( WAL_FRAME_HDRSIZE==24 ); - sqlite3Put4byte(&aFrame[0], iPage); - sqlite3Put4byte(&aFrame[4], nTruncate); + tdsqlite3Put4byte(&aFrame[0], iPage); + tdsqlite3Put4byte(&aFrame[4], nTruncate); if( pWal->iReCksum==0 ){ memcpy(&aFrame[8], pWal->hdr.aSalt, 8); @@ -58285,8 +64275,8 @@ static void walEncodeFrame( walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); - sqlite3Put4byte(&aFrame[16], aCksum[0]); - sqlite3Put4byte(&aFrame[20], aCksum[1]); + tdsqlite3Put4byte(&aFrame[16], aCksum[0]); + tdsqlite3Put4byte(&aFrame[20], aCksum[1]); }else{ memset(&aFrame[8], 0, 16); } @@ -58318,7 +64308,7 @@ static int walDecodeFrame( /* A frame is only valid if the page number is creater than zero. */ - pgno = sqlite3Get4byte(&aFrame[0]); + pgno = tdsqlite3Get4byte(&aFrame[0]); if( pgno==0 ){ return 0; } @@ -58331,8 +64321,8 @@ static int walDecodeFrame( nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); - if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) - || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) + if( aCksum[0]!=tdsqlite3Get4byte(&aFrame[16]) + || aCksum[1]!=tdsqlite3Get4byte(&aFrame[20]) ){ /* Checksum failed. */ return 0; @@ -58342,7 +64332,7 @@ static int walDecodeFrame( ** and the new database size. */ *piPage = pgno; - *pnTruncate = sqlite3Get4byte(&aFrame[4]); + *pnTruncate = tdsqlite3Get4byte(&aFrame[4]); return 1; } @@ -58361,7 +64351,7 @@ static const char *walLockName(int lockIdx){ return "RECOVER-LOCK"; }else{ static char zName[15]; - sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]", + tdsqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]", lockIdx-WAL_READ_LOCK(0)); return zName; } @@ -58379,7 +64369,7 @@ static const char *walLockName(int lockIdx){ static int walLockShared(Wal *pWal, int lockIdx){ int rc; if( pWal->exclusiveMode ) return SQLITE_OK; - rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, + rc = tdsqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, SQLITE_SHM_LOCK | SQLITE_SHM_SHARED); WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal, walLockName(lockIdx), rc ? "failed" : "ok")); @@ -58388,14 +64378,14 @@ static int walLockShared(Wal *pWal, int lockIdx){ } static void walUnlockShared(Wal *pWal, int lockIdx){ if( pWal->exclusiveMode ) return; - (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, + (void)tdsqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED); WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx))); } static int walLockExclusive(Wal *pWal, int lockIdx, int n){ int rc; if( pWal->exclusiveMode ) return SQLITE_OK; - rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, + rc = tdsqlite3OsShmLock(pWal->pDbFd, lockIdx, n, SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE); WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal, walLockName(lockIdx), n, rc ? "failed" : "ok")); @@ -58404,7 +64394,7 @@ static int walLockExclusive(Wal *pWal, int lockIdx, int n){ } static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){ if( pWal->exclusiveMode ) return; - (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, + (void)tdsqlite3OsShmLock(pWal->pDbFd, lockIdx, n, SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE); WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal, walLockName(lockIdx), n)); @@ -58424,48 +64414,51 @@ static int walNextHash(int iPriorHash){ return (iPriorHash+1)&(HASHTABLE_NSLOT-1); } +/* +** An instance of the WalHashLoc object is used to describe the location +** of a page hash table in the wal-index. This becomes the return value +** from walHashGet(). +*/ +typedef struct WalHashLoc WalHashLoc; +struct WalHashLoc { + volatile ht_slot *aHash; /* Start of the wal-index hash table */ + volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */ + u32 iZero; /* One less than the frame number of first indexed*/ +}; + /* ** Return pointers to the hash table and page number array stored on ** page iHash of the wal-index. The wal-index is broken into 32KB pages ** numbered starting from 0. ** -** Set output variable *paHash to point to the start of the hash table -** in the wal-index file. Set *piZero to one less than the frame +** Set output variable pLoc->aHash to point to the start of the hash table +** in the wal-index file. Set pLoc->iZero to one less than the frame ** number of the first frame indexed by this hash table. If a ** slot in the hash table is set to N, it refers to frame number -** (*piZero+N) in the log. +** (pLoc->iZero+N) in the log. ** -** Finally, set *paPgno so that *paPgno[1] is the page number of the -** first frame indexed by the hash table, frame (*piZero+1). +** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the +** first frame indexed by the hash table, frame (pLoc->iZero+1). */ static int walHashGet( Wal *pWal, /* WAL handle */ int iHash, /* Find the iHash'th table */ - volatile ht_slot **paHash, /* OUT: Pointer to hash index */ - volatile u32 **paPgno, /* OUT: Pointer to page number array */ - u32 *piZero /* OUT: Frame associated with *paPgno[0] */ + WalHashLoc *pLoc /* OUT: Hash table location */ ){ int rc; /* Return code */ - volatile u32 *aPgno; - rc = walIndexPage(pWal, iHash, &aPgno); + rc = walIndexPage(pWal, iHash, &pLoc->aPgno); assert( rc==SQLITE_OK || iHash>0 ); if( rc==SQLITE_OK ){ - u32 iZero; - volatile ht_slot *aHash; - - aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE]; + pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE]; if( iHash==0 ){ - aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)]; - iZero = 0; + pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)]; + pLoc->iZero = 0; }else{ - iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE; + pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE; } - - *paPgno = &aPgno[-1]; - *paHash = aHash; - *piZero = iZero; + pLoc->aPgno = &pLoc->aPgno[-1]; } return rc; } @@ -58511,12 +64504,11 @@ static u32 walFramePgno(Wal *pWal, u32 iFrame){ ** actually needed. */ static void walCleanupHash(Wal *pWal){ - volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */ - volatile u32 *aPgno = 0; /* Page number array for hash table */ - u32 iZero = 0; /* frame == (aHash[x]+iZero) */ + WalHashLoc sLoc; /* Hash table location */ int iLimit = 0; /* Zero values greater than this */ int nByte; /* Number of bytes to zero in aPgno[] */ int i; /* Used to iterate through aHash[] */ + int rc; /* Return code form walHashGet() */ assert( pWal->writeLock ); testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 ); @@ -58527,28 +64519,29 @@ static void walCleanupHash(Wal *pWal){ /* Obtain pointers to the hash-table and page-number array containing ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed - ** that the page said hash-table and array reside on is already mapped. + ** that the page said hash-table and array reside on is already mapped.(1) */ assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) ); assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] ); - walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero); + rc = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc); + if( NEVER(rc) ) return; /* Defense-in-depth, in case (1) above is wrong */ /* Zero all hash-table entries that correspond to frame numbers greater ** than pWal->hdr.mxFrame. */ - iLimit = pWal->hdr.mxFrame - iZero; + iLimit = pWal->hdr.mxFrame - sLoc.iZero; assert( iLimit>0 ); for(i=0; i<HASHTABLE_NSLOT; i++){ - if( aHash[i]>iLimit ){ - aHash[i] = 0; + if( sLoc.aHash[i]>iLimit ){ + sLoc.aHash[i] = 0; } } /* Zero the entries in the aPgno array that correspond to frames with ** frame numbers greater than pWal->hdr.mxFrame. */ - nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]); - memset((void *)&aPgno[iLimit+1], 0, nByte); + nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]); + memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte); #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT /* Verify that the every entry in the mapping region is still reachable @@ -58558,10 +64551,10 @@ static void walCleanupHash(Wal *pWal){ int j; /* Loop counter */ int iKey; /* Hash key */ for(j=1; j<=iLimit; j++){ - for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){ - if( aHash[iKey]==j ) break; + for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){ + if( sLoc.aHash[iKey]==j ) break; } - assert( aHash[iKey]==j ); + assert( sLoc.aHash[iKey]==j ); } } #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ @@ -58574,11 +64567,9 @@ static void walCleanupHash(Wal *pWal){ */ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ int rc; /* Return code */ - u32 iZero = 0; /* One less than frame number of aPgno[1] */ - volatile u32 *aPgno = 0; /* Page number array */ - volatile ht_slot *aHash = 0; /* Hash table */ + WalHashLoc sLoc; /* Wal-index hash table location */ - rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero); + rc = walHashGet(pWal, walFramePage(iFrame), &sLoc); /* Assuming the wal-index file was successfully mapped, populate the ** page number array and hash table entry. @@ -58588,15 +64579,16 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ int idx; /* Value to write to hash-table slot */ int nCollide; /* Number of hash collisions */ - idx = iFrame - iZero; + idx = iFrame - sLoc.iZero; assert( idx <= HASHTABLE_NSLOT/2 + 1 ); /* If this is the first entry to be added to this hash-table, zero the ** entire hash table and aPgno[] array before proceeding. */ if( idx==1 ){ - int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]); - memset((void*)&aPgno[1], 0, nByte); + int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT] + - (u8 *)&sLoc.aPgno[1]); + memset((void*)&sLoc.aPgno[1], 0, nByte); } /* If the entry in aPgno[] is already set, then the previous writer @@ -58605,18 +64597,18 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ ** Remove the remnants of that writers uncommitted transaction from ** the hash-table before writing any new entries. */ - if( aPgno[idx] ){ + if( sLoc.aPgno[idx] ){ walCleanupHash(pWal); - assert( !aPgno[idx] ); + assert( !sLoc.aPgno[idx] ); } /* Write the aPgno[] array entry and the hash-table slot. */ nCollide = idx; - for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){ + for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){ if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT; } - aPgno[idx] = iPage; - aHash[iKey] = (ht_slot)idx; + sLoc.aPgno[idx] = iPage; + sLoc.aHash[iKey] = (ht_slot)idx; #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT /* Verify that the number of entries in the hash table exactly equals @@ -58625,7 +64617,7 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ { int i; /* Loop counter */ int nEntry = 0; /* Number of entries in the hash table */ - for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; } + for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; } assert( nEntry==idx ); } @@ -58637,10 +64629,12 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ if( (idx&0x3ff)==0 ){ int i; /* Loop counter */ for(i=1; i<=idx; i++){ - for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){ - if( aHash[iKey]==i ) break; + for(iKey=walHash(sLoc.aPgno[i]); + sLoc.aHash[iKey]; + iKey=walNextHash(iKey)){ + if( sLoc.aHash[iKey]==i ) break; } - assert( aHash[iKey]==i ); + assert( sLoc.aHash[iKey]==i ); } } #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ @@ -58666,7 +64660,6 @@ static int walIndexRecover(Wal *pWal){ i64 nSize; /* Size of log file */ u32 aFrameCksum[2] = {0, 0}; int iLock; /* Lock offset to lock for checkpoint */ - int nLock; /* Number of locks to hold */ /* Obtain an exclusive lock on all byte in the locking range not already ** locked by the caller. The caller is guaranteed to have locked the @@ -58679,16 +64672,22 @@ static int walIndexRecover(Wal *pWal){ assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE ); assert( pWal->writeLock ); iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock; - nLock = SQLITE_SHM_NLOCK - iLock; - rc = walLockExclusive(pWal, iLock, nLock); + rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock); + if( rc==SQLITE_OK ){ + rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); + if( rc!=SQLITE_OK ){ + walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock); + } + } if( rc ){ return rc; } + WALTRACE(("WAL%p: recovery begin...\n", pWal)); memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); - rc = sqlite3OsFileSize(pWal->pWalFd, &nSize); + rc = tdsqlite3OsFileSize(pWal->pWalFd, &nSize); if( rc!=SQLITE_OK ){ goto recovery_error; } @@ -58706,7 +64705,7 @@ static int walIndexRecover(Wal *pWal){ int isValid; /* True if this frame is valid */ /* Read in the WAL header. */ - rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0); + rc = tdsqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0); if( rc!=SQLITE_OK ){ goto recovery_error; } @@ -58716,8 +64715,8 @@ static int walIndexRecover(Wal *pWal){ ** data. Similarly, if the 'magic' value is invalid, ignore the whole ** WAL file. */ - magic = sqlite3Get4byte(&aBuf[0]); - szPage = sqlite3Get4byte(&aBuf[8]); + magic = tdsqlite3Get4byte(&aBuf[0]); + szPage = tdsqlite3Get4byte(&aBuf[8]); if( (magic&0xFFFFFFFE)!=WAL_MAGIC || szPage&(szPage-1) || szPage>SQLITE_MAX_PAGE_SIZE @@ -58727,22 +64726,22 @@ static int walIndexRecover(Wal *pWal){ } pWal->hdr.bigEndCksum = (u8)(magic&0x00000001); pWal->szPage = szPage; - pWal->nCkpt = sqlite3Get4byte(&aBuf[12]); + pWal->nCkpt = tdsqlite3Get4byte(&aBuf[12]); memcpy(&pWal->hdr.aSalt, &aBuf[16], 8); /* Verify that the WAL header checksum is correct */ walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum ); - if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24]) - || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28]) + if( pWal->hdr.aFrameCksum[0]!=tdsqlite3Get4byte(&aBuf[24]) + || pWal->hdr.aFrameCksum[1]!=tdsqlite3Get4byte(&aBuf[28]) ){ goto finished; } /* Verify that the version number on the WAL format is one that ** are able to understand */ - version = sqlite3Get4byte(&aBuf[4]); + version = tdsqlite3Get4byte(&aBuf[4]); if( version!=WAL_MAX_VERSION ){ rc = SQLITE_CANTOPEN_BKPT; goto finished; @@ -58750,7 +64749,7 @@ static int walIndexRecover(Wal *pWal){ /* Malloc a buffer to read frames into. */ szFrame = szPage + WAL_FRAME_HDRSIZE; - aFrame = (u8 *)sqlite3_malloc64(szFrame); + aFrame = (u8 *)tdsqlite3_malloc64(szFrame); if( !aFrame ){ rc = SQLITE_NOMEM_BKPT; goto recovery_error; @@ -58765,7 +64764,7 @@ static int walIndexRecover(Wal *pWal){ /* Read and decode the next log frame. */ iFrame++; - rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); + rc = tdsqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); if( rc!=SQLITE_OK ) break; isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame); if( !isValid ) break; @@ -58784,7 +64783,7 @@ static int walIndexRecover(Wal *pWal){ } } - sqlite3_free(aFrame); + tdsqlite3_free(aFrame); } finished: @@ -58807,12 +64806,12 @@ finished: if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame; /* If more than one frame was recovered from the log file, report an - ** event via sqlite3_log(). This is to help with identifying performance + ** event via tdsqlite3_log(). This is to help with identifying performance ** problems caused by applications routinely shutting down without ** checkpointing the log file. */ if( pWal->hdr.nPage ){ - sqlite3_log(SQLITE_NOTICE_RECOVER_WAL, + tdsqlite3_log(SQLITE_NOTICE_RECOVER_WAL, "recovered %d frames from WAL file %s", pWal->hdr.mxFrame, pWal->zWalName ); @@ -58821,7 +64820,8 @@ finished: recovery_error: WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok")); - walUnlockExclusive(pWal, iLock, nLock); + walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock); + walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); return rc; } @@ -58829,14 +64829,15 @@ recovery_error: ** Close an open wal-index. */ static void walIndexClose(Wal *pWal, int isDelete){ - if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ + if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){ int i; for(i=0; i<pWal->nWiData; i++){ - sqlite3_free((void *)pWal->apWiData[i]); + tdsqlite3_free((void *)pWal->apWiData[i]); pWal->apWiData[i] = 0; } - }else{ - sqlite3OsShmUnmap(pWal->pDbFd, isDelete); + } + if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){ + tdsqlite3OsShmUnmap(pWal->pDbFd, isDelete); } } @@ -58855,9 +64856,9 @@ static void walIndexClose(Wal *pWal, int isDelete){ ** *ppWal is set to point to a new WAL handle. If an error occurs, ** an SQLite error code is returned and *ppWal is left unmodified. */ -SQLITE_PRIVATE int sqlite3WalOpen( - sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */ - sqlite3_file *pDbFd, /* The open database file */ +SQLITE_PRIVATE int tdsqlite3WalOpen( + tdsqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */ + tdsqlite3_file *pDbFd, /* The open database file */ const char *zWalName, /* Name of the WAL file */ int bNoShm, /* True to run in heap-memory mode */ i64 mxWalSize, /* Truncate WAL to this size on reset */ @@ -58888,13 +64889,13 @@ SQLITE_PRIVATE int sqlite3WalOpen( /* Allocate an instance of struct Wal to return. */ *ppWal = 0; - pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile); + pRet = (Wal*)tdsqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile); if( !pRet ){ return SQLITE_NOMEM_BKPT; } pRet->pVfs = pVfs; - pRet->pWalFd = (sqlite3_file *)&pRet[1]; + pRet->pWalFd = (tdsqlite3_file *)&pRet[1]; pRet->pDbFd = pDbFd; pRet->readLock = -1; pRet->mxWalSize = mxWalSize; @@ -58905,17 +64906,17 @@ SQLITE_PRIVATE int sqlite3WalOpen( /* Open file handle on the write-ahead log file. */ flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL); - rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags); + rc = tdsqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags); if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){ pRet->readOnly = WAL_RDONLY; } if( rc!=SQLITE_OK ){ walIndexClose(pRet, 0); - sqlite3OsClose(pRet->pWalFd); - sqlite3_free(pRet); + tdsqlite3OsClose(pRet->pWalFd); + tdsqlite3_free(pRet); }else{ - int iDC = sqlite3OsDeviceCharacteristics(pDbFd); + int iDC = tdsqlite3OsDeviceCharacteristics(pDbFd); if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; } if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){ pRet->padToSectorBoundary = 0; @@ -58929,7 +64930,7 @@ SQLITE_PRIVATE int sqlite3WalOpen( /* ** Change the size to which the WAL file is trucated on each reset. */ -SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){ +SQLITE_PRIVATE void tdsqlite3WalLimit(Wal *pWal, i64 iLimit){ if( pWal ) pWal->mxWalSize = iLimit; } @@ -59117,13 +65118,14 @@ static void walMergesort( ** Free an iterator allocated by walIteratorInit(). */ static void walIteratorFree(WalIterator *p){ - sqlite3_free(p); + tdsqlite3_free(p); } /* ** Construct a WalInterator object that can be used to loop over all -** pages in the WAL in ascending order. The caller must hold the checkpoint -** lock. +** pages in the WAL following frame nBackfill in ascending order. Frames +** nBackfill or earlier may be included - excluding them is an optimization +** only. The caller must hold the checkpoint lock. ** ** On success, make *pp point to the newly allocated WalInterator object ** return SQLITE_OK. Otherwise, return an error code. If this routine @@ -59132,11 +65134,11 @@ static void walIteratorFree(WalIterator *p){ ** The calling routine should invoke walIteratorFree() to destroy the ** WalIterator object when it has finished with it. */ -static int walIteratorInit(Wal *pWal, WalIterator **pp){ +static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){ WalIterator *p; /* Return value */ int nSegment; /* Number of segments to merge */ u32 iLast; /* Last frame in log */ - int nByte; /* Number of bytes to allocate */ + tdsqlite3_int64 nByte; /* Number of bytes to allocate */ int i; /* Iterator variable */ ht_slot *aTmp; /* Temp space used by merge-sort */ int rc = SQLITE_OK; /* Return Code */ @@ -59152,7 +65154,7 @@ static int walIteratorInit(Wal *pWal, WalIterator **pp){ nByte = sizeof(WalIterator) + (nSegment-1)*sizeof(struct WalSegment) + iLast*sizeof(ht_slot); - p = (WalIterator *)sqlite3_malloc64(nByte); + p = (WalIterator *)tdsqlite3_malloc64(nByte); if( !p ){ return SQLITE_NOMEM_BKPT; } @@ -59162,47 +65164,46 @@ static int walIteratorInit(Wal *pWal, WalIterator **pp){ /* Allocate temporary space used by the merge-sort routine. This block ** of memory will be freed before this function returns. */ - aTmp = (ht_slot *)sqlite3_malloc64( + aTmp = (ht_slot *)tdsqlite3_malloc64( sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast) ); if( !aTmp ){ rc = SQLITE_NOMEM_BKPT; } - for(i=0; rc==SQLITE_OK && i<nSegment; i++){ - volatile ht_slot *aHash; - u32 iZero; - volatile u32 *aPgno; + for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){ + WalHashLoc sLoc; - rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero); + rc = walHashGet(pWal, i, &sLoc); if( rc==SQLITE_OK ){ int j; /* Counter variable */ int nEntry; /* Number of entries in this segment */ ht_slot *aIndex; /* Sorted index for this segment */ - aPgno++; + sLoc.aPgno++; if( (i+1)==nSegment ){ - nEntry = (int)(iLast - iZero); + nEntry = (int)(iLast - sLoc.iZero); }else{ - nEntry = (int)((u32*)aHash - (u32*)aPgno); + nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno); } - aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero]; - iZero++; + aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero]; + sLoc.iZero++; for(j=0; j<nEntry; j++){ aIndex[j] = (ht_slot)j; } - walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry); - p->aSegment[i].iZero = iZero; + walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry); + p->aSegment[i].iZero = sLoc.iZero; p->aSegment[i].nEntry = nEntry; p->aSegment[i].aIndex = aIndex; - p->aSegment[i].aPgno = (u32 *)aPgno; + p->aSegment[i].aPgno = (u32 *)sLoc.aPgno; } } - sqlite3_free(aTmp); + tdsqlite3_free(aTmp); if( rc!=SQLITE_OK ){ walIteratorFree(p); + p = 0; } *pp = p; return rc; @@ -59251,7 +65252,7 @@ static int walPagesize(Wal *pWal){ ** ** The value of parameter salt1 is used as the aSalt[1] value in the ** new wal-index header. It should be passed a pseudo-random value (i.e. -** one obtained from sqlite3_randomness()). +** one obtained from tdsqlite3_randomness()). */ static void walRestartHdr(Wal *pWal, u32 salt1){ volatile WalCkptInfo *pInfo = walCkptInfo(pWal); @@ -59259,7 +65260,7 @@ static void walRestartHdr(Wal *pWal, u32 salt1){ u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */ pWal->nCkpt++; pWal->hdr.mxFrame = 0; - sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0])); + tdsqlite3Put4byte((u8*)&aSalt[0], 1 + tdsqlite3Get4byte((u8*)&aSalt[0])); memcpy(&pWal->hdr.aSalt[1], &salt1, 4); walIndexWriteHdr(pWal); pInfo->nBackfill = 0; @@ -59271,7 +65272,7 @@ static void walRestartHdr(Wal *pWal, u32 salt1){ /* ** Copy as much content as we can from the WAL back into the database file -** in response to an sqlite3_wal_checkpoint() request or the equivalent. +** in response to an tdsqlite3_wal_checkpoint() request or the equivalent. ** ** The amount of information copies from WAL to database might be limited ** by active readers. This routine will never overwrite a database page @@ -59302,6 +65303,7 @@ static void walRestartHdr(Wal *pWal, u32 salt1){ */ static int walCheckpoint( Wal *pWal, /* Wal connection */ + tdsqlite3 *db, /* Check for interrupts on this handle */ int eMode, /* One of PASSIVE, FULL or RESTART */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ @@ -59324,13 +65326,6 @@ static int walCheckpoint( pInfo = walCkptInfo(pWal); if( pInfo->nBackfill<pWal->hdr.mxFrame ){ - /* Allocate the iterator */ - rc = walIteratorInit(pWal, &pIter); - if( rc!=SQLITE_OK ){ - return rc; - } - assert( pIter ); - /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 ); @@ -59350,7 +65345,19 @@ static int walCheckpoint( ** not decreasing it. So assuming either that either the "old" or ** "new" version of the value is read, and not some arbitrary value ** that would never be written by a real client, things are still - ** safe. */ + ** safe. + ** + ** Astute readers have pointed out that the assumption stated in the + ** last sentence of the previous paragraph is not guaranteed to be + ** true for all conforming systems. However, the assumption is true + ** for all compilers and architectures in common use today (circa + ** 2019-11-27) and the alternatives are both slow and complex, and + ** so we will continue to go with the current design for now. If this + ** bothers you, or if you really are running on a system where aligned + ** 32-bit reads and writes are not atomic, then you can simply avoid + ** the use of WAL mode, or only use WAL mode together with + ** PRAGMA locking_mode=EXCLUSIVE and all will be well. + */ u32 y = pInfo->aReadMark[i]; if( mxSafeFrame>y ){ assert( y<=pWal->hdr.mxFrame ); @@ -59367,27 +65374,31 @@ static int walCheckpoint( } } - if( pInfo->nBackfill<mxSafeFrame + /* Allocate the iterator */ + if( pInfo->nBackfill<mxSafeFrame ){ + rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter); + assert( rc==SQLITE_OK || pIter==0 ); + } + + if( pIter && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK ){ - i64 nSize; /* Current size of database file */ u32 nBackfill = pInfo->nBackfill; pInfo->nBackfillAttempted = mxSafeFrame; /* Sync the WAL to disk */ - if( sync_flags ){ - rc = sqlite3OsSync(pWal->pWalFd, sync_flags); - } + rc = tdsqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags)); /* If the database may grow as a result of this checkpoint, hint ** about the eventual size of the db file to the VFS layer. */ if( rc==SQLITE_OK ){ i64 nReq = ((i64)mxPage * szPage); - rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); + i64 nSize; /* Current size of database file */ + rc = tdsqlite3OsFileSize(pWal->pDbFd, &nSize); if( rc==SQLITE_OK && nSize<nReq ){ - sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq); + tdsqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq); } } @@ -59396,16 +65407,20 @@ static int walCheckpoint( while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){ i64 iOffset; assert( walFramePgno(pWal, iFrame)==iDbpage ); + if( db->u1.isInterrupted ){ + rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; + break; + } if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){ continue; } iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE; /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */ - rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); + rc = tdsqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); if( rc!=SQLITE_OK ) break; iOffset = (iDbpage-1)*(i64)szPage; testcase( IS_BIG_INT(iOffset) ); - rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); + rc = tdsqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); if( rc!=SQLITE_OK ) break; } @@ -59414,12 +65429,16 @@ static int walCheckpoint( if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){ i64 szDb = pWal->hdr.nPage*(i64)szPage; testcase( IS_BIG_INT(szDb) ); - rc = sqlite3OsTruncate(pWal->pDbFd, szDb); - if( rc==SQLITE_OK && sync_flags ){ - rc = sqlite3OsSync(pWal->pDbFd, sync_flags); + rc = tdsqlite3OsTruncate(pWal->pDbFd, szDb); + if( rc==SQLITE_OK ){ + rc = tdsqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags)); } } if( rc==SQLITE_OK ){ + rc = tdsqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0); + if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; + } + if( rc==SQLITE_OK ){ pInfo->nBackfill = mxSafeFrame; } } @@ -59446,7 +65465,7 @@ static int walCheckpoint( rc = SQLITE_BUSY; }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){ u32 salt1; - sqlite3_randomness(4, &salt1); + tdsqlite3_randomness(4, &salt1); assert( pInfo->nBackfill==pWal->hdr.mxFrame ); rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1); if( rc==SQLITE_OK ){ @@ -59465,7 +65484,7 @@ static int walCheckpoint( ** file-system. To avoid this, update the wal-index header to ** indicate that the log file contains zero valid frames. */ walRestartHdr(pWal, salt1); - rc = sqlite3OsTruncate(pWal->pWalFd, 0); + rc = tdsqlite3OsTruncate(pWal->pWalFd, 0); } walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); } @@ -59484,22 +65503,23 @@ static int walCheckpoint( static void walLimitSize(Wal *pWal, i64 nMax){ i64 sz; int rx; - sqlite3BeginBenignMalloc(); - rx = sqlite3OsFileSize(pWal->pWalFd, &sz); + tdsqlite3BeginBenignMalloc(); + rx = tdsqlite3OsFileSize(pWal->pWalFd, &sz); if( rx==SQLITE_OK && (sz > nMax ) ){ - rx = sqlite3OsTruncate(pWal->pWalFd, nMax); + rx = tdsqlite3OsTruncate(pWal->pWalFd, nMax); } - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); if( rx ){ - sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName); + tdsqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName); } } /* ** Close a connection to a log file. */ -SQLITE_PRIVATE int sqlite3WalClose( +SQLITE_PRIVATE int tdsqlite3WalClose( Wal *pWal, /* Wal to close */ + tdsqlite3 *db, /* For interrupt flag */ int sync_flags, /* Flags to pass to OsSync() (or 0) */ int nBuf, u8 *zBuf /* Buffer of at least nBuf bytes */ @@ -59516,17 +65536,18 @@ SQLITE_PRIVATE int sqlite3WalClose( ** ** The EXCLUSIVE lock is not released before returning. */ - rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE); - if( rc==SQLITE_OK ){ + if( zBuf!=0 + && SQLITE_OK==(rc = tdsqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE)) + ){ if( pWal->exclusiveMode==WAL_NORMAL_MODE ){ pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; } - rc = sqlite3WalCheckpoint( - pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0 + rc = tdsqlite3WalCheckpoint(pWal, db, + SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0 ); if( rc==SQLITE_OK ){ int bPersist = -1; - sqlite3OsFileControlHint( + tdsqlite3OsFileControlHint( pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist ); if( bPersist!=1 ){ @@ -59547,15 +65568,15 @@ SQLITE_PRIVATE int sqlite3WalClose( } walIndexClose(pWal, isDelete); - sqlite3OsClose(pWal->pWalFd); + tdsqlite3OsClose(pWal->pWalFd); if( isDelete ){ - sqlite3BeginBenignMalloc(); - sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0); - sqlite3EndBenignMalloc(); + tdsqlite3BeginBenignMalloc(); + tdsqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0); + tdsqlite3EndBenignMalloc(); } WALTRACE(("WAL%p: closed\n", pWal)); - sqlite3_free((void *)pWal->apWiData); - sqlite3_free(pWal); + tdsqlite3_free((void *)pWal->apWiData); + tdsqlite3_free(pWal); } return rc; } @@ -59624,6 +65645,12 @@ static int walIndexTryHdr(Wal *pWal, int *pChanged){ } /* +** This is the value that walTryBeginRead returns when it needs to +** be retried. +*/ +#define WAL_RETRY (-1) + +/* ** Read the wal-index header from the wal-index and into pWal->hdr. ** If the wal-header appears to be corrupt, try to reconstruct the ** wal-index from the WAL before returning. @@ -59646,9 +65673,29 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){ assert( pChanged ); rc = walIndexPage(pWal, 0, &page0); if( rc!=SQLITE_OK ){ - return rc; - }; - assert( page0 || pWal->writeLock==0 ); + assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */ + if( rc==SQLITE_READONLY_CANTINIT ){ + /* The SQLITE_READONLY_CANTINIT return means that the shared-memory + ** was openable but is not writable, and this thread is unable to + ** confirm that another write-capable connection has the shared-memory + ** open, and hence the content of the shared-memory is unreliable, + ** since the shared-memory might be inconsistent with the WAL file + ** and there is no writer on hand to fix it. */ + assert( page0==0 ); + assert( pWal->writeLock==0 ); + assert( pWal->readOnly & WAL_SHM_RDONLY ); + pWal->bShmUnreliable = 1; + pWal->exclusiveMode = WAL_HEAPMEMORY_MODE; + *pChanged = 1; + }else{ + return rc; /* Any other non-OK return is just an error */ + } + }else{ + /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock + ** is zero, which prevents the SHM from growing */ + testcase( page0!=0 ); + } + assert( page0!=0 || pWal->writeLock==0 ); /* If the first page of the wal-index has been mapped, try to read the ** wal-index header immediately, without holding any lock. This usually @@ -59662,7 +65709,7 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){ */ assert( badHdr==0 || pWal->writeLock==0 ); if( badHdr ){ - if( pWal->readOnly & WAL_SHM_RDONLY ){ + if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){ if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){ walUnlockShared(pWal, WAL_WRITE_LOCK); rc = SQLITE_READONLY_RECOVERY; @@ -59692,15 +65739,193 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){ if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){ rc = SQLITE_CANTOPEN_BKPT; } + if( pWal->bShmUnreliable ){ + if( rc!=SQLITE_OK ){ + walIndexClose(pWal, 0); + pWal->bShmUnreliable = 0; + assert( pWal->nWiData>0 && pWal->apWiData[0]==0 ); + /* walIndexRecover() might have returned SHORT_READ if a concurrent + ** writer truncated the WAL out from under it. If that happens, it + ** indicates that a writer has fixed the SHM file for us, so retry */ + if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY; + } + pWal->exclusiveMode = WAL_NORMAL_MODE; + } return rc; } /* -** This is the value that walTryBeginRead returns when it needs to -** be retried. +** Open a transaction in a connection where the shared-memory is read-only +** and where we cannot verify that there is a separate write-capable connection +** on hand to keep the shared-memory up-to-date with the WAL file. +** +** This can happen, for example, when the shared-memory is implemented by +** memory-mapping a *-shm file, where a prior writer has shut down and +** left the *-shm file on disk, and now the present connection is trying +** to use that database but lacks write permission on the *-shm file. +** Other scenarios are also possible, depending on the VFS implementation. +** +** Precondition: +** +** The *-wal file has been read and an appropriate wal-index has been +** constructed in pWal->apWiData[] using heap memory instead of shared +** memory. +** +** If this function returns SQLITE_OK, then the read transaction has +** been successfully opened. In this case output variable (*pChanged) +** is set to true before returning if the caller should discard the +** contents of the page cache before proceeding. Or, if it returns +** WAL_RETRY, then the heap memory wal-index has been discarded and +** the caller should retry opening the read transaction from the +** beginning (including attempting to map the *-shm file). +** +** If an error occurs, an SQLite error code is returned. */ -#define WAL_RETRY (-1) +static int walBeginShmUnreliable(Wal *pWal, int *pChanged){ + i64 szWal; /* Size of wal file on disk in bytes */ + i64 iOffset; /* Current offset when reading wal file */ + u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */ + u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */ + int szFrame; /* Number of bytes in buffer aFrame[] */ + u8 *aData; /* Pointer to data part of aFrame buffer */ + volatile void *pDummy; /* Dummy argument for xShmMap */ + int rc; /* Return code */ + u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */ + + assert( pWal->bShmUnreliable ); + assert( pWal->readOnly & WAL_SHM_RDONLY ); + assert( pWal->nWiData>0 && pWal->apWiData[0] ); + + /* Take WAL_READ_LOCK(0). This has the effect of preventing any + ** writers from running a checkpoint, but does not stop them + ** from running recovery. */ + rc = walLockShared(pWal, WAL_READ_LOCK(0)); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_BUSY ) rc = WAL_RETRY; + goto begin_unreliable_shm_out; + } + pWal->readLock = 0; + + /* Check to see if a separate writer has attached to the shared-memory area, + ** thus making the shared-memory "reliable" again. Do this by invoking + ** the xShmMap() routine of the VFS and looking to see if the return + ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT. + ** + ** If the shared-memory is now "reliable" return WAL_RETRY, which will + ** cause the heap-memory WAL-index to be discarded and the actual + ** shared memory to be used in its place. + ** + ** This step is important because, even though this connection is holding + ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might + ** have already checkpointed the WAL file and, while the current + ** is active, wrap the WAL and start overwriting frames that this + ** process wants to use. + ** + ** Once tdsqlite3OsShmMap() has been called for an tdsqlite3_file and has + ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY + ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations, + ** even if some external agent does a "chmod" to make the shared-memory + ** writable by us, until tdsqlite3OsShmUnmap() has been called. + ** This is a requirement on the VFS implementation. + */ + rc = tdsqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy); + assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */ + if( rc!=SQLITE_READONLY_CANTINIT ){ + rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc); + goto begin_unreliable_shm_out; + } + + /* We reach this point only if the real shared-memory is still unreliable. + ** Assume the in-memory WAL-index substitute is correct and load it + ** into pWal->hdr. + */ + memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr)); + + /* Make sure some writer hasn't come in and changed the WAL file out + ** from under us, then disconnected, while we were not looking. + */ + rc = tdsqlite3OsFileSize(pWal->pWalFd, &szWal); + if( rc!=SQLITE_OK ){ + goto begin_unreliable_shm_out; + } + if( szWal<WAL_HDRSIZE ){ + /* If the wal file is too small to contain a wal-header and the + ** wal-index header has mxFrame==0, then it must be safe to proceed + ** reading the database file only. However, the page cache cannot + ** be trusted, as a read/write connection may have connected, written + ** the db, run a checkpoint, truncated the wal file and disconnected + ** since this client's last read transaction. */ + *pChanged = 1; + rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY); + goto begin_unreliable_shm_out; + } + + /* Check the salt keys at the start of the wal file still match. */ + rc = tdsqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0); + if( rc!=SQLITE_OK ){ + goto begin_unreliable_shm_out; + } + if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){ + /* Some writer has wrapped the WAL file while we were not looking. + ** Return WAL_RETRY which will cause the in-memory WAL-index to be + ** rebuilt. */ + rc = WAL_RETRY; + goto begin_unreliable_shm_out; + } + + /* Allocate a buffer to read frames into */ + szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE; + aFrame = (u8 *)tdsqlite3_malloc64(szFrame); + if( aFrame==0 ){ + rc = SQLITE_NOMEM_BKPT; + goto begin_unreliable_shm_out; + } + aData = &aFrame[WAL_FRAME_HDRSIZE]; + + /* Check to see if a complete transaction has been appended to the + ** wal file since the heap-memory wal-index was created. If so, the + ** heap-memory wal-index is discarded and WAL_RETRY returned to + ** the caller. */ + aSaveCksum[0] = pWal->hdr.aFrameCksum[0]; + aSaveCksum[1] = pWal->hdr.aFrameCksum[1]; + for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage); + iOffset+szFrame<=szWal; + iOffset+=szFrame + ){ + u32 pgno; /* Database page number for frame */ + u32 nTruncate; /* dbsize field from frame header */ + + /* Read and decode the next log frame. */ + rc = tdsqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); + if( rc!=SQLITE_OK ) break; + if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break; + + /* If nTruncate is non-zero, then a complete transaction has been + ** appended to this wal file. Set rc to WAL_RETRY and break out of + ** the loop. */ + if( nTruncate ){ + rc = WAL_RETRY; + break; + } + } + pWal->hdr.aFrameCksum[0] = aSaveCksum[0]; + pWal->hdr.aFrameCksum[1] = aSaveCksum[1]; + + begin_unreliable_shm_out: + tdsqlite3_free(aFrame); + if( rc!=SQLITE_OK ){ + int i; + for(i=0; i<pWal->nWiData; i++){ + tdsqlite3_free((void*)pWal->apWiData[i]); + pWal->apWiData[i] = 0; + } + pWal->bShmUnreliable = 0; + tdsqlite3WalEndReadTransaction(pWal); + *pChanged = 1; + } + return rc; +} /* ** Attempt to start a read transaction. This might fail due to a race or @@ -59716,7 +65941,7 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){ ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr() ** to make a copy of the wal-index header into pWal->hdr. If the ** wal-index header has changed, *pChanged is set to 1 (as an indication -** to the caller that the local paget cache is obsolete and needs to be +** to the caller that the local page cache is obsolete and needs to be ** flushed.) When useWal==1, the wal-index header is assumed to already ** be loaded and the pChanged parameter is unused. ** @@ -59762,6 +65987,9 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ assert( pWal->readLock<0 ); /* Not currently locked */ + /* useWal may only be set for read/write connections */ + assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 ); + /* Take steps to avoid spinning forever if there is a protocol error. ** ** Circumstances that cause a RETRY should only last for the briefest @@ -59772,8 +66000,8 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ ** during the few nanoseconds that it is holding the lock. In that case, ** it might take longer than normal for the lock to free. ** - ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few - ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this + ** After 5 RETRYs, we begin calling tdsqlite3OsSleep(). The first few + ** calls to tdsqlite3OsSleep() have a delay of 1 microsecond. Really this ** is more of a scheduler yield than an actual delay. But on the 10th ** an subsequent retries, the delays start becoming longer and longer, ** so that on the 100th (and last) RETRY we delay for 323 milliseconds. @@ -59786,11 +66014,14 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ return SQLITE_PROTOCOL; } if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39; - sqlite3OsSleep(pWal->pVfs, nDelay); + tdsqlite3OsSleep(pWal->pVfs, nDelay); } if( !useWal ){ - rc = walIndexReadHdr(pWal, pChanged); + assert( rc==SQLITE_OK ); + if( pWal->bShmUnreliable==0 ){ + rc = walIndexReadHdr(pWal, pChanged); + } if( rc==SQLITE_BUSY ){ /* If there is not a recovery running in another thread or process ** then convert BUSY errors to WAL_RETRY. If recovery is known to @@ -59819,13 +66050,17 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ if( rc!=SQLITE_OK ){ return rc; } + else if( pWal->bShmUnreliable ){ + return walBeginShmUnreliable(pWal, pChanged); + } } + assert( pWal->nWiData>0 ); + assert( pWal->apWiData[0]!=0 ); pInfo = walCkptInfo(pWal); - if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame + if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame #ifdef SQLITE_ENABLE_SNAPSHOT - && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0 - || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr))) + && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0) #endif ){ /* The WAL has been completely backfilled (or it is empty). @@ -59872,7 +66107,7 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ } #endif for(i=1; i<WAL_NREADER; i++){ - u32 thisMark = pInfo->aReadMark[i]; + u32 thisMark = AtomicLoad(pInfo->aReadMark+i); if( mxReadMark<=thisMark && thisMark<=mxFrame ){ assert( thisMark!=READMARK_NOT_USED ); mxReadMark = thisMark; @@ -59885,7 +66120,7 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ for(i=1; i<WAL_NREADER; i++){ rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1); if( rc==SQLITE_OK ){ - mxReadMark = pInfo->aReadMark[i] = mxFrame; + mxReadMark = AtomicStore(pInfo->aReadMark+i,mxFrame); mxI = i; walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); break; @@ -59896,7 +66131,7 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ } if( mxI==0 ){ assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 ); - return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK; + return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT; } rc = walLockShared(pWal, WAL_READ_LOCK(mxI)); @@ -59937,9 +66172,9 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ ** we can guarantee that the checkpointer that set nBackfill could not ** see any pages past pWal->hdr.mxFrame, this problem does not come up. */ - pWal->minFrame = pInfo->nBackfill+1; + pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1; walShmBarrier(pWal); - if( pInfo->aReadMark[mxI]!=mxReadMark + if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){ walUnlockShared(pWal, WAL_READ_LOCK(mxI)); @@ -59951,10 +66186,86 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ return rc; } +#ifdef SQLITE_ENABLE_SNAPSHOT +/* +** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted +** variable so that older snapshots can be accessed. To do this, loop +** through all wal frames from nBackfillAttempted to (nBackfill+1), +** comparing their content to the corresponding page with the database +** file, if any. Set nBackfillAttempted to the frame number of the +** first frame for which the wal file content matches the db file. +** +** This is only really safe if the file-system is such that any page +** writes made by earlier checkpointers were atomic operations, which +** is not always true. It is also possible that nBackfillAttempted +** may be left set to a value larger than expected, if a wal frame +** contains content that duplicate of an earlier version of the same +** page. +** +** SQLITE_OK is returned if successful, or an SQLite error code if an +** error occurs. It is not an error if nBackfillAttempted cannot be +** decreased at all. +*/ +SQLITE_PRIVATE int tdsqlite3WalSnapshotRecover(Wal *pWal){ + int rc; + + assert( pWal->readLock>=0 ); + rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); + if( rc==SQLITE_OK ){ + volatile WalCkptInfo *pInfo = walCkptInfo(pWal); + int szPage = (int)pWal->szPage; + i64 szDb; /* Size of db file in bytes */ + + rc = tdsqlite3OsFileSize(pWal->pDbFd, &szDb); + if( rc==SQLITE_OK ){ + void *pBuf1 = tdsqlite3_malloc(szPage); + void *pBuf2 = tdsqlite3_malloc(szPage); + if( pBuf1==0 || pBuf2==0 ){ + rc = SQLITE_NOMEM; + }else{ + u32 i = pInfo->nBackfillAttempted; + for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){ + WalHashLoc sLoc; /* Hash table location */ + u32 pgno; /* Page number in db file */ + i64 iDbOff; /* Offset of db file entry */ + i64 iWalOff; /* Offset of wal file entry */ + + rc = walHashGet(pWal, walFramePage(i), &sLoc); + if( rc!=SQLITE_OK ) break; + pgno = sLoc.aPgno[i-sLoc.iZero]; + iDbOff = (i64)(pgno-1) * szPage; + + if( iDbOff+szPage<=szDb ){ + iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE; + rc = tdsqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff); + + if( rc==SQLITE_OK ){ + rc = tdsqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff); + } + + if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){ + break; + } + } + + pInfo->nBackfillAttempted = i-1; + } + } + + tdsqlite3_free(pBuf1); + tdsqlite3_free(pBuf2); + } + walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); + } + + return rc; +} +#endif /* SQLITE_ENABLE_SNAPSHOT */ + /* ** Begin a read transaction on the database. ** -** This routine used to be called sqlite3OpenSnapshot() and with good reason: +** This routine used to be called tdsqlite3OpenSnapshot() and with good reason: ** it takes a snapshot of the state of the WAL and wal-index for the current ** instant in time. The current thread will continue to use this snapshot. ** Other threads might append new content to the WAL and wal-index but @@ -59962,10 +66273,10 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ ** ** If the database contents have changes since the previous read ** transaction, then *pChanged is set to 1 before returning. The -** Pager layer will use this to know that is cache is stale and +** Pager layer will use this to know that its cache is stale and ** needs to be flushed. */ -SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ +SQLITE_PRIVATE int tdsqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ int rc; /* Return code */ int cnt = 0; /* Number of TryBeginRead attempts */ @@ -60013,14 +66324,18 @@ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ ** has not yet set the pInfo->nBackfillAttempted variable to indicate ** its intent. To avoid the race condition this leads to, ensure that ** there is no checkpointer process by taking a shared CKPT lock - ** before checking pInfo->nBackfillAttempted. */ + ** before checking pInfo->nBackfillAttempted. + ** + ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing + ** this already? + */ rc = walLockShared(pWal, WAL_CKPT_LOCK); if( rc==SQLITE_OK ){ /* Check that the wal file has not been wrapped. Assuming that it has ** not, also check that no checkpointer has attempted to checkpoint any ** frames beyond pSnapshot->mxFrame. If either of these conditions are - ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr + ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr ** with *pSnapshot and set *pChanged as appropriate for opening the ** snapshot. */ if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt)) @@ -60030,16 +66345,17 @@ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr)); *pChanged = bChanged; }else{ - rc = SQLITE_BUSY_SNAPSHOT; + rc = SQLITE_ERROR_SNAPSHOT; } /* Release the shared CKPT lock obtained above. */ walUnlockShared(pWal, WAL_CKPT_LOCK); + pWal->minFrame = 1; } if( rc!=SQLITE_OK ){ - sqlite3WalEndReadTransaction(pWal); + tdsqlite3WalEndReadTransaction(pWal); } } } @@ -60051,8 +66367,8 @@ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ ** Finish with a read transaction. All this does is release the ** read-lock. */ -SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){ - sqlite3WalEndWriteTransaction(pWal); +SQLITE_PRIVATE void tdsqlite3WalEndReadTransaction(Wal *pWal){ + tdsqlite3WalEndWriteTransaction(pWal); if( pWal->readLock>=0 ){ walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); pWal->readLock = -1; @@ -60067,7 +66383,7 @@ SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){ ** Return SQLITE_OK if successful, or an error code if an error occurs. If an ** error does occur, the final value of *piRead is undefined. */ -SQLITE_PRIVATE int sqlite3WalFindFrame( +SQLITE_PRIVATE int tdsqlite3WalFindFrame( Wal *pWal, /* WAL handle */ Pgno pgno, /* Database page number to read data for */ u32 *piRead /* OUT: Frame number (or zero) */ @@ -60086,7 +66402,7 @@ SQLITE_PRIVATE int sqlite3WalFindFrame( ** then the WAL is ignored by the reader so return early, as if the ** WAL were empty. */ - if( iLast==0 || pWal->readLock==0 ){ + if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){ *piRead = 0; return SQLITE_OK; } @@ -60117,22 +66433,21 @@ SQLITE_PRIVATE int sqlite3WalFindFrame( ** table after the current read-transaction had started. */ iMinHash = walFramePage(pWal->minFrame); - for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){ - volatile ht_slot *aHash; /* Pointer to hash table */ - volatile u32 *aPgno; /* Pointer to array of page numbers */ - u32 iZero; /* Frame number corresponding to aPgno[0] */ + for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){ + WalHashLoc sLoc; /* Hash table location */ int iKey; /* Hash slot index */ int nCollide; /* Number of hash collisions remaining */ int rc; /* Error code */ - rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero); + rc = walHashGet(pWal, iHash, &sLoc); if( rc!=SQLITE_OK ){ return rc; } nCollide = HASHTABLE_NSLOT; - for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){ - u32 iFrame = aHash[iKey] + iZero; - if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){ + for(iKey=walHash(pgno); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){ + u32 iH = sLoc.aHash[iKey]; + u32 iFrame = iH + sLoc.iZero; + if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH]==pgno ){ assert( iFrame>iRead || CORRUPT_DB ); iRead = iFrame; } @@ -60140,6 +66455,7 @@ SQLITE_PRIVATE int sqlite3WalFindFrame( return SQLITE_CORRUPT_BKPT; } } + if( iRead ) break; } #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT @@ -60149,8 +66465,8 @@ SQLITE_PRIVATE int sqlite3WalFindFrame( { u32 iRead2 = 0; u32 iTest; - assert( pWal->minFrame>0 ); - for(iTest=iLast; iTest>=pWal->minFrame; iTest--){ + assert( pWal->bShmUnreliable || pWal->minFrame>0 ); + for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){ if( walFramePgno(pWal, iTest)==pgno ){ iRead2 = iTest; break; @@ -60169,7 +66485,7 @@ SQLITE_PRIVATE int sqlite3WalFindFrame( ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an ** error code otherwise. */ -SQLITE_PRIVATE int sqlite3WalReadFrame( +SQLITE_PRIVATE int tdsqlite3WalReadFrame( Wal *pWal, /* WAL handle */ u32 iRead, /* Frame to read */ int nOut, /* Size of buffer pOut in bytes */ @@ -60183,13 +66499,13 @@ SQLITE_PRIVATE int sqlite3WalReadFrame( testcase( sz>=65536 ); iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE; /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */ - return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset); + return tdsqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset); } /* ** Return the size of the database in pages (or zero, if unknown). */ -SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){ +SQLITE_PRIVATE Pgno tdsqlite3WalDbsize(Wal *pWal){ if( pWal && ALWAYS(pWal->readLock>=0) ){ return pWal->hdr.nPage; } @@ -60201,7 +66517,7 @@ SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){ ** This function starts a write transaction on the WAL. ** ** A read transaction must have already been started by a prior call -** to sqlite3WalBeginReadTransaction(). +** to tdsqlite3WalBeginReadTransaction(). ** ** If another thread or process has written into the database since ** the read transaction was started, then it is not possible for this @@ -60210,7 +66526,7 @@ SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){ ** ** There can only be a single writer active at a time. */ -SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){ +SQLITE_PRIVATE int tdsqlite3WalBeginWriteTransaction(Wal *pWal){ int rc; /* Cannot start a write transaction without first holding a read @@ -60248,7 +66564,7 @@ SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){ ** End a write transaction. The commit has already been done. This ** routine merely releases the lock. */ -SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){ +SQLITE_PRIVATE int tdsqlite3WalEndWriteTransaction(Wal *pWal){ if( pWal->writeLock ){ walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); pWal->writeLock = 0; @@ -60270,7 +66586,7 @@ SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){ ** Otherwise, if the callback function does not return an error, this ** function returns SQLITE_OK. */ -SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){ +SQLITE_PRIVATE int tdsqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){ int rc = SQLITE_OK; if( ALWAYS(pWal->writeLock) ){ Pgno iMax = pWal->hdr.mxFrame; @@ -60310,7 +66626,7 @@ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *p ** "rollback" the write position of the WAL handle back to the current ** point in the event of a savepoint rollback (via WalSavepointUndo()). */ -SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){ +SQLITE_PRIVATE void tdsqlite3WalSavepoint(Wal *pWal, u32 *aWalData){ assert( pWal->writeLock ); aWalData[0] = pWal->hdr.mxFrame; aWalData[1] = pWal->hdr.aFrameCksum[0]; @@ -60324,7 +66640,7 @@ SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){ ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated ** by a call to WalSavepoint(). */ -SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ +SQLITE_PRIVATE int tdsqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ int rc = SQLITE_OK; assert( pWal->writeLock ); @@ -60351,7 +66667,7 @@ SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ /* ** This function is called just before writing a set of frames to the log -** file (see sqlite3WalFrames()). It checks to see if, instead of appending +** file (see tdsqlite3WalFrames()). It checks to see if, instead of appending ** to the current log file, it is possible to overwrite the start of the ** existing log file with the new frames (i.e. "reset" the log). If so, ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left @@ -60370,7 +66686,7 @@ static int walRestartLog(Wal *pWal){ assert( pInfo->nBackfill==pWal->hdr.mxFrame ); if( pInfo->nBackfill>0 ){ u32 salt1; - sqlite3_randomness(4, &salt1); + tdsqlite3_randomness(4, &salt1); rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); if( rc==SQLITE_OK ){ /* If all readers are using WAL_READ_LOCK(0) (in other words if no @@ -60380,7 +66696,7 @@ static int walRestartLog(Wal *pWal){ ** ** In theory it would be Ok to update the cache of the header only ** at this point. But updating the actual wal-index header is also - ** safe and means there is no special case for sqlite3WalUndo() + ** safe and means there is no special case for tdsqlite3WalUndo() ** to handle if this transaction is rolled back. */ walRestartHdr(pWal, salt1); walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); @@ -60405,13 +66721,13 @@ static int walRestartLog(Wal *pWal){ /* ** Information about the current state of the WAL file and where -** the next fsync should occur - passed from sqlite3WalFrames() into +** the next fsync should occur - passed from tdsqlite3WalFrames() into ** walWriteToLog(). */ typedef struct WalWriter { Wal *pWal; /* The complete WAL information */ - sqlite3_file *pFd; /* The WAL file to which we write */ - sqlite3_int64 iSyncPoint; /* Fsync at this offset */ + tdsqlite3_file *pFd; /* The WAL file to which we write */ + tdsqlite3_int64 iSyncPoint; /* Fsync at this offset */ int syncFlags; /* Flags for the fsync */ int szPage; /* Size of one page */ } WalWriter; @@ -60428,21 +66744,21 @@ static int walWriteToLog( WalWriter *p, /* WAL to write to */ void *pContent, /* Content to be written */ int iAmt, /* Number of bytes to write */ - sqlite3_int64 iOffset /* Start writing at this offset */ + tdsqlite3_int64 iOffset /* Start writing at this offset */ ){ int rc; if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){ int iFirstAmt = (int)(p->iSyncPoint - iOffset); - rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset); + rc = tdsqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset); if( rc ) return rc; iOffset += iFirstAmt; iAmt -= iFirstAmt; pContent = (void*)(iFirstAmt + (char*)pContent); - assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) ); - rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK); + assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 ); + rc = tdsqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags)); if( iAmt==0 || rc ) return rc; } - rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset); + rc = tdsqlite3OsWrite(p->pFd, pContent, iAmt, iOffset); return rc; } @@ -60453,13 +66769,13 @@ static int walWriteOneFrame( WalWriter *p, /* Where to write the frame */ PgHdr *pPage, /* The page of the frame to be written */ int nTruncate, /* The commit flag. Usually 0. >0 for commit */ - sqlite3_int64 iOffset /* Byte offset at which to write */ + tdsqlite3_int64 iOffset /* Byte offset at which to write */ ){ int rc; /* Result code from subfunctions */ void *pData; /* Data actually written */ u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */ #if defined(SQLITE_HAS_CODEC) - if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT; + if( (pData = tdsqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT; #else pData = pPage->pData; #endif @@ -60487,7 +66803,7 @@ static int walRewriteChecksums(Wal *pWal, u32 iLast){ u32 iRead; /* Next frame to read from wal file */ i64 iCksumOff; - aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE); + aBuf = tdsqlite3_malloc(szPage + WAL_FRAME_HDRSIZE); if( aBuf==0 ) return SQLITE_NOMEM_BKPT; /* Find the checksum values to use as input for the recalculating the @@ -60501,34 +66817,34 @@ static int walRewriteChecksums(Wal *pWal, u32 iLast){ }else{ iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16; } - rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff); - pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf); - pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]); + rc = tdsqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff); + pWal->hdr.aFrameCksum[0] = tdsqlite3Get4byte(aBuf); + pWal->hdr.aFrameCksum[1] = tdsqlite3Get4byte(&aBuf[sizeof(u32)]); iRead = pWal->iReCksum; pWal->iReCksum = 0; for(; rc==SQLITE_OK && iRead<=iLast; iRead++){ i64 iOff = walFrameOffset(iRead, szPage); - rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff); + rc = tdsqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff); if( rc==SQLITE_OK ){ u32 iPgno, nDbSize; - iPgno = sqlite3Get4byte(aBuf); - nDbSize = sqlite3Get4byte(&aBuf[4]); + iPgno = tdsqlite3Get4byte(aBuf); + nDbSize = tdsqlite3Get4byte(&aBuf[4]); walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame); - rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff); + rc = tdsqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff); } } - sqlite3_free(aBuf); + tdsqlite3_free(aBuf); return rc; } /* ** Write a set of frames to the log. The caller must hold the write-lock -** on the log file (obtained using sqlite3WalBeginWriteTransaction()). +** on the log file (obtained using tdsqlite3WalBeginWriteTransaction()). */ -SQLITE_PRIVATE int sqlite3WalFrames( +SQLITE_PRIVATE int tdsqlite3WalFrames( Wal *pWal, /* Wal handle to write to */ int szPage, /* Database page-size in bytes */ PgHdr *pList, /* List of dirty pages to write */ @@ -60582,15 +66898,15 @@ SQLITE_PRIVATE int sqlite3WalFrames( u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */ u32 aCksum[2]; /* Checksum for wal-header */ - sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN)); - sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION); - sqlite3Put4byte(&aWalHdr[8], szPage); - sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt); - if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt); + tdsqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN)); + tdsqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION); + tdsqlite3Put4byte(&aWalHdr[8], szPage); + tdsqlite3Put4byte(&aWalHdr[12], pWal->nCkpt); + if( pWal->nCkpt==0 ) tdsqlite3_randomness(8, pWal->hdr.aSalt); memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8); walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum); - sqlite3Put4byte(&aWalHdr[24], aCksum[0]); - sqlite3Put4byte(&aWalHdr[28], aCksum[1]); + tdsqlite3Put4byte(&aWalHdr[24], aCksum[0]); + tdsqlite3Put4byte(&aWalHdr[28], aCksum[1]); pWal->szPage = szPage; pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN; @@ -60598,7 +66914,7 @@ SQLITE_PRIVATE int sqlite3WalFrames( pWal->hdr.aFrameCksum[1] = aCksum[1]; pWal->truncateOnCommit = 1; - rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0); + rc = tdsqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0); WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok")); if( rc!=SQLITE_OK ){ return rc; @@ -60609,10 +66925,10 @@ SQLITE_PRIVATE int sqlite3WalFrames( ** an out-of-order write following a WAL restart could result in ** database corruption. See the ticket: ** - ** http://localhost:591/sqlite/info/ff5be73dee + ** https://sqlite.org/src/info/ff5be73dee */ - if( pWal->syncHeader && sync_flags ){ - rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK); + if( pWal->syncHeader ){ + rc = tdsqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags)); if( rc ) return rc; } } @@ -60637,7 +66953,7 @@ SQLITE_PRIVATE int sqlite3WalFrames( ** checksums must be recomputed when the transaction is committed. */ if( iFirst && (p->pDirty || isCommit==0) ){ u32 iWrite = 0; - VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite); + VVA_ONLY(rc =) tdsqlite3WalFindFrame(pWal, p->pgno, &iWrite); assert( rc==SQLITE_OK || iWrite==0 ); if( iWrite>=iFirst ){ i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE; @@ -60646,11 +66962,11 @@ SQLITE_PRIVATE int sqlite3WalFrames( pWal->iReCksum = iWrite; } #if defined(SQLITE_HAS_CODEC) - if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM; + if( (pData = tdsqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM; #else pData = p->pData; #endif - rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff); + rc = tdsqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff); if( rc ) return rc; p->flags &= ~PGHDR_WAL_APPEND; continue; @@ -60687,10 +67003,10 @@ SQLITE_PRIVATE int sqlite3WalFrames( ** sector boundary is synced; the part of the last frame that extends ** past the sector boundary is written after the sync. */ - if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){ + if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){ int bSync = 1; if( pWal->padToSectorBoundary ){ - int sectorSize = sqlite3SectorSize(pWal->pWalFd); + int sectorSize = tdsqlite3SectorSize(pWal->pWalFd); w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize; bSync = (w.iSyncPoint==iOffset); testcase( bSync ); @@ -60699,11 +67015,12 @@ SQLITE_PRIVATE int sqlite3WalFrames( if( rc ) return rc; iOffset += szFrame; nExtra++; + assert( pLast!=0 ); } } if( bSync ){ assert( rc==SQLITE_OK ); - rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK); + rc = tdsqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags)); } } @@ -60731,6 +67048,7 @@ SQLITE_PRIVATE int sqlite3WalFrames( iFrame++; rc = walIndexAppend(pWal, iFrame, p->pgno); } + assert( pLast!=0 || nExtra==0 ); while( rc==SQLITE_OK && nExtra>0 ){ iFrame++; nExtra--; @@ -60759,7 +67077,7 @@ SQLITE_PRIVATE int sqlite3WalFrames( } /* -** This routine is called to implement sqlite3_wal_checkpoint() and +** This routine is called to implement tdsqlite3_wal_checkpoint() and ** related interfaces. ** ** Obtain a CHECKPOINT lock and then backfill as much information as @@ -60768,8 +67086,9 @@ SQLITE_PRIVATE int sqlite3WalFrames( ** If parameter xBusy is not NULL, it is a pointer to a busy-handler ** callback. In this case this function runs a blocking checkpoint. */ -SQLITE_PRIVATE int sqlite3WalCheckpoint( +SQLITE_PRIVATE int tdsqlite3WalCheckpoint( Wal *pWal, /* Wal connection */ + tdsqlite3 *db, /* Check this handle's interrupt flag */ int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */ int (*xBusy)(void*), /* Function to call when busy */ void *pBusyArg, /* Context argument for xBusyHandler */ @@ -60834,7 +67153,7 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint( if( rc==SQLITE_OK ){ rc = walIndexReadHdr(pWal, &isChanged); if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){ - sqlite3OsUnfetch(pWal->pDbFd, 0, 0); + tdsqlite3OsUnfetch(pWal->pDbFd, 0, 0); } } @@ -60844,7 +67163,7 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint( if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){ rc = SQLITE_CORRUPT_BKPT; }else{ - rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf); + rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf); } /* If no error occurred, set the output variables. */ @@ -60865,19 +67184,19 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint( } /* Release the locks. */ - sqlite3WalEndWriteTransaction(pWal); + tdsqlite3WalEndWriteTransaction(pWal); walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); pWal->ckptLock = 0; WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok")); return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc); } -/* Return the value to pass to a sqlite3_wal_hook callback, the +/* Return the value to pass to a tdsqlite3_wal_hook callback, the ** number of frames in the WAL at the point of the last commit since -** sqlite3WalCallback() was called. If no commits have occurred since +** tdsqlite3WalCallback() was called. If no commits have occurred since ** the last call, then return 0. */ -SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){ +SQLITE_PRIVATE int tdsqlite3WalCallback(Wal *pWal){ u32 ret = 0; if( pWal ){ ret = pWal->iCallback; @@ -60910,7 +67229,7 @@ SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){ ** should acquire the database exclusive lock prior to invoking ** the op==1 case. */ -SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){ +SQLITE_PRIVATE int tdsqlite3WalExclusiveMode(Wal *pWal, int op){ int rc; assert( pWal->writeLock==0 ); assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 ); @@ -60925,24 +67244,24 @@ SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){ assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) ); if( op==0 ){ - if( pWal->exclusiveMode ){ - pWal->exclusiveMode = 0; + if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){ + pWal->exclusiveMode = WAL_NORMAL_MODE; if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){ - pWal->exclusiveMode = 1; + pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; } - rc = pWal->exclusiveMode==0; + rc = pWal->exclusiveMode==WAL_NORMAL_MODE; }else{ /* Already in locking_mode=NORMAL */ rc = 0; } }else if( op>0 ){ - assert( pWal->exclusiveMode==0 ); + assert( pWal->exclusiveMode==WAL_NORMAL_MODE ); assert( pWal->readLock>=0 ); walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); - pWal->exclusiveMode = 1; + pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; rc = 1; }else{ - rc = pWal->exclusiveMode==0; + rc = pWal->exclusiveMode==WAL_NORMAL_MODE; } return rc; } @@ -60952,7 +67271,7 @@ SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){ ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the ** WAL module is using shared-memory, return false. */ -SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){ +SQLITE_PRIVATE int tdsqlite3WalHeapMemory(Wal *pWal){ return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ); } @@ -60961,18 +67280,23 @@ SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){ ** every other subsystem, so the WAL module can put whatever it needs ** in the object. */ -SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){ +SQLITE_PRIVATE int tdsqlite3WalSnapshotGet(Wal *pWal, tdsqlite3_snapshot **ppSnapshot){ int rc = SQLITE_OK; WalIndexHdr *pRet; + static const u32 aZero[4] = { 0, 0, 0, 0 }; assert( pWal->readLock>=0 && pWal->writeLock==0 ); - pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr)); + if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){ + *ppSnapshot = 0; + return SQLITE_ERROR; + } + pRet = (WalIndexHdr*)tdsqlite3_malloc(sizeof(WalIndexHdr)); if( pRet==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr)); - *ppSnapshot = (sqlite3_snapshot*)pRet; + *ppSnapshot = (tdsqlite3_snapshot*)pRet; } return rc; @@ -60980,7 +67304,7 @@ SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapsho /* Try to open on pSnapshot when the next read-transaction starts */ -SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){ +SQLITE_PRIVATE void tdsqlite3WalSnapshotOpen(Wal *pWal, tdsqlite3_snapshot *pSnapshot){ pWal->pSnapshot = (WalIndexHdr*)pSnapshot; } @@ -60988,7 +67312,7 @@ SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapsho ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if ** p1 is older than p2 and zero if p1 and p2 are the same snapshot. */ -SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){ +SQLITE_API int tdsqlite3_snapshot_cmp(tdsqlite3_snapshot *p1, tdsqlite3_snapshot *p2){ WalIndexHdr *pHdr1 = (WalIndexHdr*)p1; WalIndexHdr *pHdr2 = (WalIndexHdr*)p2; @@ -61000,6 +67324,43 @@ SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){ if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1; return 0; } + +/* +** The caller currently has a read transaction open on the database. +** This function takes a SHARED lock on the CHECKPOINTER slot and then +** checks if the snapshot passed as the second argument is still +** available. If so, SQLITE_OK is returned. +** +** If the snapshot is not available, SQLITE_ERROR is returned. Or, if +** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error +** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER +** lock is released before returning. +*/ +SQLITE_PRIVATE int tdsqlite3WalSnapshotCheck(Wal *pWal, tdsqlite3_snapshot *pSnapshot){ + int rc; + rc = walLockShared(pWal, WAL_CKPT_LOCK); + if( rc==SQLITE_OK ){ + WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot; + if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt)) + || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted + ){ + rc = SQLITE_ERROR_SNAPSHOT; + walUnlockShared(pWal, WAL_CKPT_LOCK); + } + } + return rc; +} + +/* +** Release a lock obtained by an earlier successful call to +** tdsqlite3WalSnapshotCheck(). +*/ +SQLITE_PRIVATE void tdsqlite3WalSnapshotUnlock(Wal *pWal){ + assert( pWal ); + walUnlockShared(pWal, WAL_CKPT_LOCK); +} + + #endif /* SQLITE_ENABLE_SNAPSHOT */ #ifdef SQLITE_ENABLE_ZIPVFS @@ -61008,15 +67369,15 @@ SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){ ** read-lock. This function returns the database page-size if it is known, ** or zero if it is not (or if pWal is NULL). */ -SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){ +SQLITE_PRIVATE int tdsqlite3WalFramesize(Wal *pWal){ assert( pWal==0 || pWal->readLock>=0 ); return (pWal ? pWal->szPage : 0); } #endif -/* Return the sqlite3_file object for the WAL file +/* Return the tdsqlite3_file object for the WAL file */ -SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){ +SQLITE_PRIVATE tdsqlite3_file *tdsqlite3WalFile(Wal *pWal){ return pWal->pWalFd; } @@ -61052,10 +67413,10 @@ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){ */ static void lockBtreeMutex(Btree *p){ assert( p->locked==0 ); - assert( sqlite3_mutex_notheld(p->pBt->mutex) ); - assert( sqlite3_mutex_held(p->db->mutex) ); + assert( tdsqlite3_mutex_notheld(p->pBt->mutex) ); + assert( tdsqlite3_mutex_held(p->db->mutex) ); - sqlite3_mutex_enter(p->pBt->mutex); + tdsqlite3_mutex_enter(p->pBt->mutex); p->pBt->db = p->db; p->locked = 1; } @@ -61067,11 +67428,11 @@ static void lockBtreeMutex(Btree *p){ static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){ BtShared *pBt = p->pBt; assert( p->locked==1 ); - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( sqlite3_mutex_held(p->db->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(p->db->mutex) ); assert( p->db==pBt->db ); - sqlite3_mutex_leave(pBt->mutex); + tdsqlite3_mutex_leave(pBt->mutex); p->locked = 0; } @@ -61094,7 +67455,7 @@ static void SQLITE_NOINLINE btreeLockCarefully(Btree *p); ** for the lock to become available on p, then relock all of the ** subsequent Btrees that desire a lock. */ -SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ +SQLITE_PRIVATE void tdsqlite3BtreeEnter(Btree *p){ /* Some basic sanity checking on the Btree. The list of Btrees ** connected by pNext and pPrev should be in sorted order by ** Btree.pBt value. All elements of the list should belong to @@ -61110,7 +67471,7 @@ SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ assert( p->sharable || p->wantToLock==0 ); /* We should already hold a lock on the database connection */ - assert( sqlite3_mutex_held(p->db->mutex) ); + assert( tdsqlite3_mutex_held(p->db->mutex) ); /* Unless the database is sharable and unlocked, then BtShared.db ** should already be set correctly. */ @@ -61122,10 +67483,10 @@ SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ btreeLockCarefully(p); } -/* This is a helper function for sqlite3BtreeLock(). By moving -** complex, but seldom used logic, out of sqlite3BtreeLock() and +/* This is a helper function for tdsqlite3BtreeLock(). By moving +** complex, but seldom used logic, out of tdsqlite3BtreeLock() and ** into this routine, we avoid unnecessary stack pointer changes -** and thus help the sqlite3BtreeLock() routine to run much faster +** and thus help the tdsqlite3BtreeLock() routine to run much faster ** in the common case. */ static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){ @@ -61135,7 +67496,7 @@ static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){ ** want without having to go through the ascending lock ** procedure that follows. Just be sure not to block. */ - if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ + if( tdsqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ p->pBt->db = p->db; p->locked = 1; return; @@ -61166,8 +67527,8 @@ static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){ /* ** Exit the recursive mutex on a Btree. */ -SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){ - assert( sqlite3_mutex_held(p->db->mutex) ); +SQLITE_PRIVATE void tdsqlite3BtreeLeave(Btree *p){ + assert( tdsqlite3_mutex_held(p->db->mutex) ); if( p->sharable ){ assert( p->wantToLock>0 ); p->wantToLock--; @@ -61184,11 +67545,11 @@ SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){ ** ** This routine is used only from within assert() statements. */ -SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeHoldsMutex(Btree *p){ assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); - assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); - assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); + assert( p->sharable==0 || p->locked==0 || tdsqlite3_mutex_held(p->pBt->mutex) ); + assert( p->sharable==0 || p->locked==0 || tdsqlite3_mutex_held(p->db->mutex) ); return (p->sharable==0 || p->locked); } @@ -61209,24 +67570,35 @@ SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){ ** two or more btrees in common both try to lock all their btrees ** at the same instant. */ -SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ +static void SQLITE_NOINLINE btreeEnterAll(tdsqlite3 *db){ int i; + int skipOk = 1; Btree *p; - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nDb; i++){ p = db->aDb[i].pBt; - if( p ) sqlite3BtreeEnter(p); + if( p && p->sharable ){ + tdsqlite3BtreeEnter(p); + skipOk = 0; + } } + db->noSharedCache = skipOk; } -SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3BtreeEnterAll(tdsqlite3 *db){ + if( db->noSharedCache==0 ) btreeEnterAll(db); +} +static void SQLITE_NOINLINE btreeLeaveAll(tdsqlite3 *db){ int i; Btree *p; - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nDb; i++){ p = db->aDb[i].pBt; - if( p ) sqlite3BtreeLeave(p); + if( p ) tdsqlite3BtreeLeave(p); } } +SQLITE_PRIVATE void tdsqlite3BtreeLeaveAll(tdsqlite3 *db){ + if( db->noSharedCache==0 ) btreeLeaveAll(db); +} #ifndef NDEBUG /* @@ -61235,16 +67607,16 @@ SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){ ** ** This routine is used inside assert() statements only. */ -SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ +SQLITE_PRIVATE int tdsqlite3BtreeHoldsAllMutexes(tdsqlite3 *db){ int i; - if( !sqlite3_mutex_held(db->mutex) ){ + if( !tdsqlite3_mutex_held(db->mutex) ){ return 0; } for(i=0; i<db->nDb; i++){ Btree *p; p = db->aDb[i].pBt; if( p && p->sharable && - (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ + (p->wantToLock==0 || !tdsqlite3_mutex_held(p->pBt->mutex)) ){ return 0; } } @@ -61262,14 +67634,14 @@ SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. ** ** If pSchema is not NULL, then iDb is computed from pSchema and -** db using sqlite3SchemaToIndex(). +** db using tdsqlite3SchemaToIndex(). */ -SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){ +SQLITE_PRIVATE int tdsqlite3SchemaMutexHeld(tdsqlite3 *db, int iDb, Schema *pSchema){ Btree *p; assert( db!=0 ); - if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); + if( pSchema ) iDb = tdsqlite3SchemaToIndex(db, pSchema); assert( iDb>=0 && iDb<db->nDb ); - if( !sqlite3_mutex_held(db->mutex) ) return 0; + if( !tdsqlite3_mutex_held(db->mutex) ) return 0; if( iDb==1 ) return 1; p = db->aDb[iDb].pBt; assert( p!=0 ); @@ -61288,10 +67660,10 @@ SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema) ** the ones below, are no-ops and are null #defines in btree.h. */ -SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ +SQLITE_PRIVATE void tdsqlite3BtreeEnter(Btree *p){ p->pBt->db = p->db; } -SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3BtreeEnterAll(tdsqlite3 *db){ int i; for(i=0; i<db->nDb; i++){ Btree *p = db->aDb[i].pBt; @@ -61310,12 +67682,12 @@ SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not ** the build is threadsafe. Leave() is only required by threadsafe builds. */ -SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){ - sqlite3BtreeEnter(pCur->pBtree); +SQLITE_PRIVATE void tdsqlite3BtreeEnterCursor(BtCursor *pCur){ + tdsqlite3BtreeEnter(pCur->pBtree); } # if SQLITE_THREADSAFE -SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){ - sqlite3BtreeLeave(pCur->pBtree); +SQLITE_PRIVATE void tdsqlite3BtreeLeaveCursor(BtCursor *pCur){ + tdsqlite3BtreeLeave(pCur->pBtree); } # endif #endif /* ifndef SQLITE_OMIT_INCRBLOB */ @@ -61352,8 +67724,8 @@ static const char zMagicHeader[] = SQLITE_FILE_HEADER; ** macro. */ #if 0 -int sqlite3BtreeTrace=1; /* True to enable tracing */ -# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} +int tdsqlite3BtreeTrace=1; /* True to enable tracing */ +# define TRACE(X) if(tdsqlite3BtreeTrace){printf X;fflush(stdout);} #else # define TRACE(X) #endif @@ -61398,9 +67770,9 @@ int sqlite3BtreeTrace=1; /* True to enable tracing */ ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. */ #ifdef SQLITE_TEST -SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; +SQLITE_PRIVATE BtShared *SQLITE_WSD tdsqlite3SharedCacheList = 0; #else -static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; +static BtShared *SQLITE_WSD tdsqlite3SharedCacheList = 0; #endif #endif /* SQLITE_OMIT_SHARED_CACHE */ @@ -61410,10 +67782,10 @@ static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; ** ** This routine has no effect on existing database connections. ** The shared cache setting effects only future calls to -** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). +** tdsqlite3_open(), tdsqlite3_open16(), or tdsqlite3_open_v2(). */ -SQLITE_API int sqlite3_enable_shared_cache(int enable){ - sqlite3GlobalConfig.sharedCacheEnabled = enable; +SQLITE_API int tdsqlite3_enable_shared_cache(int enable){ + tdsqlite3GlobalConfig.sharedCacheEnabled = enable; return SQLITE_OK; } #endif @@ -61438,6 +67810,34 @@ SQLITE_API int sqlite3_enable_shared_cache(int enable){ #define hasReadConflicts(a, b) 0 #endif +/* +** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single +** (MemPage*) as an argument. The (MemPage*) must not be NULL. +** +** If SQLITE_DEBUG is not defined, then this macro is equivalent to +** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message +** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented +** with the page number and filename associated with the (MemPage*). +*/ +#ifdef SQLITE_DEBUG +int corruptPageError(int lineno, MemPage *p){ + char *zMsg; + tdsqlite3BeginBenignMalloc(); + zMsg = tdsqlite3_mprintf("database corruption page %d of %s", + (int)p->pgno, tdsqlite3PagerFilename(p->pBt->pPager, 0) + ); + tdsqlite3EndBenignMalloc(); + if( zMsg ){ + tdsqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg); + } + tdsqlite3_free(zMsg); + return SQLITE_CORRUPT_BKPT; +} +# define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage) +#else +# define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno) +#endif + #ifndef SQLITE_OMIT_SHARED_CACHE #ifdef SQLITE_DEBUG @@ -61478,7 +67878,7 @@ static int hasSharedCacheTableLock( ** Return true immediately. */ if( (pBtree->sharable==0) - || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted)) + || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit)) ){ return 1; } @@ -61555,7 +67955,7 @@ static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ for(p=pBtree->pBt->pCursor; p; p=p->pNext){ if( p->pgnoRoot==iRoot && p->pBtree!=pBtree - && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted) + && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit) ){ return 1; } @@ -61574,10 +67974,10 @@ static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ BtShared *pBt = p->pBt; BtLock *pIter; - assert( sqlite3BtreeHoldsMutex(p) ); + assert( tdsqlite3BtreeHoldsMutex(p) ); assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); assert( p->db!=0 ); - assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 ); + assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 ); /* If requesting a write-lock, then the Btree must have an open write ** transaction on this file. And, obviously, for this to be so there @@ -61595,7 +67995,7 @@ static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ ** requested lock may not be obtained. */ if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ - sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); + tdsqlite3ConnectionBlocked(p->db, pBt->pWriter->db); return SQLITE_LOCKED_SHAREDCACHE; } @@ -61612,7 +68012,7 @@ static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ - sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); + tdsqlite3ConnectionBlocked(p->db, pIter->pBtree->db); if( eLock==WRITE_LOCK ){ assert( p==pBt->pWriter ); pBt->btsFlags |= BTS_PENDING; @@ -61647,7 +68047,7 @@ static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ BtLock *pLock = 0; BtLock *pIter; - assert( sqlite3BtreeHoldsMutex(p) ); + assert( tdsqlite3BtreeHoldsMutex(p) ); assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); assert( p->db!=0 ); @@ -61655,7 +68055,7 @@ static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ ** obtain a read-lock using this function. The only read-lock obtained ** by a connection in read-uncommitted mode is on the sqlite_master ** table, and that lock is obtained in BtreeBeginTrans(). */ - assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK ); + assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK ); /* This function should only be called on a sharable b-tree after it ** has been determined that no other b-tree holds a conflicting lock. */ @@ -61674,7 +68074,7 @@ static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ ** with table iTable, allocate one and link it into the list. */ if( !pLock ){ - pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); + pLock = (BtLock *)tdsqlite3MallocZero(sizeof(BtLock)); if( !pLock ){ return SQLITE_NOMEM_BKPT; } @@ -61710,7 +68110,7 @@ static void clearAllSharedCacheTableLocks(Btree *p){ BtShared *pBt = p->pBt; BtLock **ppIter = &pBt->pLock; - assert( sqlite3BtreeHoldsMutex(p) ); + assert( tdsqlite3BtreeHoldsMutex(p) ); assert( p->sharable || 0==*ppIter ); assert( p->inTrans>0 ); @@ -61722,7 +68122,7 @@ static void clearAllSharedCacheTableLocks(Btree *p){ *ppIter = pLock->pNext; assert( pLock->iTable!=1 || pLock==&p->lock ); if( pLock->iTable!=1 ){ - sqlite3_free(pLock); + tdsqlite3_free(pLock); } }else{ ppIter = &pLock->pNext; @@ -61765,7 +68165,9 @@ static void downgradeAllSharedCacheTableLocks(Btree *p){ #endif /* SQLITE_OMIT_SHARED_CACHE */ -static void releasePage(MemPage *pPage); /* Forward reference */ +static void releasePage(MemPage *pPage); /* Forward reference */ +static void releasePageOne(MemPage *pPage); /* Forward reference */ +static void releasePageNotNull(MemPage *pPage); /* Forward reference */ /* ***** This routine is used inside of assert() only **** @@ -61774,7 +68176,7 @@ static void releasePage(MemPage *pPage); /* Forward reference */ */ #ifdef SQLITE_DEBUG static int cursorHoldsMutex(BtCursor *p){ - return sqlite3_mutex_held(p->pBt->mutex); + return tdsqlite3_mutex_held(p->pBt->mutex); } /* Verify that the cursor and the BtShared agree about what is the current @@ -61803,7 +68205,7 @@ static int cursorOwnsBtShared(BtCursor *p){ */ static void invalidateAllOverflowCache(BtShared *pBt){ BtCursor *p; - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); for(p=pBt->pCursor; p; p=p->pNext){ invalidateOverflowCache(p); } @@ -61825,17 +68227,18 @@ static void invalidateAllOverflowCache(BtShared *pBt){ */ static void invalidateIncrblobCursors( Btree *pBtree, /* The database file to check */ + Pgno pgnoRoot, /* The table that might be changing */ i64 iRow, /* The rowid that might be changing */ int isClearTable /* True if all rows are being deleted */ ){ BtCursor *p; if( pBtree->hasIncrblobCur==0 ) return; - assert( sqlite3BtreeHoldsMutex(pBtree) ); + assert( tdsqlite3BtreeHoldsMutex(pBtree) ); pBtree->hasIncrblobCur = 0; for(p=pBtree->pBt->pCursor; p; p=p->pNext){ if( (p->curFlags & BTCF_Incrblob)!=0 ){ pBtree->hasIncrblobCur = 1; - if( isClearTable || p->info.nKey==iRow ){ + if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){ p->eState = CURSOR_INVALID; } } @@ -61844,7 +68247,7 @@ static void invalidateIncrblobCursors( #else /* Stub function when INCRBLOB is omitted */ - #define invalidateIncrblobCursors(x,y,z) + #define invalidateIncrblobCursors(w,x,y,z) #endif /* SQLITE_OMIT_INCRBLOB */ /* @@ -61886,13 +68289,13 @@ static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ int rc = SQLITE_OK; if( !pBt->pHasContent ){ assert( pgno<=pBt->nPage ); - pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); + pBt->pHasContent = tdsqlite3BitvecCreate(pBt->nPage); if( !pBt->pHasContent ){ rc = SQLITE_NOMEM_BKPT; } } - if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ - rc = sqlite3BitvecSet(pBt->pHasContent, pgno); + if( rc==SQLITE_OK && pgno<=tdsqlite3BitvecSize(pBt->pHasContent) ){ + rc = tdsqlite3BitvecSet(pBt->pHasContent, pgno); } return rc; } @@ -61906,7 +68309,7 @@ static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ */ static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ Bitvec *p = pBt->pHasContent; - return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno))); + return (p && (pgno>tdsqlite3BitvecSize(p) || tdsqlite3BitvecTest(p, pgno))); } /* @@ -61914,7 +68317,7 @@ static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ ** invoked at the conclusion of each write-transaction. */ static void btreeClearHasContent(BtShared *pBt){ - sqlite3BitvecDestroy(pBt->pHasContent); + tdsqlite3BitvecDestroy(pBt->pHasContent); pBt->pHasContent = 0; } @@ -61923,11 +68326,13 @@ static void btreeClearHasContent(BtShared *pBt){ */ static void btreeReleaseAllCursorPages(BtCursor *pCur){ int i; - for(i=0; i<=pCur->iPage; i++){ - releasePage(pCur->apPage[i]); - pCur->apPage[i] = 0; + if( pCur->iPage>=0 ){ + for(i=0; i<pCur->iPage; i++){ + releasePageNotNull(pCur->apPage[i]); + } + releasePageNotNull(pCur->pPage); + pCur->iPage = -1; } - pCur->iPage = -1; } /* @@ -61951,18 +68356,24 @@ static int saveCursorKey(BtCursor *pCur){ if( pCur->curIntKey ){ /* Only the rowid is required for a table btree */ - pCur->nKey = sqlite3BtreeIntegerKey(pCur); - }else{ - /* For an index btree, save the complete key content */ + pCur->nKey = tdsqlite3BtreeIntegerKey(pCur); + }else{ + /* For an index btree, save the complete key content. It is possible + ** that the current key is corrupt. In that case, it is possible that + ** the tdsqlite3VdbeRecordUnpack() function may overread the buffer by + ** up to the size of 1 varint plus 1 8-byte value when the cursor + ** position is restored. Hence the 17 bytes of padding allocated + ** below. */ void *pKey; - pCur->nKey = sqlite3BtreePayloadSize(pCur); - pKey = sqlite3Malloc( pCur->nKey ); + pCur->nKey = tdsqlite3BtreePayloadSize(pCur); + pKey = tdsqlite3Malloc( pCur->nKey + 9 + 8 ); if( pKey ){ - rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey); + rc = tdsqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey); if( rc==SQLITE_OK ){ + memset(((u8*)pKey)+pCur->nKey, 0, 9+8); pCur->pKey = pKey; }else{ - sqlite3_free(pKey); + tdsqlite3_free(pKey); } }else{ rc = SQLITE_NOMEM_BKPT; @@ -61986,6 +68397,9 @@ static int saveCursorPosition(BtCursor *pCur){ assert( 0==pCur->pKey ); assert( cursorHoldsMutex(pCur) ); + if( pCur->curFlags & BTCF_Pinned ){ + return SQLITE_CONSTRAINT_PINNED; + } if( pCur->eState==CURSOR_SKIPNEXT ){ pCur->eState = CURSOR_VALID; }else{ @@ -62028,7 +68442,7 @@ static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*); */ static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ BtCursor *p; - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); assert( pExcept==0 || pExcept->pBt==pBt ); for(p=pBt->pCursor; p; p=p->pNext){ if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break; @@ -62056,7 +68470,7 @@ static int SQLITE_NOINLINE saveCursorsOnList( return rc; } }else{ - testcase( p->iPage>0 ); + testcase( p->iPage>=0 ); btreeReleaseAllCursorPages(p); } } @@ -62068,9 +68482,9 @@ static int SQLITE_NOINLINE saveCursorsOnList( /* ** Clear the current cursor position. */ -SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){ +SQLITE_PRIVATE void tdsqlite3BtreeClearCursor(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); - sqlite3_free(pCur->pKey); + tdsqlite3_free(pCur->pKey); pCur->pKey = 0; pCur->eState = CURSOR_INVALID; } @@ -62089,26 +68503,24 @@ static int btreeMoveto( ){ int rc; /* Status code */ UnpackedRecord *pIdxKey; /* Unpacked index key */ - char aSpace[384]; /* Temp space for pIdxKey - to avoid a malloc */ - char *pFree = 0; if( pKey ){ + KeyInfo *pKeyInfo = pCur->pKeyInfo; assert( nKey==(i64)(int)nKey ); - pIdxKey = sqlite3VdbeAllocUnpackedRecord( - pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree - ); + pIdxKey = tdsqlite3VdbeAllocUnpackedRecord(pKeyInfo); if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT; - sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey); - if( pIdxKey->nField==0 ){ - sqlite3DbFree(pCur->pKeyInfo->db, pFree); - return SQLITE_CORRUPT_BKPT; + tdsqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey); + if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){ + rc = SQLITE_CORRUPT_BKPT; + goto moveto_done; } }else{ pIdxKey = 0; } - rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); - if( pFree ){ - sqlite3DbFree(pCur->pKeyInfo->db, pFree); + rc = tdsqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); +moveto_done: + if( pIdxKey ){ + tdsqlite3DbFree(pCur->pKeyInfo->db, pIdxKey); } return rc; } @@ -62122,19 +68534,23 @@ static int btreeMoveto( */ static int btreeRestoreCursorPosition(BtCursor *pCur){ int rc; - int skipNext; + int skipNext = 0; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState>=CURSOR_REQUIRESEEK ); if( pCur->eState==CURSOR_FAULT ){ return pCur->skipNext; } pCur->eState = CURSOR_INVALID; - rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); + if( tdsqlite3FaultSim(410) ){ + rc = SQLITE_IOERR; + }else{ + rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); + } if( rc==SQLITE_OK ){ - sqlite3_free(pCur->pKey); + tdsqlite3_free(pCur->pKey); pCur->pKey = 0; assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); - pCur->skipNext |= skipNext; + if( skipNext ) pCur->skipNext = skipNext; if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ pCur->eState = CURSOR_SKIPNEXT; } @@ -62156,11 +68572,26 @@ static int btreeRestoreCursorPosition(BtCursor *pCur){ ** ** Calling this routine with a NULL cursor pointer returns false. ** -** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor +** Use the separate tdsqlite3BtreeCursorRestore() routine to restore a cursor ** back to where it ought to be if this routine returns true. */ -SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ - return pCur->eState!=CURSOR_VALID; +SQLITE_PRIVATE int tdsqlite3BtreeCursorHasMoved(BtCursor *pCur){ + assert( EIGHT_BYTE_ALIGNMENT(pCur) + || pCur==tdsqlite3BtreeFakeValidCursor() ); + assert( offsetof(BtCursor, eState)==0 ); + assert( sizeof(pCur->eState)==1 ); + return CURSOR_VALID != *(u8*)pCur; +} + +/* +** Return a pointer to a fake BtCursor object that will always answer +** false to the tdsqlite3BtreeCursorHasMoved() routine above. The fake +** cursor returned must not be used with any other Btree interface. +*/ +SQLITE_PRIVATE BtCursor *tdsqlite3BtreeFakeValidCursor(void){ + static u8 fakeCursor = CURSOR_VALID; + assert( offsetof(BtCursor, eState)==0 ); + return (BtCursor*)&fakeCursor; } /* @@ -62174,9 +68605,9 @@ SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ ** nearby row. ** ** This routine should only be called for a cursor that just returned -** TRUE from sqlite3BtreeCursorHasMoved(). +** TRUE from tdsqlite3BtreeCursorHasMoved(). */ -SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ +SQLITE_PRIVATE int tdsqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ int rc; assert( pCur!=0 ); @@ -62189,7 +68620,6 @@ SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow) if( pCur->eState!=CURSOR_VALID ){ *pDifferentRow = 1; }else{ - assert( pCur->skipNext==0 ); *pDifferentRow = 0; } return SQLITE_OK; @@ -62201,7 +68631,7 @@ SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow) ** and number of the varargs parameters) is determined by the eHintType ** parameter. See the definitions of the BTREE_HINT_* macros for details. */ -SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ +SQLITE_PRIVATE void tdsqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ /* Used only by system that substitute their own storage engine */ } #endif @@ -62209,7 +68639,7 @@ SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ /* ** Provide flag hints to the cursor. */ -SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ +SQLITE_PRIVATE void tdsqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 ); pCur->hints = x; } @@ -62228,7 +68658,7 @@ SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ int nPagesPerMapPage; Pgno iPtrMap, ret; - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); if( pgno<2 ) return 0; nPagesPerMapPage = (pBt->usableSize/5)+1; iPtrMap = (pgno-2)/nPagesPerMapPage; @@ -62258,7 +68688,7 @@ static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ if( *pRC ) return; - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); /* The master-journal page number must never be used as a pointer map page */ assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); @@ -62268,22 +68698,29 @@ static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ return; } iPtrmap = PTRMAP_PAGENO(pBt, key); - rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); + rc = tdsqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); if( rc!=SQLITE_OK ){ *pRC = rc; return; } + if( ((char*)tdsqlite3PagerGetExtra(pDbPage))[0]!=0 ){ + /* The first byte of the extra data is the MemPage.isInit byte. + ** If that byte is set, it means this page is also being used + ** as a btree page. */ + *pRC = SQLITE_CORRUPT_BKPT; + goto ptrmap_exit; + } offset = PTRMAP_PTROFFSET(iPtrmap, key); if( offset<0 ){ *pRC = SQLITE_CORRUPT_BKPT; goto ptrmap_exit; } assert( offset <= (int)pBt->usableSize-5 ); - pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); + pPtrmap = (u8 *)tdsqlite3PagerGetData(pDbPage); if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); - *pRC= rc = sqlite3PagerWrite(pDbPage); + *pRC= rc = tdsqlite3PagerWrite(pDbPage); if( rc==SQLITE_OK ){ pPtrmap[offset] = eType; put4byte(&pPtrmap[offset+1], parent); @@ -62291,7 +68728,7 @@ static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ } ptrmap_exit: - sqlite3PagerUnref(pDbPage); + tdsqlite3PagerUnref(pDbPage); } /* @@ -62308,18 +68745,18 @@ static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ int offset; /* Offset of entry in pointer map */ int rc; - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); iPtrmap = PTRMAP_PAGENO(pBt, key); - rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); + rc = tdsqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); if( rc!=0 ){ return rc; } - pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); + pPtrmap = (u8 *)tdsqlite3PagerGetData(pDbPage); offset = PTRMAP_PTROFFSET(iPtrmap, key); if( offset<0 ){ - sqlite3PagerUnref(pDbPage); + tdsqlite3PagerUnref(pDbPage); return SQLITE_CORRUPT_BKPT; } assert( offset <= (int)pBt->usableSize-5 ); @@ -62327,15 +68764,15 @@ static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ *pEType = pPtrmap[offset]; if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); - sqlite3PagerUnref(pDbPage); - if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT; + tdsqlite3PagerUnref(pDbPage); + if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap); return SQLITE_OK; } #else /* if defined SQLITE_OMIT_AUTOVACUUM */ #define ptrmapPut(w,x,y,z,rc) #define ptrmapGet(w,x,y,z) SQLITE_OK - #define ptrmapPutOvflPtr(x, y, rc) + #define ptrmapPutOvflPtr(x, y, z, rc) #endif /* @@ -62410,7 +68847,7 @@ static void btreeParseCellPtrNoPayload( u8 *pCell, /* Pointer to the cell text. */ CellInfo *pInfo /* Fill in this structure */ ){ - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->leaf==0 ); assert( pPage->childPtrSize==4 ); #ifndef SQLITE_DEBUG @@ -62431,7 +68868,7 @@ static void btreeParseCellPtr( u32 nPayload; /* Number of bytes of cell payload */ u64 iKey; /* Extracted Key value */ - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->leaf==0 || pPage->leaf==1 ); assert( pPage->intKeyLeaf ); assert( pPage->childPtrSize==0 ); @@ -62498,7 +68935,7 @@ static void btreeParseCellPtrIndex( u8 *pIter; /* For scanning through pCell */ u32 nPayload; /* Number of bytes of cell payload */ - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); assert( pPage->leaf==0 || pPage->leaf==1 ); assert( pPage->intKeyLeaf==0 ); pIter = pCell + pPage->childPtrSize; @@ -62628,17 +69065,24 @@ static u16 cellSize(MemPage *pPage, int iCell){ #ifndef SQLITE_OMIT_AUTOVACUUM /* -** If the cell pCell, part of page pPage contains a pointer -** to an overflow page, insert an entry into the pointer-map -** for the overflow page. +** The cell pCell is currently part of page pSrc but will ultimately be part +** of pPage. (pSrc and pPager are often the same.) If pCell contains a +** pointer to an overflow page, insert an entry into the pointer-map for +** the overflow page that will be valid after pCell has been moved to pPage. */ -static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ +static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){ CellInfo info; if( *pRC ) return; assert( pCell!=0 ); pPage->xParseCell(pPage, pCell, &info); if( info.nLocal<info.nPayload ){ - Pgno ovfl = get4byte(&pCell[info.nSize-4]); + Pgno ovfl; + if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){ + testcase( pSrc!=pPage ); + *pRC = SQLITE_CORRUPT_BKPT; + return; + } + ovfl = get4byte(&pCell[info.nSize-4]); ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); } } @@ -62646,17 +69090,18 @@ static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ /* -** Defragment the page given. All Cells are moved to the -** end of the page and all free space is collected into one -** big FreeBlk that occurs in between the header and cell -** pointer array and the cell content area. +** Defragment the page given. This routine reorganizes cells within the +** page so that there are no free-blocks on the free-block list. +** +** Parameter nMaxFrag is the maximum amount of fragmented space that may be +** present in the page after this routine returns. ** ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a ** b-tree page so that there are no freeblocks or fragment bytes, all ** unused bytes are contained in the unallocated space region, and all ** cells are packed tightly at the end of the page. */ -static int defragmentPage(MemPage *pPage){ +static int defragmentPage(MemPage *pPage, int nMaxFrag){ int i; /* Loop counter */ int pc; /* Address of the i-th cell */ int hdr; /* Offset to the page header */ @@ -62671,21 +69116,64 @@ static int defragmentPage(MemPage *pPage){ int iCellFirst; /* First allowable cell index */ int iCellLast; /* Last possible cell index */ - - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( tdsqlite3PagerIswriteable(pPage->pDbPage) ); assert( pPage->pBt!=0 ); assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); assert( pPage->nOverflow==0 ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); temp = 0; src = data = pPage->aData; hdr = pPage->hdrOffset; cellOffset = pPage->cellOffset; nCell = pPage->nCell; - assert( nCell==get2byte(&data[hdr+3]) ); + assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB ); + iCellFirst = cellOffset + 2*nCell; usableSize = pPage->pBt->usableSize; + + /* This block handles pages with two or fewer free blocks and nMaxFrag + ** or fewer fragmented bytes. In this case it is faster to move the + ** two (or one) blocks of cells using memmove() and add the required + ** offsets to each pointer in the cell-pointer array than it is to + ** reconstruct the entire page. */ + if( (int)data[hdr+7]<=nMaxFrag ){ + int iFree = get2byte(&data[hdr+1]); + if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage); + if( iFree ){ + int iFree2 = get2byte(&data[iFree]); + if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage); + if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){ + u8 *pEnd = &data[cellOffset + nCell*2]; + u8 *pAddr; + int sz2 = 0; + int sz = get2byte(&data[iFree+2]); + int top = get2byte(&data[hdr+5]); + if( NEVER(top>=iFree) ){ + return SQLITE_CORRUPT_PAGE(pPage); + } + if( iFree2 ){ + if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage); + sz2 = get2byte(&data[iFree2+2]); + if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage); + memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz)); + sz += sz2; + }else if( NEVER(iFree+sz>usableSize) ){ + return SQLITE_CORRUPT_PAGE(pPage); + } + + cbrk = top+sz; + assert( cbrk+(iFree-top) <= usableSize ); + memmove(&data[cbrk], &data[top], iFree-top); + for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){ + pc = get2byte(pAddr); + if( pc<iFree ){ put2byte(pAddr, pc+sz); } + else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); } + } + goto defragment_out; + } + } + } + cbrk = usableSize; - iCellFirst = cellOffset + 2*nCell; iCellLast = usableSize - 4; for(i=0; i<nCell; i++){ u8 *pAddr; /* The i-th cell pointer */ @@ -62697,13 +69185,13 @@ static int defragmentPage(MemPage *pPage){ ** if PRAGMA cell_size_check=ON. */ if( pc<iCellFirst || pc>iCellLast ){ - return SQLITE_CORRUPT_BKPT; + return SQLITE_CORRUPT_PAGE(pPage); } assert( pc>=iCellFirst && pc<=iCellLast ); size = pPage->xCellSize(pPage, &src[pc]); cbrk -= size; if( cbrk<iCellFirst || pc+size>usableSize ){ - return SQLITE_CORRUPT_BKPT; + return SQLITE_CORRUPT_PAGE(pPage); } assert( cbrk+size<=usableSize && cbrk>=iCellFirst ); testcase( cbrk+size==usableSize ); @@ -62712,23 +69200,26 @@ static int defragmentPage(MemPage *pPage){ if( temp==0 ){ int x; if( cbrk==pc ) continue; - temp = sqlite3PagerTempSpace(pPage->pBt->pPager); + temp = tdsqlite3PagerTempSpace(pPage->pBt->pPager); x = get2byte(&data[hdr+5]); memcpy(&temp[x], &data[x], (cbrk+size) - x); src = temp; } memcpy(&data[cbrk], &src[pc], size); } + data[hdr+7] = 0; + + defragment_out: + assert( pPage->nFree>=0 ); + if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){ + return SQLITE_CORRUPT_PAGE(pPage); + } assert( cbrk>=iCellFirst ); put2byte(&data[hdr+5], cbrk); data[hdr+1] = 0; data[hdr+2] = 0; - data[hdr+7] = 0; memset(&data[iCellFirst], 0, cbrk-iCellFirst); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - if( cbrk-iCellFirst!=pPage->nFree ){ - return SQLITE_CORRUPT_BKPT; - } + assert( tdsqlite3PagerIswriteable(pPage->pDbPage) ); return SQLITE_OK; } @@ -62747,22 +69238,16 @@ static int defragmentPage(MemPage *pPage){ ** causes the fragmentation count to exceed 60. */ static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ - const int hdr = pPg->hdrOffset; - u8 * const aData = pPg->aData; - int iAddr = hdr + 1; - int pc = get2byte(&aData[iAddr]); - int x; - int usableSize = pPg->pBt->usableSize; + const int hdr = pPg->hdrOffset; /* Offset to page header */ + u8 * const aData = pPg->aData; /* Page data */ + int iAddr = hdr + 1; /* Address of ptr to pc */ + int pc = get2byte(&aData[iAddr]); /* Address of a free slot */ + int x; /* Excess size of the slot */ + int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */ + int size; /* Size of the free slot */ assert( pc>0 ); - do{ - int size; /* Size of the free slot */ - /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of - ** increasing offset. */ - if( pc>usableSize-4 || pc<iAddr+4 ){ - *pRc = SQLITE_CORRUPT_BKPT; - return 0; - } + while( pc<=maxPC ){ /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each ** freeblock form a big-endian integer which is the size of the freeblock ** in bytes, including the 4-byte header. */ @@ -62770,10 +69255,7 @@ static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ if( (x = size - nByte)>=0 ){ testcase( x==4 ); testcase( x==3 ); - if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){ - *pRc = SQLITE_CORRUPT_BKPT; - return 0; - }else if( x<4 ){ + if( x<4 ){ /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total ** number of bytes in fragments may not exceed 60. */ if( aData[hdr+7]>57 ) return 0; @@ -62782,17 +69264,31 @@ static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ ** fragmented bytes within the page. */ memcpy(&aData[iAddr], &aData[pc], 2); aData[hdr+7] += (u8)x; + }else if( x+pc > maxPC ){ + /* This slot extends off the end of the usable part of the page */ + *pRc = SQLITE_CORRUPT_PAGE(pPg); + return 0; }else{ /* The slot remains on the free-list. Reduce its size to account - ** for the portion used by the new allocation. */ + ** for the portion used by the new allocation. */ put2byte(&aData[pc+2], x); } return &aData[pc + x]; } iAddr = pc; pc = get2byte(&aData[pc]); - }while( pc ); - + if( pc<=iAddr+size ){ + if( pc ){ + /* The next slot in the chain is not past the end of the current slot */ + *pRc = SQLITE_CORRUPT_PAGE(pPg); + } + return 0; + } + } + if( pc>maxPC+nByte-4 ){ + /* The free slot chain extends off the end of the page */ + *pRc = SQLITE_CORRUPT_PAGE(pPg); + } return 0; } @@ -62816,9 +69312,9 @@ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ int rc = SQLITE_OK; /* Integer return code */ int gap; /* First byte of gap between cell pointers and cell content */ - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( tdsqlite3PagerIswriteable(pPage->pDbPage) ); assert( pPage->pBt ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); assert( nByte>=0 ); /* Minimum cell size is 4 */ assert( pPage->nFree>=nByte ); assert( pPage->nOverflow==0 ); @@ -62833,18 +69329,18 @@ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ ** However, that integer is too large to be stored in a 2-byte unsigned ** integer, so a value of 0 is used in its place. */ top = get2byte(&data[hdr+5]); - assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */ + assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */ if( gap>top ){ if( top==0 && pPage->pBt->usableSize==65536 ){ top = 65536; }else{ - return SQLITE_CORRUPT_BKPT; + return SQLITE_CORRUPT_PAGE(pPage); } } - /* If there is enough space between gap and top for one more cell pointer - ** array entry offset, and if the freelist is not empty, then search the - ** freelist looking for a free slot big enough to satisfy the request. + /* If there is enough space between gap and top for one more cell pointer, + ** and if the freelist is not empty, then search the + ** freelist looking for a slot big enough to satisfy the request. */ testcase( gap+2==top ); testcase( gap+1==top ); @@ -62852,9 +69348,14 @@ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){ u8 *pSpace = pageFindSlot(pPage, nByte, &rc); if( pSpace ){ - assert( pSpace>=data && (pSpace - data)<65536 ); - *pIdx = (int)(pSpace - data); - return SQLITE_OK; + int g2; + assert( pSpace+nByte<=data+pPage->pBt->usableSize ); + *pIdx = g2 = (int)(pSpace-data); + if( NEVER(g2<=gap) ){ + return SQLITE_CORRUPT_PAGE(pPage); + }else{ + return SQLITE_OK; + } }else if( rc ){ return rc; } @@ -62866,15 +69367,16 @@ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ testcase( gap+2+nByte==top ); if( gap+2+nByte>top ){ assert( pPage->nCell>0 || CORRUPT_DB ); - rc = defragmentPage(pPage); + assert( pPage->nFree>=0 ); + rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte))); if( rc ) return rc; top = get2byteNotZero(&data[hdr+5]); - assert( gap+nByte<=top ); + assert( gap+2+nByte<=top ); } /* Allocate memory from the gap in between the cell pointer array - ** and the cell content area. The btreeInitPage() call has already + ** and the cell content area. The btreeComputeFreeSpace() call has already ** validated the freelist. Given that the freelist is valid, there ** is no way that the allocation can extend off the end of the page. ** The assert() below verifies the previous sentence. @@ -62893,7 +69395,7 @@ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ ** ** Adjacent freeblocks are coalesced. ** -** Note that even though the freeblock list was checked by btreeInitPage(), +** Even though the freeblock list was checked by btreeComputeFreeSpace(), ** that routine will not detect overlap between cells or freeblocks. Nor ** does it detect cells or freeblocks that encrouch into the reserved bytes ** at the end of the page. So do additional corruption checks inside this @@ -62905,23 +69407,17 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ u8 hdr; /* Page header size. 0 or 100 */ u8 nFrag = 0; /* Reduction in fragmentation */ u16 iOrigSize = iSize; /* Original value of iSize */ - u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */ + u16 x; /* Offset to cell content area */ u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */ unsigned char *data = pPage->aData; /* Page content */ assert( pPage->pBt!=0 ); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( tdsqlite3PagerIswriteable(pPage->pDbPage) ); assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize ); assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); assert( iSize>=4 ); /* Minimum cell size is 4 */ - assert( iStart<=iLast ); - - /* Overwrite deleted information with zeros when the secure_delete - ** option is enabled */ - if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){ - memset(&data[iStart], 0, iSize); - } + assert( iStart<=pPage->pBt->usableSize-4 ); /* The list of freeblocks must be in ascending order. Find the ** spot on the list where iStart should be inserted. @@ -62933,12 +69429,14 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ }else{ while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){ if( iFreeBlk<iPtr+4 ){ - if( iFreeBlk==0 ) break; - return SQLITE_CORRUPT_BKPT; + if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */ + return SQLITE_CORRUPT_PAGE(pPage); } iPtr = iFreeBlk; } - if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT; + if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */ + return SQLITE_CORRUPT_PAGE(pPage); + } assert( iFreeBlk>iPtr || iFreeBlk==0 ); /* At this point: @@ -62949,9 +69447,11 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ */ if( iFreeBlk && iEnd+3>=iFreeBlk ){ nFrag = iFreeBlk - iEnd; - if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT; + if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage); iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); - if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT; + if( NEVER(iEnd > pPage->pBt->usableSize) ){ + return SQLITE_CORRUPT_PAGE(pPage); + } iSize = iEnd - iStart; iFreeBlk = get2byte(&data[iFreeBlk]); } @@ -62963,28 +69463,35 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ if( iPtr>hdr+1 ){ int iPtrEnd = iPtr + get2byte(&data[iPtr+2]); if( iPtrEnd+3>=iStart ){ - if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT; + if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage); nFrag += iStart - iPtrEnd; iSize = iEnd - iPtr; iStart = iPtr; } } - if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT; + if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage); data[hdr+7] -= nFrag; } - if( iStart==get2byte(&data[hdr+5]) ){ + x = get2byte(&data[hdr+5]); + if( iStart<=x ){ /* The new freeblock is at the beginning of the cell content area, ** so just extend the cell content area rather than create another ** freelist entry */ - if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT; + if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage); + if( NEVER(iPtr!=hdr+1) ) return SQLITE_CORRUPT_PAGE(pPage); put2byte(&data[hdr+1], iFreeBlk); put2byte(&data[hdr+5], iEnd); }else{ /* Insert the new freeblock into the freelist */ put2byte(&data[iPtr], iStart); - put2byte(&data[iStart], iFreeBlk); - put2byte(&data[iStart+2], iSize); } + if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){ + /* Overwrite deleted information with zeros when the secure_delete + ** option is enabled */ + memset(&data[iStart], 0, iSize); + } + put2byte(&data[iStart], iFreeBlk); + put2byte(&data[iStart+2], iSize); pPage->nFree += iOrigSize; return SQLITE_OK; } @@ -63005,7 +69512,7 @@ static int decodeFlags(MemPage *pPage, int flagByte){ BtShared *pBt; /* A copy of pPage->pBt */ assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); flagByte &= ~PTF_LEAF; pPage->childPtrSize = 4-4*pPage->leaf; @@ -63044,144 +69551,184 @@ static int decodeFlags(MemPage *pPage, int flagByte){ }else{ /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is ** an error. */ - return SQLITE_CORRUPT_BKPT; + return SQLITE_CORRUPT_PAGE(pPage); } pPage->max1bytePayload = pBt->max1bytePayload; return SQLITE_OK; } /* -** Initialize the auxiliary information for a disk block. -** -** Return SQLITE_OK on success. If we see that the page does -** not contain a well-formed database page, then return -** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not -** guarantee that the page is well-formed. It only shows that -** we failed to detect any corruption. +** Compute the amount of freespace on the page. In other words, fill +** in the pPage->nFree field. */ -static int btreeInitPage(MemPage *pPage){ +static int btreeComputeFreeSpace(MemPage *pPage){ + int pc; /* Address of a freeblock within pPage->aData[] */ + u8 hdr; /* Offset to beginning of page header */ + u8 *data; /* Equal to pPage->aData */ + int usableSize; /* Amount of usable space on each page */ + int nFree; /* Number of unused bytes on the page */ + int top; /* First byte of the cell content area */ + int iCellFirst; /* First allowable cell or freeblock offset */ + int iCellLast; /* Last possible cell or freeblock offset */ assert( pPage->pBt!=0 ); assert( pPage->pBt->db!=0 ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); - assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); - assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); - - if( !pPage->isInit ){ - u16 pc; /* Address of a freeblock within pPage->aData[] */ - u8 hdr; /* Offset to beginning of page header */ - u8 *data; /* Equal to pPage->aData */ - BtShared *pBt; /* The main btree structure */ - int usableSize; /* Amount of usable space on each page */ - u16 cellOffset; /* Offset from start of page to first cell pointer */ - int nFree; /* Number of unused bytes on the page */ - int top; /* First byte of the cell content area */ - int iCellFirst; /* First allowable cell or freeblock offset */ - int iCellLast; /* Last possible cell or freeblock offset */ - - pBt = pPage->pBt; - - hdr = pPage->hdrOffset; - data = pPage->aData; - /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating - ** the b-tree page type. */ - if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT; - assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); - pPage->maskPage = (u16)(pBt->pageSize - 1); - pPage->nOverflow = 0; - usableSize = pBt->usableSize; - pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize; - pPage->aDataEnd = &data[usableSize]; - pPage->aCellIdx = &data[cellOffset]; - pPage->aDataOfst = &data[pPage->childPtrSize]; - /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates - ** the start of the cell content area. A zero value for this integer is - ** interpreted as 65536. */ - top = get2byteNotZero(&data[hdr+5]); - /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the - ** number of cells on the page. */ - pPage->nCell = get2byte(&data[hdr+3]); - if( pPage->nCell>MX_CELL(pBt) ){ - /* To many cells for a single page. The page must be corrupt */ - return SQLITE_CORRUPT_BKPT; - } - testcase( pPage->nCell==MX_CELL(pBt) ); - /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only - ** possible for a root page of a table that contains no rows) then the - ** offset to the cell content area will equal the page size minus the - ** bytes of reserved space. */ - assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + assert( pPage->pgno==tdsqlite3PagerPagenumber(pPage->pDbPage) ); + assert( pPage == tdsqlite3PagerGetExtra(pPage->pDbPage) ); + assert( pPage->aData == tdsqlite3PagerGetData(pPage->pDbPage) ); + assert( pPage->isInit==1 ); + assert( pPage->nFree<0 ); - /* A malformed database page might cause us to read past the end - ** of page when parsing a cell. - ** - ** The following block of code checks early to see if a cell extends - ** past the end of a page boundary and causes SQLITE_CORRUPT to be - ** returned if it does. - */ - iCellFirst = cellOffset + 2*pPage->nCell; - iCellLast = usableSize - 4; - if( pBt->db->flags & SQLITE_CellSizeCk ){ - int i; /* Index into the cell pointer array */ - int sz; /* Size of a cell */ - - if( !pPage->leaf ) iCellLast--; - for(i=0; i<pPage->nCell; i++){ - pc = get2byteAligned(&data[cellOffset+i*2]); - testcase( pc==iCellFirst ); - testcase( pc==iCellLast ); - if( pc<iCellFirst || pc>iCellLast ){ - return SQLITE_CORRUPT_BKPT; - } - sz = pPage->xCellSize(pPage, &data[pc]); - testcase( pc+sz==usableSize ); - if( pc+sz>usableSize ){ - return SQLITE_CORRUPT_BKPT; - } - } - if( !pPage->leaf ) iCellLast++; - } + usableSize = pPage->pBt->usableSize; + hdr = pPage->hdrOffset; + data = pPage->aData; + /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates + ** the start of the cell content area. A zero value for this integer is + ** interpreted as 65536. */ + top = get2byteNotZero(&data[hdr+5]); + iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell; + iCellLast = usableSize - 4; - /* Compute the total free space on the page - ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the - ** start of the first freeblock on the page, or is zero if there are no - ** freeblocks. */ - pc = get2byte(&data[hdr+1]); - nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */ - while( pc>0 ){ - u16 next, size; - if( pc<iCellFirst || pc>iCellLast ){ - /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will - ** always be at least one cell before the first freeblock. - ** - ** Or, the freeblock is off the end of the page - */ - return SQLITE_CORRUPT_BKPT; + /* Compute the total free space on the page + ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the + ** start of the first freeblock on the page, or is zero if there are no + ** freeblocks. */ + pc = get2byte(&data[hdr+1]); + nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */ + if( pc>0 ){ + u32 next, size; + if( pc<top ){ + /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will + ** always be at least one cell before the first freeblock. + */ + return SQLITE_CORRUPT_PAGE(pPage); + } + while( 1 ){ + if( pc>iCellLast ){ + /* Freeblock off the end of the page */ + return SQLITE_CORRUPT_PAGE(pPage); } next = get2byte(&data[pc]); size = get2byte(&data[pc+2]); - if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){ - /* Free blocks must be in ascending order. And the last byte of - ** the free-block must lie on the database page. */ - return SQLITE_CORRUPT_BKPT; - } nFree = nFree + size; + if( next<=pc+size+3 ) break; pc = next; } + if( next>0 ){ + /* Freeblock not in ascending order */ + return SQLITE_CORRUPT_PAGE(pPage); + } + if( pc+size>(unsigned int)usableSize ){ + /* Last freeblock extends past page end */ + return SQLITE_CORRUPT_PAGE(pPage); + } + } - /* At this point, nFree contains the sum of the offset to the start - ** of the cell-content area plus the number of free bytes within - ** the cell-content area. If this is greater than the usable-size - ** of the page, then the page must be corrupted. This check also - ** serves to verify that the offset to the start of the cell-content - ** area, according to the page header, lies within the page. - */ - if( nFree>usableSize ){ - return SQLITE_CORRUPT_BKPT; + /* At this point, nFree contains the sum of the offset to the start + ** of the cell-content area plus the number of free bytes within + ** the cell-content area. If this is greater than the usable-size + ** of the page, then the page must be corrupted. This check also + ** serves to verify that the offset to the start of the cell-content + ** area, according to the page header, lies within the page. + */ + if( nFree>usableSize || nFree<iCellFirst ){ + return SQLITE_CORRUPT_PAGE(pPage); + } + pPage->nFree = (u16)(nFree - iCellFirst); + return SQLITE_OK; +} + +/* +** Do additional sanity check after btreeInitPage() if +** PRAGMA cell_size_check=ON +*/ +static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){ + int iCellFirst; /* First allowable cell or freeblock offset */ + int iCellLast; /* Last possible cell or freeblock offset */ + int i; /* Index into the cell pointer array */ + int sz; /* Size of a cell */ + int pc; /* Address of a freeblock within pPage->aData[] */ + u8 *data; /* Equal to pPage->aData */ + int usableSize; /* Maximum usable space on the page */ + int cellOffset; /* Start of cell content area */ + + iCellFirst = pPage->cellOffset + 2*pPage->nCell; + usableSize = pPage->pBt->usableSize; + iCellLast = usableSize - 4; + data = pPage->aData; + cellOffset = pPage->cellOffset; + if( !pPage->leaf ) iCellLast--; + for(i=0; i<pPage->nCell; i++){ + pc = get2byteAligned(&data[cellOffset+i*2]); + testcase( pc==iCellFirst ); + testcase( pc==iCellLast ); + if( pc<iCellFirst || pc>iCellLast ){ + return SQLITE_CORRUPT_PAGE(pPage); } - pPage->nFree = (u16)(nFree - iCellFirst); - pPage->isInit = 1; + sz = pPage->xCellSize(pPage, &data[pc]); + testcase( pc+sz==usableSize ); + if( pc+sz>usableSize ){ + return SQLITE_CORRUPT_PAGE(pPage); + } + } + return SQLITE_OK; +} + +/* +** Initialize the auxiliary information for a disk block. +** +** Return SQLITE_OK on success. If we see that the page does +** not contain a well-formed database page, then return +** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not +** guarantee that the page is well-formed. It only shows that +** we failed to detect any corruption. +*/ +static int btreeInitPage(MemPage *pPage){ + u8 *data; /* Equal to pPage->aData */ + BtShared *pBt; /* The main btree structure */ + + assert( pPage->pBt!=0 ); + assert( pPage->pBt->db!=0 ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + assert( pPage->pgno==tdsqlite3PagerPagenumber(pPage->pDbPage) ); + assert( pPage == tdsqlite3PagerGetExtra(pPage->pDbPage) ); + assert( pPage->aData == tdsqlite3PagerGetData(pPage->pDbPage) ); + assert( pPage->isInit==0 ); + + pBt = pPage->pBt; + data = pPage->aData + pPage->hdrOffset; + /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating + ** the b-tree page type. */ + if( decodeFlags(pPage, data[0]) ){ + return SQLITE_CORRUPT_PAGE(pPage); + } + assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); + pPage->maskPage = (u16)(pBt->pageSize - 1); + pPage->nOverflow = 0; + pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize; + pPage->aCellIdx = data + pPage->childPtrSize + 8; + pPage->aDataEnd = pPage->aData + pBt->usableSize; + pPage->aDataOfst = pPage->aData + pPage->childPtrSize; + /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the + ** number of cells on the page. */ + pPage->nCell = get2byte(&data[3]); + if( pPage->nCell>MX_CELL(pBt) ){ + /* To many cells for a single page. The page must be corrupt */ + return SQLITE_CORRUPT_PAGE(pPage); + } + testcase( pPage->nCell==MX_CELL(pBt) ); + /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only + ** possible for a root page of a table that contains no rows) then the + ** offset to the cell content area will equal the page size minus the + ** bytes of reserved space. */ + assert( pPage->nCell>0 + || get2byteNotZero(&data[5])==(int)pBt->usableSize + || CORRUPT_DB ); + pPage->nFree = -1; /* Indicate that this value is yet uncomputed */ + pPage->isInit = 1; + if( pBt->db->flags & SQLITE_CellSizeCk ){ + return btreeCellSizeCheck(pPage); } return SQLITE_OK; } @@ -63196,12 +69743,12 @@ static void zeroPage(MemPage *pPage, int flags){ u8 hdr = pPage->hdrOffset; u16 first; - assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); - assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); - assert( sqlite3PagerGetData(pPage->pDbPage) == data ); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - assert( sqlite3_mutex_held(pBt->mutex) ); - if( pBt->btsFlags & BTS_SECURE_DELETE ){ + assert( tdsqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); + assert( tdsqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); + assert( tdsqlite3PagerGetData(pPage->pDbPage) == data ); + assert( tdsqlite3PagerIswriteable(pPage->pDbPage) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); + if( pBt->btsFlags & BTS_FAST_SECURE ){ memset(&data[hdr], 0, pBt->usableSize - hdr); } data[hdr] = (char)flags; @@ -63228,15 +69775,15 @@ static void zeroPage(MemPage *pPage, int flags){ ** the btree layer. */ static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ - MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); + MemPage *pPage = (MemPage*)tdsqlite3PagerGetExtra(pDbPage); if( pgno!=pPage->pgno ){ - pPage->aData = sqlite3PagerGetData(pDbPage); + pPage->aData = tdsqlite3PagerGetData(pDbPage); pPage->pDbPage = pDbPage; pPage->pBt = pBt; pPage->pgno = pgno; pPage->hdrOffset = pgno==1 ? 100 : 0; } - assert( pPage->aData==sqlite3PagerGetData(pDbPage) ); + assert( pPage->aData==tdsqlite3PagerGetData(pDbPage) ); return pPage; } @@ -63247,7 +69794,7 @@ static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care ** about the content of the page at this time. So do not go to the disk ** to fetch the content. Just fill in the content with zeros for now. -** If in the future we call sqlite3PagerWrite() on this page, that +** If in the future we call tdsqlite3PagerWrite() on this page, that ** means we have started to be concerned about content and the disk ** read should occur at that point. */ @@ -63261,8 +69808,8 @@ static int btreeGetPage( DbPage *pDbPage; assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); - assert( sqlite3_mutex_held(pBt->mutex) ); - rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); + assert( tdsqlite3_mutex_held(pBt->mutex) ); + rc = tdsqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); if( rc ) return rc; *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); return SQLITE_OK; @@ -63275,8 +69822,8 @@ static int btreeGetPage( */ static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ DbPage *pDbPage; - assert( sqlite3_mutex_held(pBt->mutex) ); - pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); + assert( tdsqlite3_mutex_held(pBt->mutex) ); + pDbPage = tdsqlite3PagerLookup(pBt->pPager, pgno); if( pDbPage ){ return btreePageFromDbPage(pDbPage, pgno, pBt); } @@ -63288,12 +69835,12 @@ static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ ** error, return ((unsigned int)-1). */ static Pgno btreePagecount(BtShared *pBt){ + assert( (pBt->nPage & 0x80000000)==0 || CORRUPT_DB ); return pBt->nPage; } -SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){ - assert( sqlite3BtreeHoldsMutex(p) ); - assert( ((p->pBt->nPage)&0x8000000)==0 ); - return btreePagecount(p->pBt); +SQLITE_PRIVATE u32 tdsqlite3BtreeLastPage(Btree *p){ + assert( tdsqlite3BtreeHoldsMutex(p) ); + return btreePagecount(p->pBt) & 0x7fffffff; } /* @@ -63318,42 +69865,45 @@ static int getAndInitPage( ){ int rc; DbPage *pDbPage; - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); + assert( pCur==0 || ppPage==&pCur->pPage ); assert( pCur==0 || bReadOnly==pCur->curPagerFlags ); assert( pCur==0 || pCur->iPage>0 ); if( pgno>btreePagecount(pBt) ){ rc = SQLITE_CORRUPT_BKPT; - goto getAndInitPage_error; + goto getAndInitPage_error1; } - rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); + rc = tdsqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); if( rc ){ - goto getAndInitPage_error; + goto getAndInitPage_error1; } - *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); + *ppPage = (MemPage*)tdsqlite3PagerGetExtra(pDbPage); if( (*ppPage)->isInit==0 ){ btreePageFromDbPage(pDbPage, pgno, pBt); rc = btreeInitPage(*ppPage); if( rc!=SQLITE_OK ){ - releasePage(*ppPage); - goto getAndInitPage_error; + goto getAndInitPage_error2; } } assert( (*ppPage)->pgno==pgno ); - assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) ); + assert( (*ppPage)->aData==tdsqlite3PagerGetData(pDbPage) ); /* If obtaining a child page for a cursor, we must verify that the page is ** compatible with the root page. */ if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){ - rc = SQLITE_CORRUPT_BKPT; - releasePage(*ppPage); - goto getAndInitPage_error; + rc = SQLITE_CORRUPT_PGNO(pgno); + goto getAndInitPage_error2; } return SQLITE_OK; -getAndInitPage_error: - if( pCur ) pCur->iPage--; +getAndInitPage_error2: + releasePage(*ppPage); +getAndInitPage_error1: + if( pCur ){ + pCur->iPage--; + pCur->pPage = pCur->apPage[pCur->iPage]; + } testcase( pgno==0 ); assert( pgno!=0 || rc==SQLITE_CORRUPT ); return rc; @@ -63362,19 +69912,31 @@ getAndInitPage_error: /* ** Release a MemPage. This should be called once for each prior ** call to btreeGetPage. +** +** Page1 is a special case and must be released using releasePageOne(). */ static void releasePageNotNull(MemPage *pPage){ assert( pPage->aData ); assert( pPage->pBt ); assert( pPage->pDbPage!=0 ); - assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); - assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - sqlite3PagerUnrefNotNull(pPage->pDbPage); + assert( tdsqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); + assert( tdsqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + tdsqlite3PagerUnrefNotNull(pPage->pDbPage); } static void releasePage(MemPage *pPage){ if( pPage ) releasePageNotNull(pPage); } +static void releasePageOne(MemPage *pPage){ + assert( pPage!=0 ); + assert( pPage->aData ); + assert( pPage->pBt ); + assert( pPage->pDbPage!=0 ); + assert( tdsqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); + assert( tdsqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + tdsqlite3PagerUnrefPageOne(pPage->pDbPage); +} /* ** Get an unused page. @@ -63393,7 +69955,7 @@ static int btreeGetUnusedPage( ){ int rc = btreeGetPage(pBt, pgno, ppPage, flags); if( rc==SQLITE_OK ){ - if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ + if( tdsqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ releasePage(*ppPage); *ppPage = 0; return SQLITE_CORRUPT_BKPT; @@ -63416,12 +69978,12 @@ static int btreeGetUnusedPage( */ static void pageReinit(DbPage *pData){ MemPage *pPage; - pPage = (MemPage *)sqlite3PagerGetExtra(pData); - assert( sqlite3PagerPageRefcount(pData)>0 ); + pPage = (MemPage *)tdsqlite3PagerGetExtra(pData); + assert( tdsqlite3PagerPageRefcount(pData)>0 ); if( pPage->isInit ){ - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); pPage->isInit = 0; - if( sqlite3PagerPageRefcount(pData)>1 ){ + if( tdsqlite3PagerPageRefcount(pData)>1 ){ /* pPage might not be a btree page; it might be an overflow page ** or ptrmap page or a free page. In those cases, the following ** call to btreeInitPage() will likely return SQLITE_CORRUPT. @@ -63439,8 +70001,9 @@ static void pageReinit(DbPage *pData){ static int btreeInvokeBusyHandler(void *pArg){ BtShared *pBt = (BtShared*)pArg; assert( pBt->db ); - assert( sqlite3_mutex_held(pBt->db->mutex) ); - return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); + assert( tdsqlite3_mutex_held(pBt->db->mutex) ); + return tdsqlite3InvokeBusyHandler(&pBt->db->busyHandler, + tdsqlite3PagerFile(pBt->pPager)); } /* @@ -63450,7 +70013,7 @@ static int btreeInvokeBusyHandler(void *pArg){ ** then an ephemeral database is created. The ephemeral database might ** be exclusively in memory, or it might use a disk-based memory cache. ** Either way, the ephemeral database will be automatically deleted -** when sqlite3BtreeClose() is called. +** when tdsqlite3BtreeClose() is called. ** ** If zFilename is ":memory:" then an in-memory database is created ** that is automatically destroyed when it is closed. @@ -63464,17 +70027,17 @@ static int btreeInvokeBusyHandler(void *pArg){ ** objects in the same database connection since doing so will lead ** to problems with locking. */ -SQLITE_PRIVATE int sqlite3BtreeOpen( - sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ +SQLITE_PRIVATE int tdsqlite3BtreeOpen( + tdsqlite3_vfs *pVfs, /* VFS to use for this b-tree */ const char *zFilename, /* Name of the file containing the BTree database */ - sqlite3 *db, /* Associated database handle */ + tdsqlite3 *db, /* Associated database handle */ Btree **ppBtree, /* Pointer to new Btree object written here */ int flags, /* Options */ - int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ + int vfsFlags /* Flags passed through to tdsqlite3_vfs.xOpen() */ ){ BtShared *pBt = 0; /* Shared part of btree structure */ Btree *p; /* Handle to return */ - sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ + tdsqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ int rc = SQLITE_OK; /* Result code from this function */ u8 nReserve; /* Byte of unused space on each page */ unsigned char zDbHeader[100]; /* Database header content */ @@ -63489,13 +70052,13 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( const int isMemdb = 0; #else const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) - || (isTempDb && sqlite3TempInMemory(db)) + || (isTempDb && tdsqlite3TempInMemory(db)) || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; #endif assert( db!=0 ); assert( pVfs!=0 ); - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ @@ -63510,7 +70073,7 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; } - p = sqlite3MallocZero(sizeof(Btree)); + p = tdsqlite3MallocZero(sizeof(Btree)); if( !p ){ return SQLITE_NOMEM_BKPT; } @@ -63528,45 +70091,49 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( */ if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ - int nFilename = sqlite3Strlen30(zFilename)+1; + int nFilename = tdsqlite3Strlen30(zFilename)+1; int nFullPathname = pVfs->mxPathname+1; - char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename)); - MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) + char *zFullPathname = tdsqlite3Malloc(MAX(nFullPathname,nFilename)); + MUTEX_LOGIC( tdsqlite3_mutex *mutexShared; ) p->sharable = 1; if( !zFullPathname ){ - sqlite3_free(p); + tdsqlite3_free(p); return SQLITE_NOMEM_BKPT; } if( isMemdb ){ memcpy(zFullPathname, zFilename, nFilename); }else{ - rc = sqlite3OsFullPathname(pVfs, zFilename, + rc = tdsqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname); if( rc ){ - sqlite3_free(zFullPathname); - sqlite3_free(p); - return rc; + if( rc==SQLITE_OK_SYMLINK ){ + rc = SQLITE_OK; + }else{ + tdsqlite3_free(zFullPathname); + tdsqlite3_free(p); + return rc; + } } } #if SQLITE_THREADSAFE - mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); - sqlite3_mutex_enter(mutexOpen); - mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); - sqlite3_mutex_enter(mutexShared); + mutexOpen = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); + tdsqlite3_mutex_enter(mutexOpen); + mutexShared = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); + tdsqlite3_mutex_enter(mutexShared); #endif - for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ + for(pBt=GLOBAL(BtShared*,tdsqlite3SharedCacheList); pBt; pBt=pBt->pNext){ assert( pBt->nRef>0 ); - if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) - && sqlite3PagerVfs(pBt->pPager)==pVfs ){ + if( 0==strcmp(zFullPathname, tdsqlite3PagerFilename(pBt->pPager, 0)) + && tdsqlite3PagerVfs(pBt->pPager)==pVfs ){ int iDb; for(iDb=db->nDb-1; iDb>=0; iDb--){ Btree *pExisting = db->aDb[iDb].pBt; if( pExisting && pExisting->pBt==pBt ){ - sqlite3_mutex_leave(mutexShared); - sqlite3_mutex_leave(mutexOpen); - sqlite3_free(zFullPathname); - sqlite3_free(p); + tdsqlite3_mutex_leave(mutexShared); + tdsqlite3_mutex_leave(mutexOpen); + tdsqlite3_free(zFullPathname); + tdsqlite3_free(p); return SQLITE_CONSTRAINT; } } @@ -63575,14 +70142,14 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( break; } } - sqlite3_mutex_leave(mutexShared); - sqlite3_free(zFullPathname); + tdsqlite3_mutex_leave(mutexShared); + tdsqlite3_free(zFullPathname); } #ifdef SQLITE_DEBUG else{ /* In debug mode, we mark all persistent databases as sharable ** even when they are not. This exercises the locking code and - ** gives more opportunity for asserts(sqlite3_mutex_held()) + ** gives more opportunity for asserts(tdsqlite3_mutex_held()) ** statements to find locking problems. */ p->sharable = 1; @@ -63602,30 +70169,32 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( assert( sizeof(u16)==2 ); assert( sizeof(Pgno)==4 ); - pBt = sqlite3MallocZero( sizeof(*pBt) ); + pBt = tdsqlite3MallocZero( sizeof(*pBt) ); if( pBt==0 ){ rc = SQLITE_NOMEM_BKPT; goto btree_open_out; } - rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, - EXTRA_SIZE, flags, vfsFlags, pageReinit); + rc = tdsqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, + sizeof(MemPage), flags, vfsFlags, pageReinit); if( rc==SQLITE_OK ){ - sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); - rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); + tdsqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); + rc = tdsqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); } if( rc!=SQLITE_OK ){ goto btree_open_out; } pBt->openFlags = (u8)flags; pBt->db = db; - sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); + tdsqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt); p->pBt = pBt; pBt->pCursor = 0; pBt->pPage1 = 0; - if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; -#ifdef SQLITE_SECURE_DELETE + if( tdsqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; +#if defined(SQLITE_SECURE_DELETE) pBt->btsFlags |= BTS_SECURE_DELETE; +#elif defined(SQLITE_FAST_SECURE_DELETE) + pBt->btsFlags |= BTS_OVERWRITE; #endif /* EVIDENCE-OF: R-51873-39618 The page size for a database file is ** determined by the 2-byte integer located at an offset of 16 bytes from @@ -63658,7 +70227,7 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); #endif } - rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); + rc = tdsqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); if( rc ) goto btree_open_out; pBt->usableSize = pBt->pageSize - nReserve; assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ @@ -63668,19 +70237,19 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( */ pBt->nRef = 1; if( p->sharable ){ - MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) - MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);) - if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ - pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); + MUTEX_LOGIC( tdsqlite3_mutex *mutexShared; ) + MUTEX_LOGIC( mutexShared = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);) + if( SQLITE_THREADSAFE && tdsqlite3GlobalConfig.bCoreMutex ){ + pBt->mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_FAST); if( pBt->mutex==0 ){ rc = SQLITE_NOMEM_BKPT; goto btree_open_out; } } - sqlite3_mutex_enter(mutexShared); - pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); - GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; - sqlite3_mutex_leave(mutexShared); + tdsqlite3_mutex_enter(mutexShared); + pBt->pNext = GLOBAL(BtShared*,tdsqlite3SharedCacheList); + GLOBAL(BtShared*,tdsqlite3SharedCacheList) = pBt; + tdsqlite3_mutex_leave(mutexShared); } #endif } @@ -63721,25 +70290,32 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( btree_open_out: if( rc!=SQLITE_OK ){ if( pBt && pBt->pPager ){ - sqlite3PagerClose(pBt->pPager); + tdsqlite3PagerClose(pBt->pPager, 0); } - sqlite3_free(pBt); - sqlite3_free(p); + tdsqlite3_free(pBt); + tdsqlite3_free(p); *ppBtree = 0; }else{ + tdsqlite3_file *pFile; + /* If the B-Tree was successfully opened, set the pager-cache size to the ** default value. Except, when opening on an existing shared pager-cache, ** do not change the pager-cache size. */ - if( sqlite3BtreeSchema(p, 0, 0)==0 ){ - sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE); + if( tdsqlite3BtreeSchema(p, 0, 0)==0 ){ + tdsqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE); + } + + pFile = tdsqlite3PagerFile(pBt->pPager); + if( pFile->pMethods ){ + tdsqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db); } } if( mutexOpen ){ - assert( sqlite3_mutex_held(mutexOpen) ); - sqlite3_mutex_leave(mutexOpen); + assert( tdsqlite3_mutex_held(mutexOpen) ); + tdsqlite3_mutex_leave(mutexOpen); } - assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 ); + assert( rc!=SQLITE_OK || tdsqlite3BtreeConnectionCount(*ppBtree)>0 ); return rc; } @@ -63751,19 +70327,19 @@ btree_open_out: */ static int removeFromSharingList(BtShared *pBt){ #ifndef SQLITE_OMIT_SHARED_CACHE - MUTEX_LOGIC( sqlite3_mutex *pMaster; ) + MUTEX_LOGIC( tdsqlite3_mutex *pMaster; ) BtShared *pList; int removed = 0; - assert( sqlite3_mutex_notheld(pBt->mutex) ); - MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) - sqlite3_mutex_enter(pMaster); + assert( tdsqlite3_mutex_notheld(pBt->mutex) ); + MUTEX_LOGIC( pMaster = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + tdsqlite3_mutex_enter(pMaster); pBt->nRef--; if( pBt->nRef<=0 ){ - if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ - GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; + if( GLOBAL(BtShared*,tdsqlite3SharedCacheList)==pBt ){ + GLOBAL(BtShared*,tdsqlite3SharedCacheList) = pBt->pNext; }else{ - pList = GLOBAL(BtShared*,sqlite3SharedCacheList); + pList = GLOBAL(BtShared*,tdsqlite3SharedCacheList); while( ALWAYS(pList) && pList->pNext!=pBt ){ pList=pList->pNext; } @@ -63772,11 +70348,11 @@ static int removeFromSharingList(BtShared *pBt){ } } if( SQLITE_THREADSAFE ){ - sqlite3_mutex_free(pBt->mutex); + tdsqlite3_mutex_free(pBt->mutex); } removed = 1; } - sqlite3_mutex_leave(pMaster); + tdsqlite3_mutex_leave(pMaster); return removed; #else return 1; @@ -63790,7 +70366,7 @@ static int removeFromSharingList(BtShared *pBt){ */ static void allocateTempSpace(BtShared *pBt){ if( !pBt->pTmpSpace ){ - pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); + pBt->pTmpSpace = tdsqlite3PageMalloc( pBt->pageSize ); /* One of the uses of pBt->pTmpSpace is to format cells before ** inserting them into a leaf page (function fillInCell()). If @@ -63820,7 +70396,7 @@ static void allocateTempSpace(BtShared *pBt){ static void freeTempSpace(BtShared *pBt){ if( pBt->pTmpSpace ){ pBt->pTmpSpace -= 4; - sqlite3PageFree(pBt->pTmpSpace); + tdsqlite3PageFree(pBt->pTmpSpace); pBt->pTmpSpace = 0; } } @@ -63828,28 +70404,28 @@ static void freeTempSpace(BtShared *pBt){ /* ** Close an open database and invalidate all cursors. */ -SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeClose(Btree *p){ BtShared *pBt = p->pBt; BtCursor *pCur; /* Close all cursors opened via this handle. */ - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); + assert( tdsqlite3_mutex_held(p->db->mutex) ); + tdsqlite3BtreeEnter(p); pCur = pBt->pCursor; while( pCur ){ BtCursor *pTmp = pCur; pCur = pCur->pNext; if( pTmp->pBtree==p ){ - sqlite3BtreeCloseCursor(pTmp); + tdsqlite3BtreeCloseCursor(pTmp); } } /* Rollback any active transaction and free the handle structure. - ** The call to sqlite3BtreeRollback() drops any table-locks held by + ** The call to tdsqlite3BtreeRollback() drops any table-locks held by ** this handle. */ - sqlite3BtreeRollback(p, SQLITE_OK, 0); - sqlite3BtreeLeave(p); + tdsqlite3BtreeRollback(p, SQLITE_OK, 0); + tdsqlite3BtreeLeave(p); /* If there are still other outstanding references to the shared-btree ** structure, return now. The remainder of this procedure cleans @@ -63863,13 +70439,13 @@ SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){ ** Clean out and delete the BtShared object. */ assert( !pBt->pCursor ); - sqlite3PagerClose(pBt->pPager); + tdsqlite3PagerClose(pBt->pPager, p->db); if( pBt->xFreeSchema && pBt->pSchema ){ pBt->xFreeSchema(pBt->pSchema); } - sqlite3DbFree(0, pBt->pSchema); + tdsqlite3DbFree(0, pBt->pSchema); freeTempSpace(pBt); - sqlite3_free(pBt); + tdsqlite3_free(pBt); } #ifndef SQLITE_OMIT_SHARED_CACHE @@ -63879,7 +70455,7 @@ SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){ if( p->pNext ) p->pNext->pPrev = p->pPrev; #endif - sqlite3_free(p); + tdsqlite3_free(p); return SQLITE_OK; } @@ -63890,12 +70466,12 @@ SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){ ** cache is allowed to grow larger than this limit if it contains ** dirty pages or pages still in active use. */ -SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ +SQLITE_PRIVATE int tdsqlite3BtreeSetCacheSize(Btree *p, int mxPage){ BtShared *pBt = p->pBt; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - sqlite3PagerSetCachesize(pBt->pPager, mxPage); - sqlite3BtreeLeave(p); + assert( tdsqlite3_mutex_held(p->db->mutex) ); + tdsqlite3BtreeEnter(p); + tdsqlite3PagerSetCachesize(pBt->pPager, mxPage); + tdsqlite3BtreeLeave(p); return SQLITE_OK; } @@ -63909,13 +70485,13 @@ SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ ** as an argument, no changes are made to the spill size setting, so ** using mxPage of 0 is a way to query the current spill size. */ -SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){ +SQLITE_PRIVATE int tdsqlite3BtreeSetSpillSize(Btree *p, int mxPage){ BtShared *pBt = p->pBt; int res; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage); - sqlite3BtreeLeave(p); + assert( tdsqlite3_mutex_held(p->db->mutex) ); + tdsqlite3BtreeEnter(p); + res = tdsqlite3PagerSetSpillsize(pBt->pPager, mxPage); + tdsqlite3BtreeLeave(p); return res; } @@ -63924,12 +70500,12 @@ SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){ ** Change the limit on the amount of the database file that may be ** memory mapped. */ -SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ +SQLITE_PRIVATE int tdsqlite3BtreeSetMmapLimit(Btree *p, tdsqlite3_int64 szMmap){ BtShared *pBt = p->pBt; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); - sqlite3BtreeLeave(p); + assert( tdsqlite3_mutex_held(p->db->mutex) ); + tdsqlite3BtreeEnter(p); + tdsqlite3PagerSetMmapLimit(pBt->pPager, szMmap); + tdsqlite3BtreeLeave(p); return SQLITE_OK; } #endif /* SQLITE_MAX_MMAP_SIZE>0 */ @@ -63943,15 +70519,15 @@ SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ ** probability of damage to near zero but with a write performance reduction. */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS -SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags( +SQLITE_PRIVATE int tdsqlite3BtreeSetPagerFlags( Btree *p, /* The btree to set the safety level on */ unsigned pgFlags /* Various PAGER_* flags */ ){ BtShared *pBt = p->pBt; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - sqlite3PagerSetFlags(pBt->pPager, pgFlags); - sqlite3BtreeLeave(p); + assert( tdsqlite3_mutex_held(p->db->mutex) ); + tdsqlite3BtreeEnter(p); + tdsqlite3PagerSetFlags(pBt->pPager, pgFlags); + tdsqlite3BtreeLeave(p); return SQLITE_OK; } #endif @@ -63976,16 +70552,16 @@ SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags( ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size ** and autovacuum mode can no longer be changed. */ -SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ +SQLITE_PRIVATE int tdsqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ int rc = SQLITE_OK; BtShared *pBt = p->pBt; assert( nReserve>=-1 && nReserve<=255 ); - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); #if SQLITE_HAS_CODEC if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve; #endif if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return SQLITE_READONLY; } if( nReserve<0 ){ @@ -63999,34 +70575,34 @@ SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, pBt->pageSize = (u32)pageSize; freeTempSpace(pBt); } - rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); + rc = tdsqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); pBt->usableSize = pBt->pageSize - (u16)nReserve; if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } /* ** Return the currently defined page size */ -SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeGetPageSize(Btree *p){ return p->pBt->pageSize; } /* -** This function is similar to sqlite3BtreeGetReserve(), except that it +** This function is similar to tdsqlite3BtreeGetReserve(), except that it ** may only be called if it is guaranteed that the b-tree mutex is already ** held. ** ** This is useful in one special case in the backup API code where it is ** known that the shared b-tree mutex is held, but the mutex on the -** database handle that owns *p is not. In this case if sqlite3BtreeEnter() +** database handle that owns *p is not. In this case if tdsqlite3BtreeEnter() ** were to be called, it might collide with some other operation on the ** database handle that owns *p, causing undefined behavior. */ -SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeGetReserveNoMutex(Btree *p){ int n; - assert( sqlite3_mutex_held(p->pBt->mutex) ); + assert( tdsqlite3_mutex_held(p->pBt->mutex) ); n = p->pBt->pageSize - p->pBt->usableSize; return n; } @@ -64040,14 +70616,14 @@ SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){ ** greater of the current reserved space and the maximum requested ** reserve space. */ -SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeGetOptimalReserve(Btree *p){ int n; - sqlite3BtreeEnter(p); - n = sqlite3BtreeGetReserveNoMutex(p); + tdsqlite3BtreeEnter(p); + n = tdsqlite3BtreeGetReserveNoMutex(p); #ifdef SQLITE_HAS_CODEC if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve; #endif - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return n; } @@ -64057,29 +70633,44 @@ SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){ ** No changes are made if mxPage is 0 or negative. ** Regardless of the value of mxPage, return the maximum page count. */ -SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ +SQLITE_PRIVATE int tdsqlite3BtreeMaxPageCount(Btree *p, int mxPage){ int n; - sqlite3BtreeEnter(p); - n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); - sqlite3BtreeLeave(p); + tdsqlite3BtreeEnter(p); + n = tdsqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); + tdsqlite3BtreeLeave(p); return n; } /* -** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1, -** then make no changes. Always return the value of the BTS_SECURE_DELETE -** setting after the change. +** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags: +** +** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared +** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared +** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set +** newFlag==(-1) No changes +** +** This routine acts as a query if newFlag is less than zero +** +** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but +** freelist leaf pages are not written back to the database. Thus in-page +** deleted content is cleared, but freelist deleted content is not. +** +** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition +** that freelist leaf pages are written back into the database, increasing +** the amount of disk I/O. */ -SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ +SQLITE_PRIVATE int tdsqlite3BtreeSecureDelete(Btree *p, int newFlag){ int b; if( p==0 ) return 0; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); + assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 ); + assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) ); if( newFlag>=0 ){ - p->pBt->btsFlags &= ~BTS_SECURE_DELETE; - if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE; - } - b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0; - sqlite3BtreeLeave(p); + p->pBt->btsFlags &= ~BTS_FAST_SECURE; + p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag; + } + b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE; + tdsqlite3BtreeLeave(p); return b; } @@ -64089,7 +70680,7 @@ SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ ** is disabled. The default value for the auto-vacuum property is ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. */ -SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ +SQLITE_PRIVATE int tdsqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ #ifdef SQLITE_OMIT_AUTOVACUUM return SQLITE_READONLY; #else @@ -64097,14 +70688,14 @@ SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ int rc = SQLITE_OK; u8 av = (u8)autoVacuum; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ rc = SQLITE_READONLY; }else{ pBt->autoVacuum = av ?1:0; pBt->incrVacuum = av==2 ?1:0; } - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; #endif } @@ -64113,22 +70704,52 @@ SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ ** Return the value of the 'auto-vacuum' property. If auto-vacuum is ** enabled 1 is returned. Otherwise 0. */ -SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeGetAutoVacuum(Btree *p){ #ifdef SQLITE_OMIT_AUTOVACUUM return BTREE_AUTOVACUUM_NONE; #else int rc; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); rc = ( (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: BTREE_AUTOVACUUM_INCR ); - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; #endif } +/* +** If the user has not set the safety-level for this database connection +** using "PRAGMA synchronous", and if the safety-level is not already +** set to the value passed to this function as the second parameter, +** set it so. +*/ +#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \ + && !defined(SQLITE_OMIT_WAL) +static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){ + tdsqlite3 *db; + Db *pDb; + if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){ + while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; } + if( pDb->bSyncSet==0 + && pDb->safety_level!=safety_level + && pDb!=&db->aDb[1] + ){ + pDb->safety_level = safety_level; + tdsqlite3PagerSetFlags(pBt->pPager, + pDb->safety_level | (db->flags & PAGER_FLAGS_MASK)); + } + } +} +#else +# define setDefaultSyncFlag(pBt,safety_level) +#endif + +/* Forward declaration */ +static int newDatabase(BtShared*); + /* ** Get a reference to pPage1 of the database file. This will @@ -64142,13 +70763,13 @@ SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){ static int lockBtree(BtShared *pBt){ int rc; /* Result code from subfunctions */ MemPage *pPage1; /* Page 1 of the database file */ - int nPage; /* Number of pages in the database */ - int nPageFile = 0; /* Number of pages in the database file */ - int nPageHeader; /* Number of pages in the database according to hdr */ + u32 nPage; /* Number of pages in the database */ + u32 nPageFile = 0; /* Number of pages in the database file */ + u32 nPageHeader; /* Number of pages in the database according to hdr */ - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); assert( pBt->pPage1==0 ); - rc = sqlite3PagerSharedLock(pBt->pPager); + rc = tdsqlite3PagerSharedLock(pBt->pPager); if( rc!=SQLITE_OK ) return rc; rc = btreeGetPage(pBt, 1, &pPage1, 0); if( rc!=SQLITE_OK ) return rc; @@ -64157,10 +70778,13 @@ static int lockBtree(BtShared *pBt){ ** a valid database file. */ nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData); - sqlite3PagerPagecount(pBt->pPager, &nPageFile); + tdsqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile); if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ nPage = nPageFile; } + if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){ + nPage = 0; + } if( nPage>0 ){ u32 pageSize; u32 usableSize; @@ -64198,30 +70822,19 @@ static int lockBtree(BtShared *pBt){ */ if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ int isOpen = 0; - rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); + rc = tdsqlite3PagerOpenWal(pBt->pPager, &isOpen); if( rc!=SQLITE_OK ){ goto page1_init_failed; }else{ -#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS - sqlite3 *db; - Db *pDb; - if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){ - while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; } - if( pDb->bSyncSet==0 - && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1 - ){ - pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1; - sqlite3PagerSetFlags(pBt->pPager, - pDb->safety_level | (db->flags & PAGER_FLAGS_MASK)); - } - } -#endif + setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1); if( isOpen==0 ){ - releasePage(pPage1); + releasePageOne(pPage1); return SQLITE_OK; } } rc = SQLITE_NOTADB; + }else{ + setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1); } #endif @@ -64246,6 +70859,7 @@ static int lockBtree(BtShared *pBt){ ){ goto page1_init_failed; } + pBt->btsFlags |= BTS_PAGESIZE_FIXED; assert( (pageSize & 7)==0 ); /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte ** integer at offset 20 is the number of bytes of space at the end of @@ -64262,15 +70876,15 @@ static int lockBtree(BtShared *pBt){ ** zero and return SQLITE_OK. The caller will call this function ** again with the correct page-size. */ - releasePage(pPage1); + releasePageOne(pPage1); pBt->usableSize = usableSize; pBt->pageSize = pageSize; freeTempSpace(pBt); - rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, + rc = tdsqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, pageSize-usableSize); return rc; } - if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){ + if( tdsqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){ rc = SQLITE_CORRUPT_BKPT; goto page1_init_failed; } @@ -64316,7 +70930,7 @@ static int lockBtree(BtShared *pBt){ return SQLITE_OK; page1_init_failed: - releasePage(pPage1); + releasePageOne(pPage1); pBt->pPage1 = 0; return rc; } @@ -64354,14 +70968,14 @@ static int countValidCursors(BtShared *pBt, int wrOnly){ ** If there is a transaction in progress, this routine is a no-op. */ static void unlockBtreeIfUnused(BtShared *pBt){ - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ MemPage *pPage1 = pBt->pPage1; assert( pPage1->aData ); - assert( sqlite3PagerRefcount(pBt->pPager)==1 ); + assert( tdsqlite3PagerRefcount(pBt->pPager)==1 ); pBt->pPage1 = 0; - releasePageNotNull(pPage1); + releasePageOne(pPage1); } } @@ -64375,14 +70989,14 @@ static int newDatabase(BtShared *pBt){ unsigned char *data; int rc; - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); if( pBt->nPage>0 ){ return SQLITE_OK; } pP1 = pBt->pPage1; assert( pP1!=0 ); data = pP1->aData; - rc = sqlite3PagerWrite(pP1->pDbPage); + rc = tdsqlite3PagerWrite(pP1->pDbPage); if( rc ) return rc; memcpy(data, zMagicHeader, sizeof(zMagicHeader)); assert( sizeof(zMagicHeader)==16 ); @@ -64414,12 +71028,12 @@ static int newDatabase(BtShared *pBt){ ** consisting of a single page and no schema objects). Return SQLITE_OK ** if successful, or an SQLite error code otherwise. */ -SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeNewDb(Btree *p){ int rc; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); p->pBt->nPage = 0; rc = newDatabase(p->pBt); - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } @@ -64436,13 +71050,13 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){ ** changes to the database. None of the following routines ** will work unless a transaction is started first: ** -** sqlite3BtreeCreateTable() -** sqlite3BtreeCreateIndex() -** sqlite3BtreeClearTable() -** sqlite3BtreeDropTable() -** sqlite3BtreeInsert() -** sqlite3BtreeDelete() -** sqlite3BtreeUpdateMeta() +** tdsqlite3BtreeCreateTable() +** tdsqlite3BtreeCreateIndex() +** tdsqlite3BtreeClearTable() +** tdsqlite3BtreeDropTable() +** tdsqlite3BtreeInsert() +** tdsqlite3BtreeDelete() +** tdsqlite3BtreeUpdateMeta() ** ** If an initial attempt to acquire the lock fails because of lock contention ** and the database was previously unlocked, then invoke the busy handler @@ -64458,11 +71072,11 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){ ** when A already has a read lock, we encourage A to give up and let B ** proceed. */ -SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ +SQLITE_PRIVATE int tdsqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){ BtShared *pBt = p->pBt; int rc = SQLITE_OK; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); btreeIntegrity(p); /* If the btree is already in a write-transaction, or it @@ -64474,6 +71088,12 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ } assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); + if( (p->db->flags & SQLITE_ResetDatabase) + && tdsqlite3PagerIsreadonly(pBt->pPager)==0 + ){ + pBt->btsFlags &= ~BTS_READ_ONLY; + } + /* Write transactions are not possible on a read-only database */ if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ rc = SQLITE_READONLY; @@ -64482,7 +71102,7 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ #ifndef SQLITE_OMIT_SHARED_CACHE { - sqlite3 *pBlock = 0; + tdsqlite3 *pBlock = 0; /* If another database handle has already opened a write transaction ** on this shared-btree structure and a second write transaction is ** requested, return SQLITE_LOCKED. @@ -64501,7 +71121,7 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ } } if( pBlock ){ - sqlite3ConnectionBlocked(p->db, pBlock); + tdsqlite3ConnectionBlocked(p->db, pBlock); rc = SQLITE_LOCKED_SHAREDCACHE; goto trans_begun; } @@ -64530,9 +71150,14 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ rc = SQLITE_READONLY; }else{ - rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db)); + rc = tdsqlite3PagerBegin(pBt->pPager,wrflag>1,tdsqlite3TempInMemory(p->db)); if( rc==SQLITE_OK ){ rc = newDatabase(pBt); + }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){ + /* if there was no transaction opened when this function was + ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error + ** code to SQLITE_BUSY. */ + rc = SQLITE_BUSY; } } } @@ -64542,6 +71167,7 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ } }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && btreeInvokeBusyHandler(pBt) ); + tdsqlite3PagerResetLockTimeout(pBt->pPager); if( rc==SQLITE_OK ){ if( p->inTrans==TRANS_NONE ){ @@ -64575,7 +71201,7 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ ** rollback occurs within the transaction. */ if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ - rc = sqlite3PagerWrite(pPage1->pDbPage); + rc = tdsqlite3PagerWrite(pPage1->pDbPage); if( rc==SQLITE_OK ){ put4byte(&pPage1->aData[28], pBt->nPage); } @@ -64583,18 +71209,22 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ } } - trans_begun: - if( rc==SQLITE_OK && wrflag ){ - /* This call makes sure that the pager has the correct number of - ** open savepoints. If the second parameter is greater than 0 and - ** the sub-journal is not already open, then it will be opened here. - */ - rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint); + if( rc==SQLITE_OK ){ + if( pSchemaVersion ){ + *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]); + } + if( wrflag ){ + /* This call makes sure that the pager has the correct number of + ** open savepoints. If the second parameter is greater than 0 and + ** the sub-journal is not already open, then it will be opened here. + */ + rc = tdsqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint); + } } btreeIntegrity(p); - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } @@ -64610,20 +71240,17 @@ static int setChildPtrmaps(MemPage *pPage){ int nCell; /* Number of cells in page pPage */ int rc; /* Return code */ BtShared *pBt = pPage->pBt; - u8 isInitOrig = pPage->isInit; Pgno pgno = pPage->pgno; - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - rc = btreeInitPage(pPage); - if( rc!=SQLITE_OK ){ - goto set_child_ptrmaps_out; - } + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage); + if( rc!=SQLITE_OK ) return rc; nCell = pPage->nCell; for(i=0; i<nCell; i++){ u8 *pCell = findCell(pPage, i); - ptrmapPutOvflPtr(pPage, pCell, &rc); + ptrmapPutOvflPtr(pPage, pPage, pCell, &rc); if( !pPage->leaf ){ Pgno childPgno = get4byte(pCell); @@ -64636,8 +71263,6 @@ static int setChildPtrmaps(MemPage *pPage){ ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); } -set_child_ptrmaps_out: - pPage->isInit = isInitOrig; return rc; } @@ -64656,21 +71281,20 @@ set_child_ptrmaps_out: ** overflow page in the list. */ static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3PagerIswriteable(pPage->pDbPage) ); if( eType==PTRMAP_OVERFLOW2 ){ /* The pointer is always the first 4 bytes of the page in this case. */ if( get4byte(pPage->aData)!=iFrom ){ - return SQLITE_CORRUPT_BKPT; + return SQLITE_CORRUPT_PAGE(pPage); } put4byte(pPage->aData, iTo); }else{ - u8 isInitOrig = pPage->isInit; int i; int nCell; int rc; - rc = btreeInitPage(pPage); + rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage); if( rc ) return rc; nCell = pPage->nCell; @@ -64679,12 +71303,14 @@ static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ if( eType==PTRMAP_OVERFLOW1 ){ CellInfo info; pPage->xParseCell(pPage, pCell, &info); - if( info.nLocal<info.nPayload - && pCell+info.nSize-1<=pPage->aData+pPage->maskPage - && iFrom==get4byte(pCell+info.nSize-4) - ){ - put4byte(pCell+info.nSize-4, iTo); - break; + if( info.nLocal<info.nPayload ){ + if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){ + return SQLITE_CORRUPT_PAGE(pPage); + } + if( iFrom==get4byte(pCell+info.nSize-4) ){ + put4byte(pCell+info.nSize-4, iTo); + break; + } } }else{ if( get4byte(pCell)==iFrom ){ @@ -64697,12 +71323,10 @@ static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ if( i==nCell ){ if( eType!=PTRMAP_BTREE || get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ - return SQLITE_CORRUPT_BKPT; + return SQLITE_CORRUPT_PAGE(pPage); } put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); } - - pPage->isInit = isInitOrig; } return SQLITE_OK; } @@ -64723,7 +71347,7 @@ static int relocatePage( u8 eType, /* Pointer map 'type' entry for pDbPage */ Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ Pgno iFreePage, /* The location to move pDbPage to */ - int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ + int isCommit /* isCommit flag passed to tdsqlite3PagerMovepage */ ){ MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ Pgno iDbPage = pDbPage->pgno; @@ -64732,13 +71356,14 @@ static int relocatePage( assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); assert( pDbPage->pBt==pBt ); + if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT; /* Move page iDbPage from its current location to page number iFreePage */ TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", iDbPage, iFreePage, iPtrPage, eType)); - rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); + rc = tdsqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); if( rc!=SQLITE_OK ){ return rc; } @@ -64776,7 +71401,7 @@ static int relocatePage( if( rc!=SQLITE_OK ){ return rc; } - rc = sqlite3PagerWrite(pPtrPage->pDbPage); + rc = tdsqlite3PagerWrite(pPtrPage->pDbPage); if( rc!=SQLITE_OK ){ releasePage(pPtrPage); return rc; @@ -64814,7 +71439,7 @@ static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ Pgno nFreeList; /* Number of pages still on the free-list */ int rc; - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); assert( iLastPg>nFin ); if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ @@ -64932,11 +71557,11 @@ static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ ** SQLITE_DONE is returned. If it is not finished, but no error occurred, ** SQLITE_OK is returned. Otherwise an SQLite error code. */ -SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeIncrVacuum(Btree *p){ int rc; BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); if( !pBt->autoVacuum ){ rc = SQLITE_DONE; @@ -64954,19 +71579,19 @@ SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){ rc = incrVacuumStep(pBt, nFin, nOrig, 0); } if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + rc = tdsqlite3PagerWrite(pBt->pPage1->pDbPage); put4byte(&pBt->pPage1->aData[28], pBt->nPage); } }else{ rc = SQLITE_DONE; } } - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } /* -** This routine is called prior to sqlite3PagerCommit when a transaction +** This routine is called prior to tdsqlite3PagerCommit when a transaction ** is committed for an auto-vacuum database. ** ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages @@ -64977,9 +71602,9 @@ SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){ static int autoVacuumCommit(BtShared *pBt){ int rc = SQLITE_OK; Pager *pPager = pBt->pPager; - VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); ) + VVA_ONLY( int nRef = tdsqlite3PagerRefcount(pPager); ) - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); invalidateAllOverflowCache(pBt); assert(pBt->autoVacuum); if( !pBt->incrVacuum ){ @@ -65007,7 +71632,7 @@ static int autoVacuumCommit(BtShared *pBt){ rc = incrVacuumStep(pBt, nFin, iFree, 1); } if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + rc = tdsqlite3PagerWrite(pBt->pPage1->pDbPage); put4byte(&pBt->pPage1->aData[32], 0); put4byte(&pBt->pPage1->aData[36], 0); put4byte(&pBt->pPage1->aData[28], nFin); @@ -65015,11 +71640,11 @@ static int autoVacuumCommit(BtShared *pBt){ pBt->nPage = nFin; } if( rc!=SQLITE_OK ){ - sqlite3PagerRollback(pPager); + tdsqlite3PagerRollback(pPager); } } - assert( nRef>=sqlite3PagerRefcount(pPager) ); + assert( nRef>=tdsqlite3PagerRefcount(pPager) ); return rc; } @@ -65037,7 +71662,7 @@ static int autoVacuumCommit(BtShared *pBt){ ** database are written into the database file and flushed to oxide. ** At the end of this call, the rollback journal still exists on the ** disk and we are still holding all locks, so the transaction has not -** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the +** committed. See tdsqlite3BtreeCommitPhaseTwo() for the second phase of the ** commit process. ** ** This call is a no-op if no write-transaction is currently active on pBt. @@ -65053,25 +71678,25 @@ static int autoVacuumCommit(BtShared *pBt){ ** Once this is routine has returned, the only thing required to commit ** the write-transaction for this database file is to delete the journal. */ -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ +SQLITE_PRIVATE int tdsqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ int rc = SQLITE_OK; if( p->inTrans==TRANS_WRITE ){ BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ rc = autoVacuumCommit(pBt); if( rc!=SQLITE_OK ){ - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } } if( pBt->bDoTruncate ){ - sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); + tdsqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); } #endif - rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); - sqlite3BtreeLeave(p); + rc = tdsqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); + tdsqlite3BtreeLeave(p); } return rc; } @@ -65082,8 +71707,8 @@ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ */ static void btreeEndTransaction(Btree *p){ BtShared *pBt = p->pBt; - sqlite3 *db = p->db; - assert( sqlite3BtreeHoldsMutex(p) ); + tdsqlite3 *db = p->db; + assert( tdsqlite3BtreeHoldsMutex(p) ); #ifndef SQLITE_OMIT_AUTOVACUUM pBt->bDoTruncate = 0; @@ -65120,8 +71745,8 @@ static void btreeEndTransaction(Btree *p){ ** Commit the transaction currently in progress. ** ** This routine implements the second phase of a 2-phase commit. The -** sqlite3BtreeCommitPhaseOne() routine does the first phase and should -** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() +** tdsqlite3BtreeCommitPhaseOne() routine does the first phase and should +** be invoked prior to calling this routine. The tdsqlite3BtreeCommitPhaseOne() ** routine did all the work of writing information out to disk and flushing the ** contents so that they are written onto the disk platter. All this ** routine has to do is delete or truncate or zero the header in the @@ -65142,10 +71767,10 @@ static void btreeEndTransaction(Btree *p){ ** This will release the write lock on the database file. If there ** are no active cursors, it also releases the read lock. */ -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ +SQLITE_PRIVATE int tdsqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ if( p->inTrans==TRANS_NONE ) return SQLITE_OK; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); btreeIntegrity(p); /* If the handle has a write-transaction open, commit the shared-btrees @@ -65156,9 +71781,9 @@ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ BtShared *pBt = p->pBt; assert( pBt->inTransaction==TRANS_WRITE ); assert( pBt->nTransaction>0 ); - rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); + rc = tdsqlite3PagerCommitPhaseTwo(pBt->pPager); if( rc!=SQLITE_OK && bCleanup==0 ){ - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */ @@ -65167,21 +71792,21 @@ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ } btreeEndTransaction(p); - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return SQLITE_OK; } /* ** Do both phases of a commit. */ -SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeCommit(Btree *p){ int rc; - sqlite3BtreeEnter(p); - rc = sqlite3BtreeCommitPhaseOne(p, 0); + tdsqlite3BtreeEnter(p); + rc = tdsqlite3BtreeCommitPhaseOne(p, 0); if( rc==SQLITE_OK ){ - rc = sqlite3BtreeCommitPhaseTwo(p, 0); + rc = tdsqlite3BtreeCommitPhaseTwo(p, 0); } - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } @@ -65211,39 +71836,47 @@ SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){ ** SQLITE_OK is returned if successful, or if an error occurs while ** saving a cursor position, an SQLite error code. */ -SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ +SQLITE_PRIVATE int tdsqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ BtCursor *p; int rc = SQLITE_OK; assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 ); if( pBtree ){ - sqlite3BtreeEnter(pBtree); + tdsqlite3BtreeEnter(pBtree); for(p=pBtree->pBt->pCursor; p; p=p->pNext){ - int i; if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){ if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ rc = saveCursorPosition(p); if( rc!=SQLITE_OK ){ - (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0); + (void)tdsqlite3BtreeTripAllCursors(pBtree, rc, 0); break; } } }else{ - sqlite3BtreeClearCursor(p); + tdsqlite3BtreeClearCursor(p); p->eState = CURSOR_FAULT; p->skipNext = errCode; } - for(i=0; i<=p->iPage; i++){ - releasePage(p->apPage[i]); - p->apPage[i] = 0; - } + btreeReleaseAllCursorPages(p); } - sqlite3BtreeLeave(pBtree); + tdsqlite3BtreeLeave(pBtree); } return rc; } /* +** Set the pBt->nPage field correctly, according to the current +** state of the database. Assume pBt->pPage1 is valid. +*/ +static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){ + int nPage = get4byte(&pPage1->aData[28]); + testcase( nPage==0 ); + if( nPage==0 ) tdsqlite3PagerPagecount(pBt->pPager, &nPage); + testcase( pBt->nPage!=nPage ); + pBt->nPage = nPage; +} + +/* ** Rollback the transaction in progress. ** ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped). @@ -65254,14 +71887,14 @@ SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int wr ** This will release the write lock on the database file. If there ** are no active cursors, it also releases the read lock. */ -SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ +SQLITE_PRIVATE int tdsqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ int rc; BtShared *pBt = p->pBt; MemPage *pPage1; assert( writeOnly==1 || writeOnly==0 ); assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK ); - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); if( tripCode==SQLITE_OK ){ rc = tripCode = saveAllCursors(pBt, 0, 0); if( rc ) writeOnly = 0; @@ -65269,7 +71902,7 @@ SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ rc = SQLITE_OK; } if( tripCode ){ - int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly); + int rc2 = tdsqlite3BtreeTripAllCursors(p, tripCode, writeOnly); assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) ); if( rc2!=SQLITE_OK ) rc = rc2; } @@ -65279,7 +71912,7 @@ SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ int rc2; assert( TRANS_WRITE==pBt->inTransaction ); - rc2 = sqlite3PagerRollback(pBt->pPager); + rc2 = tdsqlite3PagerRollback(pBt->pPager); if( rc2!=SQLITE_OK ){ rc = rc2; } @@ -65288,12 +71921,8 @@ SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ ** call btreeGetPage() on page 1 again to make ** sure pPage1->aData is set correctly. */ if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ - int nPage = get4byte(28+(u8*)pPage1->aData); - testcase( nPage==0 ); - if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); - testcase( pBt->nPage!=nPage ); - pBt->nPage = nPage; - releasePage(pPage1); + btreeSetNPage(pBt, pPage1); + releasePageOne(pPage1); } assert( countValidCursors(pBt, 1)==0 ); pBt->inTransaction = TRANS_READ; @@ -65301,7 +71930,7 @@ SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ } btreeEndTransaction(p); - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } @@ -65321,12 +71950,12 @@ SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ ** including the new anonymous savepoint, open on the B-Tree. i.e. if there ** are no active savepoints and no other statement-transactions open, ** iStatement is 1. This anonymous savepoint can be released or rolled back -** using the sqlite3BtreeSavepoint() function. +** using the tdsqlite3BtreeSavepoint() function. */ -SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ +SQLITE_PRIVATE int tdsqlite3BtreeBeginStmt(Btree *p, int iStatement){ int rc; BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); assert( p->inTrans==TRANS_WRITE ); assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); assert( iStatement>0 ); @@ -65337,8 +71966,8 @@ SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ ** SQL statements. It is illegal to open, release or rollback any ** such savepoints while the statement transaction savepoint is active. */ - rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); - sqlite3BtreeLeave(p); + rc = tdsqlite3PagerOpenSavepoint(pBt->pPager, iStatement); + tdsqlite3BtreeLeave(p); return rc; } @@ -65354,27 +71983,31 @@ SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ ** from a normal transaction rollback, as no locks are released and the ** transaction remains open. */ -SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ +SQLITE_PRIVATE int tdsqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ int rc = SQLITE_OK; if( p && p->inTrans==TRANS_WRITE ){ BtShared *pBt = p->pBt; assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); - sqlite3BtreeEnter(p); - rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); + tdsqlite3BtreeEnter(p); + if( op==SAVEPOINT_ROLLBACK ){ + rc = saveAllCursors(pBt, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = tdsqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); + } if( rc==SQLITE_OK ){ if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ pBt->nPage = 0; } rc = newDatabase(pBt); - pBt->nPage = get4byte(28 + pBt->pPage1->aData); + btreeSetNPage(pBt, pBt->pPage1); - /* The database size was written into the offset 28 of the header - ** when the transaction started, so we know that the value at offset - ** 28 is nonzero. */ - assert( pBt->nPage>0 ); + /* pBt->nPage might be zero if the database was corrupt when + ** the transaction was started. Otherwise, it must be at least 1. */ + assert( CORRUPT_DB || pBt->nPage>0 ); } - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); } return rc; } @@ -65418,7 +72051,7 @@ SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ ** root page of a b-tree. If it is not, then the cursor acquired ** will not work correctly. ** -** It is assumed that the sqlite3BtreeCursorZero() has been called +** It is assumed that the tdsqlite3BtreeCursorZero() has been called ** on pCur to initialize the memory space prior to invoking this routine. */ static int btreeCursor( @@ -65431,7 +72064,7 @@ static int btreeCursor( BtShared *pBt = p->pBt; /* Shared b-tree handle */ BtCursor *pX; /* Looping over other all cursors */ - assert( sqlite3BtreeHoldsMutex(p) ); + assert( tdsqlite3BtreeHoldsMutex(p) ); assert( wrFlag==0 || wrFlag==BTREE_WRCSR || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) @@ -65440,8 +72073,9 @@ static int btreeCursor( /* The following assert statements verify that if this is a sharable ** b-tree database, the connection is holding the required table locks, ** and that no other connection has any open cursor that conflicts with - ** this lock. */ - assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) ); + ** this lock. The iTable<1 term disables the check for corrupt schemas. */ + assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) + || iTable<1 ); assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); /* Assert that the caller has opened the required transaction. */ @@ -65454,9 +72088,13 @@ static int btreeCursor( allocateTempSpace(pBt); if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT; } - if( iTable==1 && btreePagecount(pBt)==0 ){ - assert( wrFlag==0 ); - iTable = 0; + if( iTable<=1 ){ + if( iTable<1 ){ + return SQLITE_CORRUPT_BKPT; + }else if( btreePagecount(pBt)==0 ){ + assert( wrFlag==0 ); + iTable = 0; + } } /* Now that no other errors can occur, finish filling in the BtCursor @@ -65481,22 +72119,31 @@ static int btreeCursor( pCur->eState = CURSOR_INVALID; return SQLITE_OK; } -SQLITE_PRIVATE int sqlite3BtreeCursor( +static int btreeCursorWithLock( + Btree *p, /* The btree */ + int iTable, /* Root page of table to open */ + int wrFlag, /* 1 to write. 0 read-only */ + struct KeyInfo *pKeyInfo, /* First arg to comparison function */ + BtCursor *pCur /* Space for new cursor */ +){ + int rc; + tdsqlite3BtreeEnter(p); + rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); + tdsqlite3BtreeLeave(p); + return rc; +} +SQLITE_PRIVATE int tdsqlite3BtreeCursor( Btree *p, /* The btree */ int iTable, /* Root page of table to open */ int wrFlag, /* 1 to write. 0 read-only */ struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ BtCursor *pCur /* Write new cursor here */ ){ - int rc; - if( iTable<1 ){ - rc = SQLITE_CORRUPT_BKPT; + if( p->sharable ){ + return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur); }else{ - sqlite3BtreeEnter(p); - rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); - sqlite3BtreeLeave(p); + return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); } - return rc; } /* @@ -65507,7 +72154,7 @@ SQLITE_PRIVATE int sqlite3BtreeCursor( ** to users so they cannot do the sizeof() themselves - they must call ** this routine. */ -SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){ +SQLITE_PRIVATE int tdsqlite3BtreeCursorSize(void){ return ROUND8(sizeof(BtCursor)); } @@ -65519,21 +72166,19 @@ SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){ ** do not need to be zeroed and they are large, so we can save a lot ** of run-time by skipping the initialization of those elements. */ -SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){ - memset(p, 0, offsetof(BtCursor, iPage)); +SQLITE_PRIVATE void tdsqlite3BtreeCursorZero(BtCursor *p){ + memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT)); } /* ** Close a cursor. The read lock on the database file is released ** when the last cursor is closed. */ -SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){ +SQLITE_PRIVATE int tdsqlite3BtreeCloseCursor(BtCursor *pCur){ Btree *pBtree = pCur->pBtree; if( pBtree ){ - int i; BtShared *pBt = pCur->pBt; - sqlite3BtreeEnter(pBtree); - sqlite3BtreeClearCursor(pCur); + tdsqlite3BtreeEnter(pBtree); assert( pBt->pCursor!=0 ); if( pBt->pCursor==pCur ){ pBt->pCursor = pCur->pNext; @@ -65547,13 +72192,12 @@ SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){ pPrev = pPrev->pNext; }while( ALWAYS(pPrev) ); } - for(i=0; i<=pCur->iPage; i++){ - releasePage(pCur->apPage[i]); - } + btreeReleaseAllCursorPages(pCur); unlockBtreeIfUnused(pBt); - sqlite3_free(pCur->aOverflow); - /* sqlite3_free(pCur); */ - sqlite3BtreeLeave(pBtree); + tdsqlite3_free(pCur->aOverflow); + tdsqlite3_free(pCur->pKey); + tdsqlite3BtreeLeave(pBtree); + pCur->pBtree = 0; } return SQLITE_OK; } @@ -65567,21 +72211,27 @@ SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){ ** Using this cache reduces the number of calls to btreeParseCell(). */ #ifndef NDEBUG + static int cellInfoEqual(CellInfo *a, CellInfo *b){ + if( a->nKey!=b->nKey ) return 0; + if( a->pPayload!=b->pPayload ) return 0; + if( a->nPayload!=b->nPayload ) return 0; + if( a->nLocal!=b->nLocal ) return 0; + if( a->nSize!=b->nSize ) return 0; + return 1; + } static void assertCellInfo(BtCursor *pCur){ CellInfo info; - int iPage = pCur->iPage; memset(&info, 0, sizeof(info)); - btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info); - assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 ); + btreeParseCell(pCur->pPage, pCur->ix, &info); + assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) ); } #else #define assertCellInfo(x) #endif static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){ if( pCur->info.nSize==0 ){ - int iPage = pCur->iPage; pCur->curFlags |= BTCF_ValidNKey; - btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); + btreeParseCell(pCur->pPage,pCur->ix,&pCur->info); }else{ assertCellInfo(pCur); } @@ -65593,10 +72243,14 @@ static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){ ** that is currently pointing to a row in a (non-empty) table. ** This is a verification routine is used only within assert() statements. */ -SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){ +SQLITE_PRIVATE int tdsqlite3BtreeCursorIsValid(BtCursor *pCur){ return pCur && pCur->eState==CURSOR_VALID; } #endif /* NDEBUG */ +SQLITE_PRIVATE int tdsqlite3BtreeCursorIsValidNN(BtCursor *pCur){ + assert( pCur!=0 ); + return pCur->eState==CURSOR_VALID; +} /* ** Return the value of the integer key or "rowid" for a table btree. @@ -65604,7 +72258,7 @@ SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){ ** ordinary table btree. If the cursor points to an index btree or ** is invalid, the result of this routine is undefined. */ -SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){ +SQLITE_PRIVATE i64 tdsqlite3BtreeIntegerKey(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->curIntKey ); @@ -65613,6 +72267,32 @@ SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){ } /* +** Pin or unpin a cursor. +*/ +SQLITE_PRIVATE void tdsqlite3BtreeCursorPin(BtCursor *pCur){ + assert( (pCur->curFlags & BTCF_Pinned)==0 ); + pCur->curFlags |= BTCF_Pinned; +} +SQLITE_PRIVATE void tdsqlite3BtreeCursorUnpin(BtCursor *pCur){ + assert( (pCur->curFlags & BTCF_Pinned)!=0 ); + pCur->curFlags &= ~BTCF_Pinned; +} + +#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC +/* +** Return the offset into the database file for the start of the +** payload to which the cursor is pointing. +*/ +SQLITE_PRIVATE i64 tdsqlite3BtreeOffset(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + getCellInfo(pCur); + return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) + + (i64)(pCur->info.pPayload - pCur->pPage->aData); +} +#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */ + +/* ** Return the number of bytes of payload for the entry that pCur is ** currently pointing to. For table btrees, this will be the amount ** of data. For index btrees, this will be the size of the key. @@ -65621,7 +72301,7 @@ SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){ ** valid entry. In other words, the calling procedure must guarantee ** that the cursor has Cursor.eState==CURSOR_VALID. */ -SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){ +SQLITE_PRIVATE u32 tdsqlite3BtreePayloadSize(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); assert( pCur->eState==CURSOR_VALID ); getCellInfo(pCur); @@ -65629,6 +72309,25 @@ SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){ } /* +** Return an upper bound on the size of any record for the table +** that the cursor is pointing into. +** +** This is an optimization. Everything will still work if this +** routine always returns 2147483647 (which is the largest record +** that SQLite can handle) or more. But returning a smaller value might +** prevent large memory allocations when trying to interpret a +** corrupt datrabase. +** +** The current implementation merely returns the size of the underlying +** database file. +*/ +SQLITE_PRIVATE tdsqlite3_int64 tdsqlite3BtreeMaxRecordSize(BtCursor *pCur){ + assert( cursorHoldsMutex(pCur) ); + assert( pCur->eState==CURSOR_VALID ); + return pCur->pBt->pageSize * (tdsqlite3_int64)pCur->pBt->nPage; +} + +/* ** Given the page number of an overflow page in the database (parameter ** ovfl), this function finds the page number of the next page in the ** linked list of overflow pages. If possible, it uses the auto-vacuum @@ -65657,7 +72356,7 @@ static int getOverflowPage( MemPage *pPage = 0; int rc = SQLITE_OK; - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); assert(pPgnoNext); #ifndef SQLITE_OMIT_AUTOVACUUM @@ -65710,7 +72409,7 @@ static int getOverflowPage( ** pPayload is a pointer to data stored on database page pDbPage. ** If argument eOp is false, then nByte bytes of data are copied ** from pPayload to the buffer pointed at by pBuf. If eOp is true, -** then sqlite3PagerWrite() is called on pDbPage and nByte bytes +** then tdsqlite3PagerWrite() is called on pDbPage and nByte bytes ** of data are copied from the buffer pBuf to pPayload. ** ** SQLITE_OK is returned on success, otherwise an error code. @@ -65724,7 +72423,7 @@ static int copyPayload( ){ if( eOp ){ /* Copy data from buffer to page (a write operation) */ - int rc = sqlite3PagerWrite(pDbPage); + int rc = tdsqlite3PagerWrite(pDbPage); if( rc!=SQLITE_OK ){ return rc; } @@ -65743,7 +72442,6 @@ static int copyPayload( ** ** 0: The operation is a read. Populate the overflow cache. ** 1: The operation is a write. Populate the overflow cache. -** 2: The operation is a read. Do not populate the overflow cache. ** ** A total of "amt" bytes are read or written beginning at "offset". ** Data is read to or from the buffer pBuf. @@ -65751,13 +72449,13 @@ static int copyPayload( ** The content being read or written might appear on the main page ** or be scattered out on multiple overflow pages. ** -** If the current cursor entry uses one or more overflow pages and the -** eOp argument is not 2, this function may allocate space for and lazily -** populates the overflow page-list cache array (BtCursor.aOverflow). +** If the current cursor entry uses one or more overflow pages +** this function may allocate space for and lazily populate +** the overflow page-list cache array (BtCursor.aOverflow). ** Subsequent calls use this cache to make seeking to the supplied offset ** more efficient. ** -** Once an overflow page-list cache has been allocated, it may be +** Once an overflow page-list cache has been allocated, it must be ** invalidated if some other cursor writes to the same table, or if ** the cursor is moved to a different row. Additionally, in auto-vacuum ** mode, the following events may invalidate an overflow page-list cache. @@ -65776,24 +72474,20 @@ static int accessPayload( unsigned char *aPayload; int rc = SQLITE_OK; int iIdx = 0; - MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */ + MemPage *pPage = pCur->pPage; /* Btree page of current entry */ BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ #ifdef SQLITE_DIRECT_OVERFLOW_READ - unsigned char * const pBufStart = pBuf; - int bEnd; /* True if reading to end of data */ + unsigned char * const pBufStart = pBuf; /* Start of original out buffer */ #endif assert( pPage ); + assert( eOp==0 || eOp==1 ); assert( pCur->eState==CURSOR_VALID ); - assert( pCur->aiIdx[pCur->iPage]<pPage->nCell ); + assert( pCur->ix<pPage->nCell ); assert( cursorHoldsMutex(pCur) ); - assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */ getCellInfo(pCur); aPayload = pCur->info.pPayload; -#ifdef SQLITE_DIRECT_OVERFLOW_READ - bEnd = offset+amt==pCur->info.nPayload; -#endif assert( offset+amt <= pCur->info.nPayload ); assert( aPayload > pPage->aData ); @@ -65803,7 +72497,7 @@ static int accessPayload( ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ** but is recast into its current form to avoid integer overflow problems */ - return SQLITE_CORRUPT_BKPT; + return SQLITE_CORRUPT_PAGE(pPage); } /* Check if data must be read/written to/from the btree page itself. */ @@ -65812,7 +72506,7 @@ static int accessPayload( if( a+offset>pCur->info.nLocal ){ a = pCur->info.nLocal - offset; } - rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage); + rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); offset = 0; pBuf += a; amt -= a; @@ -65828,53 +72522,47 @@ static int accessPayload( nextPage = get4byte(&aPayload[pCur->info.nLocal]); /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. - ** Except, do not allocate aOverflow[] for eOp==2. ** ** The aOverflow[] array is sized at one entry for each overflow page ** in the overflow chain. The page number of the first overflow page is ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array ** means "not yet known" (the cache is lazily populated). */ - if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){ + if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){ int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; - if( nOvfl>pCur->nOvflAlloc ){ - Pgno *aNew = (Pgno*)sqlite3Realloc( + if( pCur->aOverflow==0 + || nOvfl*(int)sizeof(Pgno) > tdsqlite3MallocSize(pCur->aOverflow) + ){ + Pgno *aNew = (Pgno*)tdsqlite3Realloc( pCur->aOverflow, nOvfl*2*sizeof(Pgno) ); if( aNew==0 ){ - rc = SQLITE_NOMEM_BKPT; + return SQLITE_NOMEM_BKPT; }else{ - pCur->nOvflAlloc = nOvfl*2; pCur->aOverflow = aNew; } } - if( rc==SQLITE_OK ){ - memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); - pCur->curFlags |= BTCF_ValidOvfl; + memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); + pCur->curFlags |= BTCF_ValidOvfl; + }else{ + /* If the overflow page-list cache has been allocated and the + ** entry for the first required overflow page is valid, skip + ** directly to it. + */ + if( pCur->aOverflow[offset/ovflSize] ){ + iIdx = (offset/ovflSize); + nextPage = pCur->aOverflow[iIdx]; + offset = (offset%ovflSize); } } - /* If the overflow page-list cache has been allocated and the - ** entry for the first required overflow page is valid, skip - ** directly to it. - */ - if( (pCur->curFlags & BTCF_ValidOvfl)!=0 - && pCur->aOverflow[offset/ovflSize] - ){ - iIdx = (offset/ovflSize); - nextPage = pCur->aOverflow[iIdx]; - offset = (offset%ovflSize); - } - - for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){ - + assert( rc==SQLITE_OK && amt>0 ); + while( nextPage ){ /* If required, populate the overflow page-list cache. */ - if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){ - assert( pCur->aOverflow[iIdx]==0 - || pCur->aOverflow[iIdx]==nextPage - || CORRUPT_DB ); - pCur->aOverflow[iIdx] = nextPage; - } + assert( pCur->aOverflow[iIdx]==0 + || pCur->aOverflow[iIdx]==nextPage + || CORRUPT_DB ); + pCur->aOverflow[iIdx] = nextPage; if( offset>=ovflSize ){ /* The only reason to read this page is to obtain the page @@ -65882,11 +72570,7 @@ static int accessPayload( ** data is not required. So first try to lookup the overflow ** page-list cache, if any, then fall back to the getOverflowPage() ** function. - ** - ** Note that the aOverflow[] array must be allocated because eOp!=2 - ** here. If eOp==2, then offset==0 and this branch is never taken. */ - assert( eOp!=2 ); assert( pCur->curFlags & BTCF_ValidOvfl ); assert( pCur->pBtree->db==pBt->db ); if( pCur->aOverflow[iIdx+1] ){ @@ -65899,9 +72583,6 @@ static int accessPayload( /* Need to read this page properly. It contains some of the ** range of data that is being read (eOp==0) or written (eOp!=0). */ -#ifdef SQLITE_DIRECT_OVERFLOW_READ - sqlite3_file *fd; -#endif int a = amt; if( a + offset > ovflSize ){ a = ovflSize - offset; @@ -65912,29 +72593,27 @@ static int accessPayload( ** ** 1) this is a read operation, and ** 2) data is required from the start of this overflow page, and - ** 3) the database is file-backed, and - ** 4) there is no open write-transaction, and - ** 5) the database is not a WAL database, - ** 6) all data from the page is being read. - ** 7) at least 4 bytes have already been read into the output buffer + ** 3) there are no dirty pages in the page-cache + ** 4) the database is file-backed, and + ** 5) the page is not in the WAL file + ** 6) at least 4 bytes have already been read into the output buffer ** ** then data can be read directly from the database file into the ** output buffer, bypassing the page-cache altogether. This speeds ** up loading large records that span many overflow pages. */ - if( (eOp&0x01)==0 /* (1) */ + if( eOp==0 /* (1) */ && offset==0 /* (2) */ - && (bEnd || a==ovflSize) /* (6) */ - && pBt->inTransaction==TRANS_READ /* (4) */ - && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */ - && 0==sqlite3PagerUseWal(pBt->pPager) /* (5) */ - && &pBuf[-4]>=pBufStart /* (7) */ + && tdsqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */ + && &pBuf[-4]>=pBufStart /* (6) */ ){ + tdsqlite3_file *fd = tdsqlite3PagerFile(pBt->pPager); u8 aSave[4]; u8 *aWrite = &pBuf[-4]; - assert( aWrite>=pBufStart ); /* hence (7) */ + assert( aWrite>=pBufStart ); /* due to (6) */ memcpy(aSave, aWrite, 4); - rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); + rc = tdsqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); + if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT; nextPage = get4byte(aWrite); memcpy(aWrite, aSave, 4); }else @@ -65942,77 +72621,87 @@ static int accessPayload( { DbPage *pDbPage; - rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, - ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0) + rc = tdsqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, + (eOp==0 ? PAGER_GET_READONLY : 0) ); if( rc==SQLITE_OK ){ - aPayload = sqlite3PagerGetData(pDbPage); + aPayload = tdsqlite3PagerGetData(pDbPage); nextPage = get4byte(aPayload); - rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage); - sqlite3PagerUnref(pDbPage); + rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); + tdsqlite3PagerUnref(pDbPage); offset = 0; } } amt -= a; + if( amt==0 ) return rc; pBuf += a; } + if( rc ) break; + iIdx++; } } if( rc==SQLITE_OK && amt>0 ){ - return SQLITE_CORRUPT_BKPT; + /* Overflow chain ends prematurely */ + return SQLITE_CORRUPT_PAGE(pPage); } return rc; } /* -** Read part of the key associated with cursor pCur. Exactly -** "amt" bytes will be transferred into pBuf[]. The transfer +** Read part of the payload for the row at which that cursor pCur is currently +** pointing. "amt" bytes will be transferred into pBuf[]. The transfer ** begins at "offset". ** -** The caller must ensure that pCur is pointing to a valid row -** in the table. +** pCur can be pointing to either a table or an index b-tree. +** If pointing to a table btree, then the content section is read. If +** pCur is pointing to an index b-tree then the key section is read. +** +** For tdsqlite3BtreePayload(), the caller must ensure that pCur is pointing +** to a valid row in the table. For tdsqlite3BtreePayloadChecked(), the +** cursor might be invalid or might need to be restored before being read. ** ** Return SQLITE_OK on success or an error code if anything goes ** wrong. An error is returned if "offset+amt" is larger than ** the available payload. */ -SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ +SQLITE_PRIVATE int tdsqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ assert( cursorHoldsMutex(pCur) ); assert( pCur->eState==CURSOR_VALID ); - assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); - assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); + assert( pCur->iPage>=0 && pCur->pPage ); + assert( pCur->ix<pCur->pPage->nCell ); return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); } /* -** Read part of the data associated with cursor pCur. Exactly -** "amt" bytes will be transfered into pBuf[]. The transfer -** begins at "offset". -** -** Return SQLITE_OK on success or an error code if anything goes -** wrong. An error is returned if "offset+amt" is larger than -** the available payload. +** This variant of tdsqlite3BtreePayload() works even if the cursor has not +** in the CURSOR_VALID state. It is only used by the tdsqlite3_blob_read() +** interface. */ -SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ - int rc; - #ifndef SQLITE_OMIT_INCRBLOB +static SQLITE_NOINLINE int accessPayloadChecked( + BtCursor *pCur, + u32 offset, + u32 amt, + void *pBuf +){ + int rc; if ( pCur->eState==CURSOR_INVALID ){ return SQLITE_ABORT; } -#endif - assert( cursorOwnsBtShared(pCur) ); - rc = restoreCursorPosition(pCur); - if( rc==SQLITE_OK ){ - assert( pCur->eState==CURSOR_VALID ); - assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); - assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); - rc = accessPayload(pCur, offset, amt, pBuf, 0); + rc = btreeRestoreCursorPosition(pCur); + return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0); +} +SQLITE_PRIVATE int tdsqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ + if( pCur->eState==CURSOR_VALID ){ + assert( cursorOwnsBtShared(pCur) ); + return accessPayload(pCur, offset, amt, pBuf, 0); + }else{ + return accessPayloadChecked(pCur, offset, amt, pBuf); } - return rc; } +#endif /* SQLITE_OMIT_INCRBLOB */ /* ** Return a pointer to payload information from the entry that the @@ -66037,18 +72726,23 @@ static const void *fetchPayload( BtCursor *pCur, /* Cursor pointing to entry to read from */ u32 *pAmt /* Write the number of available bytes here */ ){ - u32 amt; - assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]); + int amt; + assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage); assert( pCur->eState==CURSOR_VALID ); - assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( tdsqlite3_mutex_held(pCur->pBtree->db->mutex) ); assert( cursorOwnsBtShared(pCur) ); - assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); + assert( pCur->ix<pCur->pPage->nCell ); assert( pCur->info.nSize>0 ); - assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB ); - assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB); - amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload); - if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal; - *pAmt = amt; + assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB ); + assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB); + amt = pCur->info.nLocal; + if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){ + /* There is too little space on the page for the expected amount + ** of local content. Database must be corrupt. */ + assert( CORRUPT_DB ); + amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload)); + } + *pAmt = (u32)amt; return (void*)pCur->info.pPayload; } @@ -66067,7 +72761,7 @@ static const void *fetchPayload( ** These routines is used to get quick access to key and data ** in the common case where no overflow pages are used. */ -SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){ +SQLITE_PRIVATE const void *tdsqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){ return fetchPayload(pCur, pAmt); } @@ -66093,13 +72787,14 @@ static int moveToChild(BtCursor *pCur, u32 newPgno){ } pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); + pCur->aiIdx[pCur->iPage] = pCur->ix; + pCur->apPage[pCur->iPage] = pCur->pPage; + pCur->ix = 0; pCur->iPage++; - pCur->aiIdx[pCur->iPage] = 0; - return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage], - pCur, pCur->curPagerFlags); + return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags); } -#if SQLITE_DEBUG +#ifdef SQLITE_DEBUG /* ** Page pParent is an internal (non-leaf) tree page. This function ** asserts that page number iChild is the left-child if the iIdx'th @@ -66130,19 +72825,23 @@ static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ ** the largest cell index. */ static void moveToParent(BtCursor *pCur){ + MemPage *pLeaf; assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); assert( pCur->iPage>0 ); - assert( pCur->apPage[pCur->iPage] ); + assert( pCur->pPage ); assertParentIndex( pCur->apPage[pCur->iPage-1], pCur->aiIdx[pCur->iPage-1], - pCur->apPage[pCur->iPage]->pgno + pCur->pPage->pgno ); testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); - releasePageNotNull(pCur->apPage[pCur->iPage--]); + pCur->ix = pCur->aiIdx[pCur->iPage-1]; + pLeaf = pCur->pPage; + pCur->pPage = pCur->apPage[--pCur->iPage]; + releasePageNotNull(pLeaf); } /* @@ -66154,9 +72853,9 @@ static void moveToParent(BtCursor *pCur){ ** single child page. This can only happen with the table rooted at page 1. ** ** If the b-tree structure is empty, the cursor state is set to -** CURSOR_INVALID. Otherwise, the cursor is set to point to the first -** cell located on the root (or virtual root) page and the cursor state -** is set to CURSOR_VALID. +** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise, +** the cursor is set to point to the first cell located on the root +** (or virtual root) page and the cursor state is set to CURSOR_VALID. ** ** If this function returns successfully, it may be assumed that the ** page-header flags indicate that the [virtual] root-page is the expected @@ -66174,34 +72873,40 @@ static int moveToRoot(BtCursor *pCur){ assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); - if( pCur->eState>=CURSOR_REQUIRESEEK ){ - if( pCur->eState==CURSOR_FAULT ){ - assert( pCur->skipNext!=SQLITE_OK ); - return pCur->skipNext; - } - sqlite3BtreeClearCursor(pCur); - } + assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 ); + assert( pCur->pgnoRoot>0 || pCur->iPage<0 ); if( pCur->iPage>=0 ){ - while( pCur->iPage ){ - assert( pCur->apPage[pCur->iPage]!=0 ); - releasePageNotNull(pCur->apPage[pCur->iPage--]); + if( pCur->iPage ){ + releasePageNotNull(pCur->pPage); + while( --pCur->iPage ){ + releasePageNotNull(pCur->apPage[pCur->iPage]); + } + pCur->pPage = pCur->apPage[0]; + goto skip_init; } }else if( pCur->pgnoRoot==0 ){ pCur->eState = CURSOR_INVALID; - return SQLITE_OK; + return SQLITE_EMPTY; }else{ assert( pCur->iPage==(-1) ); - rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0], + if( pCur->eState>=CURSOR_REQUIRESEEK ){ + if( pCur->eState==CURSOR_FAULT ){ + assert( pCur->skipNext!=SQLITE_OK ); + return pCur->skipNext; + } + tdsqlite3BtreeClearCursor(pCur); + } + rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage, 0, pCur->curPagerFlags); if( rc!=SQLITE_OK ){ pCur->eState = CURSOR_INVALID; return rc; } pCur->iPage = 0; - pCur->curIntKey = pCur->apPage[0]->intKey; + pCur->curIntKey = pCur->pPage->intKey; } - pRoot = pCur->apPage[0]; + pRoot = pCur->pPage; assert( pRoot->pgno==pCur->pgnoRoot ); /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor @@ -66216,13 +72921,15 @@ static int moveToRoot(BtCursor *pCur){ ** (or the freelist). */ assert( pRoot->intKey==1 || pRoot->intKey==0 ); if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){ - return SQLITE_CORRUPT_BKPT; + return SQLITE_CORRUPT_PAGE(pCur->pPage); } - pCur->aiIdx[0] = 0; +skip_init: + pCur->ix = 0; pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl); + pRoot = pCur->pPage; if( pRoot->nCell>0 ){ pCur->eState = CURSOR_VALID; }else if( !pRoot->leaf ){ @@ -66233,6 +72940,7 @@ static int moveToRoot(BtCursor *pCur){ rc = moveToChild(pCur, subpage); }else{ pCur->eState = CURSOR_INVALID; + rc = SQLITE_EMPTY; } return rc; } @@ -66251,9 +72959,9 @@ static int moveToLeftmost(BtCursor *pCur){ assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); - while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){ - assert( pCur->aiIdx[pCur->iPage]<pPage->nCell ); - pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage])); + while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){ + assert( pCur->ix<pPage->nCell ); + pgno = get4byte(findCell(pPage, pCur->ix)); rc = moveToChild(pCur, pgno); } return rc; @@ -66276,13 +72984,13 @@ static int moveToRightmost(BtCursor *pCur){ assert( cursorOwnsBtShared(pCur) ); assert( pCur->eState==CURSOR_VALID ); - while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){ + while( !(pPage = pCur->pPage)->leaf ){ pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); - pCur->aiIdx[pCur->iPage] = pPage->nCell; + pCur->ix = pPage->nCell; rc = moveToChild(pCur, pgno); if( rc ) return rc; } - pCur->aiIdx[pCur->iPage] = pPage->nCell-1; + pCur->ix = pPage->nCell-1; assert( pCur->info.nSize==0 ); assert( (pCur->curFlags & BTCF_ValidNKey)==0 ); return SQLITE_OK; @@ -66292,21 +73000,20 @@ static int moveToRightmost(BtCursor *pCur){ ** on success. Set *pRes to 0 if the cursor actually points to something ** or set *pRes to 1 if the table is empty. */ -SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ +SQLITE_PRIVATE int tdsqlite3BtreeFirst(BtCursor *pCur, int *pRes){ int rc; assert( cursorOwnsBtShared(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( tdsqlite3_mutex_held(pCur->pBtree->db->mutex) ); rc = moveToRoot(pCur); if( rc==SQLITE_OK ){ - if( pCur->eState==CURSOR_INVALID ){ - assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); - *pRes = 1; - }else{ - assert( pCur->apPage[pCur->iPage]->nCell>0 ); - *pRes = 0; - rc = moveToLeftmost(pCur); - } + assert( pCur->pPage->nCell>0 ); + *pRes = 0; + rc = moveToLeftmost(pCur); + }else if( rc==SQLITE_EMPTY ){ + assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); + *pRes = 1; + rc = SQLITE_OK; } return rc; } @@ -66315,11 +73022,11 @@ SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ ** on success. Set *pRes to 0 if the cursor actually points to something ** or set *pRes to 1 if the table is empty. */ -SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ +SQLITE_PRIVATE int tdsqlite3BtreeLast(BtCursor *pCur, int *pRes){ int rc; assert( cursorOwnsBtShared(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( tdsqlite3_mutex_held(pCur->pBtree->db->mutex) ); /* If the cursor already points to the last entry, this is a no-op. */ if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){ @@ -66330,28 +73037,27 @@ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ for(ii=0; ii<pCur->iPage; ii++){ assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); } - assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 ); - assert( pCur->apPage[pCur->iPage]->leaf ); + assert( pCur->ix==pCur->pPage->nCell-1 ); + assert( pCur->pPage->leaf ); #endif + *pRes = 0; return SQLITE_OK; } rc = moveToRoot(pCur); if( rc==SQLITE_OK ){ - if( CURSOR_INVALID==pCur->eState ){ - assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); - *pRes = 1; + assert( pCur->eState==CURSOR_VALID ); + *pRes = 0; + rc = moveToRightmost(pCur); + if( rc==SQLITE_OK ){ + pCur->curFlags |= BTCF_AtLast; }else{ - assert( pCur->eState==CURSOR_VALID ); - *pRes = 0; - rc = moveToRightmost(pCur); - if( rc==SQLITE_OK ){ - pCur->curFlags |= BTCF_AtLast; - }else{ - pCur->curFlags &= ~BTCF_AtLast; - } - + pCur->curFlags &= ~BTCF_AtLast; } + }else if( rc==SQLITE_EMPTY ){ + assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); + *pRes = 1; + rc = SQLITE_OK; } return rc; } @@ -66386,7 +73092,7 @@ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ ** For index tables, the pIdxKey->eqSeen field is set to 1 if there ** exists an entry in the table that exactly matches pIdxKey. */ -SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( +SQLITE_PRIVATE int tdsqlite3BtreeMovetoUnpacked( BtCursor *pCur, /* The cursor to be moved */ UnpackedRecord *pIdxKey, /* Unpacked index key */ i64 intKey, /* The table key */ @@ -66397,7 +73103,7 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( RecordCompare xRecordCompare; assert( cursorOwnsBtShared(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + assert( tdsqlite3_mutex_held(pCur->pBtree->db->mutex) ); assert( pRes ); assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) ); @@ -66411,14 +73117,34 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( *pRes = 0; return SQLITE_OK; } - if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){ - *pRes = -1; - return SQLITE_OK; + if( pCur->info.nKey<intKey ){ + if( (pCur->curFlags & BTCF_AtLast)!=0 ){ + *pRes = -1; + return SQLITE_OK; + } + /* If the requested key is one more than the previous key, then + ** try to get there using tdsqlite3BtreeNext() rather than a full + ** binary search. This is an optimization only. The correct answer + ** is still obtained without this case, only a little more slowely */ + if( pCur->info.nKey+1==intKey ){ + *pRes = 0; + rc = tdsqlite3BtreeNext(pCur, 0); + if( rc==SQLITE_OK ){ + getCellInfo(pCur); + if( pCur->info.nKey==intKey ){ + return SQLITE_OK; + } + }else if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + }else{ + return rc; + } + } } } if( pIdxKey ){ - xRecordCompare = sqlite3VdbeFindCompare(pIdxKey); + xRecordCompare = tdsqlite3VdbeFindCompare(pIdxKey); pIdxKey->errCode = 0; assert( pIdxKey->default_rc==1 || pIdxKey->default_rc==0 @@ -66430,22 +73156,23 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( rc = moveToRoot(pCur); if( rc ){ + if( rc==SQLITE_EMPTY ){ + assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); + *pRes = -1; + return SQLITE_OK; + } return rc; } - assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] ); - assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit ); - assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 ); - if( pCur->eState==CURSOR_INVALID ){ - *pRes = -1; - assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); - return SQLITE_OK; - } - assert( pCur->apPage[0]->intKey==pCur->curIntKey ); + assert( pCur->pPage ); + assert( pCur->pPage->isInit ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->pPage->nCell > 0 ); + assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey ); assert( pCur->curIntKey || pIdxKey ); for(;;){ int lwr, upr, idx, c; Pgno chldPg; - MemPage *pPage = pCur->apPage[pCur->iPage]; + MemPage *pPage = pCur->pPage; u8 *pCell; /* Pointer to current cell in pPage */ /* pPage->nCell must be greater than zero. If this is the root-page @@ -66460,14 +73187,16 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( upr = pPage->nCell-1; assert( biasRight==0 || biasRight==1 ); idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */ - pCur->aiIdx[pCur->iPage] = (u16)idx; + pCur->ix = (u16)idx; if( xRecordCompare==0 ){ for(;;){ i64 nCellKey; pCell = findCellPastPtr(pPage, idx); if( pPage->intKeyLeaf ){ while( 0x80 <= *(pCell++) ){ - if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT; + if( pCell>=pPage->aDataEnd ){ + return SQLITE_CORRUPT_PAGE(pPage); + } } } getVarint(pCell, (u64*)&nCellKey); @@ -66479,16 +73208,16 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( if( lwr>upr ){ c = +1; break; } }else{ assert( nCellKey==intKey ); - pCur->curFlags |= BTCF_ValidNKey; - pCur->info.nKey = nCellKey; - pCur->aiIdx[pCur->iPage] = (u16)idx; + pCur->ix = (u16)idx; if( !pPage->leaf ){ lwr = idx; goto moveto_next_layer; }else{ + pCur->curFlags |= BTCF_ValidNKey; + pCur->info.nKey = nCellKey; + pCur->info.nSize = 0; *pRes = 0; - rc = SQLITE_OK; - goto moveto_finish; + return SQLITE_OK; } } assert( lwr+upr>=0 ); @@ -66533,29 +73262,32 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( ** case this happens. */ void *pCellKey; u8 * const pCellBody = pCell - pPage->childPtrSize; + const int nOverrun = 18; /* Size of the overrun padding */ pPage->xParseCell(pPage, pCellBody, &pCur->info); nCell = (int)pCur->info.nKey; testcase( nCell<0 ); /* True if key size is 2^32 or more */ testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */ testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */ testcase( nCell==2 ); /* Minimum legal index key size */ - if( nCell<2 ){ - rc = SQLITE_CORRUPT_BKPT; + if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){ + rc = SQLITE_CORRUPT_PAGE(pPage); goto moveto_finish; } - pCellKey = sqlite3Malloc( nCell+18 ); + pCellKey = tdsqlite3Malloc( nCell+nOverrun ); if( pCellKey==0 ){ rc = SQLITE_NOMEM_BKPT; goto moveto_finish; } - pCur->aiIdx[pCur->iPage] = (u16)idx; - rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2); + pCur->ix = (u16)idx; + rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); + memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */ + pCur->curFlags &= ~BTCF_ValidOvfl; if( rc ){ - sqlite3_free(pCellKey); + tdsqlite3_free(pCellKey); goto moveto_finish; } - c = xRecordCompare(nCell, pCellKey, pIdxKey); - sqlite3_free(pCellKey); + c = tdsqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); + tdsqlite3_free(pCellKey); } assert( (pIdxKey->errCode!=SQLITE_CORRUPT || c==0) @@ -66569,8 +73301,8 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( assert( c==0 ); *pRes = 0; rc = SQLITE_OK; - pCur->aiIdx[pCur->iPage] = (u16)idx; - if( pIdxKey->errCode ) rc = SQLITE_CORRUPT; + pCur->ix = (u16)idx; + if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT; goto moveto_finish; } if( lwr>upr ) break; @@ -66581,8 +73313,8 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); assert( pPage->isInit ); if( pPage->leaf ){ - assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); - pCur->aiIdx[pCur->iPage] = (u16)idx; + assert( pCur->ix<pCur->pPage->nCell ); + pCur->ix = (u16)idx; *pRes = c; rc = SQLITE_OK; goto moveto_finish; @@ -66593,13 +73325,13 @@ moveto_next_layer: }else{ chldPg = get4byte(findCell(pPage, lwr)); } - pCur->aiIdx[pCur->iPage] = (u16)lwr; + pCur->ix = (u16)lwr; rc = moveToChild(pCur, chldPg); if( rc ) break; } moveto_finish: pCur->info.nSize = 0; - pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); + assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); return rc; } @@ -66607,11 +73339,11 @@ moveto_finish: /* ** Return TRUE if the cursor is not pointing at an entry of the table. ** -** TRUE will be returned after a call to sqlite3BtreeNext() moves -** past the last entry in the table or sqlite3BtreePrev() moves past +** TRUE will be returned after a call to tdsqlite3BtreeNext() moves +** past the last entry in the table or tdsqlite3BtreePrev() moves past ** the first entry. TRUE is also returned if the table is empty. */ -SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){ +SQLITE_PRIVATE int tdsqlite3BtreeEof(BtCursor *pCur){ /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries ** have been deleted? This API will need to change to return an error code ** as well as the boolean result value. @@ -66620,34 +73352,56 @@ SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){ } /* -** Advance the cursor to the next entry in the database. If -** successful then set *pRes=0. If the cursor -** was already pointing to the last entry in the database before -** this routine was called, then set *pRes=1. +** Return an estimate for the number of rows in the table that pCur is +** pointing to. Return a negative number if no estimate is currently +** available. +*/ +SQLITE_PRIVATE i64 tdsqlite3BtreeRowCountEst(BtCursor *pCur){ + i64 n; + u8 i; + + assert( cursorOwnsBtShared(pCur) ); + assert( tdsqlite3_mutex_held(pCur->pBtree->db->mutex) ); + + /* Currently this interface is only called by the OP_IfSmaller + ** opcode, and it that case the cursor will always be valid and + ** will always point to a leaf node. */ + if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1; + if( NEVER(pCur->pPage->leaf==0) ) return -1; + + n = pCur->pPage->nCell; + for(i=0; i<pCur->iPage; i++){ + n *= pCur->apPage[i]->nCell; + } + return n; +} + +/* +** Advance the cursor to the next entry in the database. +** Return value: ** -** The main entry point is sqlite3BtreeNext(). That routine is optimized +** SQLITE_OK success +** SQLITE_DONE cursor is already pointing at the last element +** otherwise some kind of error occurred +** +** The main entry point is tdsqlite3BtreeNext(). That routine is optimized ** for the common case of merely incrementing the cell counter BtCursor.aiIdx ** to the next cell on the current page. The (slower) btreeNext() helper ** routine is called when it is necessary to move to a different page or ** to restore the cursor. ** -** The calling function will set *pRes to 0 or 1. The initial *pRes value -** will be 1 if the cursor being stepped corresponds to an SQL index and -** if this routine could have been skipped if that SQL index had been -** a unique index. Otherwise the caller will have set *pRes to zero. -** Zero is the common case. The btree implementation is free to use the -** initial *pRes value as a hint to improve performance, but the current -** SQLite btree implementation does not. (Note that the comdb2 btree -** implementation does use this hint, however.) +** If bit 0x01 of the F argument in tdsqlite3BtreeNext(C,F) is 1, then the +** cursor corresponds to an SQL index and this routine could have been +** skipped if the SQL index had been a unique index. The F argument +** is a hint to the implement. SQLite btree implementation does not use +** this hint, but COMDB2 does. */ -static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){ +static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){ int rc; int idx; MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); - assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); - assert( *pRes==0 ); if( pCur->eState!=CURSOR_VALID ){ assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); rc = restoreCursorPosition(pCur); @@ -66655,30 +73409,36 @@ static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){ return rc; } if( CURSOR_INVALID==pCur->eState ){ - *pRes = 1; - return SQLITE_OK; + return SQLITE_DONE; } - if( pCur->skipNext ){ - assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); + if( pCur->eState==CURSOR_SKIPNEXT ){ pCur->eState = CURSOR_VALID; - if( pCur->skipNext>0 ){ - pCur->skipNext = 0; - return SQLITE_OK; - } - pCur->skipNext = 0; + if( pCur->skipNext>0 ) return SQLITE_OK; } } - pPage = pCur->apPage[pCur->iPage]; - idx = ++pCur->aiIdx[pCur->iPage]; - assert( pPage->isInit ); + pPage = pCur->pPage; + idx = ++pCur->ix; + if( !pPage->isInit ){ + /* The only known way for this to happen is for there to be a + ** recursive SQL function that does a DELETE operation as part of a + ** SELECT which deletes content out from under an active cursor + ** in a corrupt database file where the table being DELETE-ed from + ** has pages in common with the table being queried. See TH3 + ** module cov1/btree78.test testcase 220 (2018-06-08) for an + ** example. */ + return SQLITE_CORRUPT_BKPT; + } /* If the database file is corrupt, it is possible for the value of idx ** to be invalid here. This can only occur if a second cursor modifies ** the page while cursor pCur is holding a reference to it. Which can ** only happen if the database is corrupt in such a way as to link the - ** page into more than one b-tree structure. */ - testcase( idx>pPage->nCell ); + ** page into more than one b-tree structure. + ** + ** Update 2019-12-23: appears to long longer be possible after the + ** addition of anotherValidCursor() condition on balance_deeper(). */ + harmless( idx>pPage->nCell ); if( idx>=pPage->nCell ){ if( !pPage->leaf ){ @@ -66688,15 +73448,14 @@ static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){ } do{ if( pCur->iPage==0 ){ - *pRes = 1; pCur->eState = CURSOR_INVALID; - return SQLITE_OK; + return SQLITE_DONE; } moveToParent(pCur); - pPage = pCur->apPage[pCur->iPage]; - }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell ); + pPage = pCur->pPage; + }while( pCur->ix>=pPage->nCell ); if( pPage->intKey ){ - return sqlite3BtreeNext(pCur, pRes); + return tdsqlite3BtreeNext(pCur, 0); }else{ return SQLITE_OK; } @@ -66707,20 +73466,18 @@ static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){ return moveToLeftmost(pCur); } } -SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ +SQLITE_PRIVATE int tdsqlite3BtreeNext(BtCursor *pCur, int flags){ MemPage *pPage; + UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */ assert( cursorOwnsBtShared(pCur) ); - assert( pRes!=0 ); - assert( *pRes==0 || *pRes==1 ); - assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); + assert( flags==0 || flags==1 ); pCur->info.nSize = 0; pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); - *pRes = 0; - if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes); - pPage = pCur->apPage[pCur->iPage]; - if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){ - pCur->aiIdx[pCur->iPage]--; - return btreeNext(pCur, pRes); + if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur); + pPage = pCur->pPage; + if( (++pCur->ix)>=pPage->nCell ){ + pCur->ix--; + return btreeNext(pCur); } if( pPage->leaf ){ return SQLITE_OK; @@ -66730,34 +73487,30 @@ SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ } /* -** Step the cursor to the back to the previous entry in the database. If -** successful then set *pRes=0. If the cursor -** was already pointing to the first entry in the database before -** this routine was called, then set *pRes=1. +** Step the cursor to the back to the previous entry in the database. +** Return values: ** -** The main entry point is sqlite3BtreePrevious(). That routine is optimized +** SQLITE_OK success +** SQLITE_DONE the cursor is already on the first element of the table +** otherwise some kind of error occurred +** +** The main entry point is tdsqlite3BtreePrevious(). That routine is optimized ** for the common case of merely decrementing the cell counter BtCursor.aiIdx ** to the previous cell on the current page. The (slower) btreePrevious() ** helper routine is called when it is necessary to move to a different page ** or to restore the cursor. ** -** The calling function will set *pRes to 0 or 1. The initial *pRes value -** will be 1 if the cursor being stepped corresponds to an SQL index and -** if this routine could have been skipped if that SQL index had been -** a unique index. Otherwise the caller will have set *pRes to zero. -** Zero is the common case. The btree implementation is free to use the -** initial *pRes value as a hint to improve performance, but the current -** SQLite btree implementation does not. (Note that the comdb2 btree -** implementation does use this hint, however.) +** If bit 0x01 of the F argument to tdsqlite3BtreePrevious(C,F) is 1, then +** the cursor corresponds to an SQL index and this routine could have been +** skipped if the SQL index had been a unique index. The F argument is a +** hint to the implement. The native SQLite btree implementation does not +** use this hint, but COMDB2 does. */ -static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){ +static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){ int rc; MemPage *pPage; assert( cursorOwnsBtShared(pCur) ); - assert( pRes!=0 ); - assert( *pRes==0 ); - assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 ); assert( pCur->info.nSize==0 ); if( pCur->eState!=CURSOR_VALID ){ @@ -66766,74 +73519,65 @@ static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){ return rc; } if( CURSOR_INVALID==pCur->eState ){ - *pRes = 1; - return SQLITE_OK; + return SQLITE_DONE; } - if( pCur->skipNext ){ - assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); + if( CURSOR_SKIPNEXT==pCur->eState ){ pCur->eState = CURSOR_VALID; - if( pCur->skipNext<0 ){ - pCur->skipNext = 0; - return SQLITE_OK; - } - pCur->skipNext = 0; + if( pCur->skipNext<0 ) return SQLITE_OK; } } - pPage = pCur->apPage[pCur->iPage]; + pPage = pCur->pPage; assert( pPage->isInit ); if( !pPage->leaf ){ - int idx = pCur->aiIdx[pCur->iPage]; + int idx = pCur->ix; rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); if( rc ) return rc; rc = moveToRightmost(pCur); }else{ - while( pCur->aiIdx[pCur->iPage]==0 ){ + while( pCur->ix==0 ){ if( pCur->iPage==0 ){ pCur->eState = CURSOR_INVALID; - *pRes = 1; - return SQLITE_OK; + return SQLITE_DONE; } moveToParent(pCur); } assert( pCur->info.nSize==0 ); - assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 ); + assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 ); - pCur->aiIdx[pCur->iPage]--; - pPage = pCur->apPage[pCur->iPage]; + pCur->ix--; + pPage = pCur->pPage; if( pPage->intKey && !pPage->leaf ){ - rc = sqlite3BtreePrevious(pCur, pRes); + rc = tdsqlite3BtreePrevious(pCur, 0); }else{ rc = SQLITE_OK; } } return rc; } -SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){ +SQLITE_PRIVATE int tdsqlite3BtreePrevious(BtCursor *pCur, int flags){ assert( cursorOwnsBtShared(pCur) ); - assert( pRes!=0 ); - assert( *pRes==0 || *pRes==1 ); - assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); - *pRes = 0; + assert( flags==0 || flags==1 ); + UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */ pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey); pCur->info.nSize = 0; if( pCur->eState!=CURSOR_VALID - || pCur->aiIdx[pCur->iPage]==0 - || pCur->apPage[pCur->iPage]->leaf==0 + || pCur->ix==0 + || pCur->pPage->leaf==0 ){ - return btreePrevious(pCur, pRes); + return btreePrevious(pCur); } - pCur->aiIdx[pCur->iPage]--; + pCur->ix--; return SQLITE_OK; } /* ** Allocate a new page from the database file. ** -** The new page is marked as dirty. (In other words, sqlite3PagerWrite() +** The new page is marked as dirty. (In other words, tdsqlite3PagerWrite() ** has already been called on the new page.) The new page has also ** been referenced and the calling routine is responsible for calling -** sqlite3PagerUnref() on the new page when it is done. +** tdsqlite3PagerUnref() on the new page when it is done. ** ** SQLITE_OK is returned on success. Any other return value indicates ** an error. *ppPage is set to NULL in the event of an error. @@ -66864,7 +73608,7 @@ static int allocateBtreePage( MemPage *pPrevTrunk = 0; Pgno mxPage; /* Total size of the database file */ - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); pPage1 = pBt->pPage1; mxPage = btreePagecount(pBt); @@ -66905,7 +73649,7 @@ static int allocateBtreePage( /* Decrement the free-list count by 1. Set iTrunk to the index of the ** first free-list trunk page. iPrevTrunk is initially 1. */ - rc = sqlite3PagerWrite(pPage1->pDbPage); + rc = tdsqlite3PagerWrite(pPage1->pDbPage); if( rc ) return rc; put4byte(&pPage1->aData[36], n-1); @@ -66929,7 +73673,7 @@ static int allocateBtreePage( } testcase( iTrunk==mxPage ); if( iTrunk>mxPage || nSearch++ > n ){ - rc = SQLITE_CORRUPT_BKPT; + rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1); }else{ rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0); } @@ -66947,7 +73691,7 @@ static int allocateBtreePage( ** So extract the trunk page itself and use it as the newly ** allocated page */ assert( pPrevTrunk==0 ); - rc = sqlite3PagerWrite(pTrunk->pDbPage); + rc = tdsqlite3PagerWrite(pTrunk->pDbPage); if( rc ){ goto end_allocate_page; } @@ -66958,7 +73702,7 @@ static int allocateBtreePage( TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); }else if( k>(u32)(pBt->usableSize/4 - 2) ){ /* Value of k is out of range. Database corruption */ - rc = SQLITE_CORRUPT_BKPT; + rc = SQLITE_CORRUPT_PGNO(iTrunk); goto end_allocate_page; #ifndef SQLITE_OMIT_AUTOVACUUM }else if( searchList @@ -66970,7 +73714,7 @@ static int allocateBtreePage( *pPgno = iTrunk; *ppPage = pTrunk; searchList = 0; - rc = sqlite3PagerWrite(pTrunk->pDbPage); + rc = tdsqlite3PagerWrite(pTrunk->pDbPage); if( rc ){ goto end_allocate_page; } @@ -66978,7 +73722,7 @@ static int allocateBtreePage( if( !pPrevTrunk ){ memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); }else{ - rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); + rc = tdsqlite3PagerWrite(pPrevTrunk->pDbPage); if( rc!=SQLITE_OK ){ goto end_allocate_page; } @@ -66992,7 +73736,7 @@ static int allocateBtreePage( MemPage *pNewTrunk; Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); if( iNewTrunk>mxPage ){ - rc = SQLITE_CORRUPT_BKPT; + rc = SQLITE_CORRUPT_PGNO(iTrunk); goto end_allocate_page; } testcase( iNewTrunk==mxPage ); @@ -67000,7 +73744,7 @@ static int allocateBtreePage( if( rc!=SQLITE_OK ){ goto end_allocate_page; } - rc = sqlite3PagerWrite(pNewTrunk->pDbPage); + rc = tdsqlite3PagerWrite(pNewTrunk->pDbPage); if( rc!=SQLITE_OK ){ releasePage(pNewTrunk); goto end_allocate_page; @@ -67010,10 +73754,10 @@ static int allocateBtreePage( memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); releasePage(pNewTrunk); if( !pPrevTrunk ){ - assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); + assert( tdsqlite3PagerIswriteable(pPage1->pDbPage) ); put4byte(&pPage1->aData[32], iNewTrunk); }else{ - rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); + rc = tdsqlite3PagerWrite(pPrevTrunk->pDbPage); if( rc ){ goto end_allocate_page; } @@ -67041,9 +73785,9 @@ static int allocateBtreePage( } }else{ int dist; - dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby); + dist = tdsqlite3AbsInt32(get4byte(&aData[8]) - nearby); for(i=1; i<k; i++){ - int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby); + int d2 = tdsqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby); if( d2<dist ){ closest = i; dist = d2; @@ -67057,7 +73801,7 @@ static int allocateBtreePage( iPage = get4byte(&aData[8+closest*4]); testcase( iPage==mxPage ); if( iPage>mxPage ){ - rc = SQLITE_CORRUPT_BKPT; + rc = SQLITE_CORRUPT_PGNO(iTrunk); goto end_allocate_page; } testcase( iPage==mxPage ); @@ -67069,7 +73813,7 @@ static int allocateBtreePage( TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d" ": %d more free pages\n", *pPgno, closest+1, k, pTrunk->pgno, n-1)); - rc = sqlite3PagerWrite(pTrunk->pDbPage); + rc = tdsqlite3PagerWrite(pTrunk->pDbPage); if( rc ) goto end_allocate_page; if( closest<k-1 ){ memcpy(&aData[8+closest*4], &aData[4+k*4], 4); @@ -67078,7 +73822,7 @@ static int allocateBtreePage( noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0; rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent); if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite((*ppPage)->pDbPage); + rc = tdsqlite3PagerWrite((*ppPage)->pDbPage); if( rc!=SQLITE_OK ){ releasePage(*ppPage); *ppPage = 0; @@ -67111,7 +73855,7 @@ static int allocateBtreePage( */ int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0; - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + rc = tdsqlite3PagerWrite(pBt->pPage1->pDbPage); if( rc ) return rc; pBt->nPage++; if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; @@ -67127,7 +73871,7 @@ static int allocateBtreePage( assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent); if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite(pPg->pDbPage); + rc = tdsqlite3PagerWrite(pPg->pDbPage); releasePage(pPg); } if( rc ) return rc; @@ -67141,7 +73885,7 @@ static int allocateBtreePage( assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent); if( rc ) return rc; - rc = sqlite3PagerWrite((*ppPage)->pDbPage); + rc = tdsqlite3PagerWrite((*ppPage)->pDbPage); if( rc!=SQLITE_OK ){ releasePage(*ppPage); *ppPage = 0; @@ -67149,12 +73893,12 @@ static int allocateBtreePage( TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); } - assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); + assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) ); end_allocate_page: releasePage(pTrunk); releasePage(pPrevTrunk); - assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 ); + assert( rc!=SQLITE_OK || tdsqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 ); assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 ); return rc; } @@ -67177,22 +73921,24 @@ static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ MemPage *pPage; /* Page being freed. May be NULL. */ int rc; /* Return Code */ - int nFree; /* Initial number of pages on free-list */ + u32 nFree; /* Initial number of pages on free-list */ - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); assert( CORRUPT_DB || iPage>1 ); assert( !pMemPage || pMemPage->pgno==iPage ); - if( iPage<2 ) return SQLITE_CORRUPT_BKPT; + if( iPage<2 || iPage>pBt->nPage ){ + return SQLITE_CORRUPT_BKPT; + } if( pMemPage ){ pPage = pMemPage; - sqlite3PagerRef(pPage->pDbPage); + tdsqlite3PagerRef(pPage->pDbPage); }else{ pPage = btreePageLookup(pBt, iPage); } /* Increment the free page count on pPage1 */ - rc = sqlite3PagerWrite(pPage1->pDbPage); + rc = tdsqlite3PagerWrite(pPage1->pDbPage); if( rc ) goto freepage_out; nFree = get4byte(&pPage1->aData[36]); put4byte(&pPage1->aData[36], nFree+1); @@ -67202,7 +73948,7 @@ static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ ** always fully overwrite deleted information with zeros. */ if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) - || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) + || ((rc = tdsqlite3PagerWrite(pPage->pDbPage))!=0) ){ goto freepage_out; } @@ -67259,12 +74005,12 @@ static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ ** order that database files created by newer versions of SQLite can be ** read by older versions of SQLite. */ - rc = sqlite3PagerWrite(pTrunk->pDbPage); + rc = tdsqlite3PagerWrite(pTrunk->pDbPage); if( rc==SQLITE_OK ){ put4byte(&pTrunk->aData[4], nLeaf+1); put4byte(&pTrunk->aData[8+nLeaf*4], iPage); if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ - sqlite3PagerDontWrite(pPage->pDbPage); + tdsqlite3PagerDontWrite(pPage->pDbPage); } rc = btreeSetHasContent(pBt, iPage); } @@ -67282,7 +74028,7 @@ static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ goto freepage_out; } - rc = sqlite3PagerWrite(pPage->pDbPage); + rc = tdsqlite3PagerWrite(pPage->pDbPage); if( rc!=SQLITE_OK ){ goto freepage_out; } @@ -67306,37 +74052,38 @@ static void freePage(MemPage *pPage, int *pRC){ } /* -** Free any overflow pages associated with the given Cell. Write the -** local Cell size (the number of bytes on the original page, omitting -** overflow) into *pnSize. +** Free any overflow pages associated with the given Cell. Store +** size information about the cell in pInfo. */ static int clearCell( MemPage *pPage, /* The page that contains the Cell */ unsigned char *pCell, /* First byte of the Cell */ - u16 *pnSize /* Write the size of the Cell here */ + CellInfo *pInfo /* Size information about the cell */ ){ - BtShared *pBt = pPage->pBt; - CellInfo info; + BtShared *pBt; Pgno ovflPgno; int rc; int nOvfl; u32 ovflPageSize; - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - pPage->xParseCell(pPage, pCell, &info); - *pnSize = info.nSize; - if( info.nLocal==info.nPayload ){ + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + pPage->xParseCell(pPage, pCell, pInfo); + if( pInfo->nLocal==pInfo->nPayload ){ return SQLITE_OK; /* No overflow pages. Return without doing anything */ } - if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){ - return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */ + testcase( pCell + pInfo->nSize == pPage->aDataEnd ); + testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd ); + if( pCell + pInfo->nSize > pPage->aDataEnd ){ + /* Cell extends past end of page */ + return SQLITE_CORRUPT_PAGE(pPage); } - ovflPgno = get4byte(pCell + info.nSize - 4); + ovflPgno = get4byte(pCell + pInfo->nSize - 4); + pBt = pPage->pBt; assert( pBt->usableSize > 4 ); ovflPageSize = pBt->usableSize - 4; - nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize; + nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize; assert( nOvfl>0 || - (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize) + (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize) ); while( nOvfl-- ){ Pgno iNext = 0; @@ -67353,7 +74100,7 @@ static int clearCell( } if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) - && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 + && tdsqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 ){ /* There is no reason any cursor should have an outstanding reference ** to an overflow page belonging to a cell that is being deleted/updated. @@ -67371,7 +74118,7 @@ static int clearCell( } if( pOvfl ){ - sqlite3PagerUnref(pOvfl->pDbPage); + tdsqlite3PagerUnref(pOvfl->pDbPage); } if( rc ) return rc; ovflPgno = iNext; @@ -67399,22 +74146,21 @@ static int fillInCell( ){ int nPayload; const u8 *pSrc; - int nSrc, n, rc; + int nSrc, n, rc, mn; int spaceLeft; - MemPage *pOvfl = 0; - MemPage *pToRelease = 0; + MemPage *pToRelease; unsigned char *pPrior; unsigned char *pPayload; - BtShared *pBt = pPage->pBt; - Pgno pgnoOvfl = 0; + BtShared *pBt; + Pgno pgnoOvfl; int nHeader; - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); /* pPage is not necessarily writeable since pCell might be auxiliary ** buffer space that is separate from the pPage buffer area */ - assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize] - || sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize] + || tdsqlite3PagerIswriteable(pPage->pDbPage) ); /* Fill in the header. */ nHeader = pPage->childPtrSize; @@ -67433,25 +74179,36 @@ static int fillInCell( } /* Fill in the payload */ + pPayload = &pCell[nHeader]; if( nPayload<=pPage->maxLocal ){ + /* This is the common case where everything fits on the btree page + ** and no overflow pages are required. */ n = nHeader + nPayload; testcase( n==3 ); testcase( n==4 ); if( n<4 ) n = 4; *pnSize = n; - spaceLeft = nPayload; - pPrior = pCell; - }else{ - int mn = pPage->minLocal; - n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); - testcase( n==pPage->maxLocal ); - testcase( n==pPage->maxLocal+1 ); - if( n > pPage->maxLocal ) n = mn; - spaceLeft = n; - *pnSize = n + nHeader + 4; - pPrior = &pCell[nHeader+n]; + assert( nSrc<=nPayload ); + testcase( nSrc<nPayload ); + memcpy(pPayload, pSrc, nSrc); + memset(pPayload+nSrc, 0, nPayload-nSrc); + return SQLITE_OK; } - pPayload = &pCell[nHeader]; + + /* If we reach this point, it means that some of the content will need + ** to spill onto overflow pages. + */ + mn = pPage->minLocal; + n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); + testcase( n==pPage->maxLocal ); + testcase( n==pPage->maxLocal+1 ); + if( n > pPage->maxLocal ) n = mn; + spaceLeft = n; + *pnSize = n + nHeader + 4; + pPrior = &pCell[nHeader+n]; + pToRelease = 0; + pgnoOvfl = 0; + pBt = pPage->pBt; /* At this point variables should be set as follows: ** @@ -67465,7 +74222,7 @@ static int fillInCell( ** Use a call to btreeParseCellPtr() to verify that the values above ** were computed correctly. */ -#if SQLITE_DEBUG +#ifdef SQLITE_DEBUG { CellInfo info; pPage->xParseCell(pPage, pCell, &info); @@ -67477,8 +74234,35 @@ static int fillInCell( #endif /* Write the payload into the local Cell and any extra into overflow pages */ - while( nPayload>0 ){ + while( 1 ){ + n = nPayload; + if( n>spaceLeft ) n = spaceLeft; + + /* If pToRelease is not zero than pPayload points into the data area + ** of pToRelease. Make sure pToRelease is still writeable. */ + assert( pToRelease==0 || tdsqlite3PagerIswriteable(pToRelease->pDbPage) ); + + /* If pPayload is part of the data area of pPage, then make sure pPage + ** is still writeable */ + assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize] + || tdsqlite3PagerIswriteable(pPage->pDbPage) ); + + if( nSrc>=n ){ + memcpy(pPayload, pSrc, n); + }else if( nSrc>0 ){ + n = nSrc; + memcpy(pPayload, pSrc, n); + }else{ + memset(pPayload, 0, n); + } + nPayload -= n; + if( nPayload<=0 ) break; + pPayload += n; + pSrc += n; + nSrc -= n; + spaceLeft -= n; if( spaceLeft==0 ){ + MemPage *pOvfl = 0; #ifndef SQLITE_OMIT_AUTOVACUUM Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ if( pBt->autoVacuum ){ @@ -67516,12 +74300,12 @@ static int fillInCell( /* If pToRelease is not zero than pPrior points into the data area ** of pToRelease. Make sure pToRelease is still writeable. */ - assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); + assert( pToRelease==0 || tdsqlite3PagerIswriteable(pToRelease->pDbPage) ); /* If pPrior is part of the data area of pPage, then make sure pPage ** is still writeable */ assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize] - || sqlite3PagerIswriteable(pPage->pDbPage) ); + || tdsqlite3PagerIswriteable(pPage->pDbPage) ); put4byte(pPrior, pgnoOvfl); releasePage(pToRelease); @@ -67531,30 +74315,6 @@ static int fillInCell( pPayload = &pOvfl->aData[4]; spaceLeft = pBt->usableSize - 4; } - n = nPayload; - if( n>spaceLeft ) n = spaceLeft; - - /* If pToRelease is not zero than pPayload points into the data area - ** of pToRelease. Make sure pToRelease is still writeable. */ - assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); - - /* If pPayload is part of the data area of pPage, then make sure pPage - ** is still writeable */ - assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize] - || sqlite3PagerIswriteable(pPage->pDbPage) ); - - if( nSrc>0 ){ - if( n>nSrc ) n = nSrc; - assert( pSrc ); - memcpy(pPayload, pSrc, n); - }else{ - memset(pPayload, 0, n); - } - nPayload -= n; - pPayload += n; - pSrc += n; - nSrc -= n; - spaceLeft -= n; } releasePage(pToRelease); return SQLITE_OK; @@ -67576,18 +74336,18 @@ static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ if( *pRC ) return; - assert( idx>=0 && idx<pPage->nCell ); assert( CORRUPT_DB || sz==cellSize(pPage, idx) ); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3PagerIswriteable(pPage->pDbPage) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + assert( pPage->nFree>=0 ); data = pPage->aData; ptr = &pPage->aCellIdx[2*idx]; pc = get2byte(ptr); hdr = pPage->hdrOffset; testcase( pc==get2byte(&data[hdr+5]) ); testcase( pc+sz==pPage->pBt->usableSize ); - if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){ + if( pc+sz > pPage->pBt->usableSize ){ *pRC = SQLITE_CORRUPT_BKPT; return; } @@ -67644,13 +74404,9 @@ static void insertCell( assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB ); assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - /* The cell should normally be sized correctly. However, when moving a - ** malformed cell from a leaf page to an interior page, if the cell size - ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size - ** might be less than 8 (leaf-size + pointer) on the interior node. Hence - ** the term after the || in the following assert(). */ - assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB ); + assert( pPage->nFree>=0 ); if( pPage->nOverflow || sz+2>pPage->nFree ){ if( pTemp ){ memcpy(pTemp, pCell, sz); @@ -67660,7 +74416,10 @@ static void insertCell( put4byte(pCell, iChild); } j = pPage->nOverflow++; - assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) ); + /* Comparison against ArraySize-1 since we hold back one extra slot + ** as a contingency. In other words, never need more than 3 overflow + ** slots but 4 are allocated, just to be safe. */ + assert( j < ArraySize(pPage->apOvfl)-1 ); pPage->apOvfl[j] = pCell; pPage->aiOvfl[j] = (u16)i; @@ -67672,12 +74431,12 @@ static void insertCell( assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */ assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */ }else{ - int rc = sqlite3PagerWrite(pPage->pDbPage); + int rc = tdsqlite3PagerWrite(pPage->pDbPage); if( rc!=SQLITE_OK ){ *pRC = rc; return; } - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); + assert( tdsqlite3PagerIswriteable(pPage->pDbPage) ); data = pPage->aData; assert( &data[pPage->cellOffset]==pPage->aCellIdx ); rc = allocateSpace(pPage, sz, &idx); @@ -67688,9 +74447,16 @@ static void insertCell( assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB ); assert( idx+sz <= (int)pPage->pBt->usableSize ); pPage->nFree -= (u16)(2 + sz); - memcpy(&data[idx], pCell, sz); if( iChild ){ + /* In a corrupt database where an entry in the cell index section of + ** a btree page has a value of 3 or less, the pCell value might point + ** as many as 4 bytes in front of the start of the aData buffer for + ** the source page. Make sure this does not cause problems by not + ** reading the first 4 bytes */ + memcpy(&data[idx+4], pCell+4, sz-4); put4byte(&data[idx], iChild); + }else{ + memcpy(&data[idx], pCell, sz); } pIns = pPage->aCellIdx + i*2; memmove(pIns+2, pIns, 2*(pPage->nCell - i)); @@ -67698,21 +74464,100 @@ static void insertCell( pPage->nCell++; /* increment the cell count */ if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++; - assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell ); + assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB ); #ifndef SQLITE_OMIT_AUTOVACUUM if( pPage->pBt->autoVacuum ){ /* The cell may contain a pointer to an overflow page. If so, write ** the entry for the overflow page into the pointer map. */ - ptrmapPutOvflPtr(pPage, pCell, pRC); + ptrmapPutOvflPtr(pPage, pPage, pCell, pRC); } #endif } } /* +** The following parameters determine how many adjacent pages get involved +** in a balancing operation. NN is the number of neighbors on either side +** of the page that participate in the balancing operation. NB is the +** total number of pages that participate, including the target page and +** NN neighbors on either side. +** +** The minimum value of NN is 1 (of course). Increasing NN above 1 +** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance +** in exchange for a larger degradation in INSERT and UPDATE performance. +** The value of NN appears to give the best results overall. +** +** (Later:) The description above makes it seem as if these values are +** tunable - as if you could change them and recompile and it would all work. +** But that is unlikely. NB has been 3 since the inception of SQLite and +** we have never tested any other value. +*/ +#define NN 1 /* Number of neighbors on either side of pPage */ +#define NB 3 /* (NN*2+1): Total pages involved in the balance */ + +/* ** A CellArray object contains a cache of pointers and sizes for a ** consecutive sequence of cells that might be held on multiple pages. +** +** The cells in this array are the divider cell or cells from the pParent +** page plus up to three child pages. There are a total of nCell cells. +** +** pRef is a pointer to one of the pages that contributes cells. This is +** used to access information such as MemPage.intKey and MemPage.pBt->pageSize +** which should be common to all pages that contribute cells to this array. +** +** apCell[] and szCell[] hold, respectively, pointers to the start of each +** cell and the size of each cell. Some of the apCell[] pointers might refer +** to overflow cells. In other words, some apCel[] pointers might not point +** to content area of the pages. +** +** A szCell[] of zero means the size of that cell has not yet been computed. +** +** The cells come from as many as four different pages: +** +** ----------- +** | Parent | +** ----------- +** / | \ +** / | \ +** --------- --------- --------- +** |Child-1| |Child-2| |Child-3| +** --------- --------- --------- +** +** The order of cells is in the array is for an index btree is: +** +** 1. All cells from Child-1 in order +** 2. The first divider cell from Parent +** 3. All cells from Child-2 in order +** 4. The second divider cell from Parent +** 5. All cells from Child-3 in order +** +** For a table-btree (with rowids) the items 2 and 4 are empty because +** content exists only in leaves and there are no divider cells. +** +** For an index btree, the apEnd[] array holds pointer to the end of page +** for Child-1, the Parent, Child-2, the Parent (again), and Child-3, +** respectively. The ixNx[] array holds the number of cells contained in +** each of these 5 stages, and all stages to the left. Hence: +** +** ixNx[0] = Number of cells in Child-1. +** ixNx[1] = Number of cells in Child-1 plus 1 for first divider. +** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider. +** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells +** ixNx[4] = Total number of cells. +** +** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2] +** are used and they point to the leaf pages only, and the ixNx value are: +** +** ixNx[0] = Number of cells in Child-1. +** ixNx[1] = Number of cells in Child-1 and Child-2. +** ixNx[2] = Total number of cells. +** +** Sometimes when deleting, a child page can have zero cells. In those +** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[] +** entries, shift down. The end result is that each ixNx[] entry should +** be larger than the previous */ typedef struct CellArray CellArray; struct CellArray { @@ -67720,6 +74565,8 @@ struct CellArray { MemPage *pRef; /* Reference page */ u8 **apCell; /* All cells begin balanced */ u16 *szCell; /* Local size of all cells in apCell[] */ + u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */ + int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */ }; /* @@ -67770,36 +74617,59 @@ static u16 cachedCellSize(CellArray *p, int N){ ** responsibility of the caller to set it correctly. */ static int rebuildPage( - MemPage *pPg, /* Edit this page */ + CellArray *pCArray, /* Content to be added to page pPg */ + int iFirst, /* First cell in pCArray to use */ int nCell, /* Final number of cells on page */ - u8 **apCell, /* Array of cells */ - u16 *szCell /* Array of cell sizes */ + MemPage *pPg /* The page to be reconstructed */ ){ const int hdr = pPg->hdrOffset; /* Offset of header on pPg */ u8 * const aData = pPg->aData; /* Pointer to data for pPg */ const int usableSize = pPg->pBt->usableSize; u8 * const pEnd = &aData[usableSize]; - int i; + int i = iFirst; /* Which cell to copy from pCArray*/ + u32 j; /* Start of cell content area */ + int iEnd = i+nCell; /* Loop terminator */ u8 *pCellptr = pPg->aCellIdx; - u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); + u8 *pTmp = tdsqlite3PagerTempSpace(pPg->pBt->pPager); u8 *pData; + int k; /* Current slot in pCArray->apEnd[] */ + u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */ - i = get2byte(&aData[hdr+5]); - memcpy(&pTmp[i], &aData[i], usableSize - i); + assert( i<iEnd ); + j = get2byte(&aData[hdr+5]); + if( NEVER(j>(u32)usableSize) ){ j = 0; } + memcpy(&pTmp[j], &aData[j], usableSize - j); + + for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){} + pSrcEnd = pCArray->apEnd[k]; pData = pEnd; - for(i=0; i<nCell; i++){ - u8 *pCell = apCell[i]; + while( 1/*exit by break*/ ){ + u8 *pCell = pCArray->apCell[i]; + u16 sz = pCArray->szCell[i]; + assert( sz>0 ); if( SQLITE_WITHIN(pCell,aData,pEnd) ){ + if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT; pCell = &pTmp[pCell - aData]; + }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd + && (uptr)(pCell)<(uptr)pSrcEnd + ){ + return SQLITE_CORRUPT_BKPT; } - pData -= szCell[i]; + + pData -= sz; put2byte(pCellptr, (pData - aData)); pCellptr += 2; if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT; - memcpy(pData, pCell, szCell[i]); - assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB ); - testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) ); + memcpy(pData, pCell, sz); + assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB ); + testcase( sz!=pPg->xCellSize(pPg,pCell) ) + i++; + if( i>=iEnd ) break; + if( pCArray->ixNx[k]<=i ){ + k++; + pSrcEnd = pCArray->apEnd[k]; + } } /* The pPg->nFree field is now set incorrectly. The caller will fix it. */ @@ -67814,12 +74684,11 @@ static int rebuildPage( } /* -** Array apCell[] contains nCell pointers to b-tree cells. Array szCell -** contains the size in bytes of each such cell. This function attempts to -** add the cells stored in the array to page pPg. If it cannot (because -** the page needs to be defragmented before the cells will fit), non-zero -** is returned. Otherwise, if the cells are added successfully, zero is -** returned. +** The pCArray objects contains pointers to b-tree cells and the cell sizes. +** This function attempts to add the cells stored in the array to page pPg. +** If it cannot (because the page needs to be defragmented before the cells +** will fit), non-zero is returned. Otherwise, if the cells are added +** successfully, zero is returned. ** ** Argument pCellptr points to the first entry in the cell-pointer array ** (part of page pPg) to populate. After cell apCell[0] is written to the @@ -67841,21 +74710,27 @@ static int rebuildPage( static int pageInsertArray( MemPage *pPg, /* Page to add cells to */ u8 *pBegin, /* End of cell-pointer array */ - u8 **ppData, /* IN/OUT: Page content -area pointer */ + u8 **ppData, /* IN/OUT: Page content-area pointer */ u8 *pCellptr, /* Pointer to cell-pointer area */ int iFirst, /* Index of first cell to add */ int nCell, /* Number of cells to add to pPg */ CellArray *pCArray /* Array of cells */ ){ - int i; - u8 *aData = pPg->aData; - u8 *pData = *ppData; - int iEnd = iFirst + nCell; + int i = iFirst; /* Loop counter - cell index to insert */ + u8 *aData = pPg->aData; /* Complete page */ + u8 *pData = *ppData; /* Content area. A subset of aData[] */ + int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */ + int k; /* Current slot in pCArray->apEnd[] */ + u8 *pEnd; /* Maximum extent of cell data */ assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */ - for(i=iFirst; i<iEnd; i++){ + if( iEnd<=iFirst ) return 0; + for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){} + pEnd = pCArray->apEnd[k]; + while( 1 /*Exit by break*/ ){ int sz, rc; u8 *pSlot; - sz = cachedCellSize(pCArray, i); + assert( pCArray->szCell[i]!=0 ); + sz = pCArray->szCell[i]; if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){ if( (pData - pBegin)<sz ) return 1; pData -= sz; @@ -67867,20 +74742,33 @@ static int pageInsertArray( assert( (pSlot+sz)<=pCArray->apCell[i] || pSlot>=(pCArray->apCell[i]+sz) || CORRUPT_DB ); + if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd + && (uptr)(pCArray->apCell[i])<(uptr)pEnd + ){ + assert( CORRUPT_DB ); + (void)SQLITE_CORRUPT_BKPT; + return 1; + } memmove(pSlot, pCArray->apCell[i], sz); put2byte(pCellptr, (pSlot - aData)); pCellptr += 2; + i++; + if( i>=iEnd ) break; + if( pCArray->ixNx[k]<=i ){ + k++; + pEnd = pCArray->apEnd[k]; + } } *ppData = pData; return 0; } /* -** Array apCell[] contains nCell pointers to b-tree cells. Array szCell -** contains the size in bytes of each such cell. This function adds the -** space associated with each cell in the array that is currently stored -** within the body of pPg to the pPg free-list. The cell-pointers and other -** fields of the page are not updated. +** The pCArray object contains pointers to b-tree cells and their sizes. +** +** This function adds the space associated with each cell in the array +** that is currently stored within the body of pPg to the pPg free-list. +** The cell-pointers and other fields of the page are not updated. ** ** This function returns the total number of cells added to the free-list. */ @@ -67930,9 +74818,9 @@ static int pageFreeArray( } /* -** apCell[] and szCell[] contains pointers to and sizes of all cells in the -** pages being balanced. The current page, pPg, has pPg->nCell cells starting -** with apCell[iOld]. After balancing, this page should hold nNew cells +** pCArray contains pointers to and sizes of all cells in the page being +** balanced. The current page, pPg, has pPg->nCell cells starting with +** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells ** starting at apCell[iNew]. ** ** This routine makes the necessary adjustments to pPg so that it contains @@ -67959,18 +74847,22 @@ static int editPage( int iNewEnd = iNew + nNew; #ifdef SQLITE_DEBUG - u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); + u8 *pTmp = tdsqlite3PagerTempSpace(pPg->pBt->pPager); memcpy(pTmp, aData, pPg->pBt->usableSize); #endif /* Remove cells from the start and end of the page */ + assert( nCell>=0 ); if( iOld<iNew ){ int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray); + if( nShift>nCell ) return SQLITE_CORRUPT_BKPT; memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2); nCell -= nShift; } if( iNewEnd < iOldEnd ){ - nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); + int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); + assert( nCell>=nTail ); + nCell -= nTail; } pData = &aData[get2byteNotZero(&aData[hdr+5])]; @@ -67980,6 +74872,7 @@ static int editPage( if( iNew<iOld ){ int nAdd = MIN(nNew,iOld-iNew); assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB ); + assert( nAdd>=0 ); pCellptr = pPg->aCellIdx; memmove(&pCellptr[nAdd*2], pCellptr, nCell*2); if( pageInsertArray( @@ -67994,8 +74887,11 @@ static int editPage( int iCell = (iOld + pPg->aiOvfl[i]) - iNew; if( iCell>=0 && iCell<nNew ){ pCellptr = &pPg->aCellIdx[iCell * 2]; - memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); + if( nCell>iCell ){ + memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); + } nCell++; + cachedCellSize(pCArray, iCell+iNew); if( pageInsertArray( pPg, pBegin, &pData, pCellptr, iCell+iNew, 1, pCArray @@ -68004,6 +74900,7 @@ static int editPage( } /* Append cells to the end of the page */ + assert( nCell>=0 ); pCellptr = &pPg->aCellIdx[nCell*2]; if( pageInsertArray( pPg, pBegin, &pData, pCellptr, @@ -68032,24 +74929,9 @@ static int editPage( editpage_fail: /* Unable to edit this page. Rebuild it from scratch instead. */ populateCellCache(pCArray, iNew, nNew); - return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]); + return rebuildPage(pCArray, iNew, nNew, pPg); } -/* -** The following parameters determine how many adjacent pages get involved -** in a balancing operation. NN is the number of neighbors on either side -** of the page that participate in the balancing operation. NB is the -** total number of pages that participate, including the target page and -** NN neighbors on either side. -** -** The minimum value of NN is 1 (of course). Increasing NN above 1 -** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance -** in exchange for a larger degradation in INSERT and UPDATE performance. -** The value of NN appears to give the best results overall. -*/ -#define NN 1 /* Number of neighbors on either side of pPage */ -#define NB (NN*2+1) /* Total pages involved in the balance */ - #ifndef SQLITE_OMIT_QUICKBALANCE /* @@ -68081,12 +74963,13 @@ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ int rc; /* Return Code */ Pgno pgnoNew; /* Page number of pNew */ - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + assert( tdsqlite3_mutex_held(pPage->pBt->mutex) ); + assert( tdsqlite3PagerIswriteable(pParent->pDbPage) ); assert( pPage->nOverflow==1 ); - - /* This error condition is now caught prior to reaching this function */ - if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT; + + if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */ + assert( pPage->nFree>=0 ); + assert( pParent->nFree>=0 ); /* Allocate a new page. This page will become the right-sibling of ** pPage. Make the parent page writable, so that the new divider cell @@ -68100,12 +74983,22 @@ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ u8 *pCell = pPage->apOvfl[0]; u16 szCell = pPage->xCellSize(pPage, pCell); u8 *pStop; + CellArray b; - assert( sqlite3PagerIswriteable(pNew->pDbPage) ); - assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); + assert( tdsqlite3PagerIswriteable(pNew->pDbPage) ); + assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); - rc = rebuildPage(pNew, 1, &pCell, &szCell); - if( NEVER(rc) ) return rc; + b.nCell = 1; + b.pRef = pPage; + b.apCell = &pCell; + b.szCell = &szCell; + b.apEnd[0] = pPage->aDataEnd; + b.ixNx[0] = 2; + rc = rebuildPage(&b, 0, 1, pNew); + if( NEVER(rc) ){ + releasePage(pNew); + return rc; + } pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell; /* If this is an auto-vacuum database, update the pointer map @@ -68120,7 +75013,7 @@ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ if( ISAUTOVACUUM ){ ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc); if( szCell>pNew->minLocal ){ - ptrmapPutOvflPtr(pNew, pCell, &rc); + ptrmapPutOvflPtr(pNew, pNew, pCell, &rc); } } @@ -68246,6 +75139,7 @@ static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ */ pTo->isInit = 0; rc = btreeInitPage(pTo); + if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo); if( rc!=SQLITE_OK ){ *pRC = rc; return; @@ -68340,17 +75234,13 @@ static int balance_nonroot( b.nCell = 0; b.apCell = 0; pBt = pParent->pBt; - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( sqlite3PagerIswriteable(pParent->pDbPage) ); - -#if 0 - TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); -#endif + assert( tdsqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3PagerIswriteable(pParent->pDbPage) ); /* At this point pParent may have at most one overflow cell. And if ** this overflow cell is present, it must be the cell with ** index iParentIdx. This scenario comes about when this function - ** is called (indirectly) from sqlite3BtreeDelete(). + ** is called (indirectly) from tdsqlite3BtreeDelete(). */ assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); @@ -68358,6 +75248,7 @@ static int balance_nonroot( if( !aOvflSpace ){ return SQLITE_NOMEM_BKPT; } + assert( pParent->nFree>=0 ); /* Find the sibling pages to balance. Also locate the cells in pParent ** that divide the siblings. An attempt is made to find NN siblings on @@ -68397,10 +75288,16 @@ static int balance_nonroot( memset(apOld, 0, (i+1)*sizeof(MemPage*)); goto balance_cleanup; } - nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; + if( apOld[i]->nFree<0 ){ + rc = btreeComputeFreeSpace(apOld[i]); + if( rc ){ + memset(apOld, 0, (i)*sizeof(MemPage*)); + goto balance_cleanup; + } + } if( (i--)==0 ) break; - if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){ + if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){ apDiv[i] = pParent->apOvfl[0]; pgno = get4byte(apDiv[i]); szNew[i] = pParent->xCellSize(pParent, apDiv[i]); @@ -68422,7 +75319,7 @@ static int balance_nonroot( ** In this case, temporarily copy the cell into the aOvflSpace[] ** buffer. It will be copied out again as soon as the aSpace[] buffer ** is allocated. */ - if( pBt->btsFlags & BTS_SECURE_DELETE ){ + if( pBt->btsFlags & BTS_FAST_SECURE ){ int iOff; iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); @@ -68441,6 +75338,7 @@ static int balance_nonroot( /* Make nMaxCells a multiple of 4 in order to preserve 8-byte ** alignment */ + nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl)); nMaxCells = (nMaxCells + 3)&~3; /* @@ -68451,10 +75349,8 @@ static int balance_nonroot( + nMaxCells*sizeof(u16) /* b.szCell */ + pBt->pageSize; /* aSpace1 */ - /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer - ** that is more than 6 times the database page size. */ - assert( szScratch<=6*(int)pBt->pageSize ); - b.apCell = sqlite3ScratchMalloc( szScratch ); + assert( szScratch<=7*(int)pBt->pageSize ); + b.apCell = tdsqlite3StackAllocRaw(0, szScratch ); if( b.apCell==0 ){ rc = SQLITE_NOMEM_BKPT; goto balance_cleanup; @@ -68489,6 +75385,7 @@ static int balance_nonroot( u16 maskPage = pOld->maskPage; u8 *piCell = aData + pOld->cellOffset; u8 *piEnd; + VVA_ONLY( int nCellAtStart = b.nCell; ) /* Verify that all sibling pages are of the same "type" (table-leaf, ** table-interior, index-leaf, or index-interior). @@ -68499,7 +75396,7 @@ static int balance_nonroot( } /* Load b.apCell[] with pointers to all cells in pOld. If pOld - ** constains overflow cells, include them in the b.apCell[] array + ** contains overflow cells, include them in the b.apCell[] array ** in the correct spot. ** ** Note that when there are multiple overflow cells, it is always the @@ -68517,6 +75414,10 @@ static int balance_nonroot( */ memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow)); if( pOld->nOverflow>0 ){ + if( NEVER(limit<pOld->aiOvfl[0]) ){ + rc = SQLITE_CORRUPT_BKPT; + goto balance_cleanup; + } limit = pOld->aiOvfl[0]; for(j=0; j<limit; j++){ b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)); @@ -68536,6 +75437,7 @@ static int balance_nonroot( piCell += 2; b.nCell++; } + assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) ); cntOld[i] = b.nCell; if( i<nOld-1 && !leafData){ @@ -68589,10 +75491,20 @@ static int balance_nonroot( ** */ usableSpace = pBt->usableSize - 12 + leafCorrection; - for(i=0; i<nOld; i++){ + for(i=k=0; i<nOld; i++, k++){ MemPage *p = apOld[i]; + b.apEnd[k] = p->aDataEnd; + b.ixNx[k] = cntOld[i]; + if( k && b.ixNx[k]==b.ixNx[k-1] ){ + k--; /* Omit b.ixNx[] entry for child pages with no cells */ + } + if( !leafData ){ + k++; + b.apEnd[k] = pParent->aDataEnd; + b.ixNx[k] = cntOld[i]+1; + } + assert( p->nFree>=0 ); szNew[i] = usableSpace - p->nFree; - if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } for(j=0; j<p->nOverflow; j++){ szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]); } @@ -68707,7 +75619,7 @@ static int balance_nonroot( if( i<nOld ){ pNew = apNew[i] = apOld[i]; apOld[i] = 0; - rc = sqlite3PagerWrite(pNew->pDbPage); + rc = tdsqlite3PagerWrite(pNew->pDbPage); nNew++; if( rc ) goto balance_cleanup; }else{ @@ -68767,9 +75679,9 @@ static int balance_nonroot( aPgOrder[iBest] = 0xffffffff; if( iBest!=i ){ if( iBest>i ){ - sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0); + tdsqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0); } - sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]); + tdsqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]); apNew[i]->pgno = pgno; } } @@ -68787,7 +75699,9 @@ static int balance_nonroot( nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0 )); - assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + assert( tdsqlite3PagerIswriteable(pParent->pDbPage) ); + assert( nNew>=1 && nNew<=ArraySize(apNew) ); + assert( apNew[nNew-1]!=0 ); put4byte(pRight, apNew[nNew-1]->pgno); /* If the sibling pages are not leaves, ensure that the right-child pointer @@ -68815,19 +75729,20 @@ static int balance_nonroot( ** populated, not here. */ if( ISAUTOVACUUM ){ - MemPage *pNew = apNew[0]; - u8 *aOld = pNew->aData; + MemPage *pOld; + MemPage *pNew = pOld = apNew[0]; int cntOldNext = pNew->nCell + pNew->nOverflow; - int usableSize = pBt->usableSize; int iNew = 0; int iOld = 0; for(i=0; i<b.nCell; i++){ u8 *pCell = b.apCell[i]; - if( i==cntOldNext ){ - MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld]; + while( i==cntOldNext ){ + iOld++; + assert( iOld<nNew || iOld<nOld ); + assert( iOld>=0 && iOld<NB ); + pOld = iOld<nNew ? apNew[iOld] : apOld[iOld]; cntOldNext += pOld->nCell + pOld->nOverflow + !leafData; - aOld = pOld->aData; } if( i==cntNew[iNew] ){ pNew = apNew[++iNew]; @@ -68842,13 +75757,13 @@ static int balance_nonroot( ** overflow cell), we can skip updating the pointer map entries. */ if( iOld>=nNew || pNew->pgno!=aPgno[iOld] - || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize]) + || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd) ){ if( !leafCorrection ){ ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc); } if( cachedCellSize(&b,i)>pNew->minLocal ){ - ptrmapPutOvflPtr(pNew, pCell, &rc); + ptrmapPutOvflPtr(pNew, pOld, pCell, &rc); } if( rc ) goto balance_cleanup; } @@ -68905,7 +75820,7 @@ static int balance_nonroot( assert( iOvflSpace <= (int)pBt->pageSize ); insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc); if( rc!=SQLITE_OK ) goto balance_cleanup; - assert( sqlite3PagerIswriteable(pParent->pDbPage) ); + assert( tdsqlite3PagerIswriteable(pParent->pDbPage) ); } /* Now update the actual sibling pages. The order in which they are updated @@ -68990,10 +75905,11 @@ static int balance_nonroot( ** free space needs to be up front. */ assert( nNew==1 || CORRUPT_DB ); - rc = defragmentPage(apNew[0]); + rc = defragmentPage(apNew[0], -1); testcase( rc!=SQLITE_OK ); assert( apNew[0]->nFree == - (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) + (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset + - apNew[0]->nCell*2) || rc!=SQLITE_OK ); copyNodeContent(apNew[0], pParent, &rc); @@ -69033,7 +75949,7 @@ static int balance_nonroot( ** Cleanup before returning. */ balance_cleanup: - sqlite3ScratchFree(b.apCell); + tdsqlite3StackFree(0, b.apCell); for(i=0; i<nOld; i++){ releasePage(apOld[i]); } @@ -69071,13 +75987,13 @@ static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ BtShared *pBt = pRoot->pBt; /* The BTree */ assert( pRoot->nOverflow>0 ); - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); /* Make pRoot, the root page of the b-tree, writable. Allocate a new ** page that will become the new right-child of pPage. Copy the contents ** of the node stored on pRoot into the new child page. */ - rc = sqlite3PagerWrite(pRoot->pDbPage); + rc = tdsqlite3PagerWrite(pRoot->pDbPage); if( rc==SQLITE_OK ){ rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); copyNodeContent(pRoot, pChild, &rc); @@ -69090,9 +76006,9 @@ static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ releasePage(pChild); return rc; } - assert( sqlite3PagerIswriteable(pChild->pDbPage) ); - assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); - assert( pChild->nCell==pRoot->nCell ); + assert( tdsqlite3PagerIswriteable(pChild->pDbPage) ); + assert( tdsqlite3PagerIswriteable(pRoot->pDbPage) ); + assert( pChild->nCell==pRoot->nCell || CORRUPT_DB ); TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); @@ -69112,6 +76028,30 @@ static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ } /* +** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid +** on the same B-tree as pCur. +** +** This can if a database is corrupt with two or more SQL tables +** pointing to the same b-tree. If an insert occurs on one SQL table +** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL +** table linked to the same b-tree. If the secondary insert causes a +** rebalance, that can change content out from under the cursor on the +** first SQL table, violating invariants on the first insert. +*/ +static int anotherValidCursor(BtCursor *pCur){ + BtCursor *pOther; + for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){ + if( pOther!=pCur + && pOther->eState==CURSOR_VALID + && pOther->pPage==pCur->pPage + ){ + return SQLITE_CORRUPT_BKPT; + } + } + return SQLITE_OK; +} + +/* ** The page that pCur currently points to has just been modified in ** some way. This function figures out if this modification means the ** tree needs to be balanced, and if so calls the appropriate balancing @@ -69131,11 +76071,14 @@ static int balance(BtCursor *pCur){ VVA_ONLY( int balance_deeper_called = 0 ); do { - int iPage = pCur->iPage; - MemPage *pPage = pCur->apPage[iPage]; + int iPage; + MemPage *pPage = pCur->pPage; - if( iPage==0 ){ - if( pPage->nOverflow ){ + if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break; + if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ + break; + }else if( (iPage = pCur->iPage)==0 ){ + if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){ /* The root page of the b-tree is overfull. In this case call the ** balance_deeper() function to create a new child for the root-page ** and copy the current contents of the root-page to it. The @@ -69146,20 +76089,23 @@ static int balance(BtCursor *pCur){ rc = balance_deeper(pPage, &pCur->apPage[1]); if( rc==SQLITE_OK ){ pCur->iPage = 1; + pCur->ix = 0; pCur->aiIdx[0] = 0; - pCur->aiIdx[1] = 0; - assert( pCur->apPage[1]->nOverflow ); + pCur->apPage[0] = pPage; + pCur->pPage = pCur->apPage[1]; + assert( pCur->pPage->nOverflow ); } }else{ break; } - }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ - break; }else{ MemPage * const pParent = pCur->apPage[iPage-1]; int const iIdx = pCur->aiIdx[iPage-1]; - rc = sqlite3PagerWrite(pParent->pDbPage); + rc = tdsqlite3PagerWrite(pParent->pDbPage); + if( rc==SQLITE_OK && pParent->nFree<0 ){ + rc = btreeComputeFreeSpace(pParent); + } if( rc==SQLITE_OK ){ #ifndef SQLITE_OMIT_QUICKBALANCE if( pPage->intKeyLeaf @@ -69204,7 +76150,7 @@ static int balance(BtCursor *pCur){ ** copied either into the body of a database page or into the new ** pSpace buffer passed to the latter call to balance_nonroot(). */ - u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); + u8 *pSpace = tdsqlite3PageMalloc(pCur->pBt->pageSize); rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints&BTREE_BULKLOAD); if( pFree ){ @@ -69212,7 +76158,7 @@ static int balance(BtCursor *pCur){ ** by a previous call to balance_nonroot(). Its contents are ** now stored either on real database pages or within the ** new pSpace buffer, so it may be safely freed here. */ - sqlite3PageFree(pFree); + tdsqlite3PageFree(pFree); } /* The pSpace buffer will be freed after the next call to @@ -69228,15 +76174,110 @@ static int balance(BtCursor *pCur){ releasePage(pPage); pCur->iPage--; assert( pCur->iPage>=0 ); + pCur->pPage = pCur->apPage[pCur->iPage]; } }while( rc==SQLITE_OK ); if( pFree ){ - sqlite3PageFree(pFree); + tdsqlite3PageFree(pFree); } return rc; } +/* Overwrite content from pX into pDest. Only do the write if the +** content is different from what is already there. +*/ +static int btreeOverwriteContent( + MemPage *pPage, /* MemPage on which writing will occur */ + u8 *pDest, /* Pointer to the place to start writing */ + const BtreePayload *pX, /* Source of data to write */ + int iOffset, /* Offset of first byte to write */ + int iAmt /* Number of bytes to be written */ +){ + int nData = pX->nData - iOffset; + if( nData<=0 ){ + /* Overwritting with zeros */ + int i; + for(i=0; i<iAmt && pDest[i]==0; i++){} + if( i<iAmt ){ + int rc = tdsqlite3PagerWrite(pPage->pDbPage); + if( rc ) return rc; + memset(pDest + i, 0, iAmt - i); + } + }else{ + if( nData<iAmt ){ + /* Mixed read data and zeros at the end. Make a recursive call + ** to write the zeros then fall through to write the real data */ + int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData, + iAmt-nData); + if( rc ) return rc; + iAmt = nData; + } + if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){ + int rc = tdsqlite3PagerWrite(pPage->pDbPage); + if( rc ) return rc; + /* In a corrupt database, it is possible for the source and destination + ** buffers to overlap. This is harmless since the database is already + ** corrupt but it does cause valgrind and ASAN warnings. So use + ** memmove(). */ + memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt); + } + } + return SQLITE_OK; +} + +/* +** Overwrite the cell that cursor pCur is pointing to with fresh content +** contained in pX. +*/ +static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){ + int iOffset; /* Next byte of pX->pData to write */ + int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */ + int rc; /* Return code */ + MemPage *pPage = pCur->pPage; /* Page being written */ + BtShared *pBt; /* Btree */ + Pgno ovflPgno; /* Next overflow page to write */ + u32 ovflPageSize; /* Size to write on overflow page */ + + if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd + || pCur->info.pPayload < pPage->aData + pPage->cellOffset + ){ + return SQLITE_CORRUPT_BKPT; + } + /* Overwrite the local portion first */ + rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX, + 0, pCur->info.nLocal); + if( rc ) return rc; + if( pCur->info.nLocal==nTotal ) return SQLITE_OK; + + /* Now overwrite the overflow pages */ + iOffset = pCur->info.nLocal; + assert( nTotal>=0 ); + assert( iOffset>=0 ); + ovflPgno = get4byte(pCur->info.pPayload + iOffset); + pBt = pPage->pBt; + ovflPageSize = pBt->usableSize - 4; + do{ + rc = btreeGetPage(pBt, ovflPgno, &pPage, 0); + if( rc ) return rc; + if( tdsqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + if( iOffset+ovflPageSize<(u32)nTotal ){ + ovflPgno = get4byte(pPage->aData); + }else{ + ovflPageSize = nTotal - iOffset; + } + rc = btreeOverwriteContent(pPage, pPage->aData+4, pX, + iOffset, ovflPageSize); + } + tdsqlite3PagerUnref(pPage->pDbPage); + if( rc ) return rc; + iOffset += ovflPageSize; + }while( iOffset<nTotal ); + return SQLITE_OK; +} + /* ** Insert a new record into the BTree. The content of the new record @@ -69254,22 +76295,24 @@ static int balance(BtCursor *pCur){ ** pX.pData,nData,nZero fields must be zero. ** ** If the seekResult parameter is non-zero, then a successful call to -** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already -** been performed. seekResult is the search result returned (a negative -** number if pCur points at an entry that is smaller than (pKey, nKey), or -** a positive value if pCur points at an entry that is larger than -** (pKey, nKey)). -** -** If the seekResult parameter is non-zero, then the caller guarantees that -** cursor pCur is pointing at the existing copy of a row that is to be -** overwritten. If the seekResult parameter is 0, then cursor pCur may -** point to any entry or to no entry at all and so this function has to seek -** the cursor before the new key can be inserted. -*/ -SQLITE_PRIVATE int sqlite3BtreeInsert( +** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already +** been performed. In other words, if seekResult!=0 then the cursor +** is currently pointing to a cell that will be adjacent to the cell +** to be inserted. If seekResult<0 then pCur points to a cell that is +** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell +** that is larger than (pKey,nKey). +** +** If seekResult==0, that means pCur is pointing at some unknown location. +** In that case, this routine must seek the cursor to the correct insertion +** point for (pKey,nKey) before doing the insertion. For index btrees, +** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked +** key values and pX->aMem can be used instead of pX->pKey to avoid having +** to decode the key. +*/ +SQLITE_PRIVATE int tdsqlite3BtreeInsert( BtCursor *pCur, /* Insert data into the table of this cursor */ const BtreePayload *pX, /* Content of the row to be inserted */ - int appendBias, /* True if this is likely an append */ + int flags, /* True if this is likely an append */ int seekResult /* Result of prior MovetoUnpacked() call */ ){ int rc; @@ -69282,6 +76325,8 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( unsigned char *oldCell; unsigned char *newCell = 0; + assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags ); + if( pCur->eState==CURSOR_FAULT ){ assert( pCur->skipNext!=SQLITE_OK ); return pCur->skipNext; @@ -69304,7 +76349,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( ** ** In some cases, the call to btreeMoveto() below is a no-op. For ** example, when inserting data into a table with auto-generated integer - ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the + ** keys, the VDBE layer invokes tdsqlite3BtreeLast() to figure out the ** integer key to use. It then calls this function to actually insert the ** data into the intkey B-Tree. In this case btreeMoveto() recognizes ** that the cursor is already where it needs to be and returns without @@ -69320,27 +76365,100 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( assert( pX->pKey==0 ); /* If this is an insert into a table b-tree, invalidate any incrblob ** cursors open on the row being replaced */ - invalidateIncrblobCursors(p, pX->nKey, 0); - - /* If the cursor is currently on the last row and we are appending a - ** new row onto the end, set the "loc" to avoid an unnecessary - ** btreeMoveto() call */ - if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey>0 - && pCur->info.nKey==pX->nKey-1 ){ - loc = -1; + invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0); + + /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing + ** to a row with the same key as the new entry being inserted. + */ +#ifdef SQLITE_DEBUG + if( flags & BTREE_SAVEPOSITION ){ + assert( pCur->curFlags & BTCF_ValidNKey ); + assert( pX->nKey==pCur->info.nKey ); + assert( loc==0 ); + } +#endif + + /* On the other hand, BTREE_SAVEPOSITION==0 does not imply + ** that the cursor is not pointing to a row to be overwritten. + ** So do a complete check. + */ + if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){ + /* The cursor is pointing to the entry that is to be + ** overwritten */ + assert( pX->nData>=0 && pX->nZero>=0 ); + if( pCur->info.nSize!=0 + && pCur->info.nPayload==(u32)pX->nData+pX->nZero + ){ + /* New entry is the same size as the old. Do an overwrite */ + return btreeOverwriteCell(pCur, pX); + } + assert( loc==0 ); }else if( loc==0 ){ - rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, appendBias, &loc); + /* The cursor is *not* pointing to the cell to be overwritten, nor + ** to an adjacent cell. Move the cursor so that it is pointing either + ** to the cell to be overwritten or an adjacent cell. + */ + rc = tdsqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc); if( rc ) return rc; } - }else if( loc==0 ){ - rc = btreeMoveto(pCur, pX->pKey, pX->nKey, appendBias, &loc); - if( rc ) return rc; + }else{ + /* This is an index or a WITHOUT ROWID table */ + + /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing + ** to a row with the same key as the new entry being inserted. + */ + assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 ); + + /* If the cursor is not already pointing either to the cell to be + ** overwritten, or if a new cell is being inserted, if the cursor is + ** not pointing to an immediately adjacent cell, then move the cursor + ** so that it does. + */ + if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){ + if( pX->nMem ){ + UnpackedRecord r; + r.pKeyInfo = pCur->pKeyInfo; + r.aMem = pX->aMem; + r.nField = pX->nMem; + r.default_rc = 0; + r.errCode = 0; + r.r1 = 0; + r.r2 = 0; + r.eqSeen = 0; + rc = tdsqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc); + }else{ + rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc); + } + if( rc ) return rc; + } + + /* If the cursor is currently pointing to an entry to be overwritten + ** and the new content is the same as as the old, then use the + ** overwrite optimization. + */ + if( loc==0 ){ + getCellInfo(pCur); + if( pCur->info.nKey==pX->nKey ){ + BtreePayload x2; + x2.pData = pX->pKey; + x2.nData = pX->nKey; + x2.nZero = 0; + return btreeOverwriteCell(pCur, &x2); + } + } + } - assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) ); + assert( pCur->eState==CURSOR_VALID + || (pCur->eState==CURSOR_INVALID && loc) + || CORRUPT_DB ); - pPage = pCur->apPage[pCur->iPage]; + pPage = pCur->pPage; assert( pPage->intKey || pX->nKey>=0 ); assert( pPage->leaf || !pPage->intKey ); + if( pPage->nFree<0 ){ + rc = btreeComputeFreeSpace(pPage); + if( rc ) return rc; + } TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno, @@ -69352,11 +76470,11 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( if( rc ) goto end_insert; assert( szNew==pPage->xCellSize(pPage, newCell) ); assert( szNew <= MX_CELL_SIZE(pBt) ); - idx = pCur->aiIdx[pCur->iPage]; + idx = pCur->ix; if( loc==0 ){ - u16 szOld; + CellInfo info; assert( idx<pPage->nCell ); - rc = sqlite3PagerWrite(pPage->pDbPage); + rc = tdsqlite3PagerWrite(pPage->pDbPage); if( rc ){ goto end_insert; } @@ -69364,12 +76482,37 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( if( !pPage->leaf ){ memcpy(newCell, oldCell, 4); } - rc = clearCell(pPage, oldCell, &szOld); - dropCell(pPage, idx, szOld, &rc); + rc = clearCell(pPage, oldCell, &info); + testcase( pCur->curFlags & BTCF_ValidOvfl ); + invalidateOverflowCache(pCur); + if( info.nSize==szNew && info.nLocal==info.nPayload + && (!ISAUTOVACUUM || szNew<pPage->minLocal) + ){ + /* Overwrite the old cell with the new if they are the same size. + ** We could also try to do this if the old cell is smaller, then add + ** the leftover space to the free list. But experiments show that + ** doing that is no faster then skipping this optimization and just + ** calling dropCell() and insertCell(). + ** + ** This optimization cannot be used on an autovacuum database if the + ** new entry uses overflow pages, as the insertCell() call below is + ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */ + assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */ + if( oldCell < pPage->aData+pPage->hdrOffset+10 ){ + return SQLITE_CORRUPT_BKPT; + } + if( oldCell+szNew > pPage->aDataEnd ){ + return SQLITE_CORRUPT_BKPT; + } + memcpy(oldCell, newCell, szNew); + return SQLITE_OK; + } + dropCell(pPage, idx, info.nSize, &rc); if( rc ) goto end_insert; }else if( loc<0 && pPage->nCell>0 ){ assert( pPage->leaf ); - idx = ++pCur->aiIdx[pCur->iPage]; + idx = ++pCur->ix; + pCur->curFlags &= ~BTCF_ValidNKey; }else{ assert( pPage->leaf ); } @@ -69407,10 +76550,24 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( ** fails. Internal data structure corruption will result otherwise. ** Also, set the cursor state to invalid. This stops saveCursorPosition() ** from trying to save the current position of the cursor. */ - pCur->apPage[pCur->iPage]->nOverflow = 0; + pCur->pPage->nOverflow = 0; pCur->eState = CURSOR_INVALID; + if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){ + btreeReleaseAllCursorPages(pCur); + if( pCur->pKeyInfo ){ + assert( pCur->pKey==0 ); + pCur->pKey = tdsqlite3Malloc( pX->nKey ); + if( pCur->pKey==0 ){ + rc = SQLITE_NOMEM; + }else{ + memcpy(pCur->pKey, pX->pKey, pX->nKey); + } + } + pCur->eState = CURSOR_REQUIRESEEK; + pCur->nKey = pX->nKey; + } } - assert( pCur->apPage[pCur->iPage]->nOverflow==0 ); + assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 ); end_insert: return rc; @@ -69433,7 +76590,7 @@ end_insert: ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation, ** but which might be used by alternative storage engines. */ -SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ +SQLITE_PRIVATE int tdsqlite3BtreeDelete(BtCursor *pCur, u8 flags){ Btree *p = pCur->pBtree; BtShared *pBt = p->pBt; int rc; /* Return code */ @@ -69441,7 +76598,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ unsigned char *pCell; /* Pointer to cell to delete */ int iCellIdx; /* Index of cell to delete */ int iCellDepth; /* Depth of node containing pCell */ - u16 szCell; /* Size of the cell being deleted */ + CellInfo info; /* Size of the cell being deleted */ int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */ u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */ @@ -69451,14 +76608,18 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ assert( pCur->curFlags & BTCF_WriteFlag ); assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); assert( !hasReadConflicts(p, pCur->pgnoRoot) ); - assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); - assert( pCur->eState==CURSOR_VALID ); assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 ); + if( pCur->eState==CURSOR_REQUIRESEEK ){ + rc = btreeRestoreCursorPosition(pCur); + if( rc ) return rc; + } + assert( pCur->eState==CURSOR_VALID ); iCellDepth = pCur->iPage; - iCellIdx = pCur->aiIdx[iCellDepth]; - pPage = pCur->apPage[iCellDepth]; + iCellIdx = pCur->ix; + pPage = pCur->pPage; pCell = findCell(pPage, iCellIdx); + if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT; /* If the bPreserve flag is set to true, then the cursor position must ** be preserved following this delete operation. If the current delete @@ -69472,6 +76633,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ if( bPreserve ){ if( !pPage->leaf || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3) + || pPage->nCell==1 /* See dbfuzz001.test for a test case */ ){ /* A b-tree rebalance will be required after deleting this entry. ** Save the cursor key. */ @@ -69490,8 +76652,8 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ ** sub-tree headed by the child page of the cell being deleted. This makes ** balancing the tree following the delete operation easier. */ if( !pPage->leaf ){ - int notUsed = 0; - rc = sqlite3BtreePrevious(pCur, ¬Used); + rc = tdsqlite3BtreePrevious(pCur, 0); + assert( rc!=SQLITE_DONE ); if( rc ) return rc; } @@ -69505,16 +76667,16 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ /* If this is a delete operation to remove a row from a table b-tree, ** invalidate any incrblob cursors open on the row being deleted. */ if( pCur->pKeyInfo==0 ){ - invalidateIncrblobCursors(p, pCur->info.nKey, 0); + invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0); } /* Make the page containing the entry to be deleted writable. Then free any ** overflow pages associated with the entry and finally remove the cell ** itself from within the page. */ - rc = sqlite3PagerWrite(pPage->pDbPage); + rc = tdsqlite3PagerWrite(pPage->pDbPage); if( rc ) return rc; - rc = clearCell(pPage, pCell, &szCell); - dropCell(pPage, iCellIdx, szCell, &rc); + rc = clearCell(pPage, pCell, &info); + dropCell(pPage, iCellIdx, info.nSize, &rc); if( rc ) return rc; /* If the cell deleted was not located on a leaf page, then the cursor @@ -69523,18 +76685,27 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ ** node. The cell from the leaf node needs to be moved to the internal ** node to replace the deleted cell. */ if( !pPage->leaf ){ - MemPage *pLeaf = pCur->apPage[pCur->iPage]; + MemPage *pLeaf = pCur->pPage; int nCell; - Pgno n = pCur->apPage[iCellDepth+1]->pgno; + Pgno n; unsigned char *pTmp; + if( pLeaf->nFree<0 ){ + rc = btreeComputeFreeSpace(pLeaf); + if( rc ) return rc; + } + if( iCellDepth<pCur->iPage-1 ){ + n = pCur->apPage[iCellDepth+1]->pgno; + }else{ + n = pCur->pPage->pgno; + } pCell = findCell(pLeaf, pLeaf->nCell-1); if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT; nCell = pLeaf->xCellSize(pLeaf, pCell); assert( MX_CELL_SIZE(pBt) >= nCell ); pTmp = pBt->pTmpSpace; assert( pTmp!=0 ); - rc = sqlite3PagerWrite(pLeaf->pDbPage); + rc = tdsqlite3PagerWrite(pLeaf->pDbPage); if( rc==SQLITE_OK ){ insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); } @@ -69559,29 +76730,34 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ ** well. */ rc = balance(pCur); if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){ + releasePageNotNull(pCur->pPage); + pCur->iPage--; while( pCur->iPage>iCellDepth ){ releasePage(pCur->apPage[pCur->iPage--]); } + pCur->pPage = pCur->apPage[pCur->iPage]; rc = balance(pCur); } if( rc==SQLITE_OK ){ if( bSkipnext ){ assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) ); - assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB ); + assert( pPage==pCur->pPage || CORRUPT_DB ); assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell ); pCur->eState = CURSOR_SKIPNEXT; if( iCellIdx>=pPage->nCell ){ pCur->skipNext = -1; - pCur->aiIdx[iCellDepth] = pPage->nCell-1; + pCur->ix = pPage->nCell-1; }else{ pCur->skipNext = 1; } }else{ rc = moveToRoot(pCur); if( bPreserve ){ + btreeReleaseAllCursorPages(pCur); pCur->eState = CURSOR_REQUIRESEEK; } + if( rc==SQLITE_EMPTY ) rc = SQLITE_OK; } } return rc; @@ -69605,7 +76781,7 @@ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ int rc; int ptfFlags; /* Page-type flage for the root page of new table */ - assert( sqlite3BtreeHoldsMutex(p) ); + assert( tdsqlite3BtreeHoldsMutex(p) ); assert( pBt->inTransaction==TRANS_WRITE ); assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); @@ -69630,7 +76806,7 @@ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ ** root page of the new table should go. meta[3] is the largest root-page ** created so far, so the new root-page is (meta[3]+1). */ - sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); + tdsqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); pgnoRoot++; /* The new root-page may not be allocated on a pointer-map page, or the @@ -69697,7 +76873,7 @@ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ if( rc!=SQLITE_OK ){ return rc; } - rc = sqlite3PagerWrite(pRoot->pDbPage); + rc = tdsqlite3PagerWrite(pRoot->pDbPage); if( rc!=SQLITE_OK ){ releasePage(pRoot); return rc; @@ -69715,10 +76891,10 @@ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ /* When the new root page was allocated, page 1 was made writable in ** order either to increase the database filesize, or to decrement the - ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. + ** freelist count. Hence, the tdsqlite3BtreeUpdateMeta() call cannot fail. */ - assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); - rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); + assert( tdsqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); + rc = tdsqlite3BtreeUpdateMeta(p, 4, pgnoRoot); if( NEVER(rc) ){ releasePage(pRoot); return rc; @@ -69729,23 +76905,23 @@ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ if( rc ) return rc; } #endif - assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); + assert( tdsqlite3PagerIswriteable(pRoot->pDbPage) ); if( createTabFlags & BTREE_INTKEY ){ ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; }else{ ptfFlags = PTF_ZERODATA | PTF_LEAF; } zeroPage(pRoot, ptfFlags); - sqlite3PagerUnref(pRoot->pDbPage); + tdsqlite3PagerUnref(pRoot->pDbPage); assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 ); *piTable = (int)pgnoRoot; return SQLITE_OK; } -SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ +SQLITE_PRIVATE int tdsqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ int rc; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); rc = btreeCreateTable(p, piTable, flags); - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } @@ -69764,9 +76940,9 @@ static int clearDatabasePage( unsigned char *pCell; int i; int hdr; - u16 szCell; + CellInfo info; - assert( sqlite3_mutex_held(pBt->mutex) ); + assert( tdsqlite3_mutex_held(pBt->mutex) ); if( pgno>btreePagecount(pBt) ){ return SQLITE_CORRUPT_BKPT; } @@ -69784,7 +76960,7 @@ static int clearDatabasePage( rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); if( rc ) goto cleardatabasepage_out; } - rc = clearCell(pPage, pCell, &szCell); + rc = clearCell(pPage, pCell, &info); if( rc ) goto cleardatabasepage_out; } if( !pPage->leaf ){ @@ -69797,7 +76973,7 @@ static int clearDatabasePage( } if( freePageFlag ){ freePage(pPage, &rc); - }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ + }else if( (rc = tdsqlite3PagerWrite(pPage->pDbPage))==0 ){ zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF); } @@ -69820,10 +76996,10 @@ cleardatabasepage_out: ** integer value pointed to by pnChange is incremented by the number of ** entries in the table. */ -SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ +SQLITE_PRIVATE int tdsqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ int rc; BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); assert( p->inTrans==TRANS_WRITE ); rc = saveAllCursors(pBt, (Pgno)iTable, 0); @@ -69832,10 +77008,10 @@ SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ /* Invalidate all incrblob cursors open on table iTable (assuming iTable ** is the root of a table b-tree - if it is not, the following call is ** a no-op). */ - invalidateIncrblobCursors(p, 0, 1); + invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1); rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); } - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } @@ -69844,8 +77020,8 @@ SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ ** ** This routine only work for pCur on an ephemeral table. */ -SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){ - return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); +SQLITE_PRIVATE int tdsqlite3BtreeClearTableOfCursor(BtCursor *pCur){ + return tdsqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); } /* @@ -69873,33 +77049,16 @@ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ MemPage *pPage = 0; BtShared *pBt = p->pBt; - assert( sqlite3BtreeHoldsMutex(p) ); + assert( tdsqlite3BtreeHoldsMutex(p) ); assert( p->inTrans==TRANS_WRITE ); - - /* It is illegal to drop a table if any cursors are open on the - ** database. This is because in auto-vacuum mode the backend may - ** need to move another root-page to fill a gap left by the deleted - ** root page. If an open cursor was using this page a problem would - ** occur. - ** - ** This error is caught long before control reaches this point. - */ - if( NEVER(pBt->pCursor) ){ - sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db); - return SQLITE_LOCKED_SHAREDCACHE; - } - - /* - ** It is illegal to drop the sqlite_master table on page 1. But again, - ** this error is caught long before reaching this point. - */ - if( NEVER(iTable<2) ){ + assert( iTable>=2 ); + if( iTable>btreePagecount(pBt) ){ return SQLITE_CORRUPT_BKPT; } rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); if( rc ) return rc; - rc = sqlite3BtreeClearTable(p, iTable, 0); + rc = tdsqlite3BtreeClearTable(p, iTable, 0); if( rc ){ releasePage(pPage); return rc; @@ -69913,7 +77072,7 @@ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ #else if( pBt->autoVacuum ){ Pgno maxRootPgno; - sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); + tdsqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); if( iTable==maxRootPgno ){ /* If the table being dropped is the table with the largest root-page @@ -69962,7 +77121,7 @@ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ } assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); - rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); + rc = tdsqlite3BtreeUpdateMeta(p, 4, maxRootPgno); }else{ freePage(pPage, &rc); releasePage(pPage); @@ -69970,11 +77129,11 @@ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ #endif return rc; } -SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ +SQLITE_PRIVATE int tdsqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ int rc; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); rc = btreeDropTable(p, iTable, piMoved); - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } @@ -69999,17 +77158,17 @@ SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ ** pattern is the same as header meta values, and so it is convenient to ** read it from this routine. */ -SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ +SQLITE_PRIVATE void tdsqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); assert( p->inTrans>TRANS_NONE ); assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) ); assert( pBt->pPage1 ); assert( idx>=0 && idx<=15 ); if( idx==BTREE_DATA_VERSION ){ - *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion; + *pMeta = tdsqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion; }else{ *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); } @@ -70022,23 +77181,23 @@ SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ } #endif - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); } /* ** Write meta-information back into the database. Meta[0] is ** read-only and may not be written. */ -SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ +SQLITE_PRIVATE int tdsqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ BtShared *pBt = p->pBt; unsigned char *pP1; int rc; assert( idx>=1 && idx<=15 ); - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); assert( p->inTrans==TRANS_WRITE ); assert( pBt->pPage1!=0 ); pP1 = pBt->pPage1->aData; - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + rc = tdsqlite3PagerWrite(pBt->pPage1->pDbPage); if( rc==SQLITE_OK ){ put4byte(&pP1[36 + idx*4], iMeta); #ifndef SQLITE_OMIT_AUTOVACUUM @@ -70049,7 +77208,7 @@ SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ } #endif } - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } @@ -70062,20 +77221,20 @@ SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ ** Otherwise, if an error is encountered (i.e. an IO error or database ** corruption) an SQLite error code is returned. */ -SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ +SQLITE_PRIVATE int tdsqlite3BtreeCount(tdsqlite3 *db, BtCursor *pCur, i64 *pnEntry){ i64 nEntry = 0; /* Value to return in *pnEntry */ int rc; /* Return code */ - if( pCur->pgnoRoot==0 ){ + rc = moveToRoot(pCur); + if( rc==SQLITE_EMPTY ){ *pnEntry = 0; return SQLITE_OK; } - rc = moveToRoot(pCur); /* Unless an error occurs, the following loop runs one iteration for each ** page in the B-Tree structure (not including overflow pages). */ - while( rc==SQLITE_OK ){ + while( rc==SQLITE_OK && !db->u1.isInterrupted ){ int iIdx; /* Index of child node in parent */ MemPage *pPage; /* Current page of the b-tree */ @@ -70083,7 +77242,7 @@ SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ ** this page contains countable entries. Increment the entry counter ** accordingly. */ - pPage = pCur->apPage[pCur->iPage]; + pPage = pCur->pPage; if( pPage->leaf || !pPage->intKey ){ nEntry += pPage->nCell; } @@ -70106,16 +77265,16 @@ SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ return moveToRoot(pCur); } moveToParent(pCur); - }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell ); + }while ( pCur->ix>=pCur->pPage->nCell ); - pCur->aiIdx[pCur->iPage]++; - pPage = pCur->apPage[pCur->iPage]; + pCur->ix++; + pPage = pCur->pPage; } /* Descend to the child node of the cell that the cursor currently ** points at. This is the right-child if (iIdx==pPage->nCell). */ - iIdx = pCur->aiIdx[pCur->iPage]; + iIdx = pCur->ix; if( iIdx==pPage->nCell ){ rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); }else{ @@ -70132,7 +77291,7 @@ SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ ** Return the pager associated with a BTree. This routine is used for ** testing and debugging only. */ -SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){ +SQLITE_PRIVATE Pager *tdsqlite3BtreePager(Btree *p){ return p->pBt->pPager; } @@ -70151,14 +77310,14 @@ static void checkAppendMsg( pCheck->nErr++; va_start(ap, zFormat); if( pCheck->errMsg.nChar ){ - sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1); + tdsqlite3_str_append(&pCheck->errMsg, "\n", 1); } if( pCheck->zPfx ){ - sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2); + tdsqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2); } - sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap); + tdsqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap); va_end(ap); - if( pCheck->errMsg.accError==STRACCUM_NOMEM ){ + if( pCheck->errMsg.accError==SQLITE_NOMEM ){ pCheck->mallocFailed = 1; } } @@ -70193,8 +77352,7 @@ static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ ** Also check that the page number is in bounds. */ static int checkRef(IntegrityCk *pCheck, Pgno iPage){ - if( iPage==0 ) return 1; - if( iPage>pCheck->nPage ){ + if( iPage>pCheck->nPage || iPage==0 ){ checkAppendMsg(pCheck, "invalid page number %d", iPage); return 1; } @@ -70202,6 +77360,7 @@ static int checkRef(IntegrityCk *pCheck, Pgno iPage){ checkAppendMsg(pCheck, "2nd reference to page %d", iPage); return 1; } + if( pCheck->db->u1.isInterrupted ) return 1; setPageReferenced(pCheck, iPage); return 0; } @@ -70245,39 +77404,34 @@ static void checkList( IntegrityCk *pCheck, /* Integrity checking context */ int isFreeList, /* True for a freelist. False for overflow page list */ int iPage, /* Page number for first page in the list */ - int N /* Expected number of pages in the list */ + u32 N /* Expected number of pages in the list */ ){ int i; - int expected = N; - int iFirst = iPage; - while( N-- > 0 && pCheck->mxErr ){ + u32 expected = N; + int nErrAtStart = pCheck->nErr; + while( iPage!=0 && pCheck->mxErr ){ DbPage *pOvflPage; unsigned char *pOvflData; - if( iPage<1 ){ - checkAppendMsg(pCheck, - "%d of %d pages missing from overflow list starting at %d", - N+1, expected, iFirst); - break; - } if( checkRef(pCheck, iPage) ) break; - if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){ + N--; + if( tdsqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){ checkAppendMsg(pCheck, "failed to get page %d", iPage); break; } - pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); + pOvflData = (unsigned char *)tdsqlite3PagerGetData(pOvflPage); if( isFreeList ){ - int n = get4byte(&pOvflData[4]); + u32 n = (u32)get4byte(&pOvflData[4]); #ifndef SQLITE_OMIT_AUTOVACUUM if( pCheck->pBt->autoVacuum ){ checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0); } #endif - if( n>(int)pCheck->pBt->usableSize/4-2 ){ + if( n>pCheck->pBt->usableSize/4-2 ){ checkAppendMsg(pCheck, "freelist leaf count too big on page %d", iPage); N--; }else{ - for(i=0; i<n; i++){ + for(i=0; i<(int)n; i++){ Pgno iFreePage = get4byte(&pOvflData[8+i*4]); #ifndef SQLITE_OMIT_AUTOVACUUM if( pCheck->pBt->autoVacuum ){ @@ -70302,11 +77456,13 @@ static void checkList( } #endif iPage = get4byte(pOvflData); - sqlite3PagerUnref(pOvflPage); - - if( isFreeList && N<(iPage!=0) ){ - checkAppendMsg(pCheck, "free-page count in header is too small"); - } + tdsqlite3PagerUnref(pOvflPage); + } + if( N && nErrAtStart==pCheck->nErr ){ + checkAppendMsg(pCheck, + "%s is %d but should be %d", + isFreeList ? "size" : "overflow list length", + expected-N, expected); } } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ @@ -70433,6 +77589,11 @@ static int checkTreePage( "btreeInitPage() returns error code %d", rc); goto end_of_check; } + if( (rc = btreeComputeFreeSpace(pPage))!=0 ){ + assert( rc==SQLITE_CORRUPT ); + checkAppendMsg(pCheck, "free space corruption", rc); + goto end_of_check; + } data = pPage->aData; hdr = pPage->hdrOffset; @@ -70500,11 +77661,12 @@ static int checkTreePage( checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey); } maxKey = info.nKey; + keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */ } /* Check the content overflow list */ if( info.nPayload>info.nLocal ){ - int nPage; /* Number of pages on the overflow chain */ + u32 nPage; /* Number of pages on the overflow chain */ Pgno pgnoOvfl; /* First page of the overflow chain */ assert( pc + info.nSize - 4 <= usableSize ); nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4); @@ -70564,9 +77726,9 @@ static int checkTreePage( i = get2byte(&data[hdr+1]); while( i>0 ){ int size, j; - assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */ + assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */ size = get2byte(&data[i+2]); - assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */ + assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */ btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1)); /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a ** big-endian integer which is the offset in the b-tree page of the next @@ -70575,8 +77737,8 @@ static int checkTreePage( j = get2byte(&data[i]); /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of ** increasing offset. */ - assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */ - assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */ + assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */ + assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */ i = j; } /* Analyze the min-heap looking for overlap between cells and/or @@ -70641,7 +77803,8 @@ end_of_check: ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is ** returned. If a memory allocation error occurs, NULL is returned. */ -SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( +SQLITE_PRIVATE char *tdsqlite3BtreeIntegrityCheck( + tdsqlite3 *db, /* Database connection that is running the check */ Btree *p, /* The btree to be checked */ int *aRoot, /* An array of root pages numbers for individual trees */ int nRoot, /* Number of entries in aRoot[] */ @@ -70651,14 +77814,15 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( Pgno i; IntegrityCk sCheck; BtShared *pBt = p->pBt; - int savedDbFlags = pBt->db->flags; + u64 savedDbFlags = pBt->db->flags; char zErr[100]; VVA_ONLY( int nRef ); - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); - VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) ); + VVA_ONLY( nRef = tdsqlite3PagerRefcount(pBt->pPager) ); assert( nRef>=0 ); + sCheck.db = db; sCheck.pBt = pBt; sCheck.pPager = pBt->pPager; sCheck.nPage = btreePagecount(sCheck.pBt); @@ -70670,18 +77834,18 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( sCheck.v2 = 0; sCheck.aPgRef = 0; sCheck.heap = 0; - sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); + tdsqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL; if( sCheck.nPage==0 ){ goto integrity_ck_cleanup; } - sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); + sCheck.aPgRef = tdsqlite3MallocZero((sCheck.nPage / 8)+ 1); if( !sCheck.aPgRef ){ sCheck.mallocFailed = 1; goto integrity_ck_cleanup; } - sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); + sCheck.heap = (u32*)tdsqlite3PageMalloc( pBt->pageSize ); if( sCheck.heap==0 ){ sCheck.mallocFailed = 1; goto integrity_ck_cleanup; @@ -70699,8 +77863,26 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( /* Check all the tables. */ +#ifndef SQLITE_OMIT_AUTOVACUUM + if( pBt->autoVacuum ){ + int mx = 0; + int mxInHdr; + for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i]; + mxInHdr = get4byte(&pBt->pPage1->aData[52]); + if( mx!=mxInHdr ){ + checkAppendMsg(&sCheck, + "max rootpage (%d) disagrees with header (%d)", + mx, mxInHdr + ); + } + }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){ + checkAppendMsg(&sCheck, + "incremental_vacuum enabled with a max rootpage of zero" + ); + } +#endif testcase( pBt->db->flags & SQLITE_CellSizeCk ); - pBt->db->flags &= ~SQLITE_CellSizeCk; + pBt->db->flags &= ~(u64)SQLITE_CellSizeCk; for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ i64 notUsed; if( aRoot[i]==0 ) continue; @@ -70738,18 +77920,18 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( /* Clean up and report errors. */ integrity_ck_cleanup: - sqlite3PageFree(sCheck.heap); - sqlite3_free(sCheck.aPgRef); + tdsqlite3PageFree(sCheck.heap); + tdsqlite3_free(sCheck.aPgRef); if( sCheck.mallocFailed ){ - sqlite3StrAccumReset(&sCheck.errMsg); + tdsqlite3_str_reset(&sCheck.errMsg); sCheck.nErr++; } *pnErr = sCheck.nErr; - if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg); + if( sCheck.nErr==0 ) tdsqlite3_str_reset(&sCheck.errMsg); /* Make sure this analysis did not leave any unref() pages. */ - assert( nRef==sqlite3PagerRefcount(pBt->pPager) ); - sqlite3BtreeLeave(p); - return sqlite3StrAccumFinish(&sCheck.errMsg); + assert( nRef==tdsqlite3PagerRefcount(pBt->pPager) ); + tdsqlite3BtreeLeave(p); + return tdsqlite3StrAccumFinish(&sCheck.errMsg); } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ @@ -70760,9 +77942,9 @@ integrity_ck_cleanup: ** The pager filename is invariant as long as the pager is ** open so it is safe to access without the BtShared mutex. */ -SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){ +SQLITE_PRIVATE const char *tdsqlite3BtreeGetFilename(Btree *p){ assert( p->pBt->pPager!=0 ); - return sqlite3PagerFilename(p->pBt->pPager, 1); + return tdsqlite3PagerFilename(p->pBt->pPager, 1); } /* @@ -70773,16 +77955,16 @@ SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){ ** The pager journal filename is invariant as long as the pager is ** open so it is safe to access without the BtShared mutex. */ -SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){ +SQLITE_PRIVATE const char *tdsqlite3BtreeGetJournalname(Btree *p){ assert( p->pBt->pPager!=0 ); - return sqlite3PagerJournalname(p->pBt->pPager); + return tdsqlite3PagerJournalname(p->pBt->pPager); } /* ** Return non-zero if a transaction is active. */ -SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){ - assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); +SQLITE_PRIVATE int tdsqlite3BtreeIsInTrans(Btree *p){ + assert( p==0 || tdsqlite3_mutex_held(p->db->mutex) ); return (p && (p->inTrans==TRANS_WRITE)); } @@ -70795,17 +77977,17 @@ SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){ ** ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. */ -SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ +SQLITE_PRIVATE int tdsqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ int rc = SQLITE_OK; if( p ){ BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); if( pBt->inTransaction!=TRANS_NONE ){ rc = SQLITE_LOCKED; }else{ - rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt); + rc = tdsqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt); } - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); } return rc; } @@ -70814,15 +77996,15 @@ SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int * /* ** Return non-zero if a read (or write) transaction is active. */ -SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeIsInReadTrans(Btree *p){ assert( p ); - assert( sqlite3_mutex_held(p->db->mutex) ); + assert( tdsqlite3_mutex_held(p->db->mutex) ); return p->inTrans!=TRANS_NONE; } -SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeIsInBackup(Btree *p){ assert( p ); - assert( sqlite3_mutex_held(p->db->mutex) ); + assert( tdsqlite3_mutex_held(p->db->mutex) ); return p->nBackup!=0; } @@ -70843,17 +78025,17 @@ SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){ ** ** Just before the shared-btree is closed, the function passed as the ** xFree argument when the memory allocation was made is invoked on the -** blob of allocated memory. The xFree function should not call sqlite3_free() +** blob of allocated memory. The xFree function should not call tdsqlite3_free() ** on the memory, the btree layer does that. */ -SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ +SQLITE_PRIVATE void *tdsqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); if( !pBt->pSchema && nBytes ){ - pBt->pSchema = sqlite3DbMallocZero(0, nBytes); + pBt->pSchema = tdsqlite3DbMallocZero(0, nBytes); pBt->xFreeSchema = xFree; } - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return pBt->pSchema; } @@ -70862,13 +78044,13 @@ SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void ** btree as the argument handle holds an exclusive lock on the ** sqlite_master table. Otherwise SQLITE_OK. */ -SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeSchemaLocked(Btree *p){ int rc; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); + assert( tdsqlite3_mutex_held(p->db->mutex) ); + tdsqlite3BtreeEnter(p); rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE ); - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); return rc; } @@ -70879,7 +78061,7 @@ SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){ ** lock is a write lock if isWritelock is true or a read lock ** if it is false. */ -SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ +SQLITE_PRIVATE int tdsqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ int rc = SQLITE_OK; assert( p->inTrans!=TRANS_NONE ); if( p->sharable ){ @@ -70887,12 +78069,12 @@ SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ assert( READ_LOCK+1==WRITE_LOCK ); assert( isWriteLock==0 || isWriteLock==1 ); - sqlite3BtreeEnter(p); + tdsqlite3BtreeEnter(p); rc = querySharedCacheTableLock(p, iTab, lockType); if( rc==SQLITE_OK ){ rc = setSharedCacheTableLock(p, iTab, lockType); } - sqlite3BtreeLeave(p); + tdsqlite3BtreeLeave(p); } return rc; } @@ -70909,10 +78091,10 @@ SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ ** parameters that attempt to write past the end of the existing data, ** no modifications are made and SQLITE_CORRUPT is returned. */ -SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ +SQLITE_PRIVATE int tdsqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ int rc; assert( cursorOwnsBtShared(pCsr) ); - assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); + assert( tdsqlite3_mutex_held(pCsr->pBtree->db->mutex) ); assert( pCsr->curFlags & BTCF_Incrblob ); rc = restoreCursorPosition(pCsr); @@ -70949,7 +78131,7 @@ SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void && pCsr->pBt->inTransaction==TRANS_WRITE ); assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); - assert( pCsr->apPage[pCsr->iPage]->intKey ); + assert( pCsr->pPage->intKey ); return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); } @@ -70957,7 +78139,7 @@ SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void /* ** Mark this cursor as an incremental blob cursor. */ -SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ +SQLITE_PRIVATE void tdsqlite3BtreeIncrblobCursor(BtCursor *pCur){ pCur->curFlags |= BTCF_Incrblob; pCur->pBtree->hasIncrblobCur = 1; } @@ -70968,7 +78150,7 @@ SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ ** "write version" (single byte at byte offset 19) fields in the database ** header to iVersion. */ -SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ +SQLITE_PRIVATE int tdsqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ BtShared *pBt = pBtree->pBt; int rc; /* Return code */ @@ -70980,13 +78162,13 @@ SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ pBt->btsFlags &= ~BTS_NO_WAL; if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; - rc = sqlite3BtreeBeginTrans(pBtree, 0); + rc = tdsqlite3BtreeBeginTrans(pBtree, 0, 0); if( rc==SQLITE_OK ){ u8 *aData = pBt->pPage1->aData; if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ - rc = sqlite3BtreeBeginTrans(pBtree, 2); + rc = tdsqlite3BtreeBeginTrans(pBtree, 2, 0); if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); + rc = tdsqlite3PagerWrite(pBt->pPage1->pDbPage); if( rc==SQLITE_OK ){ aData[18] = (u8)iVersion; aData[19] = (u8)iVersion; @@ -71003,27 +78185,27 @@ SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ ** Return true if the cursor has a hint specified. This routine is ** only used from within assert() statements */ -SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){ +SQLITE_PRIVATE int tdsqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){ return (pCsr->hints & mask)!=0; } /* ** Return true if the given Btree is read-only. */ -SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeIsReadonly(Btree *p){ return (p->pBt->btsFlags & BTS_READ_ONLY)!=0; } /* ** Return the size of the header added to each page by this module. */ -SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); } +SQLITE_PRIVATE int tdsqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); } #if !defined(SQLITE_OMIT_SHARED_CACHE) /* ** Return true if the Btree passed as the only argument is sharable. */ -SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeSharable(Btree *p){ return p->sharable; } @@ -71032,7 +78214,7 @@ SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){ ** the Btree handle passed as the only argument. For private caches ** this is always 1. For shared caches it may be 1 or greater. */ -SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){ +SQLITE_PRIVATE int tdsqlite3BtreeConnectionCount(Btree *p){ testcase( p->sharable ); return p->pBt->nRef; } @@ -71051,7 +78233,7 @@ SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){ ** May you share freely, never taking more than you give. ** ************************************************************************* -** This file contains the implementation of the sqlite3_backup_XXX() +** This file contains the implementation of the tdsqlite3_backup_XXX() ** API functions and the related features. */ /* #include "sqliteInt.h" */ @@ -71060,14 +78242,14 @@ SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){ /* ** Structure allocated for each backup operation. */ -struct sqlite3_backup { - sqlite3* pDestDb; /* Destination database handle */ +struct tdsqlite3_backup { + tdsqlite3* pDestDb; /* Destination database handle */ Btree *pDest; /* Destination b-tree file */ u32 iDestSchema; /* Original schema cookie in destination */ int bDestLocked; /* True once a write-transaction is open on pDest */ Pgno iNext; /* Page number of the next source page to copy */ - sqlite3* pSrcDb; /* Source database handle */ + tdsqlite3* pSrcDb; /* Source database handle */ Btree *pSrc; /* Source b-tree file */ int rc; /* Backup process error code */ @@ -71079,16 +78261,16 @@ struct sqlite3_backup { Pgno nPagecount; /* Total number of pages to copy */ int isAttached; /* True once backup has been registered with pager */ - sqlite3_backup *pNext; /* Next backup associated with source pager */ + tdsqlite3_backup *pNext; /* Next backup associated with source pager */ }; /* ** THREAD SAFETY NOTES: ** -** Once it has been created using backup_init(), a single sqlite3_backup +** Once it has been created using backup_init(), a single tdsqlite3_backup ** structure may be accessed via two groups of thread-safe entry points: ** -** * Via the sqlite3_backup_XXX() API function backup_step() and +** * Via the tdsqlite3_backup_XXX() API function backup_step() and ** backup_finish(). Both these functions obtain the source database ** handle mutex and the mutex associated with the source BtShared ** structure, in that order. @@ -71099,7 +78281,7 @@ struct sqlite3_backup { ** associated with the source database BtShared structure will always ** be held when either of these functions are invoked. ** -** The other sqlite3_backup_XXX() API functions, backup_remaining() and +** The other tdsqlite3_backup_XXX() API functions, backup_remaining() and ** backup_pagecount() are not thread-safe functions. If they are called ** while some other thread is calling backup_step() or backup_finish(), ** the values returned may be invalid. There is no way for a call to @@ -71121,27 +78303,27 @@ struct sqlite3_backup { ** function. If an error occurs while doing so, return 0 and write an ** error message to pErrorDb. */ -static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ - int i = sqlite3FindDbName(pDb, zDb); +static Btree *findBtree(tdsqlite3 *pErrorDb, tdsqlite3 *pDb, const char *zDb){ + int i = tdsqlite3FindDbName(pDb, zDb); if( i==1 ){ Parse sParse; int rc = 0; memset(&sParse, 0, sizeof(sParse)); sParse.db = pDb; - if( sqlite3OpenTempDatabase(&sParse) ){ - sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg); + if( tdsqlite3OpenTempDatabase(&sParse) ){ + tdsqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg); rc = SQLITE_ERROR; } - sqlite3DbFree(pErrorDb, sParse.zErrMsg); - sqlite3ParserReset(&sParse); + tdsqlite3DbFree(pErrorDb, sParse.zErrMsg); + tdsqlite3ParserReset(&sParse); if( rc ){ return 0; } } if( i<0 ){ - sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb); + tdsqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb); return 0; } @@ -71152,9 +78334,9 @@ static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ ** Attempt to set the page size of the destination to match the page size ** of the source. */ -static int setDestPgsz(sqlite3_backup *p){ +static int setDestPgsz(tdsqlite3_backup *p){ int rc; - rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0); + rc = tdsqlite3BtreeSetPageSize(p->pDest,tdsqlite3BtreeGetPageSize(p->pSrc),-1,0); return rc; } @@ -71164,61 +78346,80 @@ static int setDestPgsz(sqlite3_backup *p){ ** is an open read-transaction, return SQLITE_ERROR and leave an error ** message in database handle db. */ -static int checkReadTransaction(sqlite3 *db, Btree *p){ - if( sqlite3BtreeIsInReadTrans(p) ){ - sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use"); +static int checkReadTransaction(tdsqlite3 *db, Btree *p){ + if( tdsqlite3BtreeIsInReadTrans(p) ){ + tdsqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use"); return SQLITE_ERROR; } return SQLITE_OK; } /* -** Create an sqlite3_backup process to copy the contents of zSrcDb from +** Create an tdsqlite3_backup process to copy the contents of zSrcDb from ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return -** a pointer to the new sqlite3_backup object. +** a pointer to the new tdsqlite3_backup object. ** ** If an error occurs, NULL is returned and an error code and error message ** stored in database handle pDestDb. */ -SQLITE_API sqlite3_backup *sqlite3_backup_init( - sqlite3* pDestDb, /* Database to write to */ +SQLITE_API tdsqlite3_backup *tdsqlite3_backup_init( + tdsqlite3* pDestDb, /* Database to write to */ const char *zDestDb, /* Name of database within pDestDb */ - sqlite3* pSrcDb, /* Database connection to read from */ + tdsqlite3* pSrcDb, /* Database connection to read from */ const char *zSrcDb /* Name of database within pSrcDb */ ){ - sqlite3_backup *p; /* Value to return */ + tdsqlite3_backup *p; /* Value to return */ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){ + if( !tdsqlite3SafetyCheckOk(pSrcDb)||!tdsqlite3SafetyCheckOk(pDestDb) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif +/* BEGIN SQLCIPHER */ +#ifdef SQLITE_HAS_CODEC + { + int srcNKey, destNKey; + void *zKey; + + tdsqlite3CodecGetKey(pSrcDb, sqlcipher_find_db_index(pSrcDb, zSrcDb), &zKey, &srcNKey); + tdsqlite3CodecGetKey(pDestDb, sqlcipher_find_db_index(pDestDb, zDestDb), &zKey, &destNKey); + zKey = NULL; + + /* either both databases must be plaintext, or both must be encrypted */ + if((srcNKey == 0 && destNKey > 0) || (srcNKey > 0 && destNKey == 0)) { + tdsqlite3ErrorWithMsg(pDestDb, SQLITE_ERROR, "backup is not supported with encrypted databases"); + return NULL; + } + } +#endif +/* END SQLCIPHER */ + /* Lock the source database handle. The destination database ** handle is not locked in this routine, but it is locked in - ** sqlite3_backup_step(). The user is required to ensure that no + ** tdsqlite3_backup_step(). The user is required to ensure that no ** other thread accesses the destination handle for the duration ** of the backup operation. Any attempt to use the destination ** database connection while a backup is in progress may cause ** a malfunction or a deadlock. */ - sqlite3_mutex_enter(pSrcDb->mutex); - sqlite3_mutex_enter(pDestDb->mutex); + tdsqlite3_mutex_enter(pSrcDb->mutex); + tdsqlite3_mutex_enter(pDestDb->mutex); if( pSrcDb==pDestDb ){ - sqlite3ErrorWithMsg( + tdsqlite3ErrorWithMsg( pDestDb, SQLITE_ERROR, "source and destination must be distinct" ); p = 0; }else { - /* Allocate space for a new sqlite3_backup object... - ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a - ** call to sqlite3_backup_init() and is destroyed by a call to - ** sqlite3_backup_finish(). */ - p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup)); + /* Allocate space for a new tdsqlite3_backup object... + ** EVIDENCE-OF: R-64852-21591 The tdsqlite3_backup object is created by a + ** call to tdsqlite3_backup_init() and is destroyed by a call to + ** tdsqlite3_backup_finish(). */ + p = (tdsqlite3_backup *)tdsqlite3MallocZero(sizeof(tdsqlite3_backup)); if( !p ){ - sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT); + tdsqlite3Error(pDestDb, SQLITE_NOMEM_BKPT); } } @@ -71237,9 +78438,9 @@ SQLITE_API sqlite3_backup *sqlite3_backup_init( /* One (or both) of the named databases did not exist or an OOM ** error was hit. Or there is a transaction open on the destination ** database. The error has already been written into the pDestDb - ** handle. All that is left to do here is free the sqlite3_backup + ** handle. All that is left to do here is free the tdsqlite3_backup ** structure. */ - sqlite3_free(p); + tdsqlite3_free(p); p = 0; } } @@ -71247,8 +78448,8 @@ SQLITE_API sqlite3_backup *sqlite3_backup_init( p->pSrc->nBackup++; } - sqlite3_mutex_leave(pDestDb->mutex); - sqlite3_mutex_leave(pSrcDb->mutex); + tdsqlite3_mutex_leave(pDestDb->mutex); + tdsqlite3_mutex_leave(pSrcDb->mutex); return p; } @@ -71267,27 +78468,27 @@ static int isFatalError(int rc){ ** destination database. */ static int backupOnePage( - sqlite3_backup *p, /* Backup handle */ + tdsqlite3_backup *p, /* Backup handle */ Pgno iSrcPg, /* Source database page to backup */ const u8 *zSrcData, /* Source database page data */ int bUpdate /* True for an update, false otherwise */ ){ - Pager * const pDestPager = sqlite3BtreePager(p->pDest); - const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc); - int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest); + Pager * const pDestPager = tdsqlite3BtreePager(p->pDest); + const int nSrcPgsz = tdsqlite3BtreeGetPageSize(p->pSrc); + int nDestPgsz = tdsqlite3BtreeGetPageSize(p->pDest); const int nCopy = MIN(nSrcPgsz, nDestPgsz); const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz; #ifdef SQLITE_HAS_CODEC /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is ** guaranteed that the shared-mutex is held by this thread, handle ** p->pSrc may not actually be the owner. */ - int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc); - int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest); + int nSrcReserve = tdsqlite3BtreeGetReserveNoMutex(p->pSrc); + int nDestReserve = tdsqlite3BtreeGetOptimalReserve(p->pDest); #endif int rc = SQLITE_OK; i64 iOff; - assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 ); + assert( tdsqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 ); assert( p->bDestLocked ); assert( !isFatalError(p->rc) ); assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ); @@ -71296,7 +78497,7 @@ static int backupOnePage( /* Catch the case where the destination is an in-memory database and the ** page sizes of the source and destination differ. */ - if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){ + if( nSrcPgsz!=nDestPgsz && tdsqlite3PagerIsMemdb(pDestPager) ){ rc = SQLITE_READONLY; } @@ -71304,7 +78505,7 @@ static int backupOnePage( /* Backup is not possible if the page size of the destination is changing ** and a codec is in use. */ - if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){ + if( nSrcPgsz!=nDestPgsz && tdsqlite3PagerGetCodec(pDestPager)!=0 ){ rc = SQLITE_READONLY; } @@ -71315,8 +78516,8 @@ static int backupOnePage( */ if( nSrcReserve!=nDestReserve ){ u32 newPgsz = nSrcPgsz; - rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve); - if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY; + rc = tdsqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve); + if( rc==SQLITE_OK && newPgsz!=(u32)nSrcPgsz ) rc = SQLITE_READONLY; } #endif @@ -71328,11 +78529,11 @@ static int backupOnePage( DbPage *pDestPg = 0; Pgno iDest = (Pgno)(iOff/nDestPgsz)+1; if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue; - if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0)) - && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg)) + if( SQLITE_OK==(rc = tdsqlite3PagerGet(pDestPager, iDest, &pDestPg, 0)) + && SQLITE_OK==(rc = tdsqlite3PagerWrite(pDestPg)) ){ const u8 *zIn = &zSrcData[iOff%nSrcPgsz]; - u8 *zDestData = sqlite3PagerGetData(pDestPg); + u8 *zDestData = tdsqlite3PagerGetData(pDestPg); u8 *zOut = &zDestData[iOff%nDestPgsz]; /* Copy the data from the source page into the destination page. @@ -71343,12 +78544,12 @@ static int backupOnePage( ** "MUST BE FIRST" for this purpose. */ memcpy(zOut, zIn, nCopy); - ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0; + ((u8 *)tdsqlite3PagerGetExtra(pDestPg))[0] = 0; if( iOff==0 && bUpdate==0 ){ - sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc)); + tdsqlite3Put4byte(&zOut[28], tdsqlite3BtreeLastPage(p->pSrc)); } } - sqlite3PagerUnref(pDestPg); + tdsqlite3PagerUnref(pDestPg); } return rc; @@ -71362,11 +78563,11 @@ static int backupOnePage( ** Return SQLITE_OK if everything is successful, or an SQLite error ** code if an error occurs. */ -static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){ +static int backupTruncateFile(tdsqlite3_file *pFile, i64 iSize){ i64 iCurrent; - int rc = sqlite3OsFileSize(pFile, &iCurrent); + int rc = tdsqlite3OsFileSize(pFile, &iCurrent); if( rc==SQLITE_OK && iCurrent>iSize ){ - rc = sqlite3OsTruncate(pFile, iSize); + rc = tdsqlite3OsTruncate(pFile, iSize); } return rc; } @@ -71375,10 +78576,10 @@ static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){ ** Register this backup object with the associated source pager for ** callbacks when pages are changed or the cache invalidated. */ -static void attachBackupObject(sqlite3_backup *p){ - sqlite3_backup **pp; - assert( sqlite3BtreeHoldsMutex(p->pSrc) ); - pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); +static void attachBackupObject(tdsqlite3_backup *p){ + tdsqlite3_backup **pp; + assert( tdsqlite3BtreeHoldsMutex(p->pSrc) ); + pp = tdsqlite3PagerBackupPtr(tdsqlite3BtreePager(p->pSrc)); p->pNext = *pp; *pp = p; p->isAttached = 1; @@ -71387,7 +78588,7 @@ static void attachBackupObject(sqlite3_backup *p){ /* ** Copy nPage pages from the source b-tree to the destination. */ -SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ +SQLITE_API int tdsqlite3_backup_step(tdsqlite3_backup *p, int nPage){ int rc; int destMode; /* Destination journal mode */ int pgszSrc = 0; /* Source page size */ @@ -71396,16 +78597,16 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ #ifdef SQLITE_ENABLE_API_ARMOR if( p==0 ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(p->pSrcDb->mutex); - sqlite3BtreeEnter(p->pSrc); + tdsqlite3_mutex_enter(p->pSrcDb->mutex); + tdsqlite3BtreeEnter(p->pSrc); if( p->pDestDb ){ - sqlite3_mutex_enter(p->pDestDb->mutex); + tdsqlite3_mutex_enter(p->pDestDb->mutex); } rc = p->rc; if( !isFatalError(rc) ){ - Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */ - Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */ + Pager * const pSrcPager = tdsqlite3BtreePager(p->pSrc); /* Source pager */ + Pager * const pDestPager = tdsqlite3BtreePager(p->pDest); /* Dest pager */ int ii; /* Iterator variable */ int nSrcPage = -1; /* Size of source db in pages */ int bCloseTrans = 0; /* True if src db requires unlocking */ @@ -71423,8 +78624,8 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ ** one now. If a transaction is opened here, then it will be closed ** before this function exits. */ - if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){ - rc = sqlite3BtreeBeginTrans(p->pSrc, 0); + if( rc==SQLITE_OK && 0==tdsqlite3BtreeIsInReadTrans(p->pSrc) ){ + rc = tdsqlite3BtreeBeginTrans(p->pSrc, 0, 0); bCloseTrans = 1; } @@ -71440,17 +78641,17 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ /* Lock the destination database, if it is not locked already. */ if( SQLITE_OK==rc && p->bDestLocked==0 - && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) + && SQLITE_OK==(rc = tdsqlite3BtreeBeginTrans(p->pDest, 2, + (int*)&p->iDestSchema)) ){ p->bDestLocked = 1; - sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema); } /* Do not allow backup if the destination database is in WAL mode ** and the page sizes are different between source and destination */ - pgszSrc = sqlite3BtreeGetPageSize(p->pSrc); - pgszDest = sqlite3BtreeGetPageSize(p->pDest); - destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest)); + pgszSrc = tdsqlite3BtreeGetPageSize(p->pSrc); + pgszDest = tdsqlite3BtreeGetPageSize(p->pDest); + destMode = tdsqlite3PagerGetJournalMode(tdsqlite3BtreePager(p->pDest)); if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){ rc = SQLITE_READONLY; } @@ -71458,16 +78659,16 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ /* Now that there is a read-lock on the source database, query the ** source pager for the number of pages in the database. */ - nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc); + nSrcPage = (int)tdsqlite3BtreeLastPage(p->pSrc); assert( nSrcPage>=0 ); for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){ const Pgno iSrcPg = p->iNext; /* Source page number */ if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){ DbPage *pSrcPg; /* Source page object */ - rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY); + rc = tdsqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY); if( rc==SQLITE_OK ){ - rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0); - sqlite3PagerUnref(pSrcPg); + rc = backupOnePage(p, iSrcPg, tdsqlite3PagerGetData(pSrcPg), 0); + tdsqlite3PagerUnref(pSrcPg); } } p->iNext++; @@ -71489,18 +78690,18 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ */ if( rc==SQLITE_DONE ){ if( nSrcPage==0 ){ - rc = sqlite3BtreeNewDb(p->pDest); + rc = tdsqlite3BtreeNewDb(p->pDest); nSrcPage = 1; } if( rc==SQLITE_OK || rc==SQLITE_DONE ){ - rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1); + rc = tdsqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1); } if( rc==SQLITE_OK ){ if( p->pDestDb ){ - sqlite3ResetAllSchemasOfConnection(p->pDestDb); + tdsqlite3ResetAllSchemasOfConnection(p->pDestDb); } if( destMode==PAGER_JOURNALMODE_WAL ){ - rc = sqlite3BtreeSetVersion(p->pDest, 2); + rc = tdsqlite3BtreeSetVersion(p->pDest, 2); } } if( rc==SQLITE_OK ){ @@ -71510,15 +78711,15 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ ** size may be different to the source page size. ** ** If the source page size is smaller than the destination page size, - ** round up. In this case the call to sqlite3OsTruncate() below will + ** round up. In this case the call to tdsqlite3OsTruncate() below will ** fix the size of the file. However it is important to call - ** sqlite3PagerTruncateImage() here so that any pages in the + ** tdsqlite3PagerTruncateImage() here so that any pages in the ** destination file that lie beyond the nDestTruncate page mark are ** journalled by PagerCommitPhaseOne() before they are destroyed ** by the file truncation. */ - assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) ); - assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) ); + assert( pgszSrc==tdsqlite3BtreeGetPageSize(p->pSrc) ); + assert( pgszDest==tdsqlite3BtreeGetPageSize(p->pDest) ); if( pgszSrc<pgszDest ){ int ratio = pgszDest/pgszSrc; nDestTruncate = (nSrcPage+ratio-1)/ratio; @@ -71541,7 +78742,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ ** copied into the destination database. */ const i64 iSize = (i64)pgszSrc * (i64)nSrcPage; - sqlite3_file * const pFile = sqlite3PagerFile(pDestPager); + tdsqlite3_file * const pFile = tdsqlite3PagerFile(pDestPager); Pgno iPg; int nDstPage; i64 iOff; @@ -71560,19 +78761,19 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ ** the database file in any way, knowing that if a power failure ** occurs, the original database will be reconstructed from the ** journal file. */ - sqlite3PagerPagecount(pDestPager, &nDstPage); + tdsqlite3PagerPagecount(pDestPager, &nDstPage); for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){ if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){ DbPage *pPg; - rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0); + rc = tdsqlite3PagerGet(pDestPager, iPg, &pPg, 0); if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite(pPg); - sqlite3PagerUnref(pPg); + rc = tdsqlite3PagerWrite(pPg); + tdsqlite3PagerUnref(pPg); } } } if( rc==SQLITE_OK ){ - rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1); + rc = tdsqlite3PagerCommitPhaseOne(pDestPager, 0, 1); } /* Write the extra pages and truncate the database file as required */ @@ -71584,12 +78785,12 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ ){ PgHdr *pSrcPg = 0; const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1); - rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0); + rc = tdsqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0); if( rc==SQLITE_OK ){ - u8 *zData = sqlite3PagerGetData(pSrcPg); - rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff); + u8 *zData = tdsqlite3PagerGetData(pSrcPg); + rc = tdsqlite3OsWrite(pFile, zData, pgszSrc, iOff); } - sqlite3PagerUnref(pSrcPg); + tdsqlite3PagerUnref(pSrcPg); } if( rc==SQLITE_OK ){ rc = backupTruncateFile(pFile, iSize); @@ -71597,16 +78798,16 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ /* Sync the database file to disk. */ if( rc==SQLITE_OK ){ - rc = sqlite3PagerSync(pDestPager, 0); + rc = tdsqlite3PagerSync(pDestPager, 0); } }else{ - sqlite3PagerTruncateImage(pDestPager, nDestTruncate); - rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0); + tdsqlite3PagerTruncateImage(pDestPager, nDestTruncate); + rc = tdsqlite3PagerCommitPhaseOne(pDestPager, 0, 0); } /* Finish committing the transaction to the destination database. */ if( SQLITE_OK==rc - && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0)) + && SQLITE_OK==(rc = tdsqlite3BtreeCommitPhaseTwo(p->pDest, 0)) ){ rc = SQLITE_DONE; } @@ -71620,8 +78821,8 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ */ if( bCloseTrans ){ TESTONLY( int rc2 ); - TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0); - TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0); + TESTONLY( rc2 = ) tdsqlite3BtreeCommitPhaseOne(p->pSrc, 0); + TESTONLY( rc2 |= ) tdsqlite3BtreeCommitPhaseTwo(p->pSrc, 0); assert( rc2==SQLITE_OK ); } @@ -71631,28 +78832,28 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ p->rc = rc; } if( p->pDestDb ){ - sqlite3_mutex_leave(p->pDestDb->mutex); + tdsqlite3_mutex_leave(p->pDestDb->mutex); } - sqlite3BtreeLeave(p->pSrc); - sqlite3_mutex_leave(p->pSrcDb->mutex); + tdsqlite3BtreeLeave(p->pSrc); + tdsqlite3_mutex_leave(p->pSrcDb->mutex); return rc; } /* -** Release all resources associated with an sqlite3_backup* handle. +** Release all resources associated with an tdsqlite3_backup* handle. */ -SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){ - sqlite3_backup **pp; /* Ptr to head of pagers backup list */ - sqlite3 *pSrcDb; /* Source database connection */ +SQLITE_API int tdsqlite3_backup_finish(tdsqlite3_backup *p){ + tdsqlite3_backup **pp; /* Ptr to head of pagers backup list */ + tdsqlite3 *pSrcDb; /* Source database connection */ int rc; /* Value to return */ /* Enter the mutexes */ if( p==0 ) return SQLITE_OK; pSrcDb = p->pSrcDb; - sqlite3_mutex_enter(pSrcDb->mutex); - sqlite3BtreeEnter(p->pSrc); + tdsqlite3_mutex_enter(pSrcDb->mutex); + tdsqlite3BtreeEnter(p->pSrc); if( p->pDestDb ){ - sqlite3_mutex_enter(p->pDestDb->mutex); + tdsqlite3_mutex_enter(p->pDestDb->mutex); } /* Detach this backup from the source pager. */ @@ -71660,40 +78861,42 @@ SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){ p->pSrc->nBackup--; } if( p->isAttached ){ - pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); + pp = tdsqlite3PagerBackupPtr(tdsqlite3BtreePager(p->pSrc)); + assert( pp!=0 ); while( *pp!=p ){ pp = &(*pp)->pNext; + assert( pp!=0 ); } *pp = p->pNext; } /* If a transaction is still open on the Btree, roll it back. */ - sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0); + tdsqlite3BtreeRollback(p->pDest, SQLITE_OK, 0); /* Set the error code of the destination database handle. */ rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc; if( p->pDestDb ){ - sqlite3Error(p->pDestDb, rc); + tdsqlite3Error(p->pDestDb, rc); /* Exit the mutexes and free the backup context structure. */ - sqlite3LeaveMutexAndCloseZombie(p->pDestDb); + tdsqlite3LeaveMutexAndCloseZombie(p->pDestDb); } - sqlite3BtreeLeave(p->pSrc); + tdsqlite3BtreeLeave(p->pSrc); if( p->pDestDb ){ - /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a - ** call to sqlite3_backup_init() and is destroyed by a call to - ** sqlite3_backup_finish(). */ - sqlite3_free(p); + /* EVIDENCE-OF: R-64852-21591 The tdsqlite3_backup object is created by a + ** call to tdsqlite3_backup_init() and is destroyed by a call to + ** tdsqlite3_backup_finish(). */ + tdsqlite3_free(p); } - sqlite3LeaveMutexAndCloseZombie(pSrcDb); + tdsqlite3LeaveMutexAndCloseZombie(pSrcDb); return rc; } /* ** Return the number of pages still to be backed up as of the most recent -** call to sqlite3_backup_step(). +** call to tdsqlite3_backup_step(). */ -SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){ +SQLITE_API int tdsqlite3_backup_remaining(tdsqlite3_backup *p){ #ifdef SQLITE_ENABLE_API_ARMOR if( p==0 ){ (void)SQLITE_MISUSE_BKPT; @@ -71705,9 +78908,9 @@ SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){ /* ** Return the total number of pages in the source database as of the most -** recent call to sqlite3_backup_step(). +** recent call to tdsqlite3_backup_step(). */ -SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){ +SQLITE_API int tdsqlite3_backup_pagecount(tdsqlite3_backup *p){ #ifdef SQLITE_ENABLE_API_ARMOR if( p==0 ){ (void)SQLITE_MISUSE_BKPT; @@ -71730,13 +78933,13 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){ ** called. */ static SQLITE_NOINLINE void backupUpdate( - sqlite3_backup *p, + tdsqlite3_backup *p, Pgno iPage, const u8 *aData ){ assert( p!=0 ); do{ - assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); + assert( tdsqlite3_mutex_held(p->pSrc->pBt->mutex) ); if( !isFatalError(p->rc) && iPage<p->iNext ){ /* The backup process p has already copied page iPage. But now it ** has been modified by a transaction on the source pager. Copy @@ -71744,9 +78947,9 @@ static SQLITE_NOINLINE void backupUpdate( */ int rc; assert( p->pDestDb ); - sqlite3_mutex_enter(p->pDestDb->mutex); + tdsqlite3_mutex_enter(p->pDestDb->mutex); rc = backupOnePage(p, iPage, aData, 1); - sqlite3_mutex_leave(p->pDestDb->mutex); + tdsqlite3_mutex_leave(p->pDestDb->mutex); assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED ); if( rc!=SQLITE_OK ){ p->rc = rc; @@ -71754,7 +78957,7 @@ static SQLITE_NOINLINE void backupUpdate( } }while( (p = p->pNext)!=0 ); } -SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){ +SQLITE_PRIVATE void tdsqlite3BackupUpdate(tdsqlite3_backup *pBackup, Pgno iPage, const u8 *aData){ if( pBackup ) backupUpdate(pBackup, iPage, aData); } @@ -71769,10 +78972,10 @@ SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, con ** corresponding to the source database is held when this function is ** called. */ -SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){ - sqlite3_backup *p; /* Iterator variable */ +SQLITE_PRIVATE void tdsqlite3BackupRestart(tdsqlite3_backup *pBackup){ + tdsqlite3_backup *p; /* Iterator variable */ for(p=pBackup; p; p=p->pNext){ - assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); + assert( tdsqlite3_mutex_held(p->pSrc->pBt->mutex) ); p->iNext = 1; } } @@ -71786,25 +78989,25 @@ SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){ ** goes wrong, the transaction on pTo is rolled back. If successful, the ** transaction is committed before returning. */ -SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){ +SQLITE_PRIVATE int tdsqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){ int rc; - sqlite3_file *pFd; /* File descriptor for database pTo */ - sqlite3_backup b; - sqlite3BtreeEnter(pTo); - sqlite3BtreeEnter(pFrom); + tdsqlite3_file *pFd; /* File descriptor for database pTo */ + tdsqlite3_backup b; + tdsqlite3BtreeEnter(pTo); + tdsqlite3BtreeEnter(pFrom); - assert( sqlite3BtreeIsInTrans(pTo) ); - pFd = sqlite3PagerFile(sqlite3BtreePager(pTo)); + assert( tdsqlite3BtreeIsInTrans(pTo) ); + pFd = tdsqlite3PagerFile(tdsqlite3BtreePager(pTo)); if( pFd->pMethods ){ - i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom); - rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte); + i64 nByte = tdsqlite3BtreeGetPageSize(pFrom)*(i64)tdsqlite3BtreeLastPage(pFrom); + rc = tdsqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte); if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; if( rc ) goto copy_finished; } - /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set - ** to 0. This is used by the implementations of sqlite3_backup_step() - ** and sqlite3_backup_finish() to detect that they are being called + /* Set up an tdsqlite3_backup object. tdsqlite3_backup.pDestDb must be set + ** to 0. This is used by the implementations of tdsqlite3_backup_step() + ** and tdsqlite3_backup_finish() to detect that they are being called ** from this function, not directly by the user. */ memset(&b, 0, sizeof(b)); @@ -71814,29 +79017,29 @@ SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){ b.iNext = 1; #ifdef SQLITE_HAS_CODEC - sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom)); + tdsqlite3PagerAlignReserve(tdsqlite3BtreePager(pTo), tdsqlite3BtreePager(pFrom)); #endif /* 0x7FFFFFFF is the hard limit for the number of pages in a database ** file. By passing this as the number of pages to copy to - ** sqlite3_backup_step(), we can guarantee that the copy finishes + ** tdsqlite3_backup_step(), we can guarantee that the copy finishes ** within a single call (unless an error occurs). The assert() statement ** checks this assumption - (p->rc) should be set to either SQLITE_DONE ** or an error code. */ - sqlite3_backup_step(&b, 0x7FFFFFFF); + tdsqlite3_backup_step(&b, 0x7FFFFFFF); assert( b.rc!=SQLITE_OK ); - rc = sqlite3_backup_finish(&b); + rc = tdsqlite3_backup_finish(&b); if( rc==SQLITE_OK ){ pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; }else{ - sqlite3PagerClearCache(sqlite3BtreePager(b.pDest)); + tdsqlite3PagerClearCache(tdsqlite3BtreePager(b.pDest)); } - assert( sqlite3BtreeIsInTrans(pTo)==0 ); + assert( tdsqlite3BtreeIsInTrans(pTo)==0 ); copy_finished: - sqlite3BtreeLeave(pFrom); - sqlite3BtreeLeave(pTo); + tdsqlite3BtreeLeave(pFrom); + tdsqlite3BtreeLeave(pTo); return rc; } #endif /* SQLITE_OMIT_VACUUM */ @@ -71863,16 +79066,21 @@ copy_finished: /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ +/* True if X is a power of two. 0 is considered a power of two here. +** In other words, return true if X has at most one bit set. +*/ +#define ISPOWEROF2(X) (((X)&((X)-1))==0) + #ifdef SQLITE_DEBUG /* ** Check invariants on a Mem object. ** ** This routine is intended for use inside of assert() statements, like -** this: assert( sqlite3VdbeCheckMemInvariants(pMem) ); +** this: assert( tdsqlite3VdbeCheckMemInvariants(pMem) ); */ -SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){ +SQLITE_PRIVATE int tdsqlite3VdbeCheckMemInvariants(Mem *p){ /* If MEM_Dyn is set then Mem.xDel!=0. - ** Mem.xDel is might not be initialized if MEM_Dyn is clear. + ** Mem.xDel might not be initialized if MEM_Dyn is clear. */ assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 ); @@ -71882,12 +79090,40 @@ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){ ** That saves a few cycles in inner loops. */ assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 ); - /* Cannot be both MEM_Int and MEM_Real at the same time */ - assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) ); + /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */ + assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) ); + + if( p->flags & MEM_Null ){ + /* Cannot be both MEM_Null and some other type */ + assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 ); + + /* If MEM_Null is set, then either the value is a pure NULL (the usual + ** case) or it is a pointer set using tdsqlite3_bind_pointer() or + ** tdsqlite3_result_pointer(). If a pointer, then MEM_Term must also be + ** set. + */ + if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){ + /* This is a pointer type. There may be a flag to indicate what to + ** do with the pointer. */ + assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) + + ((p->flags&MEM_Ephem)!=0 ? 1 : 0) + + ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 ); + + /* No other bits set */ + assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind + |MEM_Dyn|MEM_Ephem|MEM_Static))==0 ); + }else{ + /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn, + ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */ + } + }else{ + /* The MEM_Cleared bit is only allowed on NULLs */ + assert( (p->flags & MEM_Cleared)==0 ); + } /* The szMalloc field holds the correct memory allocation size */ assert( p->szMalloc==0 - || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) ); + || p->szMalloc==tdsqlite3DbMallocSize(p->db,p->zMalloc) ); /* If p holds a string or blob, the Mem.z must point to exactly ** one of the following: @@ -71909,6 +79145,80 @@ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){ } #endif +/* +** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal +** into a buffer. +*/ +static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){ + StrAccum acc; + assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) ); + tdsqlite3StrAccumInit(&acc, 0, zBuf, sz, 0); + if( p->flags & MEM_Int ){ + tdsqlite3_str_appendf(&acc, "%lld", p->u.i); + }else if( p->flags & MEM_IntReal ){ + tdsqlite3_str_appendf(&acc, "%!.15g", (double)p->u.i); + }else{ + tdsqlite3_str_appendf(&acc, "%!.15g", p->u.r); + } + assert( acc.zText==zBuf && acc.mxAlloc<=0 ); + zBuf[acc.nChar] = 0; /* Fast version of tdsqlite3StrAccumFinish(&acc) */ +} + +#ifdef SQLITE_DEBUG +/* +** Validity checks on pMem. pMem holds a string. +** +** (1) Check that string value of pMem agrees with its integer or real value. +** (2) Check that the string is correctly zero terminated +** +** A single int or real value always converts to the same strings. But +** many different strings can be converted into the same int or real. +** If a table contains a numeric value and an index is based on the +** corresponding string value, then it is important that the string be +** derived from the numeric value, not the other way around, to ensure +** that the index and table are consistent. See ticket +** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for +** an example. +** +** This routine looks at pMem to verify that if it has both a numeric +** representation and a string representation then the string rep has +** been derived from the numeric and not the other way around. It returns +** true if everything is ok and false if there is a problem. +** +** This routine is for use inside of assert() statements only. +*/ +SQLITE_PRIVATE int tdsqlite3VdbeMemValidStrRep(Mem *p){ + char zBuf[100]; + char *z; + int i, j, incr; + if( (p->flags & MEM_Str)==0 ) return 1; + if( p->flags & MEM_Term ){ + /* Insure that the string is properly zero-terminated. Pay particular + ** attention to the case where p->n is odd */ + if( p->szMalloc>0 && p->z==p->zMalloc ){ + assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 ); + assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 ); + } + assert( p->z[p->n]==0 ); + assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 ); + assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 ); + } + if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1; + vdbeMemRenderNum(sizeof(zBuf), zBuf, p); + z = p->z; + i = j = 0; + incr = 1; + if( p->enc!=SQLITE_UTF8 ){ + incr = 2; + if( p->enc==SQLITE_UTF16BE ) z++; + } + while( zBuf[j] ){ + if( zBuf[j++]!=z[i] ) return 0; + i += incr; + } + return 1; +} +#endif /* SQLITE_DEBUG */ /* ** If pMem is an object with a valid string representation, this routine @@ -71923,17 +79233,17 @@ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){ ** SQLITE_NOMEM may be returned if a malloc() fails during conversion ** between formats. */ -SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){ +SQLITE_PRIVATE int tdsqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){ #ifndef SQLITE_OMIT_UTF16 int rc; #endif - assert( (pMem->flags&MEM_RowSet)==0 ); + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE || desiredEnc==SQLITE_UTF16BE ); if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){ return SQLITE_OK; } - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); #ifdef SQLITE_OMIT_UTF16 return SQLITE_ERROR; #else @@ -71941,7 +79251,7 @@ SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){ /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned, ** then the encoding of the value may not have changed. */ - rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc); + rc = tdsqlite3VdbeMemTranslate(pMem, (u8)desiredEnc); assert(rc==SQLITE_OK || rc==SQLITE_NOMEM); assert(rc==SQLITE_OK || pMem->enc!=desiredEnc); assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc); @@ -71950,17 +79260,16 @@ SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){ } /* -** Make sure pMem->z points to a writable allocation of at least -** min(n,32) bytes. +** Make sure pMem->z points to a writable allocation of at least n bytes. ** ** If the bPreserve argument is true, then copy of the content of ** pMem->z into the new allocation. pMem must be either a string or ** blob if bPreserve is true. If bPreserve is false, any prior content ** in pMem->z is discarded. */ -SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){ - assert( sqlite3VdbeCheckMemInvariants(pMem) ); - assert( (pMem->flags&MEM_RowSet)==0 ); +SQLITE_PRIVATE SQLITE_NOINLINE int tdsqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){ + assert( tdsqlite3VdbeCheckMemInvariants(pMem) ); + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); testcase( pMem->db==0 ); /* If the bPreserve flag is set to true, then the memory cell must already @@ -71969,27 +79278,31 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPre testcase( bPreserve && pMem->z==0 ); assert( pMem->szMalloc==0 - || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) ); - if( pMem->szMalloc<n ){ - if( n<32 ) n = 32; - if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){ - pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n); - bPreserve = 0; - }else{ - if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc); - pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n); - } - if( pMem->zMalloc==0 ){ - sqlite3VdbeMemSetNull(pMem); - pMem->z = 0; - pMem->szMalloc = 0; - return SQLITE_NOMEM_BKPT; + || pMem->szMalloc==tdsqlite3DbMallocSize(pMem->db, pMem->zMalloc) ); + if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){ + if( pMem->db ){ + pMem->z = pMem->zMalloc = tdsqlite3DbReallocOrFree(pMem->db, pMem->z, n); }else{ - pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); + pMem->zMalloc = tdsqlite3Realloc(pMem->z, n); + if( pMem->zMalloc==0 ) tdsqlite3_free(pMem->z); + pMem->z = pMem->zMalloc; } + bPreserve = 0; + }else{ + if( pMem->szMalloc>0 ) tdsqlite3DbFreeNN(pMem->db, pMem->zMalloc); + pMem->zMalloc = tdsqlite3DbMallocRaw(pMem->db, n); + } + if( pMem->zMalloc==0 ){ + tdsqlite3VdbeMemSetNull(pMem); + pMem->z = 0; + pMem->szMalloc = 0; + return SQLITE_NOMEM_BKPT; + }else{ + pMem->szMalloc = tdsqlite3DbMallocSize(pMem->db, pMem->zMalloc); } - if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){ + if( bPreserve && pMem->z ){ + assert( pMem->z!=pMem->zMalloc ); memcpy(pMem->zMalloc, pMem->z, pMem->n); } if( (pMem->flags&MEM_Dyn)!=0 ){ @@ -72009,21 +79322,41 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPre ** ** Any prior string or blob content in the pMem object may be discarded. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str -** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null -** values are preserved. +** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal, +** and MEM_Null values are preserved. ** ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM) ** if unable to complete the resizing. */ -SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){ - assert( szNew>0 ); +SQLITE_PRIVATE int tdsqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){ + assert( CORRUPT_DB || szNew>0 ); assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 ); if( pMem->szMalloc<szNew ){ - return sqlite3VdbeMemGrow(pMem, szNew, 0); + return tdsqlite3VdbeMemGrow(pMem, szNew, 0); } assert( (pMem->flags & MEM_Dyn)==0 ); pMem->z = pMem->zMalloc; - pMem->flags &= (MEM_Null|MEM_Int|MEM_Real); + pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal); + return SQLITE_OK; +} + +/* +** It is already known that pMem contains an unterminated string. +** Add the zero terminator. +** +** Three bytes of zero are added. In this way, there is guaranteed +** to be a double-zero byte at an even byte boundary in order to +** terminate a UTF16 string, even if the initial size of the buffer +** is an odd number of bytes. +*/ +static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){ + if( tdsqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){ + return SQLITE_NOMEM_BKPT; + } + pMem->z[pMem->n] = 0; + pMem->z[pMem->n+1] = 0; + pMem->z[pMem->n+2] = 0; + pMem->flags |= MEM_Term; return SQLITE_OK; } @@ -72033,18 +79366,14 @@ SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){ ** ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails. */ -SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( (pMem->flags&MEM_RowSet)==0 ); +SQLITE_PRIVATE int tdsqlite3VdbeMemMakeWriteable(Mem *pMem){ + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){ if( ExpandBlob(pMem) ) return SQLITE_NOMEM; if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){ - if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){ - return SQLITE_NOMEM_BKPT; - } - pMem->z[pMem->n] = 0; - pMem->z[pMem->n+1] = 0; - pMem->flags |= MEM_Term; + int rc = vdbeMemAddTerminator(pMem); + if( rc ) return rc; } } pMem->flags &= ~MEM_Ephem; @@ -72060,19 +79389,21 @@ SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){ ** blob stored in dynamically allocated space. */ #ifndef SQLITE_OMIT_INCRBLOB -SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){ +SQLITE_PRIVATE int tdsqlite3VdbeMemExpandBlob(Mem *pMem){ int nByte; assert( pMem->flags & MEM_Zero ); - assert( pMem->flags&MEM_Blob ); - assert( (pMem->flags&MEM_RowSet)==0 ); - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) ); + testcase( tdsqlite3_value_nochange(pMem) ); + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); /* Set nByte to the number of bytes required to store the expanded blob. */ nByte = pMem->n + pMem->u.nZero; if( nByte<=0 ){ + if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK; nByte = 1; } - if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){ + if( tdsqlite3VdbeMemGrow(pMem, nByte, 1) ){ return SQLITE_NOMEM_BKPT; } @@ -72084,24 +79415,10 @@ SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){ #endif /* -** It is already known that pMem contains an unterminated string. -** Add the zero terminator. -*/ -static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){ - if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){ - return SQLITE_NOMEM_BKPT; - } - pMem->z[pMem->n] = 0; - pMem->z[pMem->n+1] = 0; - pMem->flags |= MEM_Term; - return SQLITE_OK; -} - -/* ** Make sure the given Mem is \u0000 terminated. */ -SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); +SQLITE_PRIVATE int tdsqlite3VdbeMemNulTerminate(Mem *pMem){ + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) ); testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 ); if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){ @@ -72112,53 +79429,42 @@ SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){ } /* -** Add MEM_Str to the set of representations for the given Mem. Numbers -** are converted using sqlite3_snprintf(). Converting a BLOB to a string -** is a no-op. +** Add MEM_Str to the set of representations for the given Mem. This +** routine is only called if pMem is a number of some kind, not a NULL +** or a BLOB. ** -** Existing representations MEM_Int and MEM_Real are invalidated if -** bForce is true but are retained if bForce is false. +** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated +** if bForce is true but are retained if bForce is false. ** ** A MEM_Null value will never be passed to this function. This function is ** used for converting values to text for returning to the user (i.e. via -** sqlite3_value_text()), or for ensuring that values to be used as btree +** tdsqlite3_value_text()), or for ensuring that values to be used as btree ** keys are strings. In the former case a NULL pointer is returned the ** user and the latter is an internal programming error. */ -SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){ - int fg = pMem->flags; +SQLITE_PRIVATE int tdsqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){ const int nByte = 32; - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( !(fg&MEM_Zero) ); - assert( !(fg&(MEM_Str|MEM_Blob)) ); - assert( fg&(MEM_Int|MEM_Real) ); - assert( (pMem->flags&MEM_RowSet)==0 ); + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); + assert( !(pMem->flags&MEM_Zero) ); + assert( !(pMem->flags&(MEM_Str|MEM_Blob)) ); + assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) ); + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){ + if( tdsqlite3VdbeMemClearAndResize(pMem, nByte) ){ pMem->enc = 0; return SQLITE_NOMEM_BKPT; } - /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8 - ** string representation of the value. Then, if the required encoding - ** is UTF-16le or UTF-16be do a translation. - ** - ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16. - */ - if( fg & MEM_Int ){ - sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i); - }else{ - assert( fg & MEM_Real ); - sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r); - } - pMem->n = sqlite3Strlen30(pMem->z); + vdbeMemRenderNum(nByte, pMem->z, pMem); + assert( pMem->z!=0 ); + pMem->n = tdsqlite3Strlen30NN(pMem->z); pMem->enc = SQLITE_UTF8; pMem->flags |= MEM_Str|MEM_Term; - if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real); - sqlite3VdbeChangeEncoding(pMem, enc); + if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal); + tdsqlite3VdbeChangeEncoding(pMem, enc); return SQLITE_OK; } @@ -72170,56 +79476,72 @@ SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){ ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK ** otherwise. */ -SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){ - int rc = SQLITE_OK; - if( ALWAYS(pFunc && pFunc->xFinalize) ){ - sqlite3_context ctx; - Mem t; - assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef ); - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - memset(&ctx, 0, sizeof(ctx)); - memset(&t, 0, sizeof(t)); - t.flags = MEM_Null; - t.db = pMem->db; - ctx.pOut = &t; - ctx.pMem = pMem; - ctx.pFunc = pFunc; - pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */ - assert( (pMem->flags & MEM_Dyn)==0 ); - if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc); - memcpy(pMem, &t, sizeof(t)); - rc = ctx.isError; - } - return rc; +SQLITE_PRIVATE int tdsqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){ + tdsqlite3_context ctx; + Mem t; + assert( pFunc!=0 ); + assert( pFunc->xFinalize!=0 ); + assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef ); + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); + memset(&ctx, 0, sizeof(ctx)); + memset(&t, 0, sizeof(t)); + t.flags = MEM_Null; + t.db = pMem->db; + ctx.pOut = &t; + ctx.pMem = pMem; + ctx.pFunc = pFunc; + pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */ + assert( (pMem->flags & MEM_Dyn)==0 ); + if( pMem->szMalloc>0 ) tdsqlite3DbFreeNN(pMem->db, pMem->zMalloc); + memcpy(pMem, &t, sizeof(t)); + return ctx.isError; } /* +** Memory cell pAccum contains the context of an aggregate function. +** This routine calls the xValue method for that function and stores +** the results in memory cell pMem. +** +** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK +** otherwise. +*/ +#ifndef SQLITE_OMIT_WINDOWFUNC +SQLITE_PRIVATE int tdsqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){ + tdsqlite3_context ctx; + assert( pFunc!=0 ); + assert( pFunc->xValue!=0 ); + assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef ); + assert( pAccum->db==0 || tdsqlite3_mutex_held(pAccum->db->mutex) ); + memset(&ctx, 0, sizeof(ctx)); + tdsqlite3VdbeMemSetNull(pOut); + ctx.pOut = pOut; + ctx.pMem = pAccum; + ctx.pFunc = pFunc; + pFunc->xValue(&ctx); + return ctx.isError; +} +#endif /* SQLITE_OMIT_WINDOWFUNC */ + +/* ** If the memory cell contains a value that must be freed by ** invoking the external callback in Mem.xDel, then this routine ** will free that value. It also sets Mem.flags to MEM_Null. ** -** This is a helper routine for sqlite3VdbeMemSetNull() and -** for sqlite3VdbeMemRelease(). Use those other routines as the +** This is a helper routine for tdsqlite3VdbeMemSetNull() and +** for tdsqlite3VdbeMemRelease(). Use those other routines as the ** entry point for releasing Mem resources. */ static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){ - assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) ); + assert( p->db==0 || tdsqlite3_mutex_held(p->db->mutex) ); assert( VdbeMemDynamic(p) ); if( p->flags&MEM_Agg ){ - sqlite3VdbeMemFinalize(p, p->u.pDef); + tdsqlite3VdbeMemFinalize(p, p->u.pDef); assert( (p->flags & MEM_Agg)==0 ); testcase( p->flags & MEM_Dyn ); } if( p->flags&MEM_Dyn ){ - assert( (p->flags&MEM_RowSet)==0 ); assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 ); p->xDel((void *)p->z); - }else if( p->flags&MEM_RowSet ){ - sqlite3RowSetClear(p->u.pRowSet); - }else if( p->flags&MEM_Frame ){ - VdbeFrame *pFrame = p->u.pFrame; - pFrame->pParent = pFrame->v->pDelFrame; - pFrame->v->pDelFrame = pFrame; } p->flags = MEM_Null; } @@ -72228,7 +79550,7 @@ static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){ ** Release memory held by the Mem p, both external memory cleared ** by p->xDel and memory in p->zMalloc. ** -** This is a helper routine invoked by sqlite3VdbeMemRelease() in +** This is a helper routine invoked by tdsqlite3VdbeMemRelease() in ** the unusual case where there really is memory in p that needs ** to be freed. */ @@ -72237,7 +79559,7 @@ static SQLITE_NOINLINE void vdbeMemClear(Mem *p){ vdbeMemClearExternAndSetNull(p); } if( p->szMalloc ){ - sqlite3DbFree(p->db, p->zMalloc); + tdsqlite3DbFreeNN(p->db, p->zMalloc); p->szMalloc = 0; } p->z = 0; @@ -72250,11 +79572,11 @@ static SQLITE_NOINLINE void vdbeMemClear(Mem *p){ ** Use this routine prior to clean up prior to abandoning a Mem, or to ** reset a Mem back to its minimum memory utilization. ** -** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space +** Use tdsqlite3VdbeMemSetNull() to release just the Mem.xDel space ** prior to inserting new content into the Mem. */ -SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){ - assert( sqlite3VdbeCheckMemInvariants(p) ); +SQLITE_PRIVATE void tdsqlite3VdbeMemRelease(Mem *p){ + assert( tdsqlite3VdbeCheckMemInvariants(p) ); if( VdbeMemDynamic(p) || p->szMalloc ){ vdbeMemClear(p); } @@ -72265,7 +79587,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){ ** If the double is out of range of a 64-bit signed integer then ** return the closest available 64-bit signed integer. */ -static i64 doubleToInt64(double r){ +static SQLITE_NOINLINE i64 doubleToInt64(double r){ #ifdef SQLITE_OMIT_FLOATING_POINT /* When floating-point is omitted, double and int64 are the same thing */ return r; @@ -72301,20 +79623,23 @@ static i64 doubleToInt64(double r){ ** ** If pMem represents a string value, its encoding might be changed. */ -SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){ +static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){ + i64 value = 0; + tdsqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc); + return value; +} +SQLITE_PRIVATE i64 tdsqlite3VdbeIntValue(Mem *pMem){ int flags; - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); flags = pMem->flags; - if( flags & MEM_Int ){ + if( flags & (MEM_Int|MEM_IntReal) ){ + testcase( flags & MEM_IntReal ); return pMem->u.i; }else if( flags & MEM_Real ){ return doubleToInt64(pMem->u.r); - }else if( flags & (MEM_Str|MEM_Blob) ){ - i64 value = 0; - assert( pMem->z || pMem->n==0 ); - sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc); - return value; + }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){ + return memIntValue(pMem); }else{ return 0; } @@ -72326,18 +79651,22 @@ SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){ ** value. If it is a string or blob, try to convert it to a double. ** If it is a NULL, return 0.0. */ -SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); +static SQLITE_NOINLINE double memRealValue(Mem *pMem){ + /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ + double val = (double)0; + tdsqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc); + return val; +} +SQLITE_PRIVATE double tdsqlite3VdbeRealValue(Mem *pMem){ + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); if( pMem->flags & MEM_Real ){ return pMem->u.r; - }else if( pMem->flags & MEM_Int ){ + }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){ + testcase( pMem->flags & MEM_IntReal ); return (double)pMem->u.i; }else if( pMem->flags & (MEM_Str|MEM_Blob) ){ - /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ - double val = (double)0; - sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc); - return val; + return memRealValue(pMem); }else{ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ return (double)0; @@ -72345,14 +79674,25 @@ SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){ } /* +** Return 1 if pMem represents true, and return 0 if pMem represents false. +** Return the value ifNull if pMem is NULL. +*/ +SQLITE_PRIVATE int tdsqlite3VdbeBooleanValue(Mem *pMem, int ifNull){ + testcase( pMem->flags & MEM_IntReal ); + if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0; + if( pMem->flags & MEM_Null ) return ifNull; + return tdsqlite3VdbeRealValue(pMem)!=0.0; +} + +/* ** The MEM structure is already a MEM_Real. Try to also make it a ** MEM_Int if we can. */ -SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){ +SQLITE_PRIVATE void tdsqlite3VdbeIntegerAffinity(Mem *pMem){ i64 ix; assert( pMem->flags & MEM_Real ); - assert( (pMem->flags & MEM_RowSet)==0 ); - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); ix = doubleToInt64(pMem->u.r); @@ -72376,12 +79716,12 @@ SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){ /* ** Convert pMem to type integer. Invalidate any prior representations. */ -SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( (pMem->flags & MEM_RowSet)==0 ); +SQLITE_PRIVATE int tdsqlite3VdbeMemIntegerify(Mem *pMem){ + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - pMem->u.i = sqlite3VdbeIntValue(pMem); + pMem->u.i = tdsqlite3VdbeIntValue(pMem); MemSetTypeFlag(pMem, MEM_Int); return SQLITE_OK; } @@ -72390,36 +79730,60 @@ SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){ ** Convert pMem so that it is of type MEM_Real. ** Invalidate any prior representations. */ -SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); +SQLITE_PRIVATE int tdsqlite3VdbeMemRealify(Mem *pMem){ + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - pMem->u.r = sqlite3VdbeRealValue(pMem); + pMem->u.r = tdsqlite3VdbeRealValue(pMem); MemSetTypeFlag(pMem, MEM_Real); return SQLITE_OK; } +/* Compare a floating point value to an integer. Return true if the two +** values are the same within the precision of the floating point value. +** +** This function assumes that i was obtained by assignment from r1. +** +** For some versions of GCC on 32-bit machines, if you do the more obvious +** comparison of "r1==(double)i" you sometimes get an answer of false even +** though the r1 and (double)i values are bit-for-bit the same. +*/ +SQLITE_PRIVATE int tdsqlite3RealSameAsInt(double r1, tdsqlite3_int64 i){ + double r2 = (double)i; + return r1==0.0 + || (memcmp(&r1, &r2, sizeof(r1))==0 + && i >= -2251799813685248LL && i < 2251799813685248LL); +} + /* -** Convert pMem so that it has types MEM_Real or MEM_Int or both. +** Convert pMem so that it has type MEM_Real or MEM_Int. ** Invalidate any prior representations. ** ** Every effort is made to force the conversion, even if the input ** is a string that does not look completely like a number. Convert ** as much of the string as we can and ignore the rest. */ -SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){ - if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){ +SQLITE_PRIVATE int tdsqlite3VdbeMemNumerify(Mem *pMem){ + testcase( pMem->flags & MEM_Int ); + testcase( pMem->flags & MEM_Real ); + testcase( pMem->flags & MEM_IntReal ); + testcase( pMem->flags & MEM_Null ); + if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){ + int rc; + tdsqlite3_int64 ix; assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){ + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); + rc = tdsqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc); + if( ((rc==0 || rc==1) && tdsqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1) + || tdsqlite3RealSameAsInt(pMem->u.r, (ix = (i64)pMem->u.r)) + ){ + pMem->u.i = ix; MemSetTypeFlag(pMem, MEM_Int); }else{ - pMem->u.r = sqlite3VdbeRealValue(pMem); MemSetTypeFlag(pMem, MEM_Real); - sqlite3VdbeIntegerAffinity(pMem); } } - assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 ); + assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 ); pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero); return SQLITE_OK; } @@ -72431,12 +79795,12 @@ SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){ ** affinity even if that results in loss of data. This routine is ** used (for example) to implement the SQL "cast()" operator. */ -SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){ - if( pMem->flags & MEM_Null ) return; +SQLITE_PRIVATE int tdsqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){ + if( pMem->flags & MEM_Null ) return SQLITE_OK; switch( aff ){ case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */ if( (pMem->flags & MEM_Blob)==0 ){ - sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); + tdsqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); assert( pMem->flags & MEM_Str || pMem->db->mallocFailed ); if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob); }else{ @@ -72445,27 +79809,28 @@ SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){ break; } case SQLITE_AFF_NUMERIC: { - sqlite3VdbeMemNumerify(pMem); + tdsqlite3VdbeMemNumerify(pMem); break; } case SQLITE_AFF_INTEGER: { - sqlite3VdbeMemIntegerify(pMem); + tdsqlite3VdbeMemIntegerify(pMem); break; } case SQLITE_AFF_REAL: { - sqlite3VdbeMemRealify(pMem); + tdsqlite3VdbeMemRealify(pMem); break; } default: { assert( aff==SQLITE_AFF_TEXT ); assert( MEM_Str==(MEM_Blob>>3) ); pMem->flags |= (pMem->flags&MEM_Blob)>>3; - sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); + tdsqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); assert( pMem->flags & MEM_Str || pMem->db->mallocFailed ); - pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero); - break; + pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero); + return tdsqlite3VdbeChangeEncoding(pMem, encoding); } } + return SQLITE_OK; } /* @@ -72473,7 +79838,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){ ** ** The minimum amount of initialization feasible is performed. */ -SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){ +SQLITE_PRIVATE void tdsqlite3VdbeMemInit(Mem *pMem, tdsqlite3 *db, u16 flags){ assert( (flags & ~MEM_TypeMask)==0 ); pMem->flags = flags; pMem->db = db; @@ -72486,30 +79851,30 @@ SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){ ** ** This routine calls the Mem.xDel destructor to dispose of values that ** require the destructor. But it preserves the Mem.zMalloc memory allocation. -** To free all resources, use sqlite3VdbeMemRelease(), which both calls this +** To free all resources, use tdsqlite3VdbeMemRelease(), which both calls this ** routine to invoke the destructor and deallocates Mem.zMalloc. ** ** Use this routine to reset the Mem prior to insert a new value. ** -** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it. +** Use tdsqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it. */ -SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){ +SQLITE_PRIVATE void tdsqlite3VdbeMemSetNull(Mem *pMem){ if( VdbeMemDynamic(pMem) ){ vdbeMemClearExternAndSetNull(pMem); }else{ pMem->flags = MEM_Null; } } -SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){ - sqlite3VdbeMemSetNull((Mem*)p); +SQLITE_PRIVATE void tdsqlite3ValueSetNull(tdsqlite3_value *p){ + tdsqlite3VdbeMemSetNull((Mem*)p); } /* ** Delete any previous value and set the value to be a BLOB of length ** n containing all zeros. */ -SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){ - sqlite3VdbeMemRelease(pMem); +SQLITE_PRIVATE void tdsqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){ + tdsqlite3VdbeMemRelease(pMem); pMem->flags = MEM_Blob|MEM_Zero; pMem->n = 0; if( n<0 ) n = 0; @@ -72524,7 +79889,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){ ** a 64-bit integer. */ static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){ - sqlite3VdbeMemSetNull(pMem); + tdsqlite3VdbeMemSetNull(pMem); pMem->u.i = val; pMem->flags = MEM_Int; } @@ -72533,7 +79898,7 @@ static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){ ** Delete any previous value and set the value stored in *pMem to val, ** manifest type INTEGER. */ -SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ +SQLITE_PRIVATE void tdsqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ if( VdbeMemDynamic(pMem) ){ vdbeReleaseAndSetInt64(pMem, val); }else{ @@ -72542,47 +79907,78 @@ SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ } } +/* A no-op destructor */ +SQLITE_PRIVATE void tdsqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); } + +/* +** Set the value stored in *pMem should already be a NULL. +** Also store a pointer to go with it. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeMemSetPointer( + Mem *pMem, + void *pPtr, + const char *zPType, + void (*xDestructor)(void*) +){ + assert( pMem->flags==MEM_Null ); + pMem->u.zPType = zPType ? zPType : ""; + pMem->z = pPtr; + pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term; + pMem->eSubtype = 'p'; + pMem->xDel = xDestructor ? xDestructor : tdsqlite3NoopDestructor; +} + #ifndef SQLITE_OMIT_FLOATING_POINT /* ** Delete any previous value and set the value stored in *pMem to val, ** manifest type REAL. */ -SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){ - sqlite3VdbeMemSetNull(pMem); - if( !sqlite3IsNaN(val) ){ +SQLITE_PRIVATE void tdsqlite3VdbeMemSetDouble(Mem *pMem, double val){ + tdsqlite3VdbeMemSetNull(pMem); + if( !tdsqlite3IsNaN(val) ){ pMem->u.r = val; pMem->flags = MEM_Real; } } #endif +#ifdef SQLITE_DEBUG +/* +** Return true if the Mem holds a RowSet object. This routine is intended +** for use inside of assert() statements. +*/ +SQLITE_PRIVATE int tdsqlite3VdbeMemIsRowSet(const Mem *pMem){ + return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn) + && pMem->xDel==tdsqlite3RowSetDelete; +} +#endif + /* ** Delete any previous value and set the value of pMem to be an ** empty boolean index. +** +** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation +** error occurs. */ -SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){ - sqlite3 *db = pMem->db; +SQLITE_PRIVATE int tdsqlite3VdbeMemSetRowSet(Mem *pMem){ + tdsqlite3 *db = pMem->db; + RowSet *p; assert( db!=0 ); - assert( (pMem->flags & MEM_RowSet)==0 ); - sqlite3VdbeMemRelease(pMem); - pMem->zMalloc = sqlite3DbMallocRawNN(db, 64); - if( db->mallocFailed ){ - pMem->flags = MEM_Null; - pMem->szMalloc = 0; - }else{ - assert( pMem->zMalloc ); - pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc); - pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc); - assert( pMem->u.pRowSet!=0 ); - pMem->flags = MEM_RowSet; - } + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); + tdsqlite3VdbeMemRelease(pMem); + p = tdsqlite3RowSetInit(db); + if( p==0 ) return SQLITE_NOMEM; + pMem->z = (char*)p; + pMem->flags = MEM_Blob|MEM_Dyn; + pMem->xDel = tdsqlite3RowSetDelete; + return SQLITE_OK; } /* ** Return true if the Mem object contains a TEXT or BLOB that is ** too large - whose size exceeds SQLITE_MAX_LENGTH. */ -SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){ +SQLITE_PRIVATE int tdsqlite3VdbeMemTooBig(Mem *p){ assert( p->db!=0 ); if( p->flags & (MEM_Str|MEM_Blob) ){ int n = p->n; @@ -72600,15 +79996,36 @@ SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){ ** its link to a shallow copy and by marking any current shallow ** copies of this cell as invalid. ** -** This is used for testing and debugging only - to make sure shallow -** copies are not misused. +** This is used for testing and debugging only - to help ensure that shallow +** copies (created by OP_SCopy) are not misused. */ -SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ +SQLITE_PRIVATE void tdsqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ int i; Mem *pX; - for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){ + for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){ if( pX->pScopyFrom==pMem ){ - pX->flags |= MEM_Undefined; + u16 mFlags; + if( pVdbe->db->flags & SQLITE_VdbeTrace ){ + tdsqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n", + (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem)); + } + /* If pX is marked as a shallow copy of pMem, then verify that + ** no significant changes have been made to pX since the OP_SCopy. + ** A significant change would indicated a missed call to this + ** function for pX. Minor changes, such as adding or removing a + ** dual type, are allowed, as long as the underlying value is the + ** same. */ + mFlags = pMem->flags & pX->flags & pX->mScopyFlags; + assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i ); + /* assert( (mFlags&MEM_Real)==0 || pMem->u.r==pX->u.r ); */ + /* ^^ */ + /* Cannot reliably compare doubles for equality */ + assert( (mFlags&MEM_Str)==0 || (pMem->n==pX->n && pMem->z==pX->z) ); + assert( (mFlags&MEM_Blob)==0 || tdsqlite3BlobCompare(pMem,pX)==0 ); + + /* pMem is the register that is changing. But also mark pX as + ** undefined so that we can quickly detect the shallow-copy error */ + pX->flags = MEM_Undefined; pX->pScopyFrom = 0; } } @@ -72616,7 +80033,6 @@ SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ } #endif /* SQLITE_DEBUG */ - /* ** Make an shallow copy of pFrom into pTo. Prior contents of ** pTo are freed. The pFrom->z field is not duplicated. If @@ -72626,10 +80042,10 @@ SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){ vdbeMemClearExternAndSetNull(pTo); assert( !VdbeMemDynamic(pTo) ); - sqlite3VdbeMemShallowCopy(pTo, pFrom, eType); + tdsqlite3VdbeMemShallowCopy(pTo, pFrom, eType); } -SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){ - assert( (pFrom->flags & MEM_RowSet)==0 ); +SQLITE_PRIVATE void tdsqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){ + assert( !tdsqlite3VdbeMemIsRowSet(pFrom) ); assert( pTo->db==pFrom->db ); if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; } memcpy(pTo, pFrom, MEMCELLSIZE); @@ -72644,17 +80060,17 @@ SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int sr ** Make a full copy of pFrom into pTo. Prior contents of pTo are ** freed before the copy is made. */ -SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ +SQLITE_PRIVATE int tdsqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ int rc = SQLITE_OK; - assert( (pFrom->flags & MEM_RowSet)==0 ); + assert( !tdsqlite3VdbeMemIsRowSet(pFrom) ); if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo); memcpy(pTo, pFrom, MEMCELLSIZE); pTo->flags &= ~MEM_Dyn; if( pTo->flags&(MEM_Str|MEM_Blob) ){ if( 0==(pFrom->flags&MEM_Static) ){ pTo->flags |= MEM_Ephem; - rc = sqlite3VdbeMemMakeWriteable(pTo); + rc = tdsqlite3VdbeMemMakeWriteable(pTo); } } @@ -72667,12 +80083,12 @@ SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ ** ** pFrom contains an SQL NULL when this routine returns. */ -SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ - assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) ); - assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) ); +SQLITE_PRIVATE void tdsqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ + assert( pFrom->db==0 || tdsqlite3_mutex_held(pFrom->db->mutex) ); + assert( pTo->db==0 || tdsqlite3_mutex_held(pTo->db->mutex) ); assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db ); - sqlite3VdbeMemRelease(pTo); + tdsqlite3VdbeMemRelease(pTo); memcpy(pTo, pFrom, sizeof(Mem)); pFrom->flags = MEM_Null; pFrom->szMalloc = 0; @@ -72693,7 +80109,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ ** is required to store the string, then value of pMem is unchanged. In ** either case, SQLITE_TOOBIG is returned. */ -SQLITE_PRIVATE int sqlite3VdbeMemSetStr( +SQLITE_PRIVATE int tdsqlite3VdbeMemSetStr( Mem *pMem, /* Memory cell to set to string value */ const char *z, /* String pointer */ int n, /* Bytes in string, or negative */ @@ -72704,12 +80120,12 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr( int iLimit; /* Maximum allowed string or blob size */ u16 flags = 0; /* New value for pMem->flags */ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( (pMem->flags & MEM_RowSet)==0 ); + assert( pMem->db==0 || tdsqlite3_mutex_held(pMem->db->mutex) ); + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); /* If z is a NULL pointer, set pMem to contain an SQL NULL. */ if( !z ){ - sqlite3VdbeMemSetNull(pMem); + tdsqlite3VdbeMemSetNull(pMem); return SQLITE_OK; } @@ -72722,8 +80138,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr( if( nByte<0 ){ assert( enc!=0 ); if( enc==SQLITE_UTF8 ){ - nByte = sqlite3Strlen30(z); - if( nByte>iLimit ) nByte = iLimit+1; + nByte = 0x7fffffff & (int)strlen(z); }else{ for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){} } @@ -72735,37 +80150,47 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr( ** management (one of MEM_Dyn or MEM_Static). */ if( xDel==SQLITE_TRANSIENT ){ - int nAlloc = nByte; + u32 nAlloc = nByte; if( flags&MEM_Term ){ nAlloc += (enc==SQLITE_UTF8?1:2); } if( nByte>iLimit ){ - return SQLITE_TOOBIG; + return tdsqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG); } testcase( nAlloc==0 ); testcase( nAlloc==31 ); testcase( nAlloc==32 ); - if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){ + if( tdsqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){ return SQLITE_NOMEM_BKPT; } memcpy(pMem->z, z, nAlloc); - }else if( xDel==SQLITE_DYNAMIC ){ - sqlite3VdbeMemRelease(pMem); - pMem->zMalloc = pMem->z = (char *)z; - pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); }else{ - sqlite3VdbeMemRelease(pMem); + tdsqlite3VdbeMemRelease(pMem); pMem->z = (char *)z; - pMem->xDel = xDel; - flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn); + if( xDel==SQLITE_DYNAMIC ){ + pMem->zMalloc = pMem->z; + pMem->szMalloc = tdsqlite3DbMallocSize(pMem->db, pMem->zMalloc); + }else{ + pMem->xDel = xDel; + flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn); + } } pMem->n = nByte; pMem->flags = flags; - pMem->enc = (enc==0 ? SQLITE_UTF8 : enc); + if( enc ){ + pMem->enc = enc; +#ifdef SQLITE_ENABLE_SESSION + }else if( pMem->db==0 ){ + pMem->enc = SQLITE_UTF8; +#endif + }else{ + assert( pMem->db!=0 ); + pMem->enc = ENC(pMem->db); + } #ifndef SQLITE_OMIT_UTF16 - if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){ + if( enc>SQLITE_UTF8 && tdsqlite3VdbeMemHandleBom(pMem) ){ return SQLITE_NOMEM_BKPT; } #endif @@ -72779,10 +80204,9 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr( /* ** Move data out of a btree key or data field and into a Mem structure. -** The data or key is taken from the entry that pCur is currently pointing +** The data is payload from the entry that pCur is currently pointing ** to. offset and amt determine what portion of the data or key to retrieve. -** key is true to get the key or false to get data. The result is written -** into the pMem element. +** The result is written into the pMem element. ** ** The pMem object must have been initialized. This routine will use ** pMem->zMalloc to hold the content from the btree, if possible. New @@ -72797,46 +80221,42 @@ static SQLITE_NOINLINE int vdbeMemFromBtreeResize( BtCursor *pCur, /* Cursor pointing at record to retrieve. */ u32 offset, /* Offset from the start of data to return bytes from. */ u32 amt, /* Number of bytes to return. */ - int key, /* If true, retrieve from the btree key, not data. */ Mem *pMem /* OUT: Return data in this Mem structure. */ ){ int rc; pMem->flags = MEM_Null; - if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){ - if( key ){ - rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z); - }else{ - rc = sqlite3BtreeData(pCur, offset, amt, pMem->z); - } + if( tdsqlite3BtreeMaxRecordSize(pCur)<offset+amt ){ + return SQLITE_CORRUPT_BKPT; + } + if( SQLITE_OK==(rc = tdsqlite3VdbeMemClearAndResize(pMem, amt+1)) ){ + rc = tdsqlite3BtreePayload(pCur, offset, amt, pMem->z); if( rc==SQLITE_OK ){ - pMem->z[amt] = 0; - pMem->z[amt+1] = 0; - pMem->flags = MEM_Blob|MEM_Term; + pMem->z[amt] = 0; /* Overrun area used when reading malformed records */ + pMem->flags = MEM_Blob; pMem->n = (int)amt; }else{ - sqlite3VdbeMemRelease(pMem); + tdsqlite3VdbeMemRelease(pMem); } } return rc; } -SQLITE_PRIVATE int sqlite3VdbeMemFromBtree( +SQLITE_PRIVATE int tdsqlite3VdbeMemFromBtree( BtCursor *pCur, /* Cursor pointing at record to retrieve. */ u32 offset, /* Offset from the start of data to return bytes from. */ u32 amt, /* Number of bytes to return. */ - int key, /* If true, retrieve from the btree key, not data. */ Mem *pMem /* OUT: Return data in this Mem structure. */ ){ char *zData; /* Data from the btree layer */ u32 available = 0; /* Number of bytes available on the local btree page */ int rc = SQLITE_OK; /* Return code */ - assert( sqlite3BtreeCursorIsValid(pCur) ); + assert( tdsqlite3BtreeCursorIsValid(pCur) ); assert( !VdbeMemDynamic(pMem) ); /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() ** that both the BtShared and database handle mutexes are held. */ - assert( (pMem->flags & MEM_RowSet)==0 ); - zData = (char *)sqlite3BtreePayloadFetch(pCur, &available); + assert( !tdsqlite3VdbeMemIsRowSet(pMem) ); + zData = (char *)tdsqlite3BtreePayloadFetch(pCur, &available); assert( zData!=0 ); if( offset+amt<=available ){ @@ -72844,7 +80264,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemFromBtree( pMem->flags = MEM_Blob|MEM_Ephem; pMem->n = (int)amt; }else{ - rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem); + rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem); } return rc; @@ -72855,31 +80275,33 @@ SQLITE_PRIVATE int sqlite3VdbeMemFromBtree( ** Convert it into a string with encoding enc and return a pointer ** to a zero-terminated version of that string. */ -static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){ +static SQLITE_NOINLINE const void *valueToText(tdsqlite3_value* pVal, u8 enc){ assert( pVal!=0 ); - assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); + assert( pVal->db==0 || tdsqlite3_mutex_held(pVal->db->mutex) ); assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); - assert( (pVal->flags & MEM_RowSet)==0 ); + assert( !tdsqlite3VdbeMemIsRowSet(pVal) ); assert( (pVal->flags & (MEM_Null))==0 ); if( pVal->flags & (MEM_Blob|MEM_Str) ){ + if( ExpandBlob(pVal) ) return 0; pVal->flags |= MEM_Str; if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){ - sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED); + tdsqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED); } if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){ assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 ); - if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){ + if( tdsqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){ return 0; } } - sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */ + tdsqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */ }else{ - sqlite3VdbeMemStringify(pVal, enc, 0); + tdsqlite3VdbeMemStringify(pVal, enc, 0); assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) ); } assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0 || pVal->db->mallocFailed ); if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){ + assert( tdsqlite3VdbeMemValidStrRep(pVal) ); return pVal->z; }else{ return 0; @@ -72887,7 +80309,7 @@ static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){ } /* This function is only available internally, it is not part of the -** external API. It works in a similar way to sqlite3_value_text(), +** external API. It works in a similar way to tdsqlite3_value_text(), ** except the data returned is in the encoding specified by the second ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or ** SQLITE_UTF8. @@ -72896,12 +80318,13 @@ static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){ ** If that is the case, then the result must be aligned on an even byte ** boundary. */ -SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){ +SQLITE_PRIVATE const void *tdsqlite3ValueText(tdsqlite3_value* pVal, u8 enc){ if( !pVal ) return 0; - assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); + assert( pVal->db==0 || tdsqlite3_mutex_held(pVal->db->mutex) ); assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); - assert( (pVal->flags & MEM_RowSet)==0 ); + assert( !tdsqlite3VdbeMemIsRowSet(pVal) ); if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){ + assert( tdsqlite3VdbeMemValidStrRep(pVal) ); return pVal->z; } if( pVal->flags&MEM_Null ){ @@ -72911,10 +80334,10 @@ SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){ } /* -** Create a new sqlite3_value object. +** Create a new tdsqlite3_value object. */ -SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){ - Mem *p = sqlite3DbMallocZero(db, sizeof(*p)); +SQLITE_PRIVATE tdsqlite3_value *tdsqlite3ValueNew(tdsqlite3 *db){ + Mem *p = tdsqlite3DbMallocZero(db, sizeof(*p)); if( p ){ p->flags = MEM_Null; p->db = db; @@ -72923,7 +80346,7 @@ SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){ } /* -** Context object passed by sqlite3Stat4ProbeSetValue() through to +** Context object passed by tdsqlite3Stat4ProbeSetValue() through to ** valueNew(). See comments above valueNew() for details. */ struct ValueNewStat4Ctx { @@ -72934,18 +80357,18 @@ struct ValueNewStat4Ctx { }; /* -** Allocate and return a pointer to a new sqlite3_value object. If +** Allocate and return a pointer to a new tdsqlite3_value object. If ** the second argument to this function is NULL, the object is allocated -** by calling sqlite3ValueNew(). +** by calling tdsqlite3ValueNew(). ** ** Otherwise, if the second argument is non-zero, then this function is -** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not +** being called indirectly by tdsqlite3Stat4ProbeSetValue(). If it has not ** already been allocated, allocate the UnpackedRecord structure that ** that function will return to its caller here. Then return a pointer to -** an sqlite3_value within the UnpackedRecord.a[] array. +** an tdsqlite3_value within the UnpackedRecord.a[] array. */ -static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +static tdsqlite3_value *valueNew(tdsqlite3 *db, struct ValueNewStat4Ctx *p){ +#ifdef SQLITE_ENABLE_STAT4 if( p ){ UnpackedRecord *pRec = p->ppRec[0]; @@ -72956,11 +80379,11 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ int nCol = pIdx->nColumn; /* Number of index columns including rowid */ nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord)); - pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte); + pRec = (UnpackedRecord*)tdsqlite3DbMallocZero(db, nByte); if( pRec ){ - pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx); + pRec->pKeyInfo = tdsqlite3KeyInfoOfIndex(p->pParse, pIdx); if( pRec->pKeyInfo ){ - assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol ); + assert( pRec->pKeyInfo->nAllField==nCol ); assert( pRec->pKeyInfo->enc==ENC(db) ); pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord))); for(i=0; i<nCol; i++){ @@ -72968,7 +80391,7 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ pRec->aMem[i].db = db; } }else{ - sqlite3DbFree(db, pRec); + tdsqlite3DbFreeNN(db, pRec); pRec = 0; } } @@ -72981,8 +80404,8 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ } #else UNUSED_PARAMETER(p); -#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */ - return sqlite3ValueNew(db); +#endif /* defined(SQLITE_ENABLE_STAT4) */ + return tdsqlite3ValueNew(db); } /* @@ -72998,27 +80421,27 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ ** object containing the result before returning SQLITE_OK. ** ** Affinity aff is applied to the result of the function before returning. -** If the result is a text value, the sqlite3_value object uses encoding +** If the result is a text value, the tdsqlite3_value object uses encoding ** enc. ** ** If the conditions above are not met, this function returns SQLITE_OK ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to ** NULL and an SQLite error code returned. */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 static int valueFromFunction( - sqlite3 *db, /* The database connection */ + tdsqlite3 *db, /* The database connection */ Expr *p, /* The expression to evaluate */ u8 enc, /* Encoding to use */ u8 aff, /* Affinity to use */ - sqlite3_value **ppVal, /* Write the new value here */ + tdsqlite3_value **ppVal, /* Write the new value here */ struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */ ){ - sqlite3_context ctx; /* Context object for function invocation */ - sqlite3_value **apVal = 0; /* Function arguments */ + tdsqlite3_context ctx; /* Context object for function invocation */ + tdsqlite3_value **apVal = 0; /* Function arguments */ int nVal = 0; /* Size of apVal[] array */ FuncDef *pFunc = 0; /* Function definition */ - sqlite3_value *pVal = 0; /* New value */ + tdsqlite3_value *pVal = 0; /* New value */ int rc = SQLITE_OK; /* Return code */ ExprList *pList = 0; /* Function arguments */ int i; /* Iterator variable */ @@ -73027,7 +80450,7 @@ static int valueFromFunction( assert( (p->flags & EP_TokenOnly)==0 ); pList = p->x.pList; if( pList ) nVal = pList->nExpr; - pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0); + pFunc = tdsqlite3FindFunction(db, p->u.zToken, nVal, enc, 0); assert( pFunc ); if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) @@ -73036,13 +80459,13 @@ static int valueFromFunction( } if( pList ){ - apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal); + apVal = (tdsqlite3_value**)tdsqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal); if( apVal==0 ){ rc = SQLITE_NOMEM_BKPT; goto value_from_function_out; } for(i=0; i<nVal; i++){ - rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]); + rc = tdsqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]); if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out; } } @@ -73060,12 +80483,12 @@ static int valueFromFunction( pFunc->xSFunc(&ctx, nVal, apVal); if( ctx.isError ){ rc = ctx.isError; - sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal)); + tdsqlite3ErrorMsg(pCtx->pParse, "%s", tdsqlite3_value_text(pVal)); }else{ - sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8); + tdsqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8); assert( rc==SQLITE_OK ); - rc = sqlite3VdbeChangeEncoding(pVal, enc); - if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){ + rc = tdsqlite3VdbeChangeEncoding(pVal, enc); + if( rc==SQLITE_OK && tdsqlite3VdbeMemTooBig(pVal) ){ rc = SQLITE_TOOBIG; pCtx->pParse->nErr++; } @@ -73078,9 +80501,9 @@ static int valueFromFunction( } if( apVal ){ for(i=0; i<nVal; i++){ - sqlite3ValueFree(apVal[i]); + tdsqlite3ValueFree(apVal[i]); } - sqlite3DbFree(db, apVal); + tdsqlite3DbFreeNN(db, apVal); } *ppVal = pVal; @@ -73088,36 +80511,40 @@ static int valueFromFunction( } #else # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK -#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */ +#endif /* defined(SQLITE_ENABLE_STAT4) */ /* ** Extract a value from the supplied expression in the manner described -** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object +** above tdsqlite3ValueFromExpr(). Allocate the tdsqlite3_value object ** using valueNew(). ** -** If pCtx is NULL and an error occurs after the sqlite3_value object +** If pCtx is NULL and an error occurs after the tdsqlite3_value object ** has been allocated, it is freed before returning. Or, if pCtx is not ** NULL, it is assumed that the caller will free any allocated object ** in all cases. */ static int valueFromExpr( - sqlite3 *db, /* The database connection */ + tdsqlite3 *db, /* The database connection */ Expr *pExpr, /* The expression to evaluate */ u8 enc, /* Encoding to use */ u8 affinity, /* Affinity to use */ - sqlite3_value **ppVal, /* Write the new value here */ + tdsqlite3_value **ppVal, /* Write the new value here */ struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */ ){ int op; char *zVal = 0; - sqlite3_value *pVal = 0; + tdsqlite3_value *pVal = 0; int negInt = 1; const char *zNeg = ""; int rc = SQLITE_OK; assert( pExpr!=0 ); while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft; +#if defined(SQLITE_ENABLE_STAT4) + if( op==TK_REGISTER ) op = pExpr->op2; +#else if( NEVER(op==TK_REGISTER) ) op = pExpr->op2; +#endif /* Compressed expressions only appear when parsing the DEFAULT clause ** on a table column definition, and hence only when pCtx==0. This @@ -73126,12 +80553,12 @@ static int valueFromExpr( assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 ); if( op==TK_CAST ){ - u8 aff = sqlite3AffinityType(pExpr->u.zToken,0); + u8 aff = tdsqlite3AffinityType(pExpr->u.zToken,0); rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx); testcase( rc!=SQLITE_OK ); if( *ppVal ){ - sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8); - sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8); + tdsqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8); + tdsqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8); } return rc; } @@ -73151,40 +80578,50 @@ static int valueFromExpr( pVal = valueNew(db, pCtx); if( pVal==0 ) goto no_mem; if( ExprHasProperty(pExpr, EP_IntValue) ){ - sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt); + tdsqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt); }else{ - zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken); + zVal = tdsqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken); if( zVal==0 ) goto no_mem; - sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC); + tdsqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC); } if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){ - sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8); + tdsqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8); }else{ - sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8); + tdsqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8); + } + assert( (pVal->flags & MEM_IntReal)==0 ); + if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){ + testcase( pVal->flags & MEM_Int ); + testcase( pVal->flags & MEM_Real ); + pVal->flags &= ~MEM_Str; } - if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str; if( enc!=SQLITE_UTF8 ){ - rc = sqlite3VdbeChangeEncoding(pVal, enc); + rc = tdsqlite3VdbeChangeEncoding(pVal, enc); } }else if( op==TK_UMINUS ) { /* This branch happens for multiple negative signs. Ex: -(-5) */ - if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) + if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx) && pVal!=0 ){ - sqlite3VdbeMemNumerify(pVal); + tdsqlite3VdbeMemNumerify(pVal); if( pVal->flags & MEM_Real ){ pVal->u.r = -pVal->u.r; }else if( pVal->u.i==SMALLEST_INT64 ){ +#ifndef SQLITE_OMIT_FLOATING_POINT pVal->u.r = -(double)SMALLEST_INT64; +#else + pVal->u.r = LARGEST_INT64; +#endif MemSetTypeFlag(pVal, MEM_Real); }else{ pVal->u.i = -pVal->u.i; } - sqlite3ValueApplyAffinity(pVal, affinity, enc); + tdsqlite3ValueApplyAffinity(pVal, affinity, enc); } }else if( op==TK_NULL ){ pVal = valueNew(db, pCtx); if( pVal==0 ) goto no_mem; + tdsqlite3VdbeMemSetNull(pVal); } #ifndef SQLITE_OMIT_BLOB_LITERAL else if( op==TK_BLOB ){ @@ -73194,104 +80631,64 @@ static int valueFromExpr( pVal = valueNew(db, pCtx); if( !pVal ) goto no_mem; zVal = &pExpr->u.zToken[2]; - nVal = sqlite3Strlen30(zVal)-1; + nVal = tdsqlite3Strlen30(zVal)-1; assert( zVal[nVal]=='\'' ); - sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2, + tdsqlite3VdbeMemSetStr(pVal, tdsqlite3HexToBlob(db, zVal, nVal), nVal/2, 0, SQLITE_DYNAMIC); } #endif - -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 else if( op==TK_FUNCTION && pCtx!=0 ){ rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx); } #endif + else if( op==TK_TRUEFALSE ){ + pVal = valueNew(db, pCtx); + if( pVal ){ + pVal->flags = MEM_Int; + pVal->u.i = pExpr->u.zToken[4]==0; + } + } *ppVal = pVal; return rc; no_mem: - sqlite3OomFault(db); - sqlite3DbFree(db, zVal); +#ifdef SQLITE_ENABLE_STAT4 + if( pCtx==0 || pCtx->pParse->nErr==0 ) +#endif + tdsqlite3OomFault(db); + tdsqlite3DbFree(db, zVal); assert( *ppVal==0 ); -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - if( pCtx==0 ) sqlite3ValueFree(pVal); +#ifdef SQLITE_ENABLE_STAT4 + if( pCtx==0 ) tdsqlite3ValueFree(pVal); #else - assert( pCtx==0 ); sqlite3ValueFree(pVal); + assert( pCtx==0 ); tdsqlite3ValueFree(pVal); #endif return SQLITE_NOMEM_BKPT; } /* -** Create a new sqlite3_value object, containing the value of pExpr. +** Create a new tdsqlite3_value object, containing the value of pExpr. ** ** This only works for very simple expressions that consist of one constant ** token (i.e. "5", "5.1", "'a string'"). If the expression can ** be converted directly into a value, then the value is allocated and ** a pointer written to *ppVal. The caller is responsible for deallocating -** the value by passing it to sqlite3ValueFree() later on. If the expression +** the value by passing it to tdsqlite3ValueFree() later on. If the expression ** cannot be converted to a value, then *ppVal is set to NULL. */ -SQLITE_PRIVATE int sqlite3ValueFromExpr( - sqlite3 *db, /* The database connection */ +SQLITE_PRIVATE int tdsqlite3ValueFromExpr( + tdsqlite3 *db, /* The database connection */ Expr *pExpr, /* The expression to evaluate */ u8 enc, /* Encoding to use */ u8 affinity, /* Affinity to use */ - sqlite3_value **ppVal /* Write the new value here */ + tdsqlite3_value **ppVal /* Write the new value here */ ){ return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0; } -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 -/* -** The implementation of the sqlite_record() function. This function accepts -** a single argument of any type. The return value is a formatted database -** record (a blob) containing the argument value. -** -** This is used to convert the value stored in the 'sample' column of the -** sqlite_stat3 table to the record format SQLite uses internally. -*/ -static void recordFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const int file_format = 1; - u32 iSerial; /* Serial type */ - int nSerial; /* Bytes of space for iSerial as varint */ - u32 nVal; /* Bytes of space required for argv[0] */ - int nRet; - sqlite3 *db; - u8 *aRet; - - UNUSED_PARAMETER( argc ); - iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal); - nSerial = sqlite3VarintLen(iSerial); - db = sqlite3_context_db_handle(context); - - nRet = 1 + nSerial + nVal; - aRet = sqlite3DbMallocRawNN(db, nRet); - if( aRet==0 ){ - sqlite3_result_error_nomem(context); - }else{ - aRet[0] = nSerial+1; - putVarint32(&aRet[1], iSerial); - sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial); - sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT); - sqlite3DbFree(db, aRet); - } -} - -/* -** Register built-in functions used to help read ANALYZE data. -*/ -SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){ - static FuncDef aAnalyzeTableFuncs[] = { - FUNCTION(sqlite_record, 1, 0, 0, recordFunc), - }; - sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs)); -} - +#ifdef SQLITE_ENABLE_STAT4 /* ** Attempt to extract a value from pExpr and use it to construct *ppVal. ** @@ -73315,33 +80712,30 @@ static int stat4ValueFromExpr( Expr *pExpr, /* The expression to extract a value from */ u8 affinity, /* Affinity to use */ struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */ - sqlite3_value **ppVal /* OUT: New value object (or NULL) */ + tdsqlite3_value **ppVal /* OUT: New value object (or NULL) */ ){ int rc = SQLITE_OK; - sqlite3_value *pVal = 0; - sqlite3 *db = pParse->db; + tdsqlite3_value *pVal = 0; + tdsqlite3 *db = pParse->db; /* Skip over any TK_COLLATE nodes */ - pExpr = sqlite3ExprSkipCollate(pExpr); + pExpr = tdsqlite3ExprSkipCollate(pExpr); + assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE ); if( !pExpr ){ pVal = valueNew(db, pAlloc); if( pVal ){ - sqlite3VdbeMemSetNull((Mem*)pVal); + tdsqlite3VdbeMemSetNull((Mem*)pVal); } - }else if( pExpr->op==TK_VARIABLE - || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE) - ){ + }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){ Vdbe *v; int iBindVar = pExpr->iColumn; - sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar); + tdsqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar); if( (v = pParse->pReprepare)!=0 ){ pVal = valueNew(db, pAlloc); if( pVal ){ - rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]); - if( rc==SQLITE_OK ){ - sqlite3ValueApplyAffinity(pVal, affinity, ENC(db)); - } + rc = tdsqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]); + tdsqlite3ValueApplyAffinity(pVal, affinity, ENC(db)); pVal->db = pParse->db; } } @@ -73367,7 +80761,7 @@ static int stat4ValueFromExpr( ** ** * The expression is a bound variable, and this is a reprepare, or ** -** * The sqlite3ValueFromExpr() function is able to extract a value +** * The tdsqlite3ValueFromExpr() function is able to extract a value ** from the expression (i.e. the expression is a literal value). ** ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the @@ -73388,7 +80782,7 @@ static int stat4ValueFromExpr( ** error if a value cannot be extracted from pExpr. If an error does ** occur, an SQLite error code is returned. */ -SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( +SQLITE_PRIVATE int tdsqlite3Stat4ProbeSetValue( Parse *pParse, /* Parse context */ Index *pIdx, /* Index being probed */ UnpackedRecord **ppRec, /* IN/OUT: Probe record */ @@ -73409,9 +80803,9 @@ SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( alloc.ppRec = ppRec; for(i=0; i<nElem; i++){ - sqlite3_value *pVal = 0; - Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0); - u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i); + tdsqlite3_value *pVal = 0; + Expr *pElem = (pExpr ? tdsqlite3VectorFieldSubexpr(pExpr, i) : 0); + u8 aff = tdsqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i); alloc.iVal = iVal+i; rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal); if( !pVal ) break; @@ -73425,7 +80819,7 @@ SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( /* ** Attempt to extract a value from expression pExpr using the methods -** as described for sqlite3Stat4ProbeSetValue() above. +** as described for tdsqlite3Stat4ProbeSetValue() above. ** ** If successful, set *ppVal to point to a new value object and return ** SQLITE_OK. If no value can be extracted, but no other error occurs @@ -73433,11 +80827,11 @@ SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( ** does occur, return an SQLite error code. The final value of *ppVal ** is undefined in this case. */ -SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr( +SQLITE_PRIVATE int tdsqlite3Stat4ValueFromExpr( Parse *pParse, /* Parse context */ Expr *pExpr, /* The expression to extract a value from */ u8 affinity, /* Affinity to use */ - sqlite3_value **ppVal /* OUT: New value object (or NULL) */ + tdsqlite3_value **ppVal /* OUT: New value object (or NULL) */ ){ return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal); } @@ -73445,23 +80839,23 @@ SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr( /* ** Extract the iCol-th column from the nRec-byte record in pRec. Write ** the column value into *ppVal. If *ppVal is initially NULL then a new -** sqlite3_value object is allocated. +** tdsqlite3_value object is allocated. ** ** If *ppVal is initially NULL then the caller is responsible for ** ensuring that the value written into *ppVal is eventually freed. */ -SQLITE_PRIVATE int sqlite3Stat4Column( - sqlite3 *db, /* Database handle */ +SQLITE_PRIVATE int tdsqlite3Stat4Column( + tdsqlite3 *db, /* Database handle */ const void *pRec, /* Pointer to buffer containing record */ int nRec, /* Size of buffer pRec in bytes */ int iCol, /* Column to extract */ - sqlite3_value **ppVal /* OUT: Extracted value */ + tdsqlite3_value **ppVal /* OUT: Extracted value */ ){ - u32 t; /* a column type code */ + u32 t = 0; /* a column type code */ int nHdr; /* Size of the header in the record */ int iHdr; /* Next unread header byte */ int iField; /* Next unread data byte */ - int szField; /* Size of the current data field */ + int szField = 0; /* Size of the current data field */ int i; /* Column index */ u8 *a = (u8*)pRec; /* Typecast byte array */ Mem *pMem = *ppVal; /* Write result into this Mem object */ @@ -73475,72 +80869,72 @@ SQLITE_PRIVATE int sqlite3Stat4Column( testcase( iHdr==nHdr ); testcase( iHdr==nHdr+1 ); if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT; - szField = sqlite3VdbeSerialTypeLen(t); + szField = tdsqlite3VdbeSerialTypeLen(t); iField += szField; } testcase( iField==nRec ); testcase( iField==nRec+1 ); if( iField>nRec ) return SQLITE_CORRUPT_BKPT; if( pMem==0 ){ - pMem = *ppVal = sqlite3ValueNew(db); + pMem = *ppVal = tdsqlite3ValueNew(db); if( pMem==0 ) return SQLITE_NOMEM_BKPT; } - sqlite3VdbeSerialGet(&a[iField-szField], t, pMem); + tdsqlite3VdbeSerialGet(&a[iField-szField], t, pMem); pMem->enc = ENC(db); return SQLITE_OK; } /* ** Unless it is NULL, the argument must be an UnpackedRecord object returned -** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes +** by an earlier call to tdsqlite3Stat4ProbeSetValue(). This call deletes ** the object. */ -SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){ +SQLITE_PRIVATE void tdsqlite3Stat4ProbeFree(UnpackedRecord *pRec){ if( pRec ){ int i; - int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField; + int nCol = pRec->pKeyInfo->nAllField; Mem *aMem = pRec->aMem; - sqlite3 *db = aMem[0].db; + tdsqlite3 *db = aMem[0].db; for(i=0; i<nCol; i++){ - sqlite3VdbeMemRelease(&aMem[i]); + tdsqlite3VdbeMemRelease(&aMem[i]); } - sqlite3KeyInfoUnref(pRec->pKeyInfo); - sqlite3DbFree(db, pRec); + tdsqlite3KeyInfoUnref(pRec->pKeyInfo); + tdsqlite3DbFreeNN(db, pRec); } } #endif /* ifdef SQLITE_ENABLE_STAT4 */ /* -** Change the string value of an sqlite3_value object +** Change the string value of an tdsqlite3_value object */ -SQLITE_PRIVATE void sqlite3ValueSetStr( - sqlite3_value *v, /* Value to be set */ +SQLITE_PRIVATE void tdsqlite3ValueSetStr( + tdsqlite3_value *v, /* Value to be set */ int n, /* Length of string z */ const void *z, /* Text of the new string */ u8 enc, /* Encoding to use */ void (*xDel)(void*) /* Destructor for the string */ ){ - if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel); + if( v ) tdsqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel); } /* -** Free an sqlite3_value object +** Free an tdsqlite3_value object */ -SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){ +SQLITE_PRIVATE void tdsqlite3ValueFree(tdsqlite3_value *v){ if( !v ) return; - sqlite3VdbeMemRelease((Mem *)v); - sqlite3DbFree(((Mem*)v)->db, v); + tdsqlite3VdbeMemRelease((Mem *)v); + tdsqlite3DbFreeNN(((Mem*)v)->db, v); } /* -** The sqlite3ValueBytes() routine returns the number of bytes in the -** sqlite3_value object assuming that it uses the encoding "enc". +** The tdsqlite3ValueBytes() routine returns the number of bytes in the +** tdsqlite3_value object assuming that it uses the encoding "enc". ** The valueBytes() routine is a helper function. */ -static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){ +static SQLITE_NOINLINE int valueBytes(tdsqlite3_value *pVal, u8 enc){ return valueToText(pVal, enc)!=0 ? pVal->n : 0; } -SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){ +SQLITE_PRIVATE int tdsqlite3ValueBytes(tdsqlite3_value *pVal, u8 enc){ Mem *p = (Mem*)pVal; assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 ); if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){ @@ -73571,18 +80965,22 @@ SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){ ** ************************************************************************* ** This file contains code used for creating, destroying, and populating -** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) +** a VDBE (or an "tdsqlite3_stmt" as it is known to the outside world.) */ /* #include "sqliteInt.h" */ /* #include "vdbeInt.h" */ +/* Forward references */ +static void freeEphemeralFunction(tdsqlite3 *db, FuncDef *pDef); +static void vdbeFreeOpArray(tdsqlite3 *, Op *, int); + /* ** Create a new virtual database engine. */ -SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){ - sqlite3 *db = pParse->db; +SQLITE_PRIVATE Vdbe *tdsqlite3VdbeCreate(Parse *pParse){ + tdsqlite3 *db = pParse->db; Vdbe *p; - p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) ); + p = tdsqlite3DbMallocRawNN(db, sizeof(Vdbe) ); if( p==0 ) return 0; memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp)); p->db = db; @@ -73594,42 +80992,87 @@ SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){ db->pVdbe = p; p->magic = VDBE_MAGIC_INIT; p->pParse = pParse; + pParse->pVdbe = p; assert( pParse->aLabel==0 ); assert( pParse->nLabel==0 ); - assert( pParse->nOpAlloc==0 ); + assert( p->nOpAlloc==0 ); assert( pParse->szOpAlloc==0 ); + tdsqlite3VdbeAddOp2(p, OP_Init, 0, 1); return p; } /* +** Return the Parse object that owns a Vdbe object. +*/ +SQLITE_PRIVATE Parse *tdsqlite3VdbeParser(Vdbe *p){ + return p->pParse; +} + +/* ** Change the error string stored in Vdbe.zErrMsg */ -SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){ +SQLITE_PRIVATE void tdsqlite3VdbeError(Vdbe *p, const char *zFormat, ...){ va_list ap; - sqlite3DbFree(p->db, p->zErrMsg); + tdsqlite3DbFree(p->db, p->zErrMsg); va_start(ap, zFormat); - p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap); + p->zErrMsg = tdsqlite3VMPrintf(p->db, zFormat, ap); va_end(ap); } /* ** Remember the SQL string for a prepared statement. */ -SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){ - assert( isPrepareV2==1 || isPrepareV2==0 ); +SQLITE_PRIVATE void tdsqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){ if( p==0 ) return; -#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG) - if( !isPrepareV2 ) return; -#endif + p->prepFlags = prepFlags; + if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){ + p->expmask = 0; + } assert( p->zSql==0 ); - p->zSql = sqlite3DbStrNDup(p->db, z, n); - p->isPrepareV2 = (u8)isPrepareV2; + p->zSql = tdsqlite3DbStrNDup(p->db, z, n); +} + +#ifdef SQLITE_ENABLE_NORMALIZE +/* +** Add a new element to the Vdbe->pDblStr list. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeAddDblquoteStr(tdsqlite3 *db, Vdbe *p, const char *z){ + if( p ){ + int n = tdsqlite3Strlen30(z); + DblquoteStr *pStr = tdsqlite3DbMallocRawNN(db, + sizeof(*pStr)+n+1-sizeof(pStr->z)); + if( pStr ){ + pStr->pNextStr = p->pDblStr; + p->pDblStr = pStr; + memcpy(pStr->z, z, n+1); + } + } +} +#endif + +#ifdef SQLITE_ENABLE_NORMALIZE +/* +** zId of length nId is a double-quoted identifier. Check to see if +** that identifier is really used as a string literal. +*/ +SQLITE_PRIVATE int tdsqlite3VdbeUsesDoubleQuotedString( + Vdbe *pVdbe, /* The prepared statement */ + const char *zId /* The double-quoted identifier, already dequoted */ +){ + DblquoteStr *pStr; + assert( zId!=0 ); + if( pVdbe->pDblStr==0 ) return 0; + for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){ + if( strcmp(zId, pStr->z)==0 ) return 1; + } + return 0; } +#endif /* ** Swap all content between two VDBE structures. */ -SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ +SQLITE_PRIVATE void tdsqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ Vdbe tmp, *pTmp; char *zTmp; assert( pA->db==pB->db ); @@ -73645,7 +81088,15 @@ SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ zTmp = pA->zSql; pA->zSql = pB->zSql; pB->zSql = zTmp; - pB->isPrepareV2 = pA->isPrepareV2; +#ifdef SQLITE_ENABLE_NORMALIZE + zTmp = pA->zNormSql; + pA->zNormSql = pB->zNormSql; + pB->zNormSql = zTmp; +#endif + pB->expmask = pA->expmask; + pB->prepFlags = pA->prepFlags; + memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter)); + pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++; } /* @@ -73654,7 +81105,7 @@ SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ ** to 1024/sizeof(Op). ** ** If an out-of-memory error occurs while resizing the array, return -** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain +** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain ** unchanged (this is so that any opcodes already allocated can be ** correctly deallocated along with the rest of the Vdbe). */ @@ -73670,18 +81121,26 @@ static int growOpArray(Vdbe *v, int nOp){ ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current ** size of the op array or add 1KB of space, whichever is smaller. */ #ifdef SQLITE_TEST_REALLOC_STRESS - int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp); + tdsqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(tdsqlite3_int64)v->nOpAlloc + : (tdsqlite3_int64)v->nOpAlloc+nOp); #else - int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op))); + tdsqlite3_int64 nNew = (v->nOpAlloc ? 2*(tdsqlite3_int64)v->nOpAlloc + : (tdsqlite3_int64)(1024/sizeof(Op))); UNUSED_PARAMETER(nOp); #endif + /* Ensure that the size of a VDBE does not grow too large */ + if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){ + tdsqlite3OomFault(p->db); + return SQLITE_NOMEM; + } + assert( nOp<=(1024/sizeof(Op)) ); - assert( nNew>=(p->nOpAlloc+nOp) ); - pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op)); + assert( nNew>=(v->nOpAlloc+nOp) ); + pNew = tdsqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op)); if( pNew ){ - p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew); - p->nOpAlloc = p->szOpAlloc/sizeof(Op); + p->szOpAlloc = tdsqlite3DbMallocSize(p->db, pNew); + v->nOpAlloc = p->szOpAlloc/sizeof(Op); v->aOp = pNew; } return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT); @@ -73690,9 +81149,16 @@ static int growOpArray(Vdbe *v, int nOp){ #ifdef SQLITE_DEBUG /* This routine is just a convenient place to set a breakpoint that will ** fire after each opcode is inserted and displayed using -** "PRAGMA vdbe_addoptrace=on". +** "PRAGMA vdbe_addoptrace=on". Parameters "pc" (program counter) and +** pOp are available to make the breakpoint conditional. +** +** Other useful labels for breakpoints include: +** test_trace_breakpoint(pc,pOp) +** tdsqlite3CorruptError(lineno) +** tdsqlite3MisuseError(lineno) +** tdsqlite3CantopenError(lineno) */ -static void test_addop_breakpoint(void){ +static void test_addop_breakpoint(int pc, Op *pOp){ static int n = 0; n++; } @@ -73710,24 +81176,24 @@ static void test_addop_breakpoint(void){ ** ** p1, p2, p3 Operands ** -** Use the sqlite3VdbeResolveLabel() function to fix an address and -** the sqlite3VdbeChangeP4() function to change the value of the P4 +** Use the tdsqlite3VdbeResolveLabel() function to fix an address and +** the tdsqlite3VdbeChangeP4() function to change the value of the P4 ** operand. */ static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){ - assert( p->pParse->nOpAlloc<=p->nOp ); + assert( p->nOpAlloc<=p->nOp ); if( growOpArray(p, 1) ) return 1; - assert( p->pParse->nOpAlloc>p->nOp ); - return sqlite3VdbeAddOp3(p, op, p1, p2, p3); + assert( p->nOpAlloc>p->nOp ); + return tdsqlite3VdbeAddOp3(p, op, p1, p2, p3); } -SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ +SQLITE_PRIVATE int tdsqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ int i; VdbeOp *pOp; i = p->nOp; assert( p->magic==VDBE_MAGIC_INIT ); assert( op>=0 && op<0xff ); - if( p->pParse->nOpAlloc<=i ){ + if( p->nOpAlloc<=i ){ return growOp3(p, op, p1, p2, p3); } p->nOp++; @@ -73744,16 +81210,8 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ #endif #ifdef SQLITE_DEBUG if( p->db->flags & SQLITE_VdbeAddopTrace ){ - int jj, kk; - Parse *pParse = p->pParse; - for(jj=kk=0; jj<pParse->nColCache; jj++){ - struct yColCache *x = pParse->aColCache + jj; - printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn); - kk++; - } - if( kk ) printf("\n"); - sqlite3VdbePrintOp(0, i, &p->aOp[i]); - test_addop_breakpoint(); + tdsqlite3VdbePrintOp(0, i, &p->aOp[i]); + test_addop_breakpoint(i, &p->aOp[i]); } #endif #ifdef VDBE_PROFILE @@ -73765,27 +81223,27 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ #endif return i; } -SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){ - return sqlite3VdbeAddOp3(p, op, 0, 0, 0); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp0(Vdbe *p, int op){ + return tdsqlite3VdbeAddOp3(p, op, 0, 0, 0); } -SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){ - return sqlite3VdbeAddOp3(p, op, p1, 0, 0); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp1(Vdbe *p, int op, int p1){ + return tdsqlite3VdbeAddOp3(p, op, p1, 0, 0); } -SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){ - return sqlite3VdbeAddOp3(p, op, p1, p2, 0); +SQLITE_PRIVATE int tdsqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){ + return tdsqlite3VdbeAddOp3(p, op, p1, p2, 0); } /* Generate code for an unconditional jump to instruction iDest */ -SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){ - return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0); +SQLITE_PRIVATE int tdsqlite3VdbeGoto(Vdbe *p, int iDest){ + return tdsqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0); } /* Generate code to cause the string zStr to be loaded into ** register iDest */ -SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){ - return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0); +SQLITE_PRIVATE int tdsqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){ + return tdsqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0); } /* @@ -73795,8 +81253,11 @@ SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){ ** "s" character in zTypes[], the register is a string if the argument is ** not NULL, or OP_Null if the value is a null pointer. For each "i" character ** in zTypes[], the register is initialized to an integer. +** +** If the input string does not end with "X" then an OP_ResultRow instruction +** is generated for the values inserted. */ -SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){ +SQLITE_PRIVATE void tdsqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){ va_list ap; int i; char c; @@ -73804,19 +81265,22 @@ SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, for(i=0; (c = zTypes[i])!=0; i++){ if( c=='s' ){ const char *z = va_arg(ap, const char*); - sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0); + tdsqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0); + }else if( c=='i' ){ + tdsqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i); }else{ - assert( c=='i' ); - sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++); + goto skip_op_resultrow; } } + tdsqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i); +skip_op_resultrow: va_end(ap); } /* ** Add an opcode that includes the p4 value as a pointer. */ -SQLITE_PRIVATE int sqlite3VdbeAddOp4( +SQLITE_PRIVATE int tdsqlite3VdbeAddOp4( Vdbe *p, /* Add the opcode to this VM */ int op, /* The new opcode */ int p1, /* The P1 operand */ @@ -73825,8 +81289,51 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp4( const char *zP4, /* The P4 operand */ int p4type /* P4 operand type */ ){ - int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); - sqlite3VdbeChangeP4(p, addr, zP4, p4type); + int addr = tdsqlite3VdbeAddOp3(p, op, p1, p2, p3); + tdsqlite3VdbeChangeP4(p, addr, zP4, p4type); + return addr; +} + +/* +** Add an OP_Function or OP_PureFunc opcode. +** +** The eCallCtx argument is information (typically taken from Expr.op2) +** that describes the calling context of the function. 0 means a general +** function call. NC_IsCheck means called by a check constraint, +** NC_IdxExpr means called as part of an index expression. NC_PartIdx +** means in the WHERE clause of a partial index. NC_GenCol means called +** while computing a generated column value. 0 is the usual case. +*/ +SQLITE_PRIVATE int tdsqlite3VdbeAddFunctionCall( + Parse *pParse, /* Parsing context */ + int p1, /* Constant argument mask */ + int p2, /* First argument register */ + int p3, /* Register into which results are written */ + int nArg, /* Number of argument */ + const FuncDef *pFunc, /* The function to be invoked */ + int eCallCtx /* Calling context */ +){ + Vdbe *v = pParse->pVdbe; + int nByte; + int addr; + tdsqlite3_context *pCtx; + assert( v ); + nByte = sizeof(*pCtx) + (nArg-1)*sizeof(tdsqlite3_value*); + pCtx = tdsqlite3DbMallocRawNN(pParse->db, nByte); + if( pCtx==0 ){ + assert( pParse->db->mallocFailed ); + freeEphemeralFunction(pParse->db, (FuncDef*)pFunc); + return 0; + } + pCtx->pOut = 0; + pCtx->pFunc = (FuncDef*)pFunc; + pCtx->pVdbe = 0; + pCtx->isError = 0; + pCtx->argc = nArg; + pCtx->iOp = tdsqlite3VdbeCurrentAddr(v); + addr = tdsqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function, + p1, p2, p3, (char*)pCtx, P4_FUNCCTX); + tdsqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef); return addr; } @@ -73834,7 +81341,7 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp4( ** Add an opcode that includes the p4 value with a P4_INT64 or ** P4_REAL type. */ -SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8( +SQLITE_PRIVATE int tdsqlite3VdbeAddOp4Dup8( Vdbe *p, /* Add the opcode to this VM */ int op, /* The new opcode */ int p1, /* The P1 operand */ @@ -73843,29 +81350,92 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8( const u8 *zP4, /* The P4 operand */ int p4type /* P4 operand type */ ){ - char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8); + char *p4copy = tdsqlite3DbMallocRawNN(tdsqlite3VdbeDb(p), 8); if( p4copy ) memcpy(p4copy, zP4, 8); - return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type); + return tdsqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type); +} + +#ifndef SQLITE_OMIT_EXPLAIN +/* +** Return the address of the current EXPLAIN QUERY PLAN baseline. +** 0 means "none". +*/ +SQLITE_PRIVATE int tdsqlite3VdbeExplainParent(Parse *pParse){ + VdbeOp *pOp; + if( pParse->addrExplain==0 ) return 0; + pOp = tdsqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain); + return pOp->p2; +} + +/* +** Set a debugger breakpoint on the following routine in order to +** monitor the EXPLAIN QUERY PLAN code generation. +*/ +#if defined(SQLITE_DEBUG) +SQLITE_PRIVATE void tdsqlite3ExplainBreakpoint(const char *z1, const char *z2){ + (void)z1; + (void)z2; +} +#endif + +/* +** Add a new OP_ opcode. +** +** If the bPush flag is true, then make this opcode the parent for +** subsequent Explains until tdsqlite3VdbeExplainPop() is called. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){ +#ifndef SQLITE_DEBUG + /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined. + ** But omit them (for performance) during production builds */ + if( pParse->explain==2 ) +#endif + { + char *zMsg; + Vdbe *v; + va_list ap; + int iThis; + va_start(ap, zFmt); + zMsg = tdsqlite3VMPrintf(pParse->db, zFmt, ap); + va_end(ap); + v = pParse->pVdbe; + iThis = v->nOp; + tdsqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0, + zMsg, P4_DYNAMIC); + tdsqlite3ExplainBreakpoint(bPush?"PUSH":"", tdsqlite3VdbeGetOp(v,-1)->p4.z); + if( bPush){ + pParse->addrExplain = iThis; + } + } +} + +/* +** Pop the EXPLAIN QUERY PLAN stack one level. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeExplainPop(Parse *pParse){ + tdsqlite3ExplainBreakpoint("POP", 0); + pParse->addrExplain = tdsqlite3VdbeExplainParent(pParse); } +#endif /* SQLITE_OMIT_EXPLAIN */ /* ** Add an OP_ParseSchema opcode. This routine is broken out from -** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees +** tdsqlite3VdbeAddOp4() since it needs to also needs to mark all btrees ** as having been used. ** -** The zWhere string must have been obtained from sqlite3_malloc(). +** The zWhere string must have been obtained from tdsqlite3_malloc(). ** This routine will take ownership of the allocated memory. */ -SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){ +SQLITE_PRIVATE void tdsqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){ int j; - sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC); - for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j); + tdsqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC); + for(j=0; j<p->db->nDb; j++) tdsqlite3VdbeUsesBtree(p, j); } /* ** Add an opcode that includes the p4 value as an integer. */ -SQLITE_PRIVATE int sqlite3VdbeAddOp4Int( +SQLITE_PRIVATE int tdsqlite3VdbeAddOp4Int( Vdbe *p, /* Add the opcode to this VM */ int op, /* The new opcode */ int p1, /* The P1 operand */ @@ -73873,15 +81443,19 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp4Int( int p3, /* The P3 operand */ int p4 /* The P4 operand as an integer */ ){ - int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); - sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32); + int addr = tdsqlite3VdbeAddOp3(p, op, p1, p2, p3); + if( p->db->mallocFailed==0 ){ + VdbeOp *pOp = &p->aOp[addr]; + pOp->p4type = P4_INT32; + pOp->p4.i = p4; + } return addr; } /* Insert the end of a co-routine */ -SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){ - sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); +SQLITE_PRIVATE void tdsqlite3VdbeEndCoroutine(Vdbe *v, int regYield){ + tdsqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); /* Clear the temporary register cache, thereby ensuring that each ** co-routine has its own independent set of registers, because co-routines @@ -73904,35 +81478,59 @@ SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){ ** The VDBE knows that a P2 value is a label because labels are ** always negative and P2 values are suppose to be non-negative. ** Hence, a negative P2 value is a label that has yet to be resolved. +** (Later:) This is only true for opcodes that have the OPFLG_JUMP +** property. +** +** Variable usage notes: ** -** Zero is returned if a malloc() fails. +** Parse.aLabel[x] Stores the address that the x-th label resolves +** into. For testing (SQLITE_DEBUG), unresolved +** labels stores -1, but that is not required. +** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[] +** Parse.nLabel The *negative* of the number of labels that have +** been issued. The negative is stored because +** that gives a performance improvement over storing +** the equivalent positive value. */ -SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){ - Parse *p = v->pParse; - int i = p->nLabel++; - assert( v->magic==VDBE_MAGIC_INIT ); - if( (i & (i-1))==0 ){ - p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, - (i*2+1)*sizeof(p->aLabel[0])); - } - if( p->aLabel ){ - p->aLabel[i] = -1; - } - return ADDR(i); +SQLITE_PRIVATE int tdsqlite3VdbeMakeLabel(Parse *pParse){ + return --pParse->nLabel; } /* ** Resolve label "x" to be the address of the next instruction to ** be inserted. The parameter "x" must have been obtained from -** a prior call to sqlite3VdbeMakeLabel(). +** a prior call to tdsqlite3VdbeMakeLabel(). */ -SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){ +static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){ + int nNewSize = 10 - p->nLabel; + p->aLabel = tdsqlite3DbReallocOrFree(p->db, p->aLabel, + nNewSize*sizeof(p->aLabel[0])); + if( p->aLabel==0 ){ + p->nLabelAlloc = 0; + }else{ +#ifdef SQLITE_DEBUG + int i; + for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1; +#endif + p->nLabelAlloc = nNewSize; + p->aLabel[j] = v->nOp; + } +} +SQLITE_PRIVATE void tdsqlite3VdbeResolveLabel(Vdbe *v, int x){ Parse *p = v->pParse; int j = ADDR(x); assert( v->magic==VDBE_MAGIC_INIT ); - assert( j<p->nLabel ); + assert( j<-p->nLabel ); assert( j>=0 ); - if( p->aLabel ){ +#ifdef SQLITE_DEBUG + if( p->db->flags & SQLITE_VdbeAddopTrace ){ + printf("RESOLVE LABEL %d to %d\n", x, v->nOp); + } +#endif + if( p->nLabelAlloc + p->nLabel < 0 ){ + resizeResolveLabel(p,v,j); + }else{ + assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */ p->aLabel[j] = v->nOp; } } @@ -73940,18 +81538,18 @@ SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){ /* ** Mark the VDBE as one that can only be run one time. */ -SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){ +SQLITE_PRIVATE void tdsqlite3VdbeRunOnlyOnce(Vdbe *p){ p->runOnlyOnce = 1; } /* ** Mark the VDBE as one that can only be run multiple times. */ -SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){ +SQLITE_PRIVATE void tdsqlite3VdbeReusable(Vdbe *p){ p->runOnlyOnce = 0; } -#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */ +#ifdef SQLITE_DEBUG /* tdsqlite3AssertMayAbort() logic */ /* ** The following type and function are used to iterate through all opcodes @@ -73966,7 +81564,7 @@ SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){ ** while( (pOp = opIterNext(&sIter)) ){ ** // Do something with pOp ** } -** sqlite3DbFree(v->db, sIter.apSub); +** tdsqlite3DbFree(v->db, sIter.apSub); ** */ typedef struct VdbeOpIter VdbeOpIter; @@ -74008,7 +81606,7 @@ static Op *opIterNext(VdbeOpIter *p){ if( p->apSub[j]==pRet->p4.pProgram ) break; } if( j==p->nSub ){ - p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte); + p->apSub = tdsqlite3DbReallocOrFree(v->db, p->apSub, nByte); if( !p->apSub ){ pRet = 0; }else{ @@ -74031,21 +81629,24 @@ static Op *opIterNext(VdbeOpIter *p){ ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort. ** * OP_Destroy ** * OP_VUpdate +** * OP_VCreate ** * OP_VRename ** * OP_FkCounter with P2==0 (immediate foreign key constraint) -** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...) +** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine +** (for CREATE TABLE AS SELECT ...) ** ** Then check that the value of Parse.mayAbort is true if an ** ABORT may be thrown, or false otherwise. Return true if it does ** match, or false otherwise. This function is intended to be used as ** part of an assert statement in the compiler. Similar to: ** -** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) ); +** assert( tdsqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) ); */ -SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ +SQLITE_PRIVATE int tdsqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ int hasAbort = 0; int hasFkCounter = 0; int hasCreateTable = 0; + int hasCreateIndex = 0; int hasInitCoroutine = 0; Op *pOp; VdbeOpIter sIter; @@ -74055,13 +81656,24 @@ SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ while( (pOp = opIterNext(&sIter))!=0 ){ int opcode = pOp->opcode; if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename + || opcode==OP_VDestroy + || opcode==OP_VCreate + || (opcode==OP_ParseSchema && pOp->p4.z==0) || ((opcode==OP_Halt || opcode==OP_HaltIfNull) - && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort)) + && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort)) ){ hasAbort = 1; break; } - if( opcode==OP_CreateTable ) hasCreateTable = 1; + if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1; + if( mayAbort ){ + /* hasCreateIndex may also be set for some DELETE statements that use + ** OP_Clear. So this routine may end up returning true in the case + ** where a "DELETE FROM tbl" has a statement-journal but does not + ** require one. This is not so bad - it is an inefficiency, not a bug. */ + if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1; + if( opcode==OP_Clear ) hasCreateIndex = 1; + } if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1; #ifndef SQLITE_OMIT_FOREIGN_KEY if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){ @@ -74069,7 +81681,7 @@ SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ } #endif } - sqlite3DbFree(v->db, sIter.apSub); + tdsqlite3DbFree(v->db, sIter.apSub); /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred. ** If malloc failed, then the while() loop above may not have iterated @@ -74077,9 +81689,36 @@ SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ ** true for this case to prevent the assert() in the callers frame ** from failing. */ return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter - || (hasCreateTable && hasInitCoroutine) ); + || (hasCreateTable && hasInitCoroutine) || hasCreateIndex + ); } -#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */ +#endif /* SQLITE_DEBUG - the tdsqlite3AssertMayAbort() function */ + +#ifdef SQLITE_DEBUG +/* +** Increment the nWrite counter in the VDBE if the cursor is not an +** ephemeral cursor, or if the cursor argument is NULL. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){ + if( pC==0 + || (pC->eCurType!=CURTYPE_SORTER + && pC->eCurType!=CURTYPE_PSEUDO + && !pC->isEphemeral) + ){ + p->nWrite++; + } +} +#endif + +#ifdef SQLITE_DEBUG +/* +** Assert if an Abort at this point in time might result in a corrupt +** database. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeAssertAbortable(Vdbe *p){ + assert( p->nWrite==0 || p->usesStmtJournal ); +} +#endif /* ** This routine is called after all opcodes have been inserted. It loops @@ -74140,6 +81779,25 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ p->bIsReader = 1; break; } + case OP_Next: + case OP_SorterNext: { + pOp->p4.xAdvance = tdsqlite3BtreeNext; + pOp->p4type = P4_ADVANCE; + /* The code generator never codes any of these opcodes as a jump + ** to a label. They are always coded as a jump backwards to a + ** known address */ + assert( pOp->p2>=0 ); + break; + } + case OP_Prev: { + pOp->p4.xAdvance = tdsqlite3BtreePrevious; + pOp->p4type = P4_ADVANCE; + /* The code generator never codes any of these opcodes as a jump + ** to a label. They are always coded as a jump backwards to a + ** known address */ + assert( pOp->p2>=0 ); + break; + } #ifndef SQLITE_OMIT_VIRTUALTABLE case OP_VUpdate: { if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2; @@ -74151,32 +81809,30 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ assert( pOp[-1].opcode==OP_Integer ); n = pOp[-1].p1; if( n>nMaxArgs ) nMaxArgs = n; - break; + /* Fall through into the default case */ } #endif - case OP_Next: - case OP_NextIfOpen: - case OP_SorterNext: { - pOp->p4.xAdvance = sqlite3BtreeNext; - pOp->p4type = P4_ADVANCE; - break; - } - case OP_Prev: - case OP_PrevIfOpen: { - pOp->p4.xAdvance = sqlite3BtreePrevious; - pOp->p4type = P4_ADVANCE; + default: { + if( pOp->p2<0 ){ + /* The mkopcodeh.tcl script has so arranged things that the only + ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to + ** have non-negative values for P2. */ + assert( (tdsqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 ); + assert( ADDR(pOp->p2)<-pParse->nLabel ); + pOp->p2 = aLabel[ADDR(pOp->p2)]; + } break; } } - if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){ - assert( ADDR(pOp->p2)<pParse->nLabel ); - pOp->p2 = aLabel[ADDR(pOp->p2)]; - } + /* The mkopcodeh.tcl script has so arranged things that the only + ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to + ** have non-negative values for P2. */ + assert( (tdsqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0); } if( pOp==p->aOp ) break; pOp--; } - sqlite3DbFree(p->db, pParse->aLabel); + tdsqlite3DbFree(p->db, pParse->aLabel); pParse->aLabel = 0; pParse->nLabel = 0; *pMaxFuncArgs = nMaxArgs; @@ -74186,7 +81842,7 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ /* ** Return the address of the next instruction to be inserted. */ -SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){ +SQLITE_PRIVATE int tdsqlite3VdbeCurrentAddr(Vdbe *p){ assert( p->magic==VDBE_MAGIC_INIT ); return p->nOp; } @@ -74195,13 +81851,40 @@ SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){ ** Verify that at least N opcode slots are available in p without ** having to malloc for more space (except when compiled using ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing -** to verify that certain calls to sqlite3VdbeAddOpList() can never +** to verify that certain calls to tdsqlite3VdbeAddOpList() can never ** fail due to a OOM fault and hence that the return value from -** sqlite3VdbeAddOpList() will always be non-NULL. +** tdsqlite3VdbeAddOpList() will always be non-NULL. +*/ +#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) +SQLITE_PRIVATE void tdsqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){ + assert( p->nOp + N <= p->nOpAlloc ); +} +#endif + +/* +** Verify that the VM passed as the only argument does not contain +** an OP_ResultRow opcode. Fail an assert() if it does. This is used +** by code in pragma.c to ensure that the implementation of certain +** pragmas comports with the flags specified in the mkpragmatab.tcl +** script. */ #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) -SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){ - assert( p->nOp + N <= p->pParse->nOpAlloc ); +SQLITE_PRIVATE void tdsqlite3VdbeVerifyNoResultRow(Vdbe *p){ + int i; + for(i=0; i<p->nOp; i++){ + assert( p->aOp[i].opcode!=OP_ResultRow ); + } +} +#endif + +/* +** Generate code (a single OP_Abortable opcode) that will +** verify that the VDBE program can safely call Abort in the current +** context. +*/ +#if defined(SQLITE_DEBUG) +SQLITE_PRIVATE void tdsqlite3VdbeVerifyAbortable(Vdbe *p, int onError){ + if( onError==OE_Abort ) tdsqlite3VdbeAddOp0(p, OP_Abortable); } #endif @@ -74216,11 +81899,11 @@ SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){ ** the number of entries in the Vdbe.apArg[] array required to execute the ** returned program. */ -SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){ +SQLITE_PRIVATE VdbeOp *tdsqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){ VdbeOp *aOp = p->aOp; assert( aOp && !p->db->mallocFailed ); - /* Check that sqlite3VdbeUsesBtree() was not called on this VM */ + /* Check that tdsqlite3VdbeUsesBtree() was not called on this VM */ assert( DbMaskAllZero(p->btreeMask) ); resolveP2Values(p, pnMaxArg); @@ -74236,7 +81919,7 @@ SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg) ** Non-zero P2 arguments to jump instructions are automatically adjusted ** so that the jump target is relative to the first operation inserted. */ -SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList( +SQLITE_PRIVATE VdbeOp *tdsqlite3VdbeAddOpList( Vdbe *p, /* Add opcodes to the prepared statement */ int nOp, /* Number of opcodes to add */ VdbeOpList const *aOp, /* The opcodes to be added */ @@ -74246,7 +81929,7 @@ SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList( VdbeOp *pOut, *pFirst; assert( nOp>0 ); assert( p->magic==VDBE_MAGIC_INIT ); - if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){ + if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){ return 0; } pFirst = pOut = &p->aOp[p->nOp]; @@ -74255,7 +81938,7 @@ SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList( pOut->p1 = aOp->p1; pOut->p2 = aOp->p2; assert( aOp->p2>=0 ); - if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){ + if( (tdsqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){ pOut->p2 += p->nOp; } pOut->p3 = aOp->p3; @@ -74272,7 +81955,7 @@ SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList( #endif #ifdef SQLITE_DEBUG if( p->db->flags & SQLITE_VdbeAddopTrace ){ - sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]); + tdsqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]); } #endif } @@ -74282,9 +81965,9 @@ SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList( #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) /* -** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus(). +** Add an entry to the array of counters managed by tdsqlite3_stmt_scanstatus(). */ -SQLITE_PRIVATE void sqlite3VdbeScanStatus( +SQLITE_PRIVATE void tdsqlite3VdbeScanStatus( Vdbe *p, /* VM to add scanstatus() to */ int addrExplain, /* Address of OP_Explain (or 0) */ int addrLoop, /* Address of loop counter */ @@ -74292,16 +81975,16 @@ SQLITE_PRIVATE void sqlite3VdbeScanStatus( LogEst nEst, /* Estimated number of output rows */ const char *zName /* Name of table or index being scanned */ ){ - int nByte = (p->nScan+1) * sizeof(ScanStatus); + tdsqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus); ScanStatus *aNew; - aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte); + aNew = (ScanStatus*)tdsqlite3DbRealloc(p->db, p->aScan, nByte); if( aNew ){ ScanStatus *pNew = &aNew[p->nScan++]; pNew->addrExplain = addrExplain; pNew->addrLoop = addrLoop; pNew->addrVisit = addrVisit; pNew->nEst = nEst; - pNew->zName = sqlite3DbStrDup(p->db, zName); + pNew->zName = tdsqlite3DbStrDup(p->db, zName); p->aScan = aNew; } } @@ -74312,19 +81995,19 @@ SQLITE_PRIVATE void sqlite3VdbeScanStatus( ** Change the value of the opcode, or P1, P2, P3, or P5 operands ** for a specific instruction. */ -SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){ - sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode; +SQLITE_PRIVATE void tdsqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){ + tdsqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode; } -SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){ - sqlite3VdbeGetOp(p,addr)->p1 = val; +SQLITE_PRIVATE void tdsqlite3VdbeChangeP1(Vdbe *p, int addr, int val){ + tdsqlite3VdbeGetOp(p,addr)->p1 = val; } -SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){ - sqlite3VdbeGetOp(p,addr)->p2 = val; +SQLITE_PRIVATE void tdsqlite3VdbeChangeP2(Vdbe *p, int addr, int val){ + tdsqlite3VdbeGetOp(p,addr)->p2 = val; } -SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){ - sqlite3VdbeGetOp(p,addr)->p3 = val; +SQLITE_PRIVATE void tdsqlite3VdbeChangeP3(Vdbe *p, int addr, int val){ + tdsqlite3VdbeGetOp(p,addr)->p3 = val; } -SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){ +SQLITE_PRIVATE void tdsqlite3VdbeChangeP5(Vdbe *p, u16 p5){ assert( p->nOp>0 || p->db->mallocFailed ); if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5; } @@ -74333,8 +82016,8 @@ SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){ ** Change the P2 operand of instruction addr so that it points to ** the address of the next instruction to be coded. */ -SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){ - sqlite3VdbeChangeP2(p, addr, p->nOp); +SQLITE_PRIVATE void tdsqlite3VdbeJumpHere(Vdbe *p, int addr){ + tdsqlite3VdbeChangeP2(p, addr, p->nOp); } @@ -74342,67 +82025,62 @@ SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){ ** If the input FuncDef structure is ephemeral, then free it. If ** the FuncDef is not ephermal, then do nothing. */ -static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){ +static void freeEphemeralFunction(tdsqlite3 *db, FuncDef *pDef){ if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){ - sqlite3DbFree(db, pDef); + tdsqlite3DbFreeNN(db, pDef); } } -static void vdbeFreeOpArray(sqlite3 *, Op *, int); - /* ** Delete a P4 value if necessary. */ -static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){ - if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc); - sqlite3DbFree(db, p); +static SQLITE_NOINLINE void freeP4Mem(tdsqlite3 *db, Mem *p){ + if( p->szMalloc ) tdsqlite3DbFree(db, p->zMalloc); + tdsqlite3DbFreeNN(db, p); } -static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){ +static SQLITE_NOINLINE void freeP4FuncCtx(tdsqlite3 *db, tdsqlite3_context *p){ freeEphemeralFunction(db, p->pFunc); - sqlite3DbFree(db, p); + tdsqlite3DbFreeNN(db, p); } -static void freeP4(sqlite3 *db, int p4type, void *p4){ +static void freeP4(tdsqlite3 *db, int p4type, void *p4){ assert( db ); switch( p4type ){ case P4_FUNCCTX: { - freeP4FuncCtx(db, (sqlite3_context*)p4); + freeP4FuncCtx(db, (tdsqlite3_context*)p4); break; } case P4_REAL: case P4_INT64: case P4_DYNAMIC: + case P4_DYNBLOB: case P4_INTARRAY: { - sqlite3DbFree(db, p4); + tdsqlite3DbFree(db, p4); break; } case P4_KEYINFO: { - if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4); + if( db->pnBytesFreed==0 ) tdsqlite3KeyInfoUnref((KeyInfo*)p4); break; } #ifdef SQLITE_ENABLE_CURSOR_HINTS case P4_EXPR: { - sqlite3ExprDelete(db, (Expr*)p4); + tdsqlite3ExprDelete(db, (Expr*)p4); break; } #endif - case P4_MPRINTF: { - if( db->pnBytesFreed==0 ) sqlite3_free(p4); - break; - } case P4_FUNCDEF: { freeEphemeralFunction(db, (FuncDef*)p4); break; } case P4_MEM: { if( db->pnBytesFreed==0 ){ - sqlite3ValueFree((sqlite3_value*)p4); + tdsqlite3ValueFree((tdsqlite3_value*)p4); }else{ freeP4Mem(db, (Mem*)p4); } break; } case P4_VTAB : { - if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4); + if( db->pnBytesFreed==0 ) tdsqlite3VtabUnlock((VTable *)p4); break; } } @@ -74413,17 +82091,17 @@ static void freeP4(sqlite3 *db, int p4type, void *p4){ ** opcodes contained within. If aOp is not NULL it is assumed to contain ** nOp entries. */ -static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){ +static void vdbeFreeOpArray(tdsqlite3 *db, Op *aOp, int nOp){ if( aOp ){ Op *pOp; - for(pOp=aOp; pOp<&aOp[nOp]; pOp++){ - if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p); + for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){ + if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p); #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - sqlite3DbFree(db, pOp->zComment); + tdsqlite3DbFree(db, pOp->zComment); #endif } + tdsqlite3DbFreeNN(db, aOp); } - sqlite3DbFree(db, aOp); } /* @@ -74431,15 +82109,22 @@ static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){ ** list at Vdbe.pSubProgram. This list is used to delete all sub-program ** objects when the VM is no longer required. */ -SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){ +SQLITE_PRIVATE void tdsqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){ p->pNext = pVdbe->pProgram; pVdbe->pProgram = p; } /* +** Return true if the given Vdbe has any SubPrograms. +*/ +SQLITE_PRIVATE int tdsqlite3VdbeHasSubProgram(Vdbe *pVdbe){ + return pVdbe->pProgram!=0; +} + +/* ** Change the opcode at addr into OP_Noop */ -SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){ +SQLITE_PRIVATE int tdsqlite3VdbeChangeToNoop(Vdbe *p, int addr){ VdbeOp *pOp; if( p->db->mallocFailed ) return 0; assert( addr>=0 && addr<p->nOp ); @@ -74455,22 +82140,57 @@ SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){ ** If the last opcode is "op" and it is not a jump destination, ** then remove it. Return true if and only if an opcode was removed. */ -SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){ +SQLITE_PRIVATE int tdsqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){ if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){ - return sqlite3VdbeChangeToNoop(p, p->nOp-1); + return tdsqlite3VdbeChangeToNoop(p, p->nOp-1); }else{ return 0; } } +#ifdef SQLITE_DEBUG +/* +** Generate an OP_ReleaseReg opcode to indicate that a range of +** registers, except any identified by mask, are no longer in use. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeReleaseRegisters( + Parse *pParse, /* Parsing context */ + int iFirst, /* Index of first register to be released */ + int N, /* Number of registers to release */ + u32 mask, /* Mask of registers to NOT release */ + int bUndefine /* If true, mark registers as undefined */ +){ + if( N==0 ) return; + assert( pParse->pVdbe ); + assert( iFirst>=1 ); + assert( iFirst+N-1<=pParse->nMem ); + if( N<=31 && mask!=0 ){ + while( N>0 && (mask&1)!=0 ){ + mask >>= 1; + iFirst++; + N--; + } + while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){ + mask &= ~MASKBIT32(N-1); + N--; + } + } + if( N>0 ){ + tdsqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask); + if( bUndefine ) tdsqlite3VdbeChangeP5(pParse->pVdbe, 1); + } +} +#endif /* SQLITE_DEBUG */ + + /* ** Change the value of the P4 operand for a specific instruction. ** This routine is useful when a large program is loaded from a -** static array using sqlite3VdbeAddOpList but we want to make a +** static array using tdsqlite3VdbeAddOpList but we want to make a ** few minor changes to the program. ** ** If n>=0 then the P4 operand is dynamic, meaning that a copy of -** the string is made into memory obtained from sqlite3_malloc(). +** the string is made into memory obtained from tdsqlite3_malloc(). ** A value of n==0 means copy bytes of zP4 up to and including the ** first null byte. If n>0 then copy n+1 bytes of zP4. ** @@ -74492,16 +82212,16 @@ static void SQLITE_NOINLINE vdbeChangeP4Full( pOp->p4.p = 0; } if( n<0 ){ - sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n); + tdsqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n); }else{ - if( n==0 ) n = sqlite3Strlen30(zP4); - pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n); + if( n==0 ) n = tdsqlite3Strlen30(zP4); + pOp->p4.z = tdsqlite3DbStrNDup(p->db, zP4, n); pOp->p4type = P4_DYNAMIC; } } -SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ +SQLITE_PRIVATE void tdsqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ Op *pOp; - sqlite3 *db; + tdsqlite3 *db; assert( p!=0 ); db = p->db; assert( p->magic==VDBE_MAGIC_INIT ); @@ -74529,7 +82249,32 @@ SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int assert( n<0 ); pOp->p4.p = (void*)zP4; pOp->p4type = (signed char)n; - if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4); + if( n==P4_VTAB ) tdsqlite3VtabLock((VTable*)zP4); + } +} + +/* +** Change the P4 operand of the most recently coded instruction +** to the value defined by the arguments. This is a high-speed +** version of tdsqlite3VdbeChangeP4(). +** +** The P4 operand must not have been previously defined. And the new +** P4 must not be P4_INT32. Use tdsqlite3VdbeChangeP4() in either of +** those cases. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){ + VdbeOp *pOp; + assert( n!=P4_INT32 && n!=P4_VTAB ); + assert( n<=0 ); + if( p->db->mallocFailed ){ + freeP4(p->db, n, pP4); + }else{ + assert( pP4!=0 ); + assert( p->nOp>0 ); + pOp = &p->aOp[p->nOp-1]; + assert( pOp->p4type==P4_NOTUSED ); + pOp->p4type = n; + pOp->p4.p = pP4; } } @@ -74537,12 +82282,13 @@ SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int ** Set the P4 on the most recently added opcode to the KeyInfo for the ** index given. */ -SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){ +SQLITE_PRIVATE void tdsqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){ Vdbe *v = pParse->pVdbe; + KeyInfo *pKeyInfo; assert( v!=0 ); assert( pIdx!=0 ); - sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx), - P4_KEYINFO); + pKeyInfo = tdsqlite3KeyInfoOfIndex(pParse, pIdx); + if( pKeyInfo ) tdsqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); } #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS @@ -74554,14 +82300,15 @@ SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){ */ static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){ assert( p->nOp>0 || p->aOp==0 ); - assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed ); + assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed + || p->pParse->nErr>0 ); if( p->nOp ){ assert( p->aOp ); - sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment); - p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap); + tdsqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment); + p->aOp[p->nOp-1].zComment = tdsqlite3VMPrintf(p->db, zFormat, ap); } } -SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){ +SQLITE_PRIVATE void tdsqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){ va_list ap; if( p ){ va_start(ap, zFormat); @@ -74569,10 +82316,10 @@ SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){ va_end(ap); } } -SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){ +SQLITE_PRIVATE void tdsqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){ va_list ap; if( p ){ - sqlite3VdbeAddOp0(p, OP_Noop); + tdsqlite3VdbeAddOp0(p, OP_Noop); va_start(ap, zFormat); vdbeVComment(p, zFormat, ap); va_end(ap); @@ -74584,8 +82331,8 @@ SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){ /* ** Set the value if the iSrcLine field for the previously coded instruction. */ -SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){ - sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine; +SQLITE_PRIVATE void tdsqlite3VdbeSetLineNumber(Vdbe *v, int iLine){ + tdsqlite3VdbeGetOp(v,-1)->iSrcLine = iLine; } #endif /* SQLITE_VDBE_COVERAGE */ @@ -74602,7 +82349,7 @@ SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){ ** dummy will never be written to. This is verified by code inspection and ** by running with Valgrind. */ -SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){ +SQLITE_PRIVATE VdbeOp *tdsqlite3VdbeGetOp(Vdbe *p, int addr){ /* C89 specifies that the constant "dummy" will be initialized to all ** zeros, which is correct. MSVC generates a warning, nevertheless. */ static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */ @@ -74635,7 +82382,7 @@ static int translateP(char c, const Op *pOp){ ** Compute a string for the "comment" field of a VDBE opcode listing. ** ** The Synopsis: field in comments in the vdbe.c source file gets converted -** to an extra string that is appended to the sqlite3OpcodeName(). In the +** to an extra string that is appended to the tdsqlite3OpcodeName(). In the ** absence of other comments, this synopsis becomes the comment on the opcode. ** Some translation occurs: ** @@ -74655,17 +82402,17 @@ static int displayComment( int nOpName; int ii, jj; char zAlt[50]; - zOpName = sqlite3OpcodeName(pOp->opcode); - nOpName = sqlite3Strlen30(zOpName); + zOpName = tdsqlite3OpcodeName(pOp->opcode); + nOpName = tdsqlite3Strlen30(zOpName); if( zOpName[nOpName+1] ){ int seenCom = 0; char c; zSynopsis = zOpName += nOpName + 1; if( strncmp(zSynopsis,"IF ",3)==0 ){ if( pOp->p5 & SQLITE_STOREP2 ){ - sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3); + tdsqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3); }else{ - sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3); + tdsqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3); } zSynopsis = zAlt; } @@ -74673,42 +82420,42 @@ static int displayComment( if( c=='P' ){ c = zSynopsis[++ii]; if( c=='4' ){ - sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4); + tdsqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4); }else if( c=='X' ){ - sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment); + tdsqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment); seenCom = 1; }else{ int v1 = translateP(c, pOp); int v2; - sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1); + tdsqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1); if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){ ii += 3; - jj += sqlite3Strlen30(zTemp+jj); + jj += tdsqlite3Strlen30(zTemp+jj); v2 = translateP(zSynopsis[ii], pOp); if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){ ii += 2; v2++; } if( v2>1 ){ - sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1); + tdsqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1); } }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){ ii += 4; } } - jj += sqlite3Strlen30(zTemp+jj); + jj += tdsqlite3Strlen30(zTemp+jj); }else{ zTemp[jj++] = c; } } if( !seenCom && jj<nTemp-5 && pOp->zComment ){ - sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment); - jj += sqlite3Strlen30(zTemp+jj); + tdsqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment); + jj += tdsqlite3Strlen30(zTemp+jj); } if( jj<nTemp ) zTemp[jj] = 0; }else if( pOp->zComment ){ - sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment); - jj = sqlite3Strlen30(zTemp); + tdsqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment); + jj = tdsqlite3Strlen30(zTemp); }else{ zTemp[0] = 0; jj = 0; @@ -74726,23 +82473,23 @@ static void displayP4Expr(StrAccum *p, Expr *pExpr){ const char *zOp = 0; switch( pExpr->op ){ case TK_STRING: - sqlite3XPrintf(p, "%Q", pExpr->u.zToken); + tdsqlite3_str_appendf(p, "%Q", pExpr->u.zToken); break; case TK_INTEGER: - sqlite3XPrintf(p, "%d", pExpr->u.iValue); + tdsqlite3_str_appendf(p, "%d", pExpr->u.iValue); break; case TK_NULL: - sqlite3XPrintf(p, "NULL"); + tdsqlite3_str_appendf(p, "NULL"); break; case TK_REGISTER: { - sqlite3XPrintf(p, "r[%d]", pExpr->iTable); + tdsqlite3_str_appendf(p, "r[%d]", pExpr->iTable); break; } case TK_COLUMN: { if( pExpr->iColumn<0 ){ - sqlite3XPrintf(p, "rowid"); + tdsqlite3_str_appendf(p, "rowid"); }else{ - sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn); + tdsqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn); } break; } @@ -74774,18 +82521,18 @@ static void displayP4Expr(StrAccum *p, Expr *pExpr){ case TK_NOTNULL: zOp = "NOTNULL"; break; default: - sqlite3XPrintf(p, "%s", "expr"); + tdsqlite3_str_appendf(p, "%s", "expr"); break; } if( zOp ){ - sqlite3XPrintf(p, "%s(", zOp); + tdsqlite3_str_appendf(p, "%s(", zOp); displayP4Expr(p, pExpr->pLeft); if( pExpr->pRight ){ - sqlite3StrAccumAppend(p, ",", 1); + tdsqlite3_str_append(p, ",", 1); displayP4Expr(p, pExpr->pRight); } - sqlite3StrAccumAppend(p, ")", 1); + tdsqlite3_str_append(p, ")", 1); } } #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */ @@ -74800,20 +82547,23 @@ static char *displayP4(Op *pOp, char *zTemp, int nTemp){ char *zP4 = zTemp; StrAccum x; assert( nTemp>=20 ); - sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0); + tdsqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0); switch( pOp->p4type ){ case P4_KEYINFO: { int j; KeyInfo *pKeyInfo = pOp->p4.pKeyInfo; - assert( pKeyInfo->aSortOrder!=0 ); - sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField); - for(j=0; j<pKeyInfo->nField; j++){ + assert( pKeyInfo->aSortFlags!=0 ); + tdsqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField); + for(j=0; j<pKeyInfo->nKeyField; j++){ CollSeq *pColl = pKeyInfo->aColl[j]; const char *zColl = pColl ? pColl->zName : ""; if( strcmp(zColl, "BINARY")==0 ) zColl = "B"; - sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl); + tdsqlite3_str_appendf(&x, ",%s%s%s", + (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "", + (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "", + zColl); } - sqlite3StrAccumAppend(&x, ")", 1); + tdsqlite3_str_append(&x, ")", 1); break; } #ifdef SQLITE_ENABLE_CURSOR_HINTS @@ -74824,41 +82574,39 @@ static char *displayP4(Op *pOp, char *zTemp, int nTemp){ #endif case P4_COLLSEQ: { CollSeq *pColl = pOp->p4.pColl; - sqlite3XPrintf(&x, "(%.20s)", pColl->zName); + tdsqlite3_str_appendf(&x, "(%.20s)", pColl->zName); break; } case P4_FUNCDEF: { FuncDef *pDef = pOp->p4.pFunc; - sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg); + tdsqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg); break; } -#ifdef SQLITE_DEBUG case P4_FUNCCTX: { FuncDef *pDef = pOp->p4.pCtx->pFunc; - sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg); + tdsqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg); break; } -#endif case P4_INT64: { - sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64); + tdsqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64); break; } case P4_INT32: { - sqlite3XPrintf(&x, "%d", pOp->p4.i); + tdsqlite3_str_appendf(&x, "%d", pOp->p4.i); break; } case P4_REAL: { - sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal); + tdsqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal); break; } case P4_MEM: { Mem *pMem = pOp->p4.pMem; if( pMem->flags & MEM_Str ){ zP4 = pMem->z; - }else if( pMem->flags & MEM_Int ){ - sqlite3XPrintf(&x, "%lld", pMem->u.i); + }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){ + tdsqlite3_str_appendf(&x, "%lld", pMem->u.i); }else if( pMem->flags & MEM_Real ){ - sqlite3XPrintf(&x, "%.16g", pMem->u.r); + tdsqlite3_str_appendf(&x, "%.16g", pMem->u.r); }else if( pMem->flags & MEM_Null ){ zP4 = "NULL"; }else{ @@ -74869,8 +82617,8 @@ static char *displayP4(Op *pOp, char *zTemp, int nTemp){ } #ifndef SQLITE_OMIT_VIRTUALTABLE case P4_VTAB: { - sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab; - sqlite3XPrintf(&x, "vtab:%p", pVtab); + tdsqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab; + tdsqlite3_str_appendf(&x, "vtab:%p", pVtab); break; } #endif @@ -74879,23 +82627,24 @@ static char *displayP4(Op *pOp, char *zTemp, int nTemp){ int *ai = pOp->p4.ai; int n = ai[0]; /* The first element of an INTARRAY is always the ** count of the number of elements to follow */ - for(i=1; i<n; i++){ - sqlite3XPrintf(&x, ",%d", ai[i]); + for(i=1; i<=n; i++){ + tdsqlite3_str_appendf(&x, ",%d", ai[i]); } zTemp[0] = '['; - sqlite3StrAccumAppend(&x, "]", 1); + tdsqlite3_str_append(&x, "]", 1); break; } case P4_SUBPROGRAM: { - sqlite3XPrintf(&x, "program"); + tdsqlite3_str_appendf(&x, "program"); break; } + case P4_DYNBLOB: case P4_ADVANCE: { zTemp[0] = 0; break; } case P4_TABLE: { - sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName); + tdsqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName); break; } default: { @@ -74906,7 +82655,7 @@ static char *displayP4(Op *pOp, char *zTemp, int nTemp){ } } } - sqlite3StrAccumFinish(&x); + tdsqlite3StrAccumFinish(&x); assert( zP4!=0 ); return zP4; } @@ -74920,11 +82669,11 @@ static char *displayP4(Op *pOp, char *zTemp, int nTemp){ ** is maintained in p->btreeMask. The p->lockMask value is the subset of ** p->btreeMask of databases that will require a lock. */ -SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){ +SQLITE_PRIVATE void tdsqlite3VdbeUsesBtree(Vdbe *p, int i){ assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 ); assert( i<(int)sizeof(p->btreeMask)*8 ); DbMaskSet(p->btreeMask, i); - if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){ + if( i!=1 && tdsqlite3BtreeSharable(p->db->aDb[i].pBt) ){ DbMaskSet(p->lockMask, i); } } @@ -74938,7 +82687,7 @@ SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){ ** that the correct busy-handler callback is invoked if required. ** ** If SQLite is not threadsafe but does support shared-cache mode, then -** sqlite3BtreeEnter() is invoked to set the BtShared.db variables +** tdsqlite3BtreeEnter() is invoked to set the BtShared.db variables ** of all of BtShared structures accessible via the database handle ** associated with the VM. ** @@ -74951,9 +82700,9 @@ SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){ ** this routine is N*N. But as N is rarely more than 1, this should not ** be a problem. */ -SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){ +SQLITE_PRIVATE void tdsqlite3VdbeEnter(Vdbe *p){ int i; - sqlite3 *db; + tdsqlite3 *db; Db *aDb; int nDb; if( DbMaskAllZero(p->lockMask) ) return; /* The common case */ @@ -74962,7 +82711,7 @@ SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){ nDb = db->nDb; for(i=0; i<nDb; i++){ if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){ - sqlite3BtreeEnter(aDb[i].pBt); + tdsqlite3BtreeEnter(aDb[i].pBt); } } } @@ -74970,11 +82719,11 @@ SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){ #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 /* -** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter(). +** Unlock all of the btrees previously locked by a call to tdsqlite3VdbeEnter(). */ static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){ int i; - sqlite3 *db; + tdsqlite3 *db; Db *aDb; int nDb; db = p->db; @@ -74982,11 +82731,11 @@ static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){ nDb = db->nDb; for(i=0; i<nDb; i++){ if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){ - sqlite3BtreeLeave(aDb[i].pBt); + tdsqlite3BtreeLeave(aDb[i].pBt); } } } -SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){ +SQLITE_PRIVATE void tdsqlite3VdbeLeave(Vdbe *p){ if( DbMaskAllZero(p->lockMask) ) return; /* The common case */ vdbeLeave(p); } @@ -74996,7 +82745,7 @@ SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){ /* ** Print a single opcode. This routine is used for debugging only. */ -SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){ +SQLITE_PRIVATE void tdsqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){ char *zP4; char zPtr[50]; char zCom[100]; @@ -75008,11 +82757,11 @@ SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){ #else zCom[0] = 0; #endif - /* NB: The sqlite3OpcodeName() function is implemented by code created + /* NB: The tdsqlite3OpcodeName() function is implemented by code created ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the ** information from the vdbe.c source text */ fprintf(pOut, zFormat1, pc, - sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5, + tdsqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5, zCom ); fflush(pOut); @@ -75022,7 +82771,7 @@ SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){ /* ** Initialize an array of N Mem element. */ -static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){ +static void initMemArray(Mem *p, int N, tdsqlite3 *db, u16 flags){ while( (N--)>0 ){ p->db = db; p->flags = flags; @@ -75040,37 +82789,36 @@ static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){ static void releaseMemArray(Mem *p, int N){ if( p && N ){ Mem *pEnd = &p[N]; - sqlite3 *db = p->db; + tdsqlite3 *db = p->db; if( db->pnBytesFreed ){ do{ - if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc); + if( p->szMalloc ) tdsqlite3DbFree(db, p->zMalloc); }while( (++p)<pEnd ); return; } do{ assert( (&p[1])==pEnd || p[0].db==p[1].db ); - assert( sqlite3VdbeCheckMemInvariants(p) ); + assert( tdsqlite3VdbeCheckMemInvariants(p) ); - /* This block is really an inlined version of sqlite3VdbeMemRelease() + /* This block is really an inlined version of tdsqlite3VdbeMemRelease() ** that takes advantage of the fact that the memory cell value is ** being set to NULL after releasing any dynamic resources. ** ** The justification for duplicating code is that according to ** callgrind, this causes a certain test case to hit the CPU 4.7 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if - ** sqlite3MemRelease() were called from here. With -O2, this jumps + ** tdsqlite3MemRelease() were called from here. With -O2, this jumps ** to 6.6 percent. The test case is inserting 1000 rows into a table ** with no indexes using a single prepared INSERT statement, bind() ** and reset(). Inserts are grouped into a transaction. */ testcase( p->flags & MEM_Agg ); testcase( p->flags & MEM_Dyn ); - testcase( p->flags & MEM_Frame ); - testcase( p->flags & MEM_RowSet ); - if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){ - sqlite3VdbeMemRelease(p); + testcase( p->xDel==tdsqlite3VdbeFrameMemDel ); + if( p->flags&(MEM_Agg|MEM_Dyn) ){ + tdsqlite3VdbeMemRelease(p); }else if( p->szMalloc ){ - sqlite3DbFree(db, p->zMalloc); + tdsqlite3DbFreeNN(db, p->zMalloc); p->szMalloc = 0; } @@ -75079,27 +82827,57 @@ static void releaseMemArray(Mem *p, int N){ } } +#ifdef SQLITE_DEBUG +/* +** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is +** and false if something is wrong. +** +** This routine is intended for use inside of assert() statements only. +*/ +SQLITE_PRIVATE int tdsqlite3VdbeFrameIsValid(VdbeFrame *pFrame){ + if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0; + return 1; +} +#endif + + +/* +** This is a destructor on a Mem object (which is really an tdsqlite3_value) +** that deletes the Frame object that is attached to it as a blob. +** +** This routine does not delete the Frame right away. It merely adds the +** frame to a list of frames to be deleted when the Vdbe halts. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeFrameMemDel(void *pArg){ + VdbeFrame *pFrame = (VdbeFrame*)pArg; + assert( tdsqlite3VdbeFrameIsValid(pFrame) ); + pFrame->pParent = pFrame->v->pDelFrame; + pFrame->v->pDelFrame = pFrame; +} + + /* ** Delete a VdbeFrame object and its contents. VdbeFrame objects are -** allocated by the OP_Program opcode in sqlite3VdbeExec(). +** allocated by the OP_Program opcode in tdsqlite3VdbeExec(). */ -SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){ +SQLITE_PRIVATE void tdsqlite3VdbeFrameDelete(VdbeFrame *p){ int i; Mem *aMem = VdbeFrameMem(p); VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem]; + assert( tdsqlite3VdbeFrameIsValid(p) ); for(i=0; i<p->nChildCsr; i++){ - sqlite3VdbeFreeCursor(p->v, apCsr[i]); + tdsqlite3VdbeFreeCursor(p->v, apCsr[i]); } releaseMemArray(aMem, p->nChildMem); - sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0); - sqlite3DbFree(p->v->db, p); + tdsqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0); + tdsqlite3DbFree(p->v->db, p); } #ifndef SQLITE_OMIT_EXPLAIN /* ** Give a listing of the program in the virtual machine. ** -** The interface is the same as sqlite3VdbeExec(). But instead of +** The interface is the same as tdsqlite3VdbeExec(). But instead of ** running the code, it invokes the callback once for each instruction. ** This feature is used to implement "EXPLAIN". ** @@ -75107,21 +82885,26 @@ SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){ ** p->explain==2, only OP_Explain instructions are listed and these ** are shown in a different format. p->explain==2 is used to implement ** EXPLAIN QUERY PLAN. +** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers +** are also shown, so that the boundaries between the main program and +** each trigger are clear. ** ** When p->explain==1, first the main program is listed, then each of ** the trigger subprograms are listed one by one. */ -SQLITE_PRIVATE int sqlite3VdbeList( +SQLITE_PRIVATE int tdsqlite3VdbeList( Vdbe *p /* The VDBE */ ){ int nRow; /* Stop when row count reaches this */ int nSub = 0; /* Number of sub-vdbes seen so far */ SubProgram **apSub = 0; /* Array of sub-vdbes */ Mem *pSub = 0; /* Memory cell hold array of subprogs */ - sqlite3 *db = p->db; /* The database connection */ + tdsqlite3 *db = p->db; /* The database connection */ int i; /* Loop counter */ int rc = SQLITE_OK; /* Return code */ Mem *pMem = &p->aMem[1]; /* First Mem of result set */ + int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0); + Op *pOp = 0; assert( p->explain ); assert( p->magic==VDBE_MAGIC_RUN ); @@ -75129,27 +82912,27 @@ SQLITE_PRIVATE int sqlite3VdbeList( /* Even though this opcode does not use dynamic strings for ** the result, result columns may become dynamic if the user calls - ** sqlite3_column_text16(), causing a translation to UTF-16 encoding. + ** tdsqlite3_column_text16(), causing a translation to UTF-16 encoding. */ releaseMemArray(pMem, 8); p->pResultSet = 0; - if( p->rc==SQLITE_NOMEM_BKPT ){ - /* This happens if a malloc() inside a call to sqlite3_column_text() or - ** sqlite3_column_text16() failed. */ - sqlite3OomFault(db); + if( p->rc==SQLITE_NOMEM ){ + /* This happens if a malloc() inside a call to tdsqlite3_column_text() or + ** tdsqlite3_column_text16() failed. */ + tdsqlite3OomFault(db); return SQLITE_ERROR; } /* When the number of output rows reaches nRow, that means the - ** listing has finished and sqlite3_step() should return SQLITE_DONE. + ** listing has finished and tdsqlite3_step() should return SQLITE_DONE. ** nRow is the sum of the number of rows in the main program, plus ** the sum of the number of rows in all trigger subprograms encountered ** so far. The nRow value will increase as new trigger subprograms are ** encountered, but p->pc will eventually catch up to nRow. */ nRow = p->nOp; - if( p->explain==1 ){ + if( bListSubprogs ){ /* The first 8 memory cells are used for the result set. So we will ** commandeer the 9th cell to use as storage for an array of pointers ** to trigger subprograms. The VDBE is guaranteed to have at least 9 @@ -75157,7 +82940,7 @@ SQLITE_PRIVATE int sqlite3VdbeList( assert( p->nMem>9 ); pSub = &p->aMem[9]; if( pSub->flags&MEM_Blob ){ - /* On the first call to sqlite3_step(), pSub will hold a NULL. It is + /* On the first call to tdsqlite3_step(), pSub will hold a NULL. It is ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */ nSub = pSub->n/sizeof(Vdbe*); apSub = (SubProgram **)pSub->z; @@ -75167,19 +82950,13 @@ SQLITE_PRIVATE int sqlite3VdbeList( } } - do{ + while(1){ /* Loop exits via break */ i = p->pc++; - }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain ); - if( i>=nRow ){ - p->rc = SQLITE_OK; - rc = SQLITE_DONE; - }else if( db->u1.isInterrupted ){ - p->rc = SQLITE_INTERRUPT; - rc = SQLITE_ERROR; - sqlite3VdbeError(p, sqlite3ErrStr(p->rc)); - }else{ - char *zP4; - Op *pOp; + if( i>=nRow ){ + p->rc = SQLITE_OK; + rc = SQLITE_DONE; + break; + } if( i<p->nOp ){ /* The output line number is small enough that we are still in the ** main program. */ @@ -75189,99 +82966,121 @@ SQLITE_PRIVATE int sqlite3VdbeList( ** pick up the appropriate opcode. */ int j; i -= p->nOp; + assert( apSub!=0 ); + assert( nSub>0 ); for(j=0; i>=apSub[j]->nOp; j++){ i -= apSub[j]->nOp; + assert( i<apSub[j]->nOp || j+1<nSub ); } pOp = &apSub[j]->aOp[i]; } - if( p->explain==1 ){ - pMem->flags = MEM_Int; - pMem->u.i = i; /* Program counter */ - pMem++; - - pMem->flags = MEM_Static|MEM_Str|MEM_Term; - pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ - assert( pMem->z!=0 ); - pMem->n = sqlite3Strlen30(pMem->z); - pMem->enc = SQLITE_UTF8; - pMem++; - /* When an OP_Program opcode is encounter (the only opcode that has - ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms - ** kept in p->aMem[9].z to hold the new program - assuming this subprogram - ** has not already been seen. - */ - if( pOp->p4type==P4_SUBPROGRAM ){ - int nByte = (nSub+1)*sizeof(SubProgram*); - int j; - for(j=0; j<nSub; j++){ - if( apSub[j]==pOp->p4.pProgram ) break; - } - if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){ - apSub = (SubProgram **)pSub->z; - apSub[nSub++] = pOp->p4.pProgram; - pSub->flags |= MEM_Blob; - pSub->n = nSub*sizeof(SubProgram*); + /* When an OP_Program opcode is encounter (the only opcode that has + ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms + ** kept in p->aMem[9].z to hold the new program - assuming this subprogram + ** has not already been seen. + */ + if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){ + int nByte = (nSub+1)*sizeof(SubProgram*); + int j; + for(j=0; j<nSub; j++){ + if( apSub[j]==pOp->p4.pProgram ) break; + } + if( j==nSub ){ + p->rc = tdsqlite3VdbeMemGrow(pSub, nByte, nSub!=0); + if( p->rc!=SQLITE_OK ){ + rc = SQLITE_ERROR; + break; } + apSub = (SubProgram **)pSub->z; + apSub[nSub++] = pOp->p4.pProgram; + pSub->flags |= MEM_Blob; + pSub->n = nSub*sizeof(SubProgram*); + nRow += pOp->p4.pProgram->nOp; } } + if( p->explain<2 ) break; + if( pOp->opcode==OP_Explain ) break; + if( pOp->opcode==OP_Init && p->pc>1 ) break; + } - pMem->flags = MEM_Int; - pMem->u.i = pOp->p1; /* P1 */ - pMem++; + if( rc==SQLITE_OK ){ + if( db->u1.isInterrupted ){ + p->rc = SQLITE_INTERRUPT; + rc = SQLITE_ERROR; + tdsqlite3VdbeError(p, tdsqlite3ErrStr(p->rc)); + }else{ + char *zP4; + if( p->explain==1 ){ + pMem->flags = MEM_Int; + pMem->u.i = i; /* Program counter */ + pMem++; + + pMem->flags = MEM_Static|MEM_Str|MEM_Term; + pMem->z = (char*)tdsqlite3OpcodeName(pOp->opcode); /* Opcode */ + assert( pMem->z!=0 ); + pMem->n = tdsqlite3Strlen30(pMem->z); + pMem->enc = SQLITE_UTF8; + pMem++; + } - pMem->flags = MEM_Int; - pMem->u.i = pOp->p2; /* P2 */ - pMem++; + pMem->flags = MEM_Int; + pMem->u.i = pOp->p1; /* P1 */ + pMem++; - pMem->flags = MEM_Int; - pMem->u.i = pOp->p3; /* P3 */ - pMem++; + pMem->flags = MEM_Int; + pMem->u.i = pOp->p2; /* P2 */ + pMem++; - if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */ - assert( p->db->mallocFailed ); - return SQLITE_ERROR; - } - pMem->flags = MEM_Str|MEM_Term; - zP4 = displayP4(pOp, pMem->z, pMem->szMalloc); - if( zP4!=pMem->z ){ - pMem->n = 0; - sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0); - }else{ - assert( pMem->z!=0 ); - pMem->n = sqlite3Strlen30(pMem->z); - pMem->enc = SQLITE_UTF8; - } - pMem++; + pMem->flags = MEM_Int; + pMem->u.i = pOp->p3; /* P3 */ + pMem++; - if( p->explain==1 ){ - if( sqlite3VdbeMemClearAndResize(pMem, 4) ){ + if( tdsqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */ assert( p->db->mallocFailed ); return SQLITE_ERROR; } pMem->flags = MEM_Str|MEM_Term; - pMem->n = 2; - sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */ - pMem->enc = SQLITE_UTF8; + zP4 = displayP4(pOp, pMem->z, pMem->szMalloc); + if( zP4!=pMem->z ){ + pMem->n = 0; + tdsqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0); + }else{ + assert( pMem->z!=0 ); + pMem->n = tdsqlite3Strlen30(pMem->z); + pMem->enc = SQLITE_UTF8; + } pMem++; - + + if( p->explain==1 ){ + if( tdsqlite3VdbeMemClearAndResize(pMem, 4) ){ + assert( p->db->mallocFailed ); + return SQLITE_ERROR; + } + pMem->flags = MEM_Str|MEM_Term; + pMem->n = 2; + tdsqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */ + pMem->enc = SQLITE_UTF8; + pMem++; + #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - if( sqlite3VdbeMemClearAndResize(pMem, 500) ){ - assert( p->db->mallocFailed ); - return SQLITE_ERROR; - } - pMem->flags = MEM_Str|MEM_Term; - pMem->n = displayComment(pOp, zP4, pMem->z, 500); - pMem->enc = SQLITE_UTF8; + if( tdsqlite3VdbeMemClearAndResize(pMem, 500) ){ + assert( p->db->mallocFailed ); + return SQLITE_ERROR; + } + pMem->flags = MEM_Str|MEM_Term; + pMem->n = displayComment(pOp, zP4, pMem->z, 500); + pMem->enc = SQLITE_UTF8; #else - pMem->flags = MEM_Null; /* Comment */ + pMem->flags = MEM_Null; /* Comment */ #endif - } + } - p->nResColumn = 8 - 4*(p->explain-1); - p->pResultSet = &p->aMem[1]; - p->rc = SQLITE_OK; - rc = SQLITE_ROW; + p->nResColumn = 8 - 4*(p->explain-1); + p->pResultSet = &p->aMem[1]; + p->rc = SQLITE_OK; + rc = SQLITE_ROW; + } } return rc; } @@ -75291,7 +83090,7 @@ SQLITE_PRIVATE int sqlite3VdbeList( /* ** Print the SQL that was used to generate a VDBE program. */ -SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){ +SQLITE_PRIVATE void tdsqlite3VdbePrintSql(Vdbe *p){ const char *z = 0; if( p->zSql ){ z = p->zSql; @@ -75299,7 +83098,7 @@ SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){ const VdbeOp *pOp = &p->aOp[0]; if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){ z = pOp->p4.z; - while( sqlite3Isspace(*z) ) z++; + while( tdsqlite3Isspace(*z) ) z++; } } if( z ) printf("SQL: [%s]\n", z); @@ -75310,19 +83109,19 @@ SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){ /* ** Print an IOTRACE message showing SQL content. */ -SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){ +SQLITE_PRIVATE void tdsqlite3VdbeIOTraceSql(Vdbe *p){ int nOp = p->nOp; VdbeOp *pOp; - if( sqlite3IoTrace==0 ) return; + if( tdsqlite3IoTrace==0 ) return; if( nOp<1 ) return; pOp = &p->aOp[0]; if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){ int i, j; char z[1000]; - sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z); - for(i=0; sqlite3Isspace(z[i]); i++){} + tdsqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z); + for(i=0; tdsqlite3Isspace(z[i]); i++){} for(j=0; z[i]; i++){ - if( sqlite3Isspace(z[i]) ){ + if( tdsqlite3Isspace(z[i]) ){ if( z[i-1]!=' ' ){ z[j++] = ' '; } @@ -75331,7 +83130,7 @@ SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){ } } z[j] = 0; - sqlite3IoTrace("SQL %s\n", z); + tdsqlite3IoTrace("SQL %s\n", z); } } #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */ @@ -75341,9 +83140,9 @@ SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){ ** of a ReusableSpace object by the allocSpace() routine below. */ struct ReusableSpace { - u8 *pSpace; /* Available memory */ - int nFree; /* Bytes of available memory */ - int nNeeded; /* Total bytes that could not be allocated */ + u8 *pSpace; /* Available memory */ + tdsqlite3_int64 nFree; /* Bytes of available memory */ + tdsqlite3_int64 nNeeded; /* Total bytes that could not be allocated */ }; /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf @@ -75363,7 +83162,7 @@ struct ReusableSpace { static void *allocSpace( struct ReusableSpace *p, /* Bulk memory available for allocation */ void *pBuf, /* Pointer to a prior allocation */ - int nByte /* Bytes of memory needed */ + tdsqlite3_int64 nByte /* Bytes of memory needed */ ){ assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) ); if( pBuf==0 ){ @@ -75383,7 +83182,7 @@ static void *allocSpace( ** Rewind the VDBE back to the beginning in preparation for ** running it. */ -SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){ +SQLITE_PRIVATE void tdsqlite3VdbeRewind(Vdbe *p){ #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) int i; #endif @@ -75423,24 +83222,24 @@ SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){ ** creating the virtual machine. This involves things such ** as allocating registers and initializing the program counter. ** After the VDBE has be prepped, it can be executed by one or more -** calls to sqlite3VdbeExec(). +** calls to tdsqlite3VdbeExec(). ** ** This function may be called exactly once on each virtual machine. ** After this routine is called the VM has been "packaged" and is ready ** to run. After this routine is called, further calls to -** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects +** tdsqlite3VdbeAddOp() functions are prohibited. This routine disconnects ** the Vdbe from the Parse object that helped generate it so that the ** the Vdbe becomes an independent entity and the Parse object can be ** destroyed. ** -** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back +** Use the tdsqlite3VdbeRewind() procedure to restore a virtual machine back ** to its initial state after it has been run. */ -SQLITE_PRIVATE void sqlite3VdbeMakeReady( +SQLITE_PRIVATE void tdsqlite3VdbeMakeReady( Vdbe *p, /* The VDBE */ Parse *pParse /* Parsing context */ ){ - sqlite3 *db; /* The database connection */ + tdsqlite3 *db; /* The database connection */ int nVar; /* Number of parameters */ int nMem; /* Number of VM memory registers */ int nCursor; /* Number of cursors required */ @@ -75481,8 +83280,26 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady( resolveP2Values(p, &nArg); p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort); - if( pParse->explain && nMem<10 ){ - nMem = 10; + if( pParse->explain ){ + static const char * const azColName[] = { + "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", + "id", "parent", "notused", "detail" + }; + int iFirst, mx, i; + if( nMem<10 ) nMem = 10; + if( pParse->explain==2 ){ + tdsqlite3VdbeSetNumCols(p, 4); + iFirst = 8; + mx = 12; + }else{ + tdsqlite3VdbeSetNumCols(p, 8); + iFirst = 0; + mx = 8; + } + for(i=iFirst; i<mx; i++){ + tdsqlite3VdbeSetColName(p, i-iFirst, COLNAME_NAME, + azColName[i], SQLITE_STATIC); + } } p->expired = 0; @@ -75496,24 +83313,30 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady( ** the leftover memory at the end of the opcode array. This can significantly ** reduce the amount of memory held by a prepared statement. */ - do { - x.nNeeded = 0; - p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem)); - p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem)); - p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*)); - p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*)); + x.nNeeded = 0; + p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem)); + p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem)); + p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*)); + p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*)); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS - p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64)); + p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64)); #endif - if( x.nNeeded==0 ) break; - x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded); + if( x.nNeeded ){ + x.pSpace = p->pFree = tdsqlite3DbMallocRawNN(db, x.nNeeded); x.nFree = x.nNeeded; - }while( !db->mallocFailed ); + if( !db->mallocFailed ){ + p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem)); + p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem)); + p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*)); + p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*)); +#ifdef SQLITE_ENABLE_STMT_SCANSTATUS + p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64)); +#endif + } + } - p->nzVar = pParse->nzVar; - p->azVar = pParse->azVar; - pParse->nzVar = 0; - pParse->azVar = 0; + p->pVList = pParse->pVList; + pParse->pVList = 0; p->explain = pParse->explain; if( db->mallocFailed ){ p->nVar = 0; @@ -75530,38 +83353,38 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady( memset(p->anExec, 0, p->nOp*sizeof(i64)); #endif } - sqlite3VdbeRewind(p); + tdsqlite3VdbeRewind(p); } /* ** Close a VDBE cursor and release all the resources that cursor ** happens to hold. */ -SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){ +SQLITE_PRIVATE void tdsqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){ if( pCx==0 ){ return; } - assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE ); + assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE ); switch( pCx->eCurType ){ case CURTYPE_SORTER: { - sqlite3VdbeSorterClose(p->db, pCx); + tdsqlite3VdbeSorterClose(p->db, pCx); break; } case CURTYPE_BTREE: { - if( pCx->pBt ){ - sqlite3BtreeClose(pCx->pBt); + if( pCx->isEphemeral ){ + if( pCx->pBtx ) tdsqlite3BtreeClose(pCx->pBtx); /* The pCx->pCursor will be close automatically, if it exists, by ** the call above. */ }else{ assert( pCx->uc.pCursor!=0 ); - sqlite3BtreeCloseCursor(pCx->uc.pCursor); + tdsqlite3BtreeCloseCursor(pCx->uc.pCursor); } break; } #ifndef SQLITE_OMIT_VIRTUALTABLE case CURTYPE_VTAB: { - sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur; - const sqlite3_module *pModule = pVCur->pVtab->pModule; + tdsqlite3_vtab_cursor *pVCur = pCx->uc.pVCur; + const tdsqlite3_module *pModule = pVCur->pVtab->pModule; assert( pVCur->pVtab->nRef>0 ); pVCur->pVtab->nRef--; pModule->xClose(pVCur); @@ -75580,7 +83403,7 @@ static void closeCursorsInFrame(Vdbe *p){ for(i=0; i<p->nCursor; i++){ VdbeCursor *pC = p->apCsr[i]; if( pC ){ - sqlite3VdbeFreeCursor(p, pC); + tdsqlite3VdbeFreeCursor(p, pC); p->apCsr[i] = 0; } } @@ -75592,7 +83415,7 @@ static void closeCursorsInFrame(Vdbe *p){ ** is used, for example, when a trigger sub-program is halted to restore ** control to the main program. */ -SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){ +SQLITE_PRIVATE int tdsqlite3VdbeFrameRestore(VdbeFrame *pFrame){ Vdbe *v = pFrame->v; closeCursorsInFrame(v); #ifdef SQLITE_ENABLE_STMT_SCANSTATUS @@ -75607,7 +83430,7 @@ SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){ v->db->lastRowid = pFrame->lastRowid; v->nChange = pFrame->nChange; v->db->nChange = pFrame->nDbChange; - sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0); + tdsqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0); v->pAuxData = pFrame->pAuxData; pFrame->pAuxData = 0; return pFrame->pc; @@ -75625,7 +83448,7 @@ static void closeAllCursors(Vdbe *p){ if( p->pFrame ){ VdbeFrame *pFrame; for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); - sqlite3VdbeFrameRestore(pFrame); + tdsqlite3VdbeFrameRestore(pFrame); p->pFrame = 0; p->nFrame = 0; } @@ -75637,66 +83460,46 @@ static void closeAllCursors(Vdbe *p){ while( p->pDelFrame ){ VdbeFrame *pDel = p->pDelFrame; p->pDelFrame = pDel->pParent; - sqlite3VdbeFrameDelete(pDel); + tdsqlite3VdbeFrameDelete(pDel); } /* Delete any auxdata allocations made by the VM */ - if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0); + if( p->pAuxData ) tdsqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0); assert( p->pAuxData==0 ); } /* -** Clean up the VM after a single run. -*/ -static void Cleanup(Vdbe *p){ - sqlite3 *db = p->db; - -#ifdef SQLITE_DEBUG - /* Execute assert() statements to ensure that the Vdbe.apCsr[] and - ** Vdbe.aMem[] arrays have already been cleaned up. */ - int i; - if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 ); - if( p->aMem ){ - for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined ); - } -#endif - - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = 0; - p->pResultSet = 0; -} - -/* ** Set the number of result columns that will be returned by this SQL ** statement. This is now set at compile time, rather than during -** execution of the vdbe program so that sqlite3_column_count() can -** be called on an SQL statement before sqlite3_step(). +** execution of the vdbe program so that tdsqlite3_column_count() can +** be called on an SQL statement before tdsqlite3_step(). */ -SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){ - Mem *pColName; +SQLITE_PRIVATE void tdsqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){ int n; - sqlite3 *db = p->db; + tdsqlite3 *db = p->db; - releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); - sqlite3DbFree(db, p->aColName); + if( p->nResColumn ){ + releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); + tdsqlite3DbFree(db, p->aColName); + } n = nResColumn*COLNAME_N; p->nResColumn = (u16)nResColumn; - p->aColName = pColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n ); + p->aColName = (Mem*)tdsqlite3DbMallocRawNN(db, sizeof(Mem)*n ); if( p->aColName==0 ) return; - initMemArray(p->aColName, n, p->db, MEM_Null); + initMemArray(p->aColName, n, db, MEM_Null); } /* ** Set the name of the idx'th column to be returned by the SQL statement. ** zName must be a pointer to a nul terminated string. ** -** This call must be made after a call to sqlite3VdbeSetNumCols(). +** This call must be made after a call to tdsqlite3VdbeSetNumCols(). ** ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed -** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed. +** to by zName will be freed by tdsqlite3DbFree() when the vdbe is destroyed. */ -SQLITE_PRIVATE int sqlite3VdbeSetColName( +SQLITE_PRIVATE int tdsqlite3VdbeSetColName( Vdbe *p, /* Vdbe being configured */ int idx, /* Index of column zName applies to */ int var, /* One of the COLNAME_* constants */ @@ -75713,7 +83516,7 @@ SQLITE_PRIVATE int sqlite3VdbeSetColName( } assert( p->aColName!=0 ); pColName = &(p->aColName[idx+var*p->nResColumn]); - rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel); + rc = tdsqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel); assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 ); return rc; } @@ -75724,7 +83527,7 @@ SQLITE_PRIVATE int sqlite3VdbeSetColName( ** write-transaction spanning more than one database file, this routine ** takes care of the master journal trickery. */ -static int vdbeCommit(sqlite3 *db, Vdbe *p){ +static int vdbeCommit(tdsqlite3 *db, Vdbe *p){ int i; int nTrans = 0; /* Number of databases with an active write-transaction ** that are candidates for a two-phase commit using a @@ -75733,7 +83536,7 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ int needXcommit = 0; #ifdef SQLITE_OMIT_VIRTUALTABLE - /* With this option, sqlite3VtabSync() is defined to be simply + /* With this option, tdsqlite3VtabSync() is defined to be simply ** SQLITE_OK so p is not used. */ UNUSED_PARAMETER(p); @@ -75745,7 +83548,7 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ ** required, as an xSync() callback may add an attached database ** to the transaction. */ - rc = sqlite3VtabSync(db, p); + rc = tdsqlite3VtabSync(db, p); /* This loop determines (a) if the commit hook should be invoked and ** (b) how many database files have open write transactions, not @@ -75755,7 +83558,7 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ */ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; - if( sqlite3BtreeIsInTrans(pBt) ){ + if( tdsqlite3BtreeIsInTrans(pBt) ){ /* Whether or not a database might need a master journal depends upon ** its journal mode (among other things). This matrix determines which ** journal modes use a master journal and which do not */ @@ -75769,16 +83572,17 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ }; Pager *pPager; /* Pager associated with pBt */ needXcommit = 1; - sqlite3BtreeEnter(pBt); - pPager = sqlite3BtreePager(pBt); + tdsqlite3BtreeEnter(pBt); + pPager = tdsqlite3BtreePager(pBt); if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF - && aMJNeeded[sqlite3PagerGetJournalMode(pPager)] + && aMJNeeded[tdsqlite3PagerGetJournalMode(pPager)] + && tdsqlite3PagerIsMemdb(pPager)==0 ){ assert( i!=1 ); nTrans++; } - rc = sqlite3PagerExclusiveLock(pPager); - sqlite3BtreeLeave(pBt); + rc = tdsqlite3PagerExclusiveLock(pPager); + tdsqlite3BtreeLeave(pBt); } } if( rc!=SQLITE_OK ){ @@ -75797,18 +83601,18 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ ** TEMP database) has a transaction active. There is no need for the ** master-journal. ** - ** If the return value of sqlite3BtreeGetFilename() is a zero length + ** If the return value of tdsqlite3BtreeGetFilename() is a zero length ** string, it means the main database is :memory: or a temp file. In ** that case we do not support atomic multi-file commits, so use the ** simple case then too. */ - if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt)) + if( 0==tdsqlite3Strlen30(tdsqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ - rc = sqlite3BtreeCommitPhaseOne(pBt, 0); + rc = tdsqlite3BtreeCommitPhaseOne(pBt, 0); } } @@ -75820,11 +83624,11 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ - rc = sqlite3BtreeCommitPhaseTwo(pBt, 0); + rc = tdsqlite3BtreeCommitPhaseTwo(pBt, 0); } } if( rc==SQLITE_OK ){ - sqlite3VtabCommit(db); + tdsqlite3VtabCommit(db); } } @@ -75834,49 +83638,49 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ */ #ifndef SQLITE_OMIT_DISKIO else{ - sqlite3_vfs *pVfs = db->pVfs; + tdsqlite3_vfs *pVfs = db->pVfs; char *zMaster = 0; /* File-name for the master journal */ - char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt); - sqlite3_file *pMaster = 0; + char const *zMainFile = tdsqlite3BtreeGetFilename(db->aDb[0].pBt); + tdsqlite3_file *pMaster = 0; i64 offset = 0; int res; int retryCount = 0; int nMainFile; /* Select a master journal file name */ - nMainFile = sqlite3Strlen30(zMainFile); - zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile); + nMainFile = tdsqlite3Strlen30(zMainFile); + zMaster = tdsqlite3MPrintf(db, "%s-mjXXXXXX9XXz%c%c", zMainFile, 0, 0); if( zMaster==0 ) return SQLITE_NOMEM_BKPT; do { u32 iRandom; if( retryCount ){ if( retryCount>100 ){ - sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster); - sqlite3OsDelete(pVfs, zMaster, 0); + tdsqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster); + tdsqlite3OsDelete(pVfs, zMaster, 0); break; }else if( retryCount==1 ){ - sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster); + tdsqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster); } } retryCount++; - sqlite3_randomness(sizeof(iRandom), &iRandom); - sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X", + tdsqlite3_randomness(sizeof(iRandom), &iRandom); + tdsqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X", (iRandom>>8)&0xffffff, iRandom&0xff); /* The antipenultimate character of the master journal name must ** be "9" to avoid name collisions when using 8+3 filenames. */ - assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' ); - sqlite3FileSuffix3(zMainFile, zMaster); - rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); + assert( zMaster[tdsqlite3Strlen30(zMaster)-3]=='9' ); + tdsqlite3FileSuffix3(zMainFile, zMaster); + rc = tdsqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); }while( rc==SQLITE_OK && res ); if( rc==SQLITE_OK ){ /* Open the master journal. */ - rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, + rc = tdsqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE| SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0 ); } if( rc!=SQLITE_OK ){ - sqlite3DbFree(db, zMaster); + tdsqlite3DbFree(db, zMaster); return rc; } @@ -75888,18 +83692,18 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ */ for(i=0; i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; - if( sqlite3BtreeIsInTrans(pBt) ){ - char const *zFile = sqlite3BtreeGetJournalname(pBt); + if( tdsqlite3BtreeIsInTrans(pBt) ){ + char const *zFile = tdsqlite3BtreeGetJournalname(pBt); if( zFile==0 ){ continue; /* Ignore TEMP and :memory: databases */ } assert( zFile[0]!=0 ); - rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset); - offset += sqlite3Strlen30(zFile)+1; + rc = tdsqlite3OsWrite(pMaster, zFile, tdsqlite3Strlen30(zFile)+1, offset); + offset += tdsqlite3Strlen30(zFile)+1; if( rc!=SQLITE_OK ){ - sqlite3OsCloseFree(pMaster); - sqlite3OsDelete(pVfs, zMaster, 0); - sqlite3DbFree(db, zMaster); + tdsqlite3OsCloseFree(pMaster); + tdsqlite3OsDelete(pVfs, zMaster, 0); + tdsqlite3DbFree(db, zMaster); return rc; } } @@ -75908,12 +83712,12 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ /* Sync the master journal file. If the IOCAP_SEQUENTIAL device ** flag is set this is not required. */ - if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL) - && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL)) + if( 0==(tdsqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL) + && SQLITE_OK!=(rc = tdsqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL)) ){ - sqlite3OsCloseFree(pMaster); - sqlite3OsDelete(pVfs, zMaster, 0); - sqlite3DbFree(db, zMaster); + tdsqlite3OsCloseFree(pMaster); + tdsqlite3OsDelete(pVfs, zMaster, 0); + tdsqlite3DbFree(db, zMaster); return rc; } @@ -75922,7 +83726,7 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ ** an error occurs here, do not delete the master journal file. ** ** If the error occurs during the first call to - ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the + ** tdsqlite3BtreeCommitPhaseOne(), then there is a chance that the ** master journal file will be orphaned. But we cannot delete it, ** in case the master journal file name was written into the journal ** file before the failure occurred. @@ -75930,13 +83734,13 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ - rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster); + rc = tdsqlite3BtreeCommitPhaseOne(pBt, zMaster); } } - sqlite3OsCloseFree(pMaster); + tdsqlite3OsCloseFree(pMaster); assert( rc!=SQLITE_BUSY ); if( rc!=SQLITE_OK ){ - sqlite3DbFree(db, zMaster); + tdsqlite3DbFree(db, zMaster); return rc; } @@ -75944,32 +83748,32 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ ** doing this the directory is synced again before any individual ** transaction files are deleted. */ - rc = sqlite3OsDelete(pVfs, zMaster, 1); - sqlite3DbFree(db, zMaster); + rc = tdsqlite3OsDelete(pVfs, zMaster, 1); + tdsqlite3DbFree(db, zMaster); zMaster = 0; if( rc ){ return rc; } /* All files and directories have already been synced, so the following - ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and + ** calls to tdsqlite3BtreeCommitPhaseTwo() are only closing files and ** deleting or truncating journals. If something goes wrong while ** this is happening we don't really care. The integrity of the ** transaction is already guaranteed, but some stray 'cold' journals ** may be lying around. Returning an error code won't help matters. */ disable_simulated_io_errors(); - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); for(i=0; i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ - sqlite3BtreeCommitPhaseTwo(pBt, 1); + tdsqlite3BtreeCommitPhaseTwo(pBt, 1); } } - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); enable_simulated_io_errors(); - sqlite3VtabCommit(db); + tdsqlite3VtabCommit(db); } #endif @@ -75986,14 +83790,14 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ ** This is a no-op if NDEBUG is defined. */ #ifndef NDEBUG -static void checkActiveVdbeCnt(sqlite3 *db){ +static void checkActiveVdbeCnt(tdsqlite3 *db){ Vdbe *p; int cnt = 0; int nWrite = 0; int nRead = 0; p = db->pVdbe; while( p ){ - if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){ + if( tdsqlite3_stmt_busy((tdsqlite3_stmt*)p) ){ cnt++; if( p->readOnly==0 ) nWrite++; if( p->bIsReader ) nRead++; @@ -76018,60 +83822,59 @@ static void checkActiveVdbeCnt(sqlite3 *db){ ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. ** Otherwise SQLITE_OK. */ -SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){ - sqlite3 *const db = p->db; +static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){ + tdsqlite3 *const db = p->db; int rc = SQLITE_OK; + int i; + const int iSavepoint = p->iStatement-1; - /* If p->iStatement is greater than zero, then this Vdbe opened a - ** statement transaction that should be closed here. The only exception - ** is that an IO error may have occurred, causing an emergency rollback. - ** In this case (db->nStatement==0), and there is nothing to do. - */ - if( db->nStatement && p->iStatement ){ - int i; - const int iSavepoint = p->iStatement-1; - - assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE); - assert( db->nStatement>0 ); - assert( p->iStatement==(db->nStatement+db->nSavepoint) ); + assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE); + assert( db->nStatement>0 ); + assert( p->iStatement==(db->nStatement+db->nSavepoint) ); - for(i=0; i<db->nDb; i++){ - int rc2 = SQLITE_OK; - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - if( eOp==SAVEPOINT_ROLLBACK ){ - rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint); - } - if( rc2==SQLITE_OK ){ - rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint); - } - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - } - db->nStatement--; - p->iStatement = 0; - - if( rc==SQLITE_OK ){ + for(i=0; i<db->nDb; i++){ + int rc2 = SQLITE_OK; + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ if( eOp==SAVEPOINT_ROLLBACK ){ - rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint); + rc2 = tdsqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint); + } + if( rc2==SQLITE_OK ){ + rc2 = tdsqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint); } if( rc==SQLITE_OK ){ - rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint); + rc = rc2; } } + } + db->nStatement--; + p->iStatement = 0; - /* If the statement transaction is being rolled back, also restore the - ** database handles deferred constraint counter to the value it had when - ** the statement transaction was opened. */ + if( rc==SQLITE_OK ){ if( eOp==SAVEPOINT_ROLLBACK ){ - db->nDeferredCons = p->nStmtDefCons; - db->nDeferredImmCons = p->nStmtDefImmCons; + rc = tdsqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint); + } + if( rc==SQLITE_OK ){ + rc = tdsqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint); } } + + /* If the statement transaction is being rolled back, also restore the + ** database handles deferred constraint counter to the value it had when + ** the statement transaction was opened. */ + if( eOp==SAVEPOINT_ROLLBACK ){ + db->nDeferredCons = p->nStmtDefCons; + db->nDeferredImmCons = p->nStmtDefImmCons; + } return rc; } +SQLITE_PRIVATE int tdsqlite3VdbeCloseStatement(Vdbe *p, int eOp){ + if( p->db->nStatement && p->iStatement ){ + return vdbeCloseStatement(p, eOp); + } + return SQLITE_OK; +} + /* ** This function is called when a transaction opened by the database @@ -76084,14 +83887,14 @@ SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){ ** and write an error message to it. Then return SQLITE_ERROR. */ #ifndef SQLITE_OMIT_FOREIGN_KEY -SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){ - sqlite3 *db = p->db; +SQLITE_PRIVATE int tdsqlite3VdbeCheckFk(Vdbe *p, int deferred){ + tdsqlite3 *db = p->db; if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) || (!deferred && p->nFkConstraint>0) ){ p->rc = SQLITE_CONSTRAINT_FOREIGNKEY; p->errorAction = OE_Abort; - sqlite3VdbeError(p, "FOREIGN KEY constraint failed"); + tdsqlite3VdbeError(p, "FOREIGN KEY constraint failed"); return SQLITE_ERROR; } return SQLITE_OK; @@ -76111,9 +83914,9 @@ SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){ ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it ** means the close did not happen and needs to be repeated. */ -SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ +SQLITE_PRIVATE int tdsqlite3VdbeHalt(Vdbe *p){ int rc; /* Used to store transient return codes */ - sqlite3 *db = p->db; + tdsqlite3 *db = p->db; /* This function contains the logic that determines if a statement or ** transaction will be committed or rolled back as a result of the @@ -76131,13 +83934,13 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ ** one, or the complete transaction if there is no statement transaction. */ + if( p->magic!=VDBE_MAGIC_RUN ){ + return SQLITE_OK; + } if( db->mallocFailed ){ p->rc = SQLITE_NOMEM_BKPT; } closeAllCursors(p); - if( p->magic!=VDBE_MAGIC_RUN ){ - return SQLITE_OK; - } checkActiveVdbeCnt(db); /* No commit or rollback needed if the program never started or if the @@ -76148,7 +83951,7 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ int isSpecialError; /* Set to true if a 'special' error */ /* Lock all btrees used by the statement */ - sqlite3VdbeEnter(p); + tdsqlite3VdbeEnter(p); /* Check for one of the special errors */ mrc = p->rc & 0xff; @@ -76174,8 +83977,8 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ /* We are forced to roll back the active transaction. Before doing ** so, abort any other statements this handle currently has active. */ - sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); - sqlite3CloseSavepoints(db); + tdsqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + tdsqlite3CloseSavepoints(db); db->autoCommit = 1; p->nChange = 0; } @@ -76183,8 +83986,8 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ } /* Check for immediate foreign key violations. */ - if( p->rc==SQLITE_OK ){ - sqlite3VdbeCheckFk(p, 0); + if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ + tdsqlite3VdbeCheckFk(p, 0); } /* If the auto-commit flag is set and this is the only active writer @@ -76193,15 +83996,15 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ ** Note: This block also runs if one of the special errors handled ** above has occurred. */ - if( !sqlite3VtabInSync(db) + if( !tdsqlite3VtabInSync(db) && db->autoCommit && db->nVdbeWrite==(p->readOnly==0) ){ if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ - rc = sqlite3VdbeCheckFk(p, 1); + rc = tdsqlite3VdbeCheckFk(p, 1); if( rc!=SQLITE_OK ){ if( NEVER(p->readOnly) ){ - sqlite3VdbeLeave(p); + tdsqlite3VdbeLeave(p); return SQLITE_ERROR; } rc = SQLITE_CONSTRAINT_FOREIGNKEY; @@ -76213,20 +84016,20 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ rc = vdbeCommit(db, p); } if( rc==SQLITE_BUSY && p->readOnly ){ - sqlite3VdbeLeave(p); + tdsqlite3VdbeLeave(p); return SQLITE_BUSY; }else if( rc!=SQLITE_OK ){ p->rc = rc; - sqlite3RollbackAll(db, SQLITE_OK); + tdsqlite3RollbackAll(db, SQLITE_OK); p->nChange = 0; }else{ db->nDeferredCons = 0; db->nDeferredImmCons = 0; - db->flags &= ~SQLITE_DeferFKs; - sqlite3CommitInternalChanges(db); + db->flags &= ~(u64)SQLITE_DeferFKs; + tdsqlite3CommitInternalChanges(db); } }else{ - sqlite3RollbackAll(db, SQLITE_OK); + tdsqlite3RollbackAll(db, SQLITE_OK); p->nChange = 0; } db->nStatement = 0; @@ -76236,29 +84039,29 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ }else if( p->errorAction==OE_Abort ){ eStatementOp = SAVEPOINT_ROLLBACK; }else{ - sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); - sqlite3CloseSavepoints(db); + tdsqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + tdsqlite3CloseSavepoints(db); db->autoCommit = 1; p->nChange = 0; } } /* If eStatementOp is non-zero, then a statement transaction needs to - ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to + ** be committed or rolled back. Call tdsqlite3VdbeCloseStatement() to ** do so. If this operation returns an error, and the current statement ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the ** current statement error code. */ if( eStatementOp ){ - rc = sqlite3VdbeCloseStatement(p, eStatementOp); + rc = tdsqlite3VdbeCloseStatement(p, eStatementOp); if( rc ){ if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){ p->rc = rc; - sqlite3DbFree(db, p->zErrMsg); + tdsqlite3DbFree(db, p->zErrMsg); p->zErrMsg = 0; } - sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); - sqlite3CloseSavepoints(db); + tdsqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + tdsqlite3CloseSavepoints(db); db->autoCommit = 1; p->nChange = 0; } @@ -76269,15 +84072,15 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ */ if( p->changeCntOn ){ if( eStatementOp!=SAVEPOINT_ROLLBACK ){ - sqlite3VdbeSetChanges(db, p->nChange); + tdsqlite3VdbeSetChanges(db, p->nChange); }else{ - sqlite3VdbeSetChanges(db, 0); + tdsqlite3VdbeSetChanges(db, 0); } p->nChange = 0; } /* Release the locks */ - sqlite3VdbeLeave(p); + tdsqlite3VdbeLeave(p); } /* We have successfully halted and closed the VM. Record this fact. */ @@ -76296,11 +84099,11 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ } /* If the auto-commit flag is set to true, then any locks that were held - ** by connection db have now been released. Call sqlite3ConnectionUnlocked() + ** by connection db have now been released. Call tdsqlite3ConnectionUnlocked() ** to invoke any required unlock-notify callbacks. */ if( db->autoCommit ){ - sqlite3ConnectionUnlocked(db); + tdsqlite3ConnectionUnlocked(db); } assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 ); @@ -76309,35 +84112,35 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ /* -** Each VDBE holds the result of the most recent sqlite3_step() call +** Each VDBE holds the result of the most recent tdsqlite3_step() call ** in p->rc. This routine sets that result back to SQLITE_OK. */ -SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){ +SQLITE_PRIVATE void tdsqlite3VdbeResetStepResult(Vdbe *p){ p->rc = SQLITE_OK; } /* ** Copy the error code and error message belonging to the VDBE passed ** as the first argument to its database handle (so that they will be -** returned by calls to sqlite3_errcode() and sqlite3_errmsg()). +** returned by calls to tdsqlite3_errcode() and tdsqlite3_errmsg()). ** ** This function does not clear the VDBE error code or message, just ** copies them to the database handle. */ -SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){ - sqlite3 *db = p->db; +SQLITE_PRIVATE int tdsqlite3VdbeTransferError(Vdbe *p){ + tdsqlite3 *db = p->db; int rc = p->rc; if( p->zErrMsg ){ db->bBenignMalloc++; - sqlite3BeginBenignMalloc(); - if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db); - sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); - sqlite3EndBenignMalloc(); + tdsqlite3BeginBenignMalloc(); + if( db->pErr==0 ) db->pErr = tdsqlite3ValueNew(db); + tdsqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); + tdsqlite3EndBenignMalloc(); db->bBenignMalloc--; - db->errCode = rc; - }else{ - sqlite3Error(db, rc); + }else if( db->pErr ){ + tdsqlite3ValueSetNull(db->pErr); } + db->errCode = rc; return rc; } @@ -76347,14 +84150,14 @@ SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){ ** invoke it. */ static void vdbeInvokeSqllog(Vdbe *v){ - if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){ - char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql); + if( tdsqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){ + char *zExpanded = tdsqlite3VdbeExpandSql(v, v->zSql); assert( v->db->init.busy==0 ); if( zExpanded ){ - sqlite3GlobalConfig.xSqllog( - sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1 + tdsqlite3GlobalConfig.xSqllog( + tdsqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1 ); - sqlite3DbFree(v->db, zExpanded); + tdsqlite3DbFree(v->db, zExpanded); } } } @@ -76373,40 +84176,53 @@ static void vdbeInvokeSqllog(Vdbe *v){ ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to ** VDBE_MAGIC_INIT. */ -SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){ - sqlite3 *db; +SQLITE_PRIVATE int tdsqlite3VdbeReset(Vdbe *p){ +#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) + int i; +#endif + + tdsqlite3 *db; db = p->db; /* If the VM did not run to completion or if it encountered an ** error, then it might not have been halted properly. So halt ** it now. */ - sqlite3VdbeHalt(p); + tdsqlite3VdbeHalt(p); - /* If the VDBE has be run even partially, then transfer the error code + /* If the VDBE has been run even partially, then transfer the error code ** and error message from the VDBE into the main database structure. But ** if the VDBE has just been set to run but has not actually executed any ** instructions yet, leave the main database error information unchanged. */ if( p->pc>=0 ){ vdbeInvokeSqllog(p); - sqlite3VdbeTransferError(p); - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = 0; + tdsqlite3VdbeTransferError(p); if( p->runOnlyOnce ) p->expired = 1; }else if( p->rc && p->expired ){ /* The expired flag was set on the VDBE before the first call - ** to sqlite3_step(). For consistency (since sqlite3_step() was + ** to tdsqlite3_step(). For consistency (since tdsqlite3_step() was ** called), set the database error in this case as well. */ - sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg); - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = 0; + tdsqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg); } - /* Reclaim all memory used by the VDBE + /* Reset register contents and reclaim error message memory. */ - Cleanup(p); +#ifdef SQLITE_DEBUG + /* Execute assert() statements to ensure that the Vdbe.apCsr[] and + ** Vdbe.aMem[] arrays have already been cleaned up. */ + if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 ); + if( p->aMem ){ + for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined ); + } +#endif + tdsqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = 0; + p->pResultSet = 0; +#ifdef SQLITE_DEBUG + p->nWrite = 0; +#endif /* Save profiling information from this VDBE run. */ @@ -76414,7 +84230,6 @@ SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){ { FILE *out = fopen("vdbe_profile.out", "a"); if( out ){ - int i; fprintf(out, "---- "); for(i=0; i<p->nOp; i++){ fprintf(out, "%02x", p->aOp[i].opcode); @@ -76432,19 +84247,18 @@ SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){ } for(i=0; i<p->nOp; i++){ char zHdr[100]; - sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ", + tdsqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ", p->aOp[i].cnt, p->aOp[i].cycles, p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0 ); fprintf(out, "%s", zHdr); - sqlite3VdbePrintOp(out, i, &p->aOp[i]); + tdsqlite3VdbePrintOp(out, i, &p->aOp[i]); } fclose(out); } } #endif - p->iCurrentTime = 0; p->magic = VDBE_MAGIC_RESET; return p->rc & db->errMask; } @@ -76453,13 +84267,13 @@ SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){ ** Clean up and delete a VDBE after execution. Return an integer which is ** the result code. Write any error message text into *pzErrMsg. */ -SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){ +SQLITE_PRIVATE int tdsqlite3VdbeFinalize(Vdbe *p){ int rc = SQLITE_OK; if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){ - rc = sqlite3VdbeReset(p); + rc = tdsqlite3VdbeReset(p); assert( (rc & p->db->errMask)==rc ); } - sqlite3VdbeDelete(p); + tdsqlite3VdbeDelete(p); return rc; } @@ -76479,20 +84293,22 @@ SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){ ** * the corresponding bit in argument mask is clear (where the first ** function parameter corresponds to bit 0 etc.). */ -SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){ +SQLITE_PRIVATE void tdsqlite3VdbeDeleteAuxData(tdsqlite3 *db, AuxData **pp, int iOp, int mask){ while( *pp ){ AuxData *pAux = *pp; if( (iOp<0) - || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg)))) + || (pAux->iAuxOp==iOp + && pAux->iAuxArg>=0 + && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg)))) ){ - testcase( pAux->iArg==31 ); - if( pAux->xDelete ){ - pAux->xDelete(pAux->pAux); + testcase( pAux->iAuxArg==31 ); + if( pAux->xDeleteAux ){ + pAux->xDeleteAux(pAux->pAux); } - *pp = pAux->pNext; - sqlite3DbFree(db, pAux); + *pp = pAux->pNextAux; + tdsqlite3DbFree(db, pAux); }else{ - pp= &pAux->pNext; + pp= &pAux->pNextAux; } } } @@ -76501,47 +84317,58 @@ SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, ** Free all memory associated with the Vdbe passed as the second argument, ** except for object itself, which is preserved. ** -** The difference between this function and sqlite3VdbeDelete() is that +** The difference between this function and tdsqlite3VdbeDelete() is that ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with ** the database connection and frees the object itself. */ -SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){ +SQLITE_PRIVATE void tdsqlite3VdbeClearObject(tdsqlite3 *db, Vdbe *p){ SubProgram *pSub, *pNext; - int i; assert( p->db==0 || p->db==db ); releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); for(pSub=p->pProgram; pSub; pSub=pNext){ pNext = pSub->pNext; vdbeFreeOpArray(db, pSub->aOp, pSub->nOp); - sqlite3DbFree(db, pSub); + tdsqlite3DbFree(db, pSub); } if( p->magic!=VDBE_MAGIC_INIT ){ releaseMemArray(p->aVar, p->nVar); - for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]); - sqlite3DbFree(db, p->azVar); - sqlite3DbFree(db, p->pFree); + tdsqlite3DbFree(db, p->pVList); + tdsqlite3DbFree(db, p->pFree); } vdbeFreeOpArray(db, p->aOp, p->nOp); - sqlite3DbFree(db, p->aColName); - sqlite3DbFree(db, p->zSql); + tdsqlite3DbFree(db, p->aColName); + tdsqlite3DbFree(db, p->zSql); +#ifdef SQLITE_ENABLE_NORMALIZE + tdsqlite3DbFree(db, p->zNormSql); + { + DblquoteStr *pThis, *pNext; + for(pThis=p->pDblStr; pThis; pThis=pNext){ + pNext = pThis->pNextStr; + tdsqlite3DbFree(db, pThis); + } + } +#endif #ifdef SQLITE_ENABLE_STMT_SCANSTATUS - for(i=0; i<p->nScan; i++){ - sqlite3DbFree(db, p->aScan[i].zName); + { + int i; + for(i=0; i<p->nScan; i++){ + tdsqlite3DbFree(db, p->aScan[i].zName); + } + tdsqlite3DbFree(db, p->aScan); } - sqlite3DbFree(db, p->aScan); #endif } /* ** Delete an entire VDBE. */ -SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){ - sqlite3 *db; +SQLITE_PRIVATE void tdsqlite3VdbeDelete(Vdbe *p){ + tdsqlite3 *db; - if( NEVER(p==0) ) return; + assert( p!=0 ); db = p->db; - assert( sqlite3_mutex_held(db->mutex) ); - sqlite3VdbeClearObject(db, p); + assert( tdsqlite3_mutex_held(db->mutex) ); + tdsqlite3VdbeClearObject(db, p); if( p->pPrev ){ p->pPrev->pNext = p->pNext; }else{ @@ -76553,7 +84380,7 @@ SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){ } p->magic = VDBE_MAGIC_DEAD; p->db = 0; - sqlite3DbFree(db, p); + tdsqlite3DbFreeNN(db, p); } /* @@ -76561,19 +84388,19 @@ SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){ ** carried out. Seek the cursor now. If an error occurs, return ** the appropriate error code. */ -static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){ +SQLITE_PRIVATE int SQLITE_NOINLINE tdsqlite3VdbeFinishMoveto(VdbeCursor *p){ int res, rc; #ifdef SQLITE_TEST - extern int sqlite3_search_count; + extern int tdsqlite3_search_count; #endif assert( p->deferredMoveto ); assert( p->isTable ); assert( p->eCurType==CURTYPE_BTREE ); - rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res); + rc = tdsqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res); if( rc ) return rc; if( res!=0 ) return SQLITE_CORRUPT_BKPT; #ifdef SQLITE_TEST - sqlite3_search_count++; + tdsqlite3_search_count++; #endif p->deferredMoveto = 0; p->cacheStatus = CACHE_STALE; @@ -76591,8 +84418,8 @@ static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){ int isDifferentRow, rc; assert( p->eCurType==CURTYPE_BTREE ); assert( p->uc.pCursor!=0 ); - assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ); - rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow); + assert( tdsqlite3BtreeCursorHasMoved(p->uc.pCursor) ); + rc = tdsqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow); p->cacheStatus = CACHE_STALE; if( isDifferentRow ) p->nullRow = 1; return rc; @@ -76602,9 +84429,9 @@ static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){ ** Check to ensure that the cursor is valid. Restore the cursor ** if need be. Return any I/O error from the restore operation. */ -SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){ +SQLITE_PRIVATE int tdsqlite3VdbeCursorRestore(VdbeCursor *p){ assert( p->eCurType==CURTYPE_BTREE ); - if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ + if( tdsqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ return handleMovedCursor(p); } return SQLITE_OK; @@ -76623,21 +84450,20 @@ SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){ ** If the cursor is already pointing to the correct row and that row has ** not been deleted out from under the cursor, then this routine is a no-op. */ -SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){ +SQLITE_PRIVATE int tdsqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){ VdbeCursor *p = *pp; - if( p->eCurType==CURTYPE_BTREE ){ - if( p->deferredMoveto ){ - int iMap; - if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){ - *pp = p->pAltCursor; - *piCol = iMap - 1; - return SQLITE_OK; - } - return handleDeferredMoveto(p); - } - if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ - return handleMovedCursor(p); + assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO ); + if( p->deferredMoveto ){ + int iMap; + if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){ + *pp = p->pAltCursor; + *piCol = iMap - 1; + return SQLITE_OK; } + return tdsqlite3VdbeFinishMoveto(p); + } + if( tdsqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ + return handleMovedCursor(p); } return SQLITE_OK; } @@ -76645,11 +84471,11 @@ SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){ /* ** The following functions: ** -** sqlite3VdbeSerialType() -** sqlite3VdbeSerialTypeLen() -** sqlite3VdbeSerialLen() -** sqlite3VdbeSerialPut() -** sqlite3VdbeSerialGet() +** tdsqlite3VdbeSerialType() +** tdsqlite3VdbeSerialTypeLen() +** tdsqlite3VdbeSerialLen() +** tdsqlite3VdbeSerialPut() +** tdsqlite3VdbeSerialGet() ** ** encapsulate the code that serializes values for storage in SQLite ** data and index records. Each serialized value consists of a @@ -76684,10 +84510,19 @@ SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){ ** of SQLite will not understand those serial types. */ +#if 0 /* Inlined into the OP_MakeRecord opcode */ /* ** Return the serial-type for the value stored in pMem. +** +** This routine might convert a large MEM_IntReal value into MEM_Real. +** +** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord +** opcode in the byte-code engine. But by moving this routine in-line, we +** can omit some redundant tests and make that opcode a lot faster. So +** this routine is now only used by the STAT3 logic and STAT3 support has +** ended. The code is kept here for historical reference only. */ -SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){ +SQLITE_PRIVATE u32 tdsqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){ int flags = pMem->flags; u32 n; @@ -76696,11 +84531,13 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){ *pLen = 0; return 0; } - if( flags&MEM_Int ){ + if( flags&(MEM_Int|MEM_IntReal) ){ /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */ # define MAX_6BYTE ((((i64)0x00008000)<<32)-1) i64 i = pMem->u.i; u64 u; + testcase( flags & MEM_Int ); + testcase( flags & MEM_IntReal ); if( i<0 ){ u = ~i; }else{ @@ -76720,6 +84557,15 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){ if( u<=2147483647 ){ *pLen = 4; return 4; } if( u<=MAX_6BYTE ){ *pLen = 6; return 5; } *pLen = 8; + if( flags&MEM_IntReal ){ + /* If the value is IntReal and is going to take up 8 bytes to store + ** as an integer, then we might as well make it an 8-byte floating + ** point value */ + pMem->u.r = (double)pMem->u.i; + pMem->flags &= ~MEM_IntReal; + pMem->flags |= MEM_Real; + return 7; + } return 6; } if( flags&MEM_Real ){ @@ -76735,11 +84581,12 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){ *pLen = n; return ((n*2) + 12 + ((flags&MEM_Str)!=0)); } +#endif /* inlined into OP_MakeRecord */ /* ** The sizes for serial types less than 128 */ -static const u8 sqlite3SmallTypeSizes[] = { +static const u8 tdsqlite3SmallTypeSizes[] = { /* 0 1 2 3 4 5 6 7 8 9 */ /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, @@ -76759,18 +84606,18 @@ static const u8 sqlite3SmallTypeSizes[] = { /* ** Return the length of the data corresponding to the supplied serial-type. */ -SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){ +SQLITE_PRIVATE u32 tdsqlite3VdbeSerialTypeLen(u32 serial_type){ if( serial_type>=128 ){ return (serial_type-12)/2; }else{ assert( serial_type<12 - || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 ); - return sqlite3SmallTypeSizes[serial_type]; + || tdsqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 ); + return tdsqlite3SmallTypeSizes[serial_type]; } } -SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){ +SQLITE_PRIVATE u8 tdsqlite3VdbeOneByteSerialTypeLen(u8 serial_type){ assert( serial_type<128 ); - return sqlite3SmallTypeSizes[serial_type]; + return tdsqlite3SmallTypeSizes[serial_type]; } /* @@ -76839,7 +84686,7 @@ static u64 floatSwap(u64 in){ ** of bytes in the zero-filled tail is included in the return value only ** if those bytes were zeroed in buf[]. */ -SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ +SQLITE_PRIVATE u32 tdsqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ u32 len; /* Integer and Real */ @@ -76853,7 +84700,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ }else{ v = pMem->u.i; } - len = i = sqlite3SmallTypeSizes[serial_type]; + len = i = tdsqlite3SmallTypeSizes[serial_type]; assert( i>0 ); do{ buf[--i] = (u8)(v&0xFF); @@ -76865,7 +84712,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ /* String or blob */ if( serial_type>=12 ){ assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0) - == (int)sqlite3VdbeSerialTypeLen(serial_type) ); + == (int)tdsqlite3VdbeSerialTypeLen(serial_type) ); len = pMem->n; if( len>0 ) memcpy(buf, pMem->z, len); return len; @@ -76893,7 +84740,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ ** routine so that in most cases the overhead of moving the stack pointer ** is avoided. */ -static u32 SQLITE_NOINLINE serialGet( +static u32 serialGet( const unsigned char *buf, /* Buffer to deserialize from */ u32 serial_type, /* Serial type to deserialize */ Mem *pMem /* Memory cell to write value into */ @@ -76925,17 +84772,23 @@ static u32 SQLITE_NOINLINE serialGet( assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 ); swapMixedEndianFloat(x); memcpy(&pMem->u.r, &x, sizeof(x)); - pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real; + pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real; } return 8; } -SQLITE_PRIVATE u32 sqlite3VdbeSerialGet( +SQLITE_PRIVATE u32 tdsqlite3VdbeSerialGet( const unsigned char *buf, /* Buffer to deserialize from */ u32 serial_type, /* Serial type to deserialize */ Mem *pMem /* Memory cell to write value into */ ){ switch( serial_type ){ - case 10: /* Reserved for future use */ + case 10: { /* Internal use only: NULL with virtual table + ** UPDATE no-change flag set */ + pMem->flags = MEM_Null|MEM_Zero; + pMem->n = 0; + pMem->u.nZero = 0; + break; + } case 11: /* Reserved for future use */ case 0: { /* Null */ /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */ @@ -77016,47 +84869,30 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet( } /* ** This routine is used to allocate sufficient space for an UnpackedRecord -** structure large enough to be used with sqlite3VdbeRecordUnpack() if +** structure large enough to be used with tdsqlite3VdbeRecordUnpack() if ** the first argument is a pointer to KeyInfo structure pKeyInfo. ** -** The space is either allocated using sqlite3DbMallocRaw() or from within +** The space is either allocated using tdsqlite3DbMallocRaw() or from within ** the unaligned buffer passed via the second and third arguments (presumably ** stack space). If the former, then *ppFree is set to a pointer that should -** be eventually freed by the caller using sqlite3DbFree(). Or, if the +** be eventually freed by the caller using tdsqlite3DbFree(). Or, if the ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL ** before returning. ** ** If an OOM error occurs, NULL is returned. */ -SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord( - KeyInfo *pKeyInfo, /* Description of the record */ - char *pSpace, /* Unaligned space available */ - int szSpace, /* Size of pSpace[] in bytes */ - char **ppFree /* OUT: Caller should free this pointer */ +SQLITE_PRIVATE UnpackedRecord *tdsqlite3VdbeAllocUnpackedRecord( + KeyInfo *pKeyInfo /* Description of the record */ ){ UnpackedRecord *p; /* Unpacked record to return */ - int nOff; /* Increment pSpace by nOff to align it */ int nByte; /* Number of bytes required for *p */ - - /* We want to shift the pointer pSpace up such that it is 8-byte aligned. - ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift - ** it by. If pSpace is already 8-byte aligned, nOff should be zero. - */ - nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7; - nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1); - if( nByte>szSpace+nOff ){ - p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte); - *ppFree = (char *)p; - if( !p ) return 0; - }else{ - p = (UnpackedRecord*)&pSpace[nOff]; - *ppFree = 0; - } - + nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1); + p = (UnpackedRecord *)tdsqlite3DbMallocRaw(pKeyInfo->db, nByte); + if( !p ) return 0; p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))]; - assert( pKeyInfo->aSortOrder!=0 ); + assert( pKeyInfo->aSortFlags!=0 ); p->pKeyInfo = pKeyInfo; - p->nField = pKeyInfo->nField + 1; + p->nField = pKeyInfo->nKeyField + 1; return p; } @@ -77065,14 +84901,14 @@ SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord( ** UnpackedRecord structure indicated by the fourth argument with the ** contents of the decoded record. */ -SQLITE_PRIVATE void sqlite3VdbeRecordUnpack( +SQLITE_PRIVATE void tdsqlite3VdbeRecordUnpack( KeyInfo *pKeyInfo, /* Information about the record format */ int nKey, /* Size of the binary record */ const void *pKey, /* The binary record */ UnpackedRecord *p /* Populate this structure before returning. */ ){ const unsigned char *aKey = (const unsigned char *)pKey; - int d; + u32 d; u32 idx; /* Offset in aKey[] to read from */ u16 u; /* Unsigned loop counter */ u32 szHdr; @@ -77083,31 +84919,38 @@ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack( idx = getVarint32(aKey, szHdr); d = szHdr; u = 0; - while( idx<szHdr && d<=nKey ){ + while( idx<szHdr && d<=(u32)nKey ){ u32 serial_type; idx += getVarint32(&aKey[idx], serial_type); pMem->enc = pKeyInfo->enc; pMem->db = pKeyInfo->db; - /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */ + /* pMem->flags = 0; // tdsqlite3VdbeSerialGet() will set this for us */ pMem->szMalloc = 0; pMem->z = 0; - d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem); + d += tdsqlite3VdbeSerialGet(&aKey[d], serial_type, pMem); pMem++; if( (++u)>=p->nField ) break; } - assert( u<=pKeyInfo->nField + 1 ); + if( d>(u32)nKey && u ){ + assert( CORRUPT_DB ); + /* In a corrupt record entry, the last pMem might have been set up using + ** uninitialized memory. Overwrite its value with NULL, to prevent + ** warnings from MSAN. */ + tdsqlite3VdbeMemSetNull(pMem-1); + } + assert( u<=pKeyInfo->nKeyField + 1 ); p->nField = u; } -#if SQLITE_DEBUG +#ifdef SQLITE_DEBUG /* ** This function compares two index or table record keys in the same way -** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(), +** as the tdsqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(), ** this function deserializes and compares values using the -** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used +** tdsqlite3VdbeSerialGet() and tdsqlite3MemCompare() functions. It is used ** in assert() statements to ensure that the optimized code in -** sqlite3VdbeRecordCompare() returns results with these two primitives. +** tdsqlite3VdbeRecordCompare() returns results with these two primitives. ** ** Return true if the result of comparison is equivalent to desiredResult. ** Return false if there is a disagreement. @@ -77130,7 +84973,7 @@ static int vdbeRecordCompareDebug( if( pKeyInfo->db==0 ) return 1; mem1.enc = pKeyInfo->enc; mem1.db = pKeyInfo->db; - /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */ + /* mem1.flags = 0; // Will be initialized by tdsqlite3VdbeSerialGet() */ VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */ /* Compilers may complain that mem1.u.i is potentially uninitialized. @@ -77145,9 +84988,9 @@ static int vdbeRecordCompareDebug( idx1 = getVarint32(aKey1, szHdr1); if( szHdr1>98307 ) return SQLITE_CORRUPT; d1 = szHdr1; - assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB ); - assert( pKeyInfo->aSortOrder!=0 ); - assert( pKeyInfo->nField>0 ); + assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB ); + assert( pKeyInfo->aSortFlags!=0 ); + assert( pKeyInfo->nKeyField>0 ); assert( idx1<=szHdr1 || CORRUPT_DB ); do{ u32 serial_type1; @@ -77159,24 +85002,30 @@ static int vdbeRecordCompareDebug( ** a buffer overread. The "d1+serial_type1+2" subexpression will ** always be greater than or equal to the amount of required key space. ** Use that approximation to avoid the more expensive call to - ** sqlite3VdbeSerialTypeLen() in the common case. + ** tdsqlite3VdbeSerialTypeLen() in the common case. */ - if( d1+serial_type1+2>(u32)nKey1 - && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 + if( d1+(u64)serial_type1+2>(u64)nKey1 + && d1+(u64)tdsqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1 ){ break; } /* Extract the values to be compared. */ - d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1); + d1 += tdsqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1); /* Do the comparison */ - rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]); + rc = tdsqlite3MemCompare(&mem1, &pPKey2->aMem[i], + pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0); if( rc!=0 ){ assert( mem1.szMalloc==0 ); /* See comment below */ - if( pKeyInfo->aSortOrder[i] ){ + if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) + && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null)) + ){ + rc = -rc; + } + if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){ rc = -rc; /* Invert the result for DESC sort order. */ } goto debugCompareEnd; @@ -77186,7 +85035,7 @@ static int vdbeRecordCompareDebug( /* No memory allocation is ever used on mem1. Prove this using ** the following assert(). If the assert() fails, it indicates a - ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). + ** memory leak and a need to call tdsqlite3VdbeMemRelease(&mem1). */ assert( mem1.szMalloc==0 ); @@ -77205,16 +85054,16 @@ debugCompareEnd: } #endif -#if SQLITE_DEBUG +#ifdef SQLITE_DEBUG /* ** Count the number of fields (a.k.a. columns) in the record given by ** pKey,nKey. The verify that this count is less than or equal to the -** limit given by pKeyInfo->nField + pKeyInfo->nXField. +** limit given by pKeyInfo->nAllField. ** ** If this constraint is not satisfied, it means that the high-speed ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will ** not work correctly. If this assert() ever fires, it probably means -** that the KeyInfo.nField or KeyInfo.nXField values were computed +** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed ** incorrectly. */ static void vdbeAssertFieldCountWithinLimits( @@ -77235,7 +85084,7 @@ static void vdbeAssertFieldCountWithinLimits( idx += getVarint32(aKey+idx, notUsed); nField++; } - assert( nField <= pKeyInfo->nField+pKeyInfo->nXField ); + assert( nField <= pKeyInfo->nAllField ); } #else # define vdbeAssertFieldCountWithinLimits(A,B,C) @@ -77260,21 +85109,22 @@ static int vdbeCompareMemString( }else{ int rc; const void *v1, *v2; - int n1, n2; Mem c1; Mem c2; - sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null); - sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null); - sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem); - sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem); - v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc); - n1 = v1==0 ? 0 : c1.n; - v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc); - n2 = v2==0 ? 0 : c2.n; - rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2); - if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT; - sqlite3VdbeMemRelease(&c1); - sqlite3VdbeMemRelease(&c2); + tdsqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null); + tdsqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null); + tdsqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem); + tdsqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem); + v1 = tdsqlite3ValueText((tdsqlite3_value*)&c1, pColl->enc); + v2 = tdsqlite3ValueText((tdsqlite3_value*)&c2, pColl->enc); + if( (v1==0 || v2==0) ){ + if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT; + rc = 0; + }else{ + rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2); + } + tdsqlite3VdbeMemRelease(&c1); + tdsqlite3VdbeMemRelease(&c2); return rc; } } @@ -77296,7 +85146,7 @@ static int isAllZero(const char *z, int n){ ** is less than, equal to, or greater than the second, respectively. ** If one blob is a prefix of the other, then the shorter is the lessor. */ -static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){ +SQLITE_PRIVATE SQLITE_NOINLINE int tdsqlite3BlobCompare(const Mem *pB1, const Mem *pB2){ int c; int n1 = pB1->n; int n2 = pB2->n; @@ -77304,7 +85154,7 @@ static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){ /* It is possible to have a Blob value that has some non-zero content ** followed by zero content. But that only comes up for Blobs formed ** by the OP_MakeRecord opcode, and such Blobs never get passed into - ** sqlite3MemCompare(). */ + ** tdsqlite3MemCompare(). */ assert( (pB1->flags & MEM_Zero)==0 || n1==0 ); assert( (pB2->flags & MEM_Zero)==0 || n2==0 ); @@ -77329,7 +85179,7 @@ static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){ ** number. Return negative, zero, or positive if the first (i64) is less than, ** equal to, or greater than the second (double). */ -static int sqlite3IntFloatCompare(i64 i, double r){ +static int tdsqlite3IntFloatCompare(i64 i, double r){ if( sizeof(LONGDOUBLE_TYPE)>8 ){ LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i; if( x<r ) return -1; @@ -77339,13 +85189,10 @@ static int sqlite3IntFloatCompare(i64 i, double r){ i64 y; double s; if( r<-9223372036854775808.0 ) return +1; - if( r>9223372036854775807.0 ) return -1; + if( r>=9223372036854775808.0 ) return -1; y = (i64)r; if( i<y ) return -1; - if( i>y ){ - if( y==SMALLEST_INT64 && r>0.0 ) return -1; - return +1; - } + if( i>y ) return +1; s = (double)i; if( s<r ) return -1; if( s>r ) return +1; @@ -77362,14 +85209,14 @@ static int sqlite3IntFloatCompare(i64 i, double r){ ** ** Two NULL values are considered equal by this function. */ -SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){ +SQLITE_PRIVATE int tdsqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){ int f1, f2; int combined_flags; f1 = pMem1->flags; f2 = pMem2->flags; combined_flags = f1|f2; - assert( (combined_flags & MEM_RowSet)==0 ); + assert( !tdsqlite3VdbeMemIsRowSet(pMem1) && !tdsqlite3VdbeMemIsRowSet(pMem2) ); /* If one value is NULL, it is less than the other. If both values ** are NULL, return 0. @@ -77380,8 +85227,13 @@ SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const C /* At least one of the two values is a number */ - if( combined_flags&(MEM_Int|MEM_Real) ){ - if( (f1 & f2 & MEM_Int)!=0 ){ + if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){ + testcase( combined_flags & MEM_Int ); + testcase( combined_flags & MEM_Real ); + testcase( combined_flags & MEM_IntReal ); + if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){ + testcase( f1 & f2 & MEM_Int ); + testcase( f1 & f2 & MEM_IntReal ); if( pMem1->u.i < pMem2->u.i ) return -1; if( pMem1->u.i > pMem2->u.i ) return +1; return 0; @@ -77391,16 +85243,24 @@ SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const C if( pMem1->u.r > pMem2->u.r ) return +1; return 0; } - if( (f1&MEM_Int)!=0 ){ + if( (f1&(MEM_Int|MEM_IntReal))!=0 ){ + testcase( f1 & MEM_Int ); + testcase( f1 & MEM_IntReal ); if( (f2&MEM_Real)!=0 ){ - return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r); + return tdsqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r); + }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){ + if( pMem1->u.i < pMem2->u.i ) return -1; + if( pMem1->u.i > pMem2->u.i ) return +1; + return 0; }else{ return -1; } } if( (f1&MEM_Real)!=0 ){ - if( (f2&MEM_Int)!=0 ){ - return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r); + if( (f2&(MEM_Int|MEM_IntReal))!=0 ){ + testcase( f2 & MEM_Int ); + testcase( f2 & MEM_IntReal ); + return -tdsqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r); }else{ return -1; } @@ -77437,7 +85297,7 @@ SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const C } /* Both values must be blobs. Compare using memcmp(). */ - return sqlite3BlobCompare(pMem1, pMem2); + return tdsqlite3BlobCompare(pMem1, pMem2); } @@ -77489,7 +85349,7 @@ static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){ ** greater than key2. The {nKey1, pKey1} key must be a blob ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2 ** key must be a parsed key such as obtained from -** sqlite3VdbeParseRecord. +** tdsqlite3VdbeParseRecord. ** ** If argument bSkip is non-zero, it is assumed that the caller has already ** determined that the first fields of the keys are equal. @@ -77503,7 +85363,7 @@ static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){ ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db). */ -SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( +SQLITE_PRIVATE int tdsqlite3VdbeRecordCompareWithSkip( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2, /* Right key */ int bSkip /* If true, skip the first field */ @@ -77514,7 +85374,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( u32 idx1; /* Offset of first type in header */ int rc = 0; /* Return value */ Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */ - KeyInfo *pKeyInfo = pPKey2->pKeyInfo; + KeyInfo *pKeyInfo; const unsigned char *aKey1 = (const unsigned char *)pKey1; Mem mem1; @@ -77525,30 +85385,32 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( u32 s1; idx1 = 1 + getVarint32(&aKey1[1], s1); szHdr1 = aKey1[0]; - d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1); + d1 = szHdr1 + tdsqlite3VdbeSerialTypeLen(s1); i = 1; pRhs++; }else{ idx1 = getVarint32(aKey1, szHdr1); d1 = szHdr1; - if( d1>(unsigned)nKey1 ){ - pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; - return 0; /* Corruption */ - } i = 0; } + if( d1>(unsigned)nKey1 ){ + pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; + return 0; /* Corruption */ + } VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */ - assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField + assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB ); - assert( pPKey2->pKeyInfo->aSortOrder!=0 ); - assert( pPKey2->pKeyInfo->nField>0 ); + assert( pPKey2->pKeyInfo->aSortFlags!=0 ); + assert( pPKey2->pKeyInfo->nKeyField>0 ); assert( idx1<=szHdr1 || CORRUPT_DB ); do{ u32 serial_type; /* RHS is an integer */ - if( pRhs->flags & MEM_Int ){ + if( pRhs->flags & (MEM_Int|MEM_IntReal) ){ + testcase( pRhs->flags & MEM_Int ); + testcase( pRhs->flags & MEM_IntReal ); serial_type = aKey1[idx1]; testcase( serial_type==12 ); if( serial_type>=10 ){ @@ -77556,8 +85418,8 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( }else if( serial_type==0 ){ rc = -1; }else if( serial_type==7 ){ - sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); - rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r); + tdsqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); + rc = -tdsqlite3IntFloatCompare(pRhs->u.i, mem1.u.r); }else{ i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]); i64 rhs = pRhs->u.i; @@ -77581,7 +85443,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( }else if( serial_type==0 ){ rc = -1; }else{ - sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); + tdsqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); if( serial_type==7 ){ if( mem1.u.r<pRhs->u.r ){ rc = -1; @@ -77589,7 +85451,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( rc = +1; } }else{ - rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r); + rc = tdsqlite3IntFloatCompare(mem1.u.i, pRhs->u.r); } } } @@ -77606,7 +85468,9 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( mem1.n = (serial_type - 12) / 2; testcase( (d1+mem1.n)==(unsigned)nKey1 ); testcase( (d1+mem1.n+1)==(unsigned)nKey1 ); - if( (d1+mem1.n) > (unsigned)nKey1 ){ + if( (d1+mem1.n) > (unsigned)nKey1 + || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i + ){ pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; return 0; /* Corruption */ }else if( pKeyInfo->aColl[i] ){ @@ -77660,8 +85524,14 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( } if( rc!=0 ){ - if( pKeyInfo->aSortOrder[i] ){ - rc = -rc; + int sortFlags = pPKey2->pKeyInfo->aSortFlags[i]; + if( sortFlags ){ + if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0 + || ((sortFlags & KEYINFO_ORDER_DESC) + !=(serial_type==0 || (pRhs->flags&MEM_Null))) + ){ + rc = -rc; + } } assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) ); assert( mem1.szMalloc==0 ); /* See comment below */ @@ -77669,14 +85539,15 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( } i++; + if( i==pPKey2->nField ) break; pRhs++; - d1 += sqlite3VdbeSerialTypeLen(serial_type); - idx1 += sqlite3VarintLen(serial_type); - }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 ); + d1 += tdsqlite3VdbeSerialTypeLen(serial_type); + idx1 += tdsqlite3VarintLen(serial_type); + }while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 ); /* No memory allocation is ever used on mem1. Prove this using ** the following assert(). If the assert() fails, it indicates a - ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */ + ** memory leak and a need to call tdsqlite3VdbeMemRelease(&mem1). */ assert( mem1.szMalloc==0 ); /* rc==0 here means that one or both of the keys ran out of fields and @@ -77684,21 +85555,21 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( ** value. */ assert( CORRUPT_DB || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) - || pKeyInfo->db->mallocFailed + || pPKey2->pKeyInfo->db->mallocFailed ); pPKey2->eqSeen = 1; return pPKey2->default_rc; } -SQLITE_PRIVATE int sqlite3VdbeRecordCompare( +SQLITE_PRIVATE int tdsqlite3VdbeRecordCompare( int nKey1, const void *pKey1, /* Left key */ UnpackedRecord *pPKey2 /* Right key */ ){ - return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0); + return tdsqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0); } /* -** This function is an optimized version of sqlite3VdbeRecordCompare() +** This function is an optimized version of tdsqlite3VdbeRecordCompare() ** that (a) the first field of pPKey2 is an integer, and (b) the ** size-of-header varint at the start of (pKey1/nKey1) fits in a single ** byte (i.e. is less than 128). @@ -77768,10 +85639,10 @@ static int vdbeRecordCompareInt( ** (as gcc is clever enough to combine the two like cases). Other ** compilers might be similar. */ case 0: case 7: - return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); + return tdsqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); default: - return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); + return tdsqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); } v = pPKey2->aMem[0].u.i; @@ -77782,7 +85653,7 @@ static int vdbeRecordCompareInt( }else if( pPKey2->nField>1 ){ /* The first fields of the two keys are equal. Compare the trailing ** fields. */ - res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); + res = tdsqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); }else{ /* The first fields of the two keys are equal and there are no trailing ** fields. Return pPKey2->default_rc in this case. */ @@ -77795,7 +85666,7 @@ static int vdbeRecordCompareInt( } /* -** This function is an optimized version of sqlite3VdbeRecordCompare() +** This function is an optimized version of tdsqlite3VdbeRecordCompare() ** that (a) the first field of pPKey2 is a string, that (b) the first field ** uses the collation sequence BINARY and (c) that the size-of-header varint ** at the start of (pKey1/nKey1) fits in a single byte. @@ -77828,11 +85699,15 @@ static int vdbeRecordCompareString( nCmp = MIN( pPKey2->aMem[0].n, nStr ); res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp); - if( res==0 ){ + if( res>0 ){ + res = pPKey2->r2; + }else if( res<0 ){ + res = pPKey2->r1; + }else{ res = nStr - pPKey2->aMem[0].n; if( res==0 ){ if( pPKey2->nField>1 ){ - res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); + res = tdsqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); }else{ res = pPKey2->default_rc; pPKey2->eqSeen = 1; @@ -77842,10 +85717,6 @@ static int vdbeRecordCompareString( }else{ res = pPKey2->r1; } - }else if( res>0 ){ - res = pPKey2->r2; - }else{ - res = pPKey2->r1; } } @@ -77857,11 +85728,11 @@ static int vdbeRecordCompareString( } /* -** Return a pointer to an sqlite3VdbeRecordCompare() compatible function +** Return a pointer to an tdsqlite3VdbeRecordCompare() compatible function ** suitable for comparing serialized records to the unpacked record passed ** as the only argument. */ -SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){ +SQLITE_PRIVATE RecordCompare tdsqlite3VdbeFindCompare(UnpackedRecord *p){ /* varintRecordCompareInt() and varintRecordCompareString() both assume ** that the size-of-header varint that occurs at the start of each record ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt() @@ -77875,9 +85746,12 @@ SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){ ** The easiest way to enforce this limit is to consider only records with ** 13 fields or less. If the first field is an integer, the maximum legal ** header size is (12*5 + 1 + 1) bytes. */ - if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){ + if( p->pKeyInfo->nAllField<=13 ){ int flags = p->aMem[0].flags; - if( p->pKeyInfo->aSortOrder[0] ){ + if( p->pKeyInfo->aSortFlags[0] ){ + if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){ + return tdsqlite3VdbeRecordCompare; + } p->r1 = 1; p->r2 = -1; }else{ @@ -77890,13 +85764,15 @@ SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){ testcase( flags & MEM_Real ); testcase( flags & MEM_Null ); testcase( flags & MEM_Blob ); - if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){ + if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0 + && p->pKeyInfo->aColl[0]==0 + ){ assert( flags & MEM_Str ); return vdbeRecordCompareString; } } - return sqlite3VdbeRecordCompare; + return tdsqlite3VdbeRecordCompare; } /* @@ -77907,7 +85783,7 @@ SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){ ** pCur might be pointing to text obtained from a corrupt database file. ** So the content cannot be trusted. Do appropriate checks on the content. */ -SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){ +SQLITE_PRIVATE int tdsqlite3VdbeIdxRowid(tdsqlite3 *db, BtCursor *pCur, i64 *rowid){ i64 nCellKey = 0; int rc; u32 szHdr; /* Size of the header */ @@ -77917,16 +85793,16 @@ SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){ /* Get the size of the index entry. Only indices entries of less ** than 2GiB are support - anything large must be database corruption. - ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so + ** Any corruption is detected in tdsqlite3BtreeParseCellPtr(), though, so ** this code can safely assume that nCellKey is 32-bits */ - assert( sqlite3BtreeCursorIsValid(pCur) ); - nCellKey = sqlite3BtreePayloadSize(pCur); + assert( tdsqlite3BtreeCursorIsValid(pCur) ); + nCellKey = tdsqlite3BtreePayloadSize(pCur); assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey ); /* Read in the complete content of the index entry */ - sqlite3VdbeMemInit(&m, db, 0); - rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m); + tdsqlite3VdbeMemInit(&m, db, 0); + rc = tdsqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m); if( rc ){ return rc; } @@ -77935,7 +85811,9 @@ SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){ (void)getVarint32((u8*)m.z, szHdr); testcase( szHdr==3 ); testcase( szHdr==m.n ); - if( unlikely(szHdr<3 || (int)szHdr>m.n) ){ + testcase( szHdr>0x7fffffff ); + assert( m.n>=0 ); + if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){ goto idx_rowid_corruption; } @@ -77953,23 +85831,23 @@ SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){ if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){ goto idx_rowid_corruption; } - lenRowid = sqlite3SmallTypeSizes[typeRowid]; + lenRowid = tdsqlite3SmallTypeSizes[typeRowid]; testcase( (u32)m.n==szHdr+lenRowid ); if( unlikely((u32)m.n<szHdr+lenRowid) ){ goto idx_rowid_corruption; } /* Fetch the integer off the end of the index record */ - sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v); + tdsqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v); *rowid = v.u.i; - sqlite3VdbeMemRelease(&m); + tdsqlite3VdbeMemRelease(&m); return SQLITE_OK; /* Jump here if database corruption is detected after m has been ** allocated. Free the m object and return SQLITE_CORRUPT. */ idx_rowid_corruption: testcase( m.szMalloc!=0 ); - sqlite3VdbeMemRelease(&m); + tdsqlite3VdbeMemRelease(&m); return SQLITE_CORRUPT_BKPT; } @@ -77984,8 +85862,8 @@ idx_rowid_corruption: ** is ignored as well. Hence, this routine only compares the prefixes ** of the keys prior to the final rowid, not the entire key. */ -SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare( - sqlite3 *db, /* Database connection */ +SQLITE_PRIVATE int tdsqlite3VdbeIdxKeyCompare( + tdsqlite3 *db, /* Database connection */ VdbeCursor *pC, /* The cursor to compare against */ UnpackedRecord *pUnpacked, /* Unpacked version of key */ int *res /* Write the comparison result here */ @@ -77997,30 +85875,30 @@ SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare( assert( pC->eCurType==CURTYPE_BTREE ); pCur = pC->uc.pCursor; - assert( sqlite3BtreeCursorIsValid(pCur) ); - nCellKey = sqlite3BtreePayloadSize(pCur); + assert( tdsqlite3BtreeCursorIsValid(pCur) ); + nCellKey = tdsqlite3BtreePayloadSize(pCur); /* nCellKey will always be between 0 and 0xffffffff because of the way - ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */ + ** that btreeParseCellPtr() and tdsqlite3GetVarint32() are implemented */ if( nCellKey<=0 || nCellKey>0x7fffffff ){ *res = 0; return SQLITE_CORRUPT_BKPT; } - sqlite3VdbeMemInit(&m, db, 0); - rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m); + tdsqlite3VdbeMemInit(&m, db, 0); + rc = tdsqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m); if( rc ){ return rc; } - *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked); - sqlite3VdbeMemRelease(&m); + *res = tdsqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0); + tdsqlite3VdbeMemRelease(&m); return SQLITE_OK; } /* ** This routine sets the value to be returned by subsequent calls to -** sqlite3_changes() on the database handle 'db'. +** tdsqlite3_changes() on the database handle 'db'. */ -SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){ - assert( sqlite3_mutex_held(db->mutex) ); +SQLITE_PRIVATE void tdsqlite3VdbeSetChanges(tdsqlite3 *db, int nChange){ + assert( tdsqlite3_mutex_held(db->mutex) ); db->nChange = nChange; db->nTotalChange += nChange; } @@ -78029,7 +85907,7 @@ SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){ ** Set a flag in the vdbe to update the change counter when it is finalised ** or reset. */ -SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){ +SQLITE_PRIVATE void tdsqlite3VdbeCountChanges(Vdbe *v){ v->changeCntOn = 1; } @@ -78042,38 +85920,54 @@ SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){ ** programs obsolete. Removing user-defined functions or collating ** sequences, or changing an authorization function are the types of ** things that make prepared statements obsolete. +** +** If iCode is 1, then expiration is advisory. The statement should +** be reprepared before being restarted, but if it is already running +** it is allowed to run to completion. +** +** Internally, this function just sets the Vdbe.expired flag on all +** prepared statements. The flag is set to 1 for an immediate expiration +** and set to 2 for an advisory expiration. */ -SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3ExpirePreparedStatements(tdsqlite3 *db, int iCode){ Vdbe *p; for(p = db->pVdbe; p; p=p->pNext){ - p->expired = 1; + p->expired = iCode+1; } } /* ** Return the database associated with the Vdbe. */ -SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){ +SQLITE_PRIVATE tdsqlite3 *tdsqlite3VdbeDb(Vdbe *v){ return v->db; } /* -** Return a pointer to an sqlite3_value structure containing the value bound +** Return the SQLITE_PREPARE flags for a Vdbe. +*/ +SQLITE_PRIVATE u8 tdsqlite3VdbePrepareFlags(Vdbe *v){ + return v->prepFlags; +} + +/* +** Return a pointer to an tdsqlite3_value structure containing the value bound ** parameter iVar of VM v. Except, if the value is an SQL NULL, return ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_* ** constants) to the value before returning it. ** -** The returned value must be freed by the caller using sqlite3ValueFree(). +** The returned value must be freed by the caller using tdsqlite3ValueFree(). */ -SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){ +SQLITE_PRIVATE tdsqlite3_value *tdsqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){ assert( iVar>0 ); if( v ){ Mem *pMem = &v->aVar[iVar-1]; + assert( (v->db->flags & SQLITE_EnableQPSG)==0 ); if( 0==(pMem->flags & MEM_Null) ){ - sqlite3_value *pRet = sqlite3ValueNew(v->db); + tdsqlite3_value *pRet = tdsqlite3ValueNew(v->db); if( pRet ){ - sqlite3VdbeMemCopy((Mem *)pRet, pMem); - sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8); + tdsqlite3VdbeMemCopy((Mem *)pRet, pMem); + tdsqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8); } return pRet; } @@ -78083,30 +85977,65 @@ SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff /* ** Configure SQL variable iVar so that binding a new value to it signals -** to sqlite3_reoptimize() that re-preparing the statement may result +** to tdsqlite3_reoptimize() that re-preparing the statement may result ** in a better query plan. */ -SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){ +SQLITE_PRIVATE void tdsqlite3VdbeSetVarmask(Vdbe *v, int iVar){ assert( iVar>0 ); - if( iVar>32 ){ - v->expmask = 0xffffffff; + assert( (v->db->flags & SQLITE_EnableQPSG)==0 ); + if( iVar>=32 ){ + v->expmask |= 0x80000000; }else{ v->expmask |= ((u32)1 << (iVar-1)); } } +/* +** Cause a function to throw an error if it was call from OP_PureFunc +** rather than OP_Function. +** +** OP_PureFunc means that the function must be deterministic, and should +** throw an error if it is given inputs that would make it non-deterministic. +** This routine is invoked by date/time functions that use non-deterministic +** features such as 'now'. +*/ +SQLITE_PRIVATE int tdsqlite3NotPureFunc(tdsqlite3_context *pCtx){ + const VdbeOp *pOp; +#ifdef SQLITE_ENABLE_STAT4 + if( pCtx->pVdbe==0 ) return 1; +#endif + pOp = pCtx->pVdbe->aOp + pCtx->iOp; + if( pOp->opcode==OP_PureFunc ){ + const char *zContext; + char *zMsg; + if( pOp->p5 & NC_IsCheck ){ + zContext = "a CHECK constraint"; + }else if( pOp->p5 & NC_GenCol ){ + zContext = "a generated column"; + }else{ + zContext = "an index"; + } + zMsg = tdsqlite3_mprintf("non-deterministic use of %s() in %s", + pCtx->pFunc->zName, zContext); + tdsqlite3_result_error(pCtx, zMsg, -1); + tdsqlite3_free(zMsg); + return 0; + } + return 1; +} + #ifndef SQLITE_OMIT_VIRTUALTABLE /* -** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored -** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored -** in memory obtained from sqlite3DbMalloc). +** Transfer error message text from an tdsqlite3_vtab.zErrMsg (text stored +** in memory obtained from tdsqlite3_malloc) into a Vdbe.zErrMsg (text stored +** in memory obtained from tdsqlite3DbMalloc). */ -SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){ +SQLITE_PRIVATE void tdsqlite3VtabImportErrmsg(Vdbe *p, tdsqlite3_vtab *pVtab){ if( pVtab->zErrMsg ){ - sqlite3 *db = p->db; - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg); - sqlite3_free(pVtab->zErrMsg); + tdsqlite3 *db = p->db; + tdsqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = tdsqlite3DbStrDup(db, pVtab->zErrMsg); + tdsqlite3_free(pVtab->zErrMsg); pVtab->zErrMsg = 0; } } @@ -78117,19 +86046,19 @@ SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){ /* ** If the second argument is not NULL, release any allocations associated ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord -** structure itself, using sqlite3DbFree(). +** structure itself, using tdsqlite3DbFree(). ** ** This function is used to free UnpackedRecord structures allocated by ** the vdbeUnpackRecord() function found in vdbeapi.c. */ -static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){ +static void vdbeFreeUnpacked(tdsqlite3 *db, int nField, UnpackedRecord *p){ if( p ){ int i; - for(i=0; i<p->nField; i++){ + for(i=0; i<nField; i++){ Mem *pMem = &p->aMem[i]; - if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem); + if( pMem->zMalloc ) tdsqlite3VdbeMemRelease(pMem); } - sqlite3DbFree(db, p); + tdsqlite3DbFreeNN(db, p); } } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ @@ -78138,10 +86067,10 @@ static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){ /* ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call, ** then cursor passed as the second argument should point to the row about -** to be update or deleted. If the application calls sqlite3_preupdate_old(), +** to be update or deleted. If the application calls tdsqlite3_preupdate_old(), ** the required value will be read from the row the cursor points to. */ -SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( +SQLITE_PRIVATE void tdsqlite3VdbePreUpdateHook( Vdbe *v, /* Vdbe pre-update hook is invoked by */ VdbeCursor *pCsr, /* Cursor to grab old.* values from */ int op, /* SQLITE_INSERT, UPDATE or DELETE */ @@ -78150,7 +86079,7 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( i64 iKey1, /* Initial key value */ int iReg /* Register for new.* record */ ){ - sqlite3 *db = v->db; + tdsqlite3 *db = v->db; i64 iKey2; PreUpdate preupdate; const char *zTbl = pTab->zName; @@ -78158,10 +86087,15 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( assert( db->pPreUpdate==0 ); memset(&preupdate, 0, sizeof(PreUpdate)); - if( op==SQLITE_UPDATE ){ - iKey2 = v->aMem[iReg].u.i; + if( HasRowid(pTab)==0 ){ + iKey1 = iKey2 = 0; + preupdate.pPk = tdsqlite3PrimaryKeyIndex(pTab); }else{ - iKey2 = iKey1; + if( op==SQLITE_UPDATE ){ + iKey2 = v->aMem[iReg].u.i; + }else{ + iKey2 = iKey1; + } } assert( pCsr->nField==pTab->nCol @@ -78174,8 +86108,8 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( preupdate.iNewReg = iReg; preupdate.keyinfo.db = db; preupdate.keyinfo.enc = ENC(db); - preupdate.keyinfo.nField = pTab->nCol; - preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder; + preupdate.keyinfo.nKeyField = pTab->nCol; + preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder; preupdate.iKey1 = iKey1; preupdate.iKey2 = iKey2; preupdate.pTab = pTab; @@ -78183,15 +86117,15 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( db->pPreUpdate = &preupdate; db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2); db->pPreUpdate = 0; - sqlite3DbFree(db, preupdate.aRecord); - vdbeFreeUnpacked(db, preupdate.pUnpacked); - vdbeFreeUnpacked(db, preupdate.pNewUnpacked); + tdsqlite3DbFree(db, preupdate.aRecord); + vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked); + vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked); if( preupdate.aNew ){ int i; for(i=0; i<pCsr->nField; i++){ - sqlite3VdbeMemRelease(&preupdate.aNew[i]); + tdsqlite3VdbeMemRelease(&preupdate.aNew[i]); } - sqlite3DbFree(db, preupdate.aNew); + tdsqlite3DbFreeNN(db, preupdate.aNew); } } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ @@ -78221,11 +86155,11 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( ** Return TRUE (non-zero) of the statement supplied as an argument needs ** to be recompiled. A statement needs to be recompiled whenever the ** execution environment changes in a way that would alter the program -** that sqlite3_prepare() generates. For example, if new functions or +** that tdsqlite3_prepare() generates. For example, if new functions or ** collating sequences are registered or if an authorizer function is ** added or changed. */ -SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){ +SQLITE_API int tdsqlite3_expired(tdsqlite3_stmt *pStmt){ Vdbe *p = (Vdbe*)pStmt; return p==0 || p->expired; } @@ -78238,7 +86172,7 @@ SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){ */ static int vdbeSafety(Vdbe *p){ if( p->db==0 ){ - sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement"); + tdsqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement"); return 1; }else{ return 0; @@ -78246,7 +86180,7 @@ static int vdbeSafety(Vdbe *p){ } static int vdbeSafetyNotNull(Vdbe *p){ if( p==0 ){ - sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement"); + tdsqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement"); return 1; }else{ return vdbeSafety(p); @@ -78258,18 +86192,20 @@ static int vdbeSafetyNotNull(Vdbe *p){ ** Invoke the profile callback. This routine is only called if we already ** know that the profile callback is defined and needs to be invoked. */ -static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){ - sqlite3_int64 iNow; - sqlite3_int64 iElapse; +static SQLITE_NOINLINE void invokeProfileCallback(tdsqlite3 *db, Vdbe *p){ + tdsqlite3_int64 iNow; + tdsqlite3_int64 iElapse; assert( p->startTime>0 ); - assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 ); + assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 ); assert( db->init.busy==0 ); assert( p->zSql!=0 ); - sqlite3OsCurrentTimeInt64(db->pVfs, &iNow); + tdsqlite3OsCurrentTimeInt64(db->pVfs, &iNow); iElapse = (iNow - p->startTime)*1000000; +#ifndef SQLITE_OMIT_DEPRECATED if( db->xProfile ){ db->xProfile(db->pProfileArg, p->zSql, iElapse); } +#endif if( db->mTrace & SQLITE_TRACE_PROFILE ){ db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse); } @@ -78287,28 +86223,28 @@ static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){ /* ** The following routine destroys a virtual machine that is created by -** the sqlite3_compile() routine. The integer returned is an SQLITE_ +** the tdsqlite3_compile() routine. The integer returned is an SQLITE_ ** success/failure code that describes the result of executing the virtual ** machine. ** ** This routine sets the error code and string returned by -** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). +** tdsqlite3_errcode(), tdsqlite3_errmsg() and tdsqlite3_errmsg16(). */ -SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){ +SQLITE_API int tdsqlite3_finalize(tdsqlite3_stmt *pStmt){ int rc; if( pStmt==0 ){ - /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL + /* IMPLEMENTATION-OF: R-57228-12904 Invoking tdsqlite3_finalize() on a NULL ** pointer is a harmless no-op. */ rc = SQLITE_OK; }else{ Vdbe *v = (Vdbe*)pStmt; - sqlite3 *db = v->db; + tdsqlite3 *db = v->db; if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT; - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); checkProfileCallback(db, v); - rc = sqlite3VdbeFinalize(v); - rc = sqlite3ApiExit(db, rc); - sqlite3LeaveMutexAndCloseZombie(db); + rc = tdsqlite3VdbeFinalize(v); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3LeaveMutexAndCloseZombie(db); } return rc; } @@ -78319,22 +86255,22 @@ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){ ** the prior execution is returned. ** ** This routine sets the error code and string returned by -** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). +** tdsqlite3_errcode(), tdsqlite3_errmsg() and tdsqlite3_errmsg16(). */ -SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){ +SQLITE_API int tdsqlite3_reset(tdsqlite3_stmt *pStmt){ int rc; if( pStmt==0 ){ rc = SQLITE_OK; }else{ Vdbe *v = (Vdbe*)pStmt; - sqlite3 *db = v->db; - sqlite3_mutex_enter(db->mutex); + tdsqlite3 *db = v->db; + tdsqlite3_mutex_enter(db->mutex); checkProfileCallback(db, v); - rc = sqlite3VdbeReset(v); - sqlite3VdbeRewind(v); + rc = tdsqlite3VdbeReset(v); + tdsqlite3VdbeRewind(v); assert( (rc & (db->errMask))==rc ); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); } return rc; } @@ -78342,31 +86278,32 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){ /* ** Set all the parameters in the compiled SQL statement to NULL. */ -SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){ +SQLITE_API int tdsqlite3_clear_bindings(tdsqlite3_stmt *pStmt){ int i; int rc = SQLITE_OK; Vdbe *p = (Vdbe*)pStmt; #if SQLITE_THREADSAFE - sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex; + tdsqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex; #endif - sqlite3_mutex_enter(mutex); + tdsqlite3_mutex_enter(mutex); for(i=0; i<p->nVar; i++){ - sqlite3VdbeMemRelease(&p->aVar[i]); + tdsqlite3VdbeMemRelease(&p->aVar[i]); p->aVar[i].flags = MEM_Null; } - if( p->isPrepareV2 && p->expmask ){ + assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 ); + if( p->expmask ){ p->expired = 1; } - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); return rc; } -/**************************** sqlite3_value_ ******************************* -** The following routines extract information from a Mem or sqlite3_value +/**************************** tdsqlite3_value_ ******************************* +** The following routines extract information from a Mem or tdsqlite3_value ** structure. */ -SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){ +SQLITE_API const void *tdsqlite3_value_blob(tdsqlite3_value *pVal){ Mem *p = (Mem*)pVal; if( p->flags & (MEM_Blob|MEM_Str) ){ if( ExpandBlob(p)!=SQLITE_OK ){ @@ -78376,90 +86313,160 @@ SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){ p->flags |= MEM_Blob; return p->n ? p->z : 0; }else{ - return sqlite3_value_text(pVal); + return tdsqlite3_value_text(pVal); } } -SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){ - return sqlite3ValueBytes(pVal, SQLITE_UTF8); +SQLITE_API int tdsqlite3_value_bytes(tdsqlite3_value *pVal){ + return tdsqlite3ValueBytes(pVal, SQLITE_UTF8); } -SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){ - return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE); +SQLITE_API int tdsqlite3_value_bytes16(tdsqlite3_value *pVal){ + return tdsqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE); } -SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){ - return sqlite3VdbeRealValue((Mem*)pVal); +SQLITE_API double tdsqlite3_value_double(tdsqlite3_value *pVal){ + return tdsqlite3VdbeRealValue((Mem*)pVal); } -SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){ - return (int)sqlite3VdbeIntValue((Mem*)pVal); +SQLITE_API int tdsqlite3_value_int(tdsqlite3_value *pVal){ + return (int)tdsqlite3VdbeIntValue((Mem*)pVal); } -SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){ - return sqlite3VdbeIntValue((Mem*)pVal); +SQLITE_API sqlite_int64 tdsqlite3_value_int64(tdsqlite3_value *pVal){ + return tdsqlite3VdbeIntValue((Mem*)pVal); } -SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){ +SQLITE_API unsigned int tdsqlite3_value_subtype(tdsqlite3_value *pVal){ Mem *pMem = (Mem*)pVal; return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0); } -SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){ - return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8); +SQLITE_API void *tdsqlite3_value_pointer(tdsqlite3_value *pVal, const char *zPType){ + Mem *p = (Mem*)pVal; + if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) == + (MEM_Null|MEM_Term|MEM_Subtype) + && zPType!=0 + && p->eSubtype=='p' + && strcmp(p->u.zPType, zPType)==0 + ){ + return (void*)p->z; + }else{ + return 0; + } +} +SQLITE_API const unsigned char *tdsqlite3_value_text(tdsqlite3_value *pVal){ + return (const unsigned char *)tdsqlite3ValueText(pVal, SQLITE_UTF8); } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){ - return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); +SQLITE_API const void *tdsqlite3_value_text16(tdsqlite3_value* pVal){ + return tdsqlite3ValueText(pVal, SQLITE_UTF16NATIVE); } -SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){ - return sqlite3ValueText(pVal, SQLITE_UTF16BE); +SQLITE_API const void *tdsqlite3_value_text16be(tdsqlite3_value *pVal){ + return tdsqlite3ValueText(pVal, SQLITE_UTF16BE); } -SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){ - return sqlite3ValueText(pVal, SQLITE_UTF16LE); +SQLITE_API const void *tdsqlite3_value_text16le(tdsqlite3_value *pVal){ + return tdsqlite3ValueText(pVal, SQLITE_UTF16LE); } #endif /* SQLITE_OMIT_UTF16 */ /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating ** point number string BLOB NULL */ -SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){ +SQLITE_API int tdsqlite3_value_type(tdsqlite3_value* pVal){ static const u8 aType[] = { - SQLITE_BLOB, /* 0x00 */ - SQLITE_NULL, /* 0x01 */ - SQLITE_TEXT, /* 0x02 */ - SQLITE_NULL, /* 0x03 */ - SQLITE_INTEGER, /* 0x04 */ - SQLITE_NULL, /* 0x05 */ - SQLITE_INTEGER, /* 0x06 */ - SQLITE_NULL, /* 0x07 */ - SQLITE_FLOAT, /* 0x08 */ - SQLITE_NULL, /* 0x09 */ - SQLITE_FLOAT, /* 0x0a */ - SQLITE_NULL, /* 0x0b */ - SQLITE_INTEGER, /* 0x0c */ - SQLITE_NULL, /* 0x0d */ - SQLITE_INTEGER, /* 0x0e */ - SQLITE_NULL, /* 0x0f */ - SQLITE_BLOB, /* 0x10 */ - SQLITE_NULL, /* 0x11 */ - SQLITE_TEXT, /* 0x12 */ - SQLITE_NULL, /* 0x13 */ - SQLITE_INTEGER, /* 0x14 */ - SQLITE_NULL, /* 0x15 */ - SQLITE_INTEGER, /* 0x16 */ - SQLITE_NULL, /* 0x17 */ - SQLITE_FLOAT, /* 0x18 */ - SQLITE_NULL, /* 0x19 */ - SQLITE_FLOAT, /* 0x1a */ - SQLITE_NULL, /* 0x1b */ - SQLITE_INTEGER, /* 0x1c */ - SQLITE_NULL, /* 0x1d */ - SQLITE_INTEGER, /* 0x1e */ - SQLITE_NULL, /* 0x1f */ + SQLITE_BLOB, /* 0x00 (not possible) */ + SQLITE_NULL, /* 0x01 NULL */ + SQLITE_TEXT, /* 0x02 TEXT */ + SQLITE_NULL, /* 0x03 (not possible) */ + SQLITE_INTEGER, /* 0x04 INTEGER */ + SQLITE_NULL, /* 0x05 (not possible) */ + SQLITE_INTEGER, /* 0x06 INTEGER + TEXT */ + SQLITE_NULL, /* 0x07 (not possible) */ + SQLITE_FLOAT, /* 0x08 FLOAT */ + SQLITE_NULL, /* 0x09 (not possible) */ + SQLITE_FLOAT, /* 0x0a FLOAT + TEXT */ + SQLITE_NULL, /* 0x0b (not possible) */ + SQLITE_INTEGER, /* 0x0c (not possible) */ + SQLITE_NULL, /* 0x0d (not possible) */ + SQLITE_INTEGER, /* 0x0e (not possible) */ + SQLITE_NULL, /* 0x0f (not possible) */ + SQLITE_BLOB, /* 0x10 BLOB */ + SQLITE_NULL, /* 0x11 (not possible) */ + SQLITE_TEXT, /* 0x12 (not possible) */ + SQLITE_NULL, /* 0x13 (not possible) */ + SQLITE_INTEGER, /* 0x14 INTEGER + BLOB */ + SQLITE_NULL, /* 0x15 (not possible) */ + SQLITE_INTEGER, /* 0x16 (not possible) */ + SQLITE_NULL, /* 0x17 (not possible) */ + SQLITE_FLOAT, /* 0x18 FLOAT + BLOB */ + SQLITE_NULL, /* 0x19 (not possible) */ + SQLITE_FLOAT, /* 0x1a (not possible) */ + SQLITE_NULL, /* 0x1b (not possible) */ + SQLITE_INTEGER, /* 0x1c (not possible) */ + SQLITE_NULL, /* 0x1d (not possible) */ + SQLITE_INTEGER, /* 0x1e (not possible) */ + SQLITE_NULL, /* 0x1f (not possible) */ + SQLITE_FLOAT, /* 0x20 INTREAL */ + SQLITE_NULL, /* 0x21 (not possible) */ + SQLITE_TEXT, /* 0x22 INTREAL + TEXT */ + SQLITE_NULL, /* 0x23 (not possible) */ + SQLITE_FLOAT, /* 0x24 (not possible) */ + SQLITE_NULL, /* 0x25 (not possible) */ + SQLITE_FLOAT, /* 0x26 (not possible) */ + SQLITE_NULL, /* 0x27 (not possible) */ + SQLITE_FLOAT, /* 0x28 (not possible) */ + SQLITE_NULL, /* 0x29 (not possible) */ + SQLITE_FLOAT, /* 0x2a (not possible) */ + SQLITE_NULL, /* 0x2b (not possible) */ + SQLITE_FLOAT, /* 0x2c (not possible) */ + SQLITE_NULL, /* 0x2d (not possible) */ + SQLITE_FLOAT, /* 0x2e (not possible) */ + SQLITE_NULL, /* 0x2f (not possible) */ + SQLITE_BLOB, /* 0x30 (not possible) */ + SQLITE_NULL, /* 0x31 (not possible) */ + SQLITE_TEXT, /* 0x32 (not possible) */ + SQLITE_NULL, /* 0x33 (not possible) */ + SQLITE_FLOAT, /* 0x34 (not possible) */ + SQLITE_NULL, /* 0x35 (not possible) */ + SQLITE_FLOAT, /* 0x36 (not possible) */ + SQLITE_NULL, /* 0x37 (not possible) */ + SQLITE_FLOAT, /* 0x38 (not possible) */ + SQLITE_NULL, /* 0x39 (not possible) */ + SQLITE_FLOAT, /* 0x3a (not possible) */ + SQLITE_NULL, /* 0x3b (not possible) */ + SQLITE_FLOAT, /* 0x3c (not possible) */ + SQLITE_NULL, /* 0x3d (not possible) */ + SQLITE_FLOAT, /* 0x3e (not possible) */ + SQLITE_NULL, /* 0x3f (not possible) */ }; +#ifdef SQLITE_DEBUG + { + int eType = SQLITE_BLOB; + if( pVal->flags & MEM_Null ){ + eType = SQLITE_NULL; + }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){ + eType = SQLITE_FLOAT; + }else if( pVal->flags & MEM_Int ){ + eType = SQLITE_INTEGER; + }else if( pVal->flags & MEM_Str ){ + eType = SQLITE_TEXT; + } + assert( eType == aType[pVal->flags&MEM_AffMask] ); + } +#endif return aType[pVal->flags&MEM_AffMask]; } -/* Make a copy of an sqlite3_value object +/* Return true if a parameter to xUpdate represents an unchanged column */ +SQLITE_API int tdsqlite3_value_nochange(tdsqlite3_value *pVal){ + return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero); +} + +/* Return true if a parameter value originated from an tdsqlite3_bind() */ +SQLITE_API int tdsqlite3_value_frombind(tdsqlite3_value *pVal){ + return (pVal->flags&MEM_FromBind)!=0; +} + +/* Make a copy of an tdsqlite3_value object */ -SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){ - sqlite3_value *pNew; +SQLITE_API tdsqlite3_value *tdsqlite3_value_dup(const tdsqlite3_value *pOrig){ + tdsqlite3_value *pNew; if( pOrig==0 ) return 0; - pNew = sqlite3_malloc( sizeof(*pNew) ); + pNew = tdsqlite3_malloc( sizeof(*pNew) ); if( pNew==0 ) return 0; memset(pNew, 0, sizeof(*pNew)); memcpy(pNew, pOrig, MEMCELLSIZE); @@ -78468,27 +86475,27 @@ SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){ if( pNew->flags&(MEM_Str|MEM_Blob) ){ pNew->flags &= ~(MEM_Static|MEM_Dyn); pNew->flags |= MEM_Ephem; - if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){ - sqlite3ValueFree(pNew); + if( tdsqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){ + tdsqlite3ValueFree(pNew); pNew = 0; } } return pNew; } -/* Destroy an sqlite3_value object previously obtained from -** sqlite3_value_dup(). +/* Destroy an tdsqlite3_value object previously obtained from +** tdsqlite3_value_dup(). */ -SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){ - sqlite3ValueFree(pOld); +SQLITE_API void tdsqlite3_value_free(tdsqlite3_value *pOld){ + tdsqlite3ValueFree(pOld); } -/**************************** sqlite3_result_ ******************************* +/**************************** tdsqlite3_result_ ******************************* ** The following routines are used by user-defined functions to specify ** the function result. ** -** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the +** The setStrOrError() function calls tdsqlite3VdbeMemSetStr() to store the ** result as a string or blob but if the string or blob is too large, it ** then sets the error code to SQLITE_TOOBIG ** @@ -78496,20 +86503,20 @@ SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){ ** on value P is not going to be used and need to be destroyed. */ static void setResultStrOrError( - sqlite3_context *pCtx, /* Function context */ + tdsqlite3_context *pCtx, /* Function context */ const char *z, /* String pointer */ int n, /* Bytes in string, or negative */ u8 enc, /* Encoding of z. 0 for BLOBs */ void (*xDel)(void*) /* Destructor function */ ){ - if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){ - sqlite3_result_error_toobig(pCtx); + if( tdsqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){ + tdsqlite3_result_error_toobig(pCtx); } } static int invokeValueDestructor( const void *p, /* Value to destroy */ void (*xDel)(void*), /* The destructor */ - sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */ + tdsqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */ ){ assert( xDel!=SQLITE_DYNAMIC ); if( xDel==0 ){ @@ -78519,26 +86526,26 @@ static int invokeValueDestructor( }else{ xDel((void*)p); } - if( pCtx ) sqlite3_result_error_toobig(pCtx); + if( pCtx ) tdsqlite3_result_error_toobig(pCtx); return SQLITE_TOOBIG; } -SQLITE_API void sqlite3_result_blob( - sqlite3_context *pCtx, +SQLITE_API void tdsqlite3_result_blob( + tdsqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ assert( n>=0 ); - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, 0, xDel); } -SQLITE_API void sqlite3_result_blob64( - sqlite3_context *pCtx, +SQLITE_API void tdsqlite3_result_blob64( + tdsqlite3_context *pCtx, const void *z, - sqlite3_uint64 n, + tdsqlite3_uint64 n, void (*xDel)(void *) ){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); assert( xDel!=SQLITE_DYNAMIC ); if( n>0x7fffffff ){ (void)invokeValueDestructor(z, xDel, pCtx); @@ -78546,59 +86553,69 @@ SQLITE_API void sqlite3_result_blob64( setResultStrOrError(pCtx, z, (int)n, 0, xDel); } } -SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetDouble(pCtx->pOut, rVal); +SQLITE_API void tdsqlite3_result_double(tdsqlite3_context *pCtx, double rVal){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); + tdsqlite3VdbeMemSetDouble(pCtx->pOut, rVal); } -SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); +SQLITE_API void tdsqlite3_result_error(tdsqlite3_context *pCtx, const char *z, int n){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); pCtx->isError = SQLITE_ERROR; - pCtx->fErrorOrAux = 1; - sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT); + tdsqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT); } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); +SQLITE_API void tdsqlite3_result_error16(tdsqlite3_context *pCtx, const void *z, int n){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); pCtx->isError = SQLITE_ERROR; - pCtx->fErrorOrAux = 1; - sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT); + tdsqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT); } #endif -SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal); +SQLITE_API void tdsqlite3_result_int(tdsqlite3_context *pCtx, int iVal){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); + tdsqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal); } -SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetInt64(pCtx->pOut, iVal); +SQLITE_API void tdsqlite3_result_int64(tdsqlite3_context *pCtx, i64 iVal){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); + tdsqlite3VdbeMemSetInt64(pCtx->pOut, iVal); } -SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetNull(pCtx->pOut); +SQLITE_API void tdsqlite3_result_null(tdsqlite3_context *pCtx){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); + tdsqlite3VdbeMemSetNull(pCtx->pOut); +} +SQLITE_API void tdsqlite3_result_pointer( + tdsqlite3_context *pCtx, + void *pPtr, + const char *zPType, + void (*xDestructor)(void*) +){ + Mem *pOut = pCtx->pOut; + assert( tdsqlite3_mutex_held(pOut->db->mutex) ); + tdsqlite3VdbeMemRelease(pOut); + pOut->flags = MEM_Null; + tdsqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor); } -SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){ +SQLITE_API void tdsqlite3_result_subtype(tdsqlite3_context *pCtx, unsigned int eSubtype){ Mem *pOut = pCtx->pOut; - assert( sqlite3_mutex_held(pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(pOut->db->mutex) ); pOut->eSubtype = eSubtype & 0xff; pOut->flags |= MEM_Subtype; } -SQLITE_API void sqlite3_result_text( - sqlite3_context *pCtx, +SQLITE_API void tdsqlite3_result_text( + tdsqlite3_context *pCtx, const char *z, int n, void (*xDel)(void *) ){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel); } -SQLITE_API void sqlite3_result_text64( - sqlite3_context *pCtx, +SQLITE_API void tdsqlite3_result_text64( + tdsqlite3_context *pCtx, const char *z, - sqlite3_uint64 n, + tdsqlite3_uint64 n, void (*xDel)(void *), unsigned char enc ){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); assert( xDel!=SQLITE_DYNAMIC ); if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE; if( n>0x7fffffff ){ @@ -78608,86 +86625,98 @@ SQLITE_API void sqlite3_result_text64( } } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API void sqlite3_result_text16( - sqlite3_context *pCtx, +SQLITE_API void tdsqlite3_result_text16( + tdsqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel); } -SQLITE_API void sqlite3_result_text16be( - sqlite3_context *pCtx, +SQLITE_API void tdsqlite3_result_text16be( + tdsqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel); } -SQLITE_API void sqlite3_result_text16le( - sqlite3_context *pCtx, +SQLITE_API void tdsqlite3_result_text16le( + tdsqlite3_context *pCtx, const void *z, int n, void (*xDel)(void *) ){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel); } #endif /* SQLITE_OMIT_UTF16 */ -SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemCopy(pCtx->pOut, pValue); +SQLITE_API void tdsqlite3_result_value(tdsqlite3_context *pCtx, tdsqlite3_value *pValue){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); + tdsqlite3VdbeMemCopy(pCtx->pOut, pValue); } -SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n); +SQLITE_API void tdsqlite3_result_zeroblob(tdsqlite3_context *pCtx, int n){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); + tdsqlite3VdbeMemSetZeroBlob(pCtx->pOut, n); } -SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){ +SQLITE_API int tdsqlite3_result_zeroblob64(tdsqlite3_context *pCtx, u64 n){ Mem *pOut = pCtx->pOut; - assert( sqlite3_mutex_held(pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(pOut->db->mutex) ); if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){ return SQLITE_TOOBIG; } - sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n); + tdsqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n); return SQLITE_OK; } -SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){ - pCtx->isError = errCode; - pCtx->fErrorOrAux = 1; +SQLITE_API void tdsqlite3_result_error_code(tdsqlite3_context *pCtx, int errCode){ + pCtx->isError = errCode ? errCode : -1; #ifdef SQLITE_DEBUG if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode; #endif if( pCtx->pOut->flags & MEM_Null ){ - sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, + tdsqlite3VdbeMemSetStr(pCtx->pOut, tdsqlite3ErrStr(errCode), -1, SQLITE_UTF8, SQLITE_STATIC); } } /* Force an SQLITE_TOOBIG error. */ -SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); +SQLITE_API void tdsqlite3_result_error_toobig(tdsqlite3_context *pCtx){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); pCtx->isError = SQLITE_TOOBIG; - pCtx->fErrorOrAux = 1; - sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, + tdsqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, SQLITE_UTF8, SQLITE_STATIC); } /* An SQLITE_NOMEM error. */ -SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetNull(pCtx->pOut); +SQLITE_API void tdsqlite3_result_error_nomem(tdsqlite3_context *pCtx){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); + tdsqlite3VdbeMemSetNull(pCtx->pOut); pCtx->isError = SQLITE_NOMEM_BKPT; - pCtx->fErrorOrAux = 1; - sqlite3OomFault(pCtx->pOut->db); + tdsqlite3OomFault(pCtx->pOut->db); } +#ifndef SQLITE_UNTESTABLE +/* Force the INT64 value currently stored as the result to be +** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL +** test-control. +*/ +SQLITE_PRIVATE void tdsqlite3ResultIntReal(tdsqlite3_context *pCtx){ + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); + if( pCtx->pOut->flags & MEM_Int ){ + pCtx->pOut->flags &= ~MEM_Int; + pCtx->pOut->flags |= MEM_IntReal; + } +} +#endif + + /* ** This function is called after a transaction has been committed. It -** invokes callbacks registered with sqlite3_wal_hook() as required. +** invokes callbacks registered with tdsqlite3_wal_hook() as required. */ -static int doWalCallbacks(sqlite3 *db){ +static int doWalCallbacks(tdsqlite3 *db){ int rc = SQLITE_OK; #ifndef SQLITE_OMIT_WAL int i; @@ -78695,10 +86724,10 @@ static int doWalCallbacks(sqlite3 *db){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ int nEntry; - sqlite3BtreeEnter(pBt); - nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt)); - sqlite3BtreeLeave(pBt); - if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){ + tdsqlite3BtreeEnter(pBt); + nEntry = tdsqlite3PagerWalCallback(tdsqlite3BtreePager(pBt)); + tdsqlite3BtreeLeave(pBt); + if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){ rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry); } } @@ -78715,17 +86744,17 @@ static int doWalCallbacks(sqlite3 *db){ ** This routine implements the bulk of the logic behind the sqlite_step() ** API. The only thing omitted is the automatic recompile if a ** schema change has occurred. That detail is handled by the -** outer sqlite3_step() wrapper procedure. +** outer tdsqlite3_step() wrapper procedure. */ -static int sqlite3Step(Vdbe *p){ - sqlite3 *db; +static int tdsqlite3Step(Vdbe *p){ + tdsqlite3 *db; int rc; assert(p); if( p->magic!=VDBE_MAGIC_RUN ){ - /* We used to require that sqlite3_reset() be called before retrying - ** sqlite3_step() after any error or after SQLITE_DONE. But beginning - ** with version 3.7.0, we changed this so that sqlite3_reset() would + /* We used to require that tdsqlite3_reset() be called before retrying + ** tdsqlite3_step() after any error or after SQLITE_DONE. But beginning + ** with version 3.7.0, we changed this so that tdsqlite3_reset() would ** be called automatically instead of throwing the SQLITE_MISUSE error. ** This "automatic-reset" change is not technically an incompatibility, ** since any application that receives an SQLITE_MISUSE is broken by @@ -78736,17 +86765,17 @@ static int sqlite3Step(Vdbe *p){ ** returns, and those were broken by the automatic-reset change. As a ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the ** legacy behavior of returning SQLITE_MISUSE for cases where the - ** previous sqlite3_step() returned something other than a SQLITE_LOCKED + ** previous tdsqlite3_step() returned something other than a SQLITE_LOCKED ** or SQLITE_BUSY error. */ #ifdef SQLITE_OMIT_AUTORESET if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){ - sqlite3_reset((sqlite3_stmt*)p); + tdsqlite3_reset((tdsqlite3_stmt*)p); }else{ return SQLITE_MISUSE_BKPT; } #else - sqlite3_reset((sqlite3_stmt*)p); + tdsqlite3_reset((tdsqlite3_stmt*)p); #endif } @@ -78757,14 +86786,14 @@ static int sqlite3Step(Vdbe *p){ return SQLITE_NOMEM_BKPT; } - if( p->pc<=0 && p->expired ){ + if( p->pc<0 && p->expired ){ p->rc = SQLITE_SCHEMA; rc = SQLITE_ERROR; goto end_of_step; } if( p->pc<0 ){ /* If there are no other statements currently running, then - ** reset the interrupt flag. This prevents a call to sqlite3_interrupt + ** reset the interrupt flag. This prevents a call to tdsqlite3_interrupt ** from interrupting a statement that has not yet started. */ if( db->nVdbeActive==0 ){ @@ -78776,9 +86805,9 @@ static int sqlite3Step(Vdbe *p){ ); #ifndef SQLITE_OMIT_TRACE - if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0) + if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 && !db->init.busy && p->zSql ){ - sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime); + tdsqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime); }else{ assert( p->startTime==0 ); } @@ -78794,187 +86823,187 @@ static int sqlite3Step(Vdbe *p){ #endif #ifndef SQLITE_OMIT_EXPLAIN if( p->explain ){ - rc = sqlite3VdbeList(p); + rc = tdsqlite3VdbeList(p); }else #endif /* SQLITE_OMIT_EXPLAIN */ { db->nVdbeExec++; - rc = sqlite3VdbeExec(p); + rc = tdsqlite3VdbeExec(p); db->nVdbeExec--; } + if( rc!=SQLITE_ROW ){ #ifndef SQLITE_OMIT_TRACE - /* If the statement completed successfully, invoke the profile callback */ - if( rc!=SQLITE_ROW ) checkProfileCallback(db, p); + /* If the statement completed successfully, invoke the profile callback */ + checkProfileCallback(db, p); #endif - if( rc==SQLITE_DONE ){ - assert( p->rc==SQLITE_OK ); - p->rc = doWalCallbacks(db); - if( p->rc!=SQLITE_OK ){ - rc = SQLITE_ERROR; + if( rc==SQLITE_DONE && db->autoCommit ){ + assert( p->rc==SQLITE_OK ); + p->rc = doWalCallbacks(db); + if( p->rc!=SQLITE_OK ){ + rc = SQLITE_ERROR; + } } } db->errCode = rc; - if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){ + if( SQLITE_NOMEM==tdsqlite3ApiExit(p->db, p->rc) ){ p->rc = SQLITE_NOMEM_BKPT; } end_of_step: /* At this point local variable rc holds the value that should be ** returned if this statement was compiled using the legacy - ** sqlite3_prepare() interface. According to the docs, this can only + ** tdsqlite3_prepare() interface. According to the docs, this can only ** be one of the values in the first assert() below. Variable p->rc - ** contains the value that would be returned if sqlite3_finalize() + ** contains the value that would be returned if tdsqlite3_finalize() ** were called on statement p. */ assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE ); assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp ); - if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ - /* If this statement was prepared using sqlite3_prepare_v2(), and an + if( rc!=SQLITE_ROW + && rc!=SQLITE_DONE + && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 + ){ + /* If this statement was prepared using saved SQL and an ** error has occurred, then return the error code in p->rc to the ** caller. Set the error code in the database handle to the same value. */ - rc = sqlite3VdbeTransferError(p); + rc = tdsqlite3VdbeTransferError(p); } return (rc&db->errMask); } /* -** This is the top-level implementation of sqlite3_step(). Call -** sqlite3Step() to do most of the work. If a schema error occurs, -** call sqlite3Reprepare() and try again. +** This is the top-level implementation of tdsqlite3_step(). Call +** tdsqlite3Step() to do most of the work. If a schema error occurs, +** call tdsqlite3Reprepare() and try again. */ -SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){ - int rc = SQLITE_OK; /* Result from sqlite3Step() */ - int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */ +SQLITE_API int tdsqlite3_step(tdsqlite3_stmt *pStmt){ + int rc = SQLITE_OK; /* Result from tdsqlite3Step() */ Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */ int cnt = 0; /* Counter to prevent infinite loop of reprepares */ - sqlite3 *db; /* The database connection */ + tdsqlite3 *db; /* The database connection */ if( vdbeSafetyNotNull(v) ){ return SQLITE_MISUSE_BKPT; } db = v->db; - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); v->doingRerun = 0; - while( (rc = sqlite3Step(v))==SQLITE_SCHEMA + while( (rc = tdsqlite3Step(v))==SQLITE_SCHEMA && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){ int savedPc = v->pc; - rc2 = rc = sqlite3Reprepare(v); - if( rc!=SQLITE_OK) break; - sqlite3_reset(pStmt); + rc = tdsqlite3Reprepare(v); + if( rc!=SQLITE_OK ){ + /* This case occurs after failing to recompile an sql statement. + ** The error message from the SQL compiler has already been loaded + ** into the database handle. This block copies the error message + ** from the database handle into the statement and sets the statement + ** program counter to 0 to ensure that when the statement is + ** finalized or reset the parser error message is available via + ** tdsqlite3_errmsg() and tdsqlite3_errcode(). + */ + const char *zErr = (const char *)tdsqlite3_value_text(db->pErr); + tdsqlite3DbFree(db, v->zErrMsg); + if( !db->mallocFailed ){ + v->zErrMsg = tdsqlite3DbStrDup(db, zErr); + v->rc = rc = tdsqlite3ApiExit(db, rc); + } else { + v->zErrMsg = 0; + v->rc = rc = SQLITE_NOMEM_BKPT; + } + break; + } + tdsqlite3_reset(pStmt); if( savedPc>=0 ) v->doingRerun = 1; assert( v->expired==0 ); } - if( rc2!=SQLITE_OK ){ - /* This case occurs after failing to recompile an sql statement. - ** The error message from the SQL compiler has already been loaded - ** into the database handle. This block copies the error message - ** from the database handle into the statement and sets the statement - ** program counter to 0 to ensure that when the statement is - ** finalized or reset the parser error message is available via - ** sqlite3_errmsg() and sqlite3_errcode(). - */ - const char *zErr = (const char *)sqlite3_value_text(db->pErr); - sqlite3DbFree(db, v->zErrMsg); - if( !db->mallocFailed ){ - v->zErrMsg = sqlite3DbStrDup(db, zErr); - v->rc = rc2; - } else { - v->zErrMsg = 0; - v->rc = rc = SQLITE_NOMEM_BKPT; - } - } - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return rc; } /* -** Extract the user data from a sqlite3_context structure and return a +** Extract the user data from a tdsqlite3_context structure and return a ** pointer to it. */ -SQLITE_API void *sqlite3_user_data(sqlite3_context *p){ +SQLITE_API void *tdsqlite3_user_data(tdsqlite3_context *p){ assert( p && p->pFunc ); return p->pFunc->pUserData; } /* -** Extract the user data from a sqlite3_context structure and return a +** Extract the user data from a tdsqlite3_context structure and return a ** pointer to it. ** -** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface +** IMPLEMENTATION-OF: R-46798-50301 The tdsqlite3_context_db_handle() interface ** returns a copy of the pointer to the database connection (the 1st -** parameter) of the sqlite3_create_function() and -** sqlite3_create_function16() routines that originally registered the +** parameter) of the tdsqlite3_create_function() and +** tdsqlite3_create_function16() routines that originally registered the ** application defined function. */ -SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){ +SQLITE_API tdsqlite3 *tdsqlite3_context_db_handle(tdsqlite3_context *p){ assert( p && p->pOut ); return p->pOut->db; } /* +** If this routine is invoked from within an xColumn method of a virtual +** table, then it returns true if and only if the the call is during an +** UPDATE operation and the value of the column will not be modified +** by the UPDATE. +** +** If this routine is called from any context other than within the +** xColumn method of a virtual table, then the return value is meaningless +** and arbitrary. +** +** Virtual table implements might use this routine to optimize their +** performance by substituting a NULL result, or some other light-weight +** value, as a signal to the xUpdate routine that the column is unchanged. +*/ +SQLITE_API int tdsqlite3_vtab_nochange(tdsqlite3_context *p){ + assert( p ); + return tdsqlite3_value_nochange(p->pOut); +} + +/* ** Return the current time for a statement. If the current time ** is requested more than once within the same run of a single prepared ** statement, the exact same time is returned for each invocation regardless ** of the amount of time that elapses between invocations. In other words, ** the time returned is always the time of the first call. */ -SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){ +SQLITE_PRIVATE tdsqlite3_int64 tdsqlite3StmtCurrentTime(tdsqlite3_context *p){ int rc; -#ifndef SQLITE_ENABLE_STAT3_OR_STAT4 - sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime; +#ifndef SQLITE_ENABLE_STAT4 + tdsqlite3_int64 *piTime = &p->pVdbe->iCurrentTime; assert( p->pVdbe!=0 ); #else - sqlite3_int64 iTime = 0; - sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime; + tdsqlite3_int64 iTime = 0; + tdsqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime; #endif if( *piTime==0 ){ - rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime); + rc = tdsqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime); if( rc ) *piTime = 0; } return *piTime; } /* -** The following is the implementation of an SQL function that always -** fails with an error message stating that the function is used in the -** wrong context. The sqlite3_overload_function() API might construct -** SQL function that use this routine so that the functions will exist -** for name resolution but are actually overloaded by the xFindFunction -** method of virtual tables. -*/ -SQLITE_PRIVATE void sqlite3InvalidFunction( - sqlite3_context *context, /* The function calling context */ - int NotUsed, /* Number of arguments to the function */ - sqlite3_value **NotUsed2 /* Value of each argument */ -){ - const char *zName = context->pFunc->zName; - char *zErr; - UNUSED_PARAMETER2(NotUsed, NotUsed2); - zErr = sqlite3_mprintf( - "unable to use function %s in the requested context", zName); - sqlite3_result_error(context, zErr, -1); - sqlite3_free(zErr); -} - -/* ** Create a new aggregate context for p and return a pointer to ** its pMem->z element. */ -static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){ +static SQLITE_NOINLINE void *createAggContext(tdsqlite3_context *p, int nByte){ Mem *pMem = p->pMem; assert( (pMem->flags & MEM_Agg)==0 ); if( nByte<=0 ){ - sqlite3VdbeMemSetNull(pMem); + tdsqlite3VdbeMemSetNull(pMem); pMem->z = 0; }else{ - sqlite3VdbeMemClearAndResize(pMem, nByte); + tdsqlite3VdbeMemClearAndResize(pMem, nByte); pMem->flags = MEM_Agg; pMem->u.pDef = p->pFunc; if( pMem->z ){ @@ -78989,9 +87018,9 @@ static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){ ** context is allocated on the first call. Subsequent calls return the ** same context that was returned on prior calls. */ -SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){ +SQLITE_API void *tdsqlite3_aggregate_context(tdsqlite3_context *p, int nByte){ assert( p && p->pFunc && p->pFunc->xFinalize ); - assert( sqlite3_mutex_held(p->pOut->db->mutex) ); + assert( tdsqlite3_mutex_held(p->pOut->db->mutex) ); testcase( nByte<0 ); if( (p->pMem->flags & MEM_Agg)==0 ){ return createAggContext(p, nByte); @@ -79003,30 +87032,43 @@ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){ /* ** Return the auxiliary data pointer, if any, for the iArg'th argument to ** the user-function defined by pCtx. +** +** The left-most argument is 0. +** +** Undocumented behavior: If iArg is negative then access a cache of +** auxiliary data pointers that is available to all functions within a +** single prepared statement. The iArg values must match. */ -SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){ +SQLITE_API void *tdsqlite3_get_auxdata(tdsqlite3_context *pCtx, int iArg){ AuxData *pAuxData; - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); -#if SQLITE_ENABLE_STAT3_OR_STAT4 + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); +#if SQLITE_ENABLE_STAT4 if( pCtx->pVdbe==0 ) return 0; #else assert( pCtx->pVdbe!=0 ); #endif - for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ - if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; + for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){ + if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){ + return pAuxData->pAux; + } } - - return (pAuxData ? pAuxData->pAux : 0); + return 0; } /* ** Set the auxiliary data pointer and delete function, for the iArg'th ** argument to the user-function defined by pCtx. Any previous value is ** deleted by calling the delete function specified when it was set. +** +** The left-most argument is 0. +** +** Undocumented behavior: If iArg is negative then make the data available +** to all functions within the current prepared statement using iArg as an +** access code. */ -SQLITE_API void sqlite3_set_auxdata( - sqlite3_context *pCtx, +SQLITE_API void tdsqlite3_set_auxdata( + tdsqlite3_context *pCtx, int iArg, void *pAux, void (*xDelete)(void*) @@ -79034,34 +87076,32 @@ SQLITE_API void sqlite3_set_auxdata( AuxData *pAuxData; Vdbe *pVdbe = pCtx->pVdbe; - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - if( iArg<0 ) goto failed; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + assert( tdsqlite3_mutex_held(pCtx->pOut->db->mutex) ); +#ifdef SQLITE_ENABLE_STAT4 if( pVdbe==0 ) goto failed; #else assert( pVdbe!=0 ); #endif - for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){ - if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break; + for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){ + if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){ + break; + } } if( pAuxData==0 ){ - pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData)); + pAuxData = tdsqlite3DbMallocZero(pVdbe->db, sizeof(AuxData)); if( !pAuxData ) goto failed; - pAuxData->iOp = pCtx->iOp; - pAuxData->iArg = iArg; - pAuxData->pNext = pVdbe->pAuxData; + pAuxData->iAuxOp = pCtx->iOp; + pAuxData->iAuxArg = iArg; + pAuxData->pNextAux = pVdbe->pAuxData; pVdbe->pAuxData = pAuxData; - if( pCtx->fErrorOrAux==0 ){ - pCtx->isError = 0; - pCtx->fErrorOrAux = 1; - } - }else if( pAuxData->xDelete ){ - pAuxData->xDelete(pAuxData->pAux); + if( pCtx->isError==0 ) pCtx->isError = -1; + }else if( pAuxData->xDeleteAux ){ + pAuxData->xDeleteAux(pAuxData->pAux); } pAuxData->pAux = pAux; - pAuxData->xDelete = xDelete; + pAuxData->xDeleteAux = xDelete; return; failed: @@ -79080,7 +87120,7 @@ failed: ** implementations should keep their own counts within their aggregate ** context. */ -SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){ +SQLITE_API int tdsqlite3_aggregate_count(tdsqlite3_context *p){ assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize ); return p->pMem->n; } @@ -79089,7 +87129,7 @@ SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){ /* ** Return the number of columns in the result set for the statement pStmt. */ -SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){ +SQLITE_API int tdsqlite3_column_count(tdsqlite3_stmt *pStmt){ Vdbe *pVm = (Vdbe *)pStmt; return pVm ? pVm->nResColumn : 0; } @@ -79098,7 +87138,7 @@ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){ ** Return the number of values available from the current row of the ** currently executing statement pStmt. */ -SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){ +SQLITE_API int tdsqlite3_data_count(tdsqlite3_stmt *pStmt){ Vdbe *pVm = (Vdbe *)pStmt; if( pVm==0 || pVm->pResultSet==0 ) return 0; return pVm->nResColumn; @@ -79131,11 +87171,11 @@ static const Mem *columnNullValue(void){ /* .zMalloc = */ (char*)0, /* .szMalloc = */ (int)0, /* .uTemp = */ (u32)0, - /* .db = */ (sqlite3*)0, + /* .db = */ (tdsqlite3*)0, /* .xDel = */ (void(*)(void*))0, #ifdef SQLITE_DEBUG /* .pScopyFrom = */ (Mem*)0, - /* .pFiller = */ (void*)0, + /* .mScopyFlags= */ 0, #endif }; return &nullMem; @@ -79147,25 +87187,25 @@ static const Mem *columnNullValue(void){ ** If iCol is not valid, return a pointer to a Mem which has a value ** of NULL. */ -static Mem *columnMem(sqlite3_stmt *pStmt, int i){ +static Mem *columnMem(tdsqlite3_stmt *pStmt, int i){ Vdbe *pVm; Mem *pOut; pVm = (Vdbe *)pStmt; if( pVm==0 ) return (Mem*)columnNullValue(); assert( pVm->db ); - sqlite3_mutex_enter(pVm->db->mutex); + tdsqlite3_mutex_enter(pVm->db->mutex); if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){ pOut = &pVm->pResultSet[i]; }else{ - sqlite3Error(pVm->db, SQLITE_RANGE); + tdsqlite3Error(pVm->db, SQLITE_RANGE); pOut = (Mem*)columnNullValue(); } return pOut; } /* -** This function is called after invoking an sqlite3_value_XXX function on a +** This function is called after invoking an tdsqlite3_value_XXX function on a ** column value (i.e. a value returned by evaluating an SQL expression in the ** select list of a SELECT statement) that may cause a malloc() failure. If ** malloc() has failed, the threads mallocFailed flag is cleared and the result @@ -79173,38 +87213,38 @@ static Mem *columnMem(sqlite3_stmt *pStmt, int i){ ** ** Specifically, this is called from within: ** -** sqlite3_column_int() -** sqlite3_column_int64() -** sqlite3_column_text() -** sqlite3_column_text16() -** sqlite3_column_real() -** sqlite3_column_bytes() -** sqlite3_column_bytes16() +** tdsqlite3_column_int() +** tdsqlite3_column_int64() +** tdsqlite3_column_text() +** tdsqlite3_column_text16() +** tdsqlite3_column_real() +** tdsqlite3_column_bytes() +** tdsqlite3_column_bytes16() ** sqiite3_column_blob() */ -static void columnMallocFailure(sqlite3_stmt *pStmt) +static void columnMallocFailure(tdsqlite3_stmt *pStmt) { /* If malloc() failed during an encoding conversion within an - ** sqlite3_column_XXX API, then set the return code of the statement to + ** tdsqlite3_column_XXX API, then set the return code of the statement to ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR ** and _finalize() will return NOMEM. */ Vdbe *p = (Vdbe *)pStmt; if( p ){ assert( p->db!=0 ); - assert( sqlite3_mutex_held(p->db->mutex) ); - p->rc = sqlite3ApiExit(p->db, p->rc); - sqlite3_mutex_leave(p->db->mutex); + assert( tdsqlite3_mutex_held(p->db->mutex) ); + p->rc = tdsqlite3ApiExit(p->db, p->rc); + tdsqlite3_mutex_leave(p->db->mutex); } } -/**************************** sqlite3_column_ ******************************* +/**************************** tdsqlite3_column_ ******************************* ** The following routines are used to access elements of the current row ** in the result set. */ -SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){ +SQLITE_API const void *tdsqlite3_column_blob(tdsqlite3_stmt *pStmt, int i){ const void *val; - val = sqlite3_value_blob( columnMem(pStmt,i) ); + val = tdsqlite3_value_blob( columnMem(pStmt,i) ); /* Even though there is no encoding conversion, value_blob() might ** need to call malloc() to expand the result of a zeroblob() ** expression. @@ -79212,54 +87252,54 @@ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){ columnMallocFailure(pStmt); return val; } -SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){ - int val = sqlite3_value_bytes( columnMem(pStmt,i) ); +SQLITE_API int tdsqlite3_column_bytes(tdsqlite3_stmt *pStmt, int i){ + int val = tdsqlite3_value_bytes( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } -SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){ - int val = sqlite3_value_bytes16( columnMem(pStmt,i) ); +SQLITE_API int tdsqlite3_column_bytes16(tdsqlite3_stmt *pStmt, int i){ + int val = tdsqlite3_value_bytes16( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } -SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){ - double val = sqlite3_value_double( columnMem(pStmt,i) ); +SQLITE_API double tdsqlite3_column_double(tdsqlite3_stmt *pStmt, int i){ + double val = tdsqlite3_value_double( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } -SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){ - int val = sqlite3_value_int( columnMem(pStmt,i) ); +SQLITE_API int tdsqlite3_column_int(tdsqlite3_stmt *pStmt, int i){ + int val = tdsqlite3_value_int( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } -SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){ - sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) ); +SQLITE_API sqlite_int64 tdsqlite3_column_int64(tdsqlite3_stmt *pStmt, int i){ + sqlite_int64 val = tdsqlite3_value_int64( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } -SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){ - const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) ); +SQLITE_API const unsigned char *tdsqlite3_column_text(tdsqlite3_stmt *pStmt, int i){ + const unsigned char *val = tdsqlite3_value_text( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } -SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){ +SQLITE_API tdsqlite3_value *tdsqlite3_column_value(tdsqlite3_stmt *pStmt, int i){ Mem *pOut = columnMem(pStmt, i); if( pOut->flags&MEM_Static ){ pOut->flags &= ~MEM_Static; pOut->flags |= MEM_Ephem; } columnMallocFailure(pStmt); - return (sqlite3_value *)pOut; + return (tdsqlite3_value *)pOut; } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){ - const void *val = sqlite3_value_text16( columnMem(pStmt,i) ); +SQLITE_API const void *tdsqlite3_column_text16(tdsqlite3_stmt *pStmt, int i){ + const void *val = tdsqlite3_value_text16( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return val; } #endif /* SQLITE_OMIT_UTF16 */ -SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){ - int iType = sqlite3_value_type( columnMem(pStmt,i) ); +SQLITE_API int tdsqlite3_column_type(tdsqlite3_stmt *pStmt, int i){ + int iType = tdsqlite3_value_type( columnMem(pStmt,i) ); columnMallocFailure(pStmt); return iType; } @@ -79281,15 +87321,15 @@ SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){ ** or a constant) then useTypes 2, 3, and 4 return NULL. */ static const void *columnName( - sqlite3_stmt *pStmt, - int N, - const void *(*xFunc)(Mem*), - int useType + tdsqlite3_stmt *pStmt, /* The statement */ + int N, /* Which column to get the name for */ + int useUtf16, /* True to return the name as UTF16 */ + int useType /* What type of name */ ){ const void *ret; Vdbe *p; int n; - sqlite3 *db; + tdsqlite3 *db; #ifdef SQLITE_ENABLE_API_ARMOR if( pStmt==0 ){ (void)SQLITE_MISUSE_BKPT; @@ -79300,20 +87340,27 @@ static const void *columnName( p = (Vdbe *)pStmt; db = p->db; assert( db!=0 ); - n = sqlite3_column_count(pStmt); + n = tdsqlite3_column_count(pStmt); if( N<n && N>=0 ){ N += useType*n; - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); assert( db->mallocFailed==0 ); - ret = xFunc(&p->aColName[N]); - /* A malloc may have failed inside of the xFunc() call. If this +#ifndef SQLITE_OMIT_UTF16 + if( useUtf16 ){ + ret = tdsqlite3_value_text16((tdsqlite3_value*)&p->aColName[N]); + }else +#endif + { + ret = tdsqlite3_value_text((tdsqlite3_value*)&p->aColName[N]); + } + /* A malloc may have failed inside of the _text() call. If this ** is the case, clear the mallocFailed flag and return NULL. */ if( db->mallocFailed ){ - sqlite3OomClear(db); + tdsqlite3OomClear(db); ret = 0; } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); } return ret; } @@ -79322,14 +87369,12 @@ static const void *columnName( ** Return the name of the Nth column of the result set returned by SQL ** statement pStmt. */ -SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME); +SQLITE_API const char *tdsqlite3_column_name(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 0, COLNAME_NAME); } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME); +SQLITE_API const void *tdsqlite3_column_name16(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 1, COLNAME_NAME); } #endif @@ -79347,14 +87392,12 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){ ** Return the column declaration type (if applicable) of the 'i'th column ** of the result set of SQL statement pStmt. */ -SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE); +SQLITE_API const char *tdsqlite3_column_decltype(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 0, COLNAME_DECLTYPE); } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE); +SQLITE_API const void *tdsqlite3_column_decltype16(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 1, COLNAME_DECLTYPE); } #endif /* SQLITE_OMIT_UTF16 */ #endif /* SQLITE_OMIT_DECLTYPE */ @@ -79365,14 +87408,12 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){ ** NULL is returned if the result column is an expression or constant or ** anything else which is not an unambiguous reference to a database column. */ -SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE); +SQLITE_API const char *tdsqlite3_column_database_name(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 0, COLNAME_DATABASE); } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE); +SQLITE_API const void *tdsqlite3_column_database_name16(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 1, COLNAME_DATABASE); } #endif /* SQLITE_OMIT_UTF16 */ @@ -79381,14 +87422,12 @@ SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N ** NULL is returned if the result column is an expression or constant or ** anything else which is not an unambiguous reference to a database column. */ -SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE); +SQLITE_API const char *tdsqlite3_column_table_name(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 0, COLNAME_TABLE); } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE); +SQLITE_API const void *tdsqlite3_column_table_name16(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 1, COLNAME_TABLE); } #endif /* SQLITE_OMIT_UTF16 */ @@ -79397,20 +87436,18 @@ SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){ ** NULL is returned if the result column is an expression or constant or ** anything else which is not an unambiguous reference to a database column. */ -SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN); +SQLITE_API const char *tdsqlite3_column_origin_name(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 0, COLNAME_COLUMN); } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN); +SQLITE_API const void *tdsqlite3_column_origin_name16(tdsqlite3_stmt *pStmt, int N){ + return columnName(pStmt, N, 1, COLNAME_COLUMN); } #endif /* SQLITE_OMIT_UTF16 */ #endif /* SQLITE_ENABLE_COLUMN_METADATA */ -/******************************* sqlite3_bind_ *************************** +/******************************* tdsqlite3_bind_ *************************** ** ** Routines used to attach values to wildcards in a compiled SQL statement. */ @@ -79430,24 +87467,24 @@ static int vdbeUnbind(Vdbe *p, int i){ if( vdbeSafetyNotNull(p) ){ return SQLITE_MISUSE_BKPT; } - sqlite3_mutex_enter(p->db->mutex); + tdsqlite3_mutex_enter(p->db->mutex); if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){ - sqlite3Error(p->db, SQLITE_MISUSE); - sqlite3_mutex_leave(p->db->mutex); - sqlite3_log(SQLITE_MISUSE, + tdsqlite3Error(p->db, SQLITE_MISUSE); + tdsqlite3_mutex_leave(p->db->mutex); + tdsqlite3_log(SQLITE_MISUSE, "bind on a busy prepared statement: [%s]", p->zSql); return SQLITE_MISUSE_BKPT; } if( i<1 || i>p->nVar ){ - sqlite3Error(p->db, SQLITE_RANGE); - sqlite3_mutex_leave(p->db->mutex); + tdsqlite3Error(p->db, SQLITE_RANGE); + tdsqlite3_mutex_leave(p->db->mutex); return SQLITE_RANGE; } i--; pVar = &p->aVar[i]; - sqlite3VdbeMemRelease(pVar); + tdsqlite3VdbeMemRelease(pVar); pVar->flags = MEM_Null; - sqlite3Error(p->db, SQLITE_OK); + p->db->errCode = SQLITE_OK; /* If the bit corresponding to this variable in Vdbe.expmask is set, then ** binding a new value to this variable invalidates the current query plan. @@ -79455,12 +87492,11 @@ static int vdbeUnbind(Vdbe *p, int i){ ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host ** parameter in the WHERE clause might influence the choice of query plan ** for a statement, then the statement will be automatically recompiled, - ** as if there had been a schema change, on the first sqlite3_step() call + ** as if there had been a schema change, on the first tdsqlite3_step() call ** following any change to the bindings of that parameter. */ - if( p->isPrepareV2 && - ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff) - ){ + assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 ); + if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){ p->expired = 1; } return SQLITE_OK; @@ -79470,7 +87506,7 @@ static int vdbeUnbind(Vdbe *p, int i){ ** Bind a text or BLOB value. */ static int bindText( - sqlite3_stmt *pStmt, /* The statement to bind against */ + tdsqlite3_stmt *pStmt, /* The statement to bind against */ int i, /* Index of the parameter to bind */ const void *zData, /* Pointer to the data to be bound */ int nData, /* Number of bytes of data to be bound */ @@ -79485,14 +87521,16 @@ static int bindText( if( rc==SQLITE_OK ){ if( zData!=0 ){ pVar = &p->aVar[i-1]; - rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel); + rc = tdsqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel); if( rc==SQLITE_OK && encoding!=0 ){ - rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db)); + rc = tdsqlite3VdbeChangeEncoding(pVar, ENC(p->db)); + } + if( rc ){ + tdsqlite3Error(p->db, rc); + rc = tdsqlite3ApiExit(p->db, rc); } - sqlite3Error(p->db, rc); - rc = sqlite3ApiExit(p->db, rc); } - sqlite3_mutex_leave(p->db->mutex); + tdsqlite3_mutex_leave(p->db->mutex); }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){ xDel((void*)zData); } @@ -79503,8 +87541,8 @@ static int bindText( /* ** Bind a blob value to an SQL statement variable. */ -SQLITE_API int sqlite3_bind_blob( - sqlite3_stmt *pStmt, +SQLITE_API int tdsqlite3_bind_blob( + tdsqlite3_stmt *pStmt, int i, const void *zData, int nData, @@ -79515,11 +87553,11 @@ SQLITE_API int sqlite3_bind_blob( #endif return bindText(pStmt, i, zData, nData, xDel, 0); } -SQLITE_API int sqlite3_bind_blob64( - sqlite3_stmt *pStmt, +SQLITE_API int tdsqlite3_bind_blob64( + tdsqlite3_stmt *pStmt, int i, const void *zData, - sqlite3_uint64 nData, + tdsqlite3_uint64 nData, void (*xDel)(void*) ){ assert( xDel!=SQLITE_DYNAMIC ); @@ -79529,40 +87567,58 @@ SQLITE_API int sqlite3_bind_blob64( return bindText(pStmt, i, zData, (int)nData, xDel, 0); } } -SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){ +SQLITE_API int tdsqlite3_bind_double(tdsqlite3_stmt *pStmt, int i, double rValue){ int rc; Vdbe *p = (Vdbe *)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ - sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue); - sqlite3_mutex_leave(p->db->mutex); + tdsqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue); + tdsqlite3_mutex_leave(p->db->mutex); } return rc; } -SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){ - return sqlite3_bind_int64(p, i, (i64)iValue); +SQLITE_API int tdsqlite3_bind_int(tdsqlite3_stmt *p, int i, int iValue){ + return tdsqlite3_bind_int64(p, i, (i64)iValue); } -SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){ +SQLITE_API int tdsqlite3_bind_int64(tdsqlite3_stmt *pStmt, int i, sqlite_int64 iValue){ int rc; Vdbe *p = (Vdbe *)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ - sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue); - sqlite3_mutex_leave(p->db->mutex); + tdsqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue); + tdsqlite3_mutex_leave(p->db->mutex); + } + return rc; +} +SQLITE_API int tdsqlite3_bind_null(tdsqlite3_stmt *pStmt, int i){ + int rc; + Vdbe *p = (Vdbe*)pStmt; + rc = vdbeUnbind(p, i); + if( rc==SQLITE_OK ){ + tdsqlite3_mutex_leave(p->db->mutex); } return rc; } -SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){ +SQLITE_API int tdsqlite3_bind_pointer( + tdsqlite3_stmt *pStmt, + int i, + void *pPtr, + const char *zPTtype, + void (*xDestructor)(void*) +){ int rc; Vdbe *p = (Vdbe*)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ - sqlite3_mutex_leave(p->db->mutex); + tdsqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor); + tdsqlite3_mutex_leave(p->db->mutex); + }else if( xDestructor ){ + xDestructor(pPtr); } return rc; } -SQLITE_API int sqlite3_bind_text( - sqlite3_stmt *pStmt, +SQLITE_API int tdsqlite3_bind_text( + tdsqlite3_stmt *pStmt, int i, const char *zData, int nData, @@ -79570,11 +87626,11 @@ SQLITE_API int sqlite3_bind_text( ){ return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8); } -SQLITE_API int sqlite3_bind_text64( - sqlite3_stmt *pStmt, +SQLITE_API int tdsqlite3_bind_text64( + tdsqlite3_stmt *pStmt, int i, const char *zData, - sqlite3_uint64 nData, + tdsqlite3_uint64 nData, void (*xDel)(void*), unsigned char enc ){ @@ -79587,8 +87643,8 @@ SQLITE_API int sqlite3_bind_text64( } } #ifndef SQLITE_OMIT_UTF16 -SQLITE_API int sqlite3_bind_text16( - sqlite3_stmt *pStmt, +SQLITE_API int tdsqlite3_bind_text16( + tdsqlite3_stmt *pStmt, int i, const void *zData, int nData, @@ -79597,22 +87653,22 @@ SQLITE_API int sqlite3_bind_text16( return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE); } #endif /* SQLITE_OMIT_UTF16 */ -SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){ +SQLITE_API int tdsqlite3_bind_value(tdsqlite3_stmt *pStmt, int i, const tdsqlite3_value *pValue){ int rc; - switch( sqlite3_value_type((sqlite3_value*)pValue) ){ + switch( tdsqlite3_value_type((tdsqlite3_value*)pValue) ){ case SQLITE_INTEGER: { - rc = sqlite3_bind_int64(pStmt, i, pValue->u.i); + rc = tdsqlite3_bind_int64(pStmt, i, pValue->u.i); break; } case SQLITE_FLOAT: { - rc = sqlite3_bind_double(pStmt, i, pValue->u.r); + rc = tdsqlite3_bind_double(pStmt, i, pValue->u.r); break; } case SQLITE_BLOB: { if( pValue->flags & MEM_Zero ){ - rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero); + rc = tdsqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero); }else{ - rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT); + rc = tdsqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT); } break; } @@ -79622,34 +87678,34 @@ SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_valu break; } default: { - rc = sqlite3_bind_null(pStmt, i); + rc = tdsqlite3_bind_null(pStmt, i); break; } } return rc; } -SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){ +SQLITE_API int tdsqlite3_bind_zeroblob(tdsqlite3_stmt *pStmt, int i, int n){ int rc; Vdbe *p = (Vdbe *)pStmt; rc = vdbeUnbind(p, i); if( rc==SQLITE_OK ){ - sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n); - sqlite3_mutex_leave(p->db->mutex); + tdsqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n); + tdsqlite3_mutex_leave(p->db->mutex); } return rc; } -SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){ +SQLITE_API int tdsqlite3_bind_zeroblob64(tdsqlite3_stmt *pStmt, int i, tdsqlite3_uint64 n){ int rc; Vdbe *p = (Vdbe *)pStmt; - sqlite3_mutex_enter(p->db->mutex); + tdsqlite3_mutex_enter(p->db->mutex); if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){ rc = SQLITE_TOOBIG; }else{ assert( (n & 0x7FFFFFFF)==n ); - rc = sqlite3_bind_zeroblob(pStmt, i, n); + rc = tdsqlite3_bind_zeroblob(pStmt, i, n); } - rc = sqlite3ApiExit(p->db, rc); - sqlite3_mutex_leave(p->db->mutex); + rc = tdsqlite3ApiExit(p->db, rc); + tdsqlite3_mutex_leave(p->db->mutex); return rc; } @@ -79657,7 +87713,7 @@ SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint6 ** Return the number of wildcards that can be potentially bound to. ** This routine is added to support DBD::SQLite. */ -SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){ +SQLITE_API int tdsqlite3_bind_parameter_count(tdsqlite3_stmt *pStmt){ Vdbe *p = (Vdbe*)pStmt; return p ? p->nVar : 0; } @@ -79668,12 +87724,10 @@ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){ ** ** The result is always UTF-8. */ -SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){ +SQLITE_API const char *tdsqlite3_bind_parameter_name(tdsqlite3_stmt *pStmt, int i){ Vdbe *p = (Vdbe*)pStmt; - if( p==0 || i<1 || i>p->nzVar ){ - return 0; - } - return p->azVar[i-1]; + if( p==0 ) return 0; + return tdsqlite3VListNumToName(p->pVList, i); } /* @@ -79681,46 +87735,35 @@ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){ ** with that name. If there is no variable with the given name, ** return 0. */ -SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){ - int i; - if( p==0 ){ - return 0; - } - if( zName ){ - for(i=0; i<p->nzVar; i++){ - const char *z = p->azVar[i]; - if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){ - return i+1; - } - } - } - return 0; +SQLITE_PRIVATE int tdsqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){ + if( p==0 || zName==0 ) return 0; + return tdsqlite3VListNameToNum(p->pVList, zName, nName); } -SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){ - return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName)); +SQLITE_API int tdsqlite3_bind_parameter_index(tdsqlite3_stmt *pStmt, const char *zName){ + return tdsqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, tdsqlite3Strlen30(zName)); } /* ** Transfer all bindings from the first statement over to the second. */ -SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ +SQLITE_PRIVATE int tdsqlite3TransferBindings(tdsqlite3_stmt *pFromStmt, tdsqlite3_stmt *pToStmt){ Vdbe *pFrom = (Vdbe*)pFromStmt; Vdbe *pTo = (Vdbe*)pToStmt; int i; assert( pTo->db==pFrom->db ); assert( pTo->nVar==pFrom->nVar ); - sqlite3_mutex_enter(pTo->db->mutex); + tdsqlite3_mutex_enter(pTo->db->mutex); for(i=0; i<pFrom->nVar; i++){ - sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]); + tdsqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]); } - sqlite3_mutex_leave(pTo->db->mutex); + tdsqlite3_mutex_leave(pTo->db->mutex); return SQLITE_OK; } #ifndef SQLITE_OMIT_DEPRECATED /* ** Deprecated external interface. Internal/core SQLite code -** should call sqlite3TransferBindings. +** should call tdsqlite3TransferBindings. ** ** It is misuse to call this routine with statements from different ** database connections. But as this is a deprecated interface, we @@ -79730,29 +87773,31 @@ SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise ** SQLITE_OK is returned. */ -SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ +SQLITE_API int tdsqlite3_transfer_bindings(tdsqlite3_stmt *pFromStmt, tdsqlite3_stmt *pToStmt){ Vdbe *pFrom = (Vdbe*)pFromStmt; Vdbe *pTo = (Vdbe*)pToStmt; if( pFrom->nVar!=pTo->nVar ){ return SQLITE_ERROR; } - if( pTo->isPrepareV2 && pTo->expmask ){ + assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 ); + if( pTo->expmask ){ pTo->expired = 1; } - if( pFrom->isPrepareV2 && pFrom->expmask ){ + assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 ); + if( pFrom->expmask ){ pFrom->expired = 1; } - return sqlite3TransferBindings(pFromStmt, pToStmt); + return tdsqlite3TransferBindings(pFromStmt, pToStmt); } #endif /* -** Return the sqlite3* database handle to which the prepared statement given +** Return the tdsqlite3* database handle to which the prepared statement given ** in the argument belongs. This is the same database handle that was -** the first argument to the sqlite3_prepare() that was used to create +** the first argument to the tdsqlite3_prepare() that was used to create ** the statement in the first place. */ -SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){ +SQLITE_API tdsqlite3 *tdsqlite3_db_handle(tdsqlite3_stmt *pStmt){ return pStmt ? ((Vdbe*)pStmt)->db : 0; } @@ -79760,14 +87805,22 @@ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){ ** Return true if the prepared statement is guaranteed to not modify the ** database. */ -SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){ +SQLITE_API int tdsqlite3_stmt_readonly(tdsqlite3_stmt *pStmt){ return pStmt ? ((Vdbe*)pStmt)->readOnly : 1; } /* +** Return 1 if the statement is an EXPLAIN and return 2 if the +** statement is an EXPLAIN QUERY PLAN +*/ +SQLITE_API int tdsqlite3_stmt_isexplain(tdsqlite3_stmt *pStmt){ + return pStmt ? ((Vdbe*)pStmt)->explain : 0; +} + +/* ** Return true if the prepared statement is in need of being reset. */ -SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){ +SQLITE_API int tdsqlite3_stmt_busy(tdsqlite3_stmt *pStmt){ Vdbe *v = (Vdbe*)pStmt; return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0; } @@ -79778,45 +87831,58 @@ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){ ** prepared statement for the database connection. Return NULL if there ** are no more. */ -SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){ - sqlite3_stmt *pNext; +SQLITE_API tdsqlite3_stmt *tdsqlite3_next_stmt(tdsqlite3 *pDb, tdsqlite3_stmt *pStmt){ + tdsqlite3_stmt *pNext; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(pDb) ){ + if( !tdsqlite3SafetyCheckOk(pDb) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - sqlite3_mutex_enter(pDb->mutex); + tdsqlite3_mutex_enter(pDb->mutex); if( pStmt==0 ){ - pNext = (sqlite3_stmt*)pDb->pVdbe; + pNext = (tdsqlite3_stmt*)pDb->pVdbe; }else{ - pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext; + pNext = (tdsqlite3_stmt*)((Vdbe*)pStmt)->pNext; } - sqlite3_mutex_leave(pDb->mutex); + tdsqlite3_mutex_leave(pDb->mutex); return pNext; } /* ** Return the value of a status counter for a prepared statement */ -SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){ +SQLITE_API int tdsqlite3_stmt_status(tdsqlite3_stmt *pStmt, int op, int resetFlag){ Vdbe *pVdbe = (Vdbe*)pStmt; u32 v; #ifdef SQLITE_ENABLE_API_ARMOR - if( !pStmt ){ + if( !pStmt + || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter))) + ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - v = pVdbe->aCounter[op]; - if( resetFlag ) pVdbe->aCounter[op] = 0; + if( op==SQLITE_STMTSTATUS_MEMUSED ){ + tdsqlite3 *db = pVdbe->db; + tdsqlite3_mutex_enter(db->mutex); + v = 0; + db->pnBytesFreed = (int*)&v; + tdsqlite3VdbeClearObject(db, pVdbe); + tdsqlite3DbFree(db, pVdbe); + db->pnBytesFreed = 0; + tdsqlite3_mutex_leave(db->mutex); + }else{ + v = pVdbe->aCounter[op]; + if( resetFlag ) pVdbe->aCounter[op] = 0; + } return (int)v; } /* ** Return the SQL associated with a prepared statement */ -SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){ +SQLITE_API const char *tdsqlite3_sql(tdsqlite3_stmt *pStmt){ Vdbe *p = (Vdbe *)pStmt; return p ? p->zSql : 0; } @@ -79824,28 +87890,44 @@ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){ /* ** Return the SQL associated with a prepared statement with ** bound parameters expanded. Space to hold the returned string is -** obtained from sqlite3_malloc(). The caller is responsible for -** freeing the returned string by passing it to sqlite3_free(). +** obtained from tdsqlite3_malloc(). The caller is responsible for +** freeing the returned string by passing it to tdsqlite3_free(). ** ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of ** expanded bound parameters. */ -SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){ +SQLITE_API char *tdsqlite3_expanded_sql(tdsqlite3_stmt *pStmt){ #ifdef SQLITE_OMIT_TRACE return 0; #else char *z = 0; - const char *zSql = sqlite3_sql(pStmt); + const char *zSql = tdsqlite3_sql(pStmt); if( zSql ){ Vdbe *p = (Vdbe *)pStmt; - sqlite3_mutex_enter(p->db->mutex); - z = sqlite3VdbeExpandSql(p, zSql); - sqlite3_mutex_leave(p->db->mutex); + tdsqlite3_mutex_enter(p->db->mutex); + z = tdsqlite3VdbeExpandSql(p, zSql); + tdsqlite3_mutex_leave(p->db->mutex); } return z; #endif } +#ifdef SQLITE_ENABLE_NORMALIZE +/* +** Return the normalized SQL associated with a prepared statement. +*/ +SQLITE_API const char *tdsqlite3_normalized_sql(tdsqlite3_stmt *pStmt){ + Vdbe *p = (Vdbe *)pStmt; + if( p==0 ) return 0; + if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){ + tdsqlite3_mutex_enter(p->db->mutex); + p->zNormSql = tdsqlite3Normalize(p, p->zSql); + tdsqlite3_mutex_leave(p->db->mutex); + } + return p->zNormSql; +} +#endif /* SQLITE_ENABLE_NORMALIZE */ + #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* ** Allocate and populate an UnpackedRecord structure based on the serialized @@ -79857,13 +87939,12 @@ static UnpackedRecord *vdbeUnpackRecord( int nKey, const void *pKey ){ - char *dummy; /* Dummy argument for AllocUnpackedRecord() */ UnpackedRecord *pRet; /* Return value */ - pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy); + pRet = tdsqlite3VdbeAllocUnpackedRecord(pKeyInfo); if( pRet ){ - memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1)); - sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet); + memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1)); + tdsqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet); } return pRet; } @@ -79872,8 +87953,9 @@ static UnpackedRecord *vdbeUnpackRecord( ** This function is called from within a pre-update callback to retrieve ** a field of the row currently being updated or deleted. */ -SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){ +SQLITE_API int tdsqlite3_preupdate_old(tdsqlite3 *db, int iIdx, tdsqlite3_value **ppValue){ PreUpdate *p = db->pPreUpdate; + Mem *pMem; int rc = SQLITE_OK; /* Test that this call is being made from within an SQLITE_DELETE or @@ -79882,6 +87964,9 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVa rc = SQLITE_MISUSE_BKPT; goto preupdate_old_out; } + if( p->pPk ){ + iIdx = tdsqlite3TableColumnToIndex(p->pPk, iIdx); + } if( iIdx>=p->pCsr->nField || iIdx<0 ){ rc = SQLITE_RANGE; goto preupdate_old_out; @@ -79892,38 +87977,37 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVa u32 nRec; u8 *aRec; - nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor); - aRec = sqlite3DbMallocRaw(db, nRec); + nRec = tdsqlite3BtreePayloadSize(p->pCsr->uc.pCursor); + aRec = tdsqlite3DbMallocRaw(db, nRec); if( !aRec ) goto preupdate_old_out; - rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec); + rc = tdsqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec); if( rc==SQLITE_OK ){ p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec); if( !p->pUnpacked ) rc = SQLITE_NOMEM; } if( rc!=SQLITE_OK ){ - sqlite3DbFree(db, aRec); + tdsqlite3DbFree(db, aRec); goto preupdate_old_out; } p->aRecord = aRec; } - if( iIdx>=p->pUnpacked->nField ){ - *ppValue = (sqlite3_value *)columnNullValue(); - }else{ - Mem *pMem = *ppValue = &p->pUnpacked->aMem[iIdx]; - *ppValue = &p->pUnpacked->aMem[iIdx]; - if( iIdx==p->pTab->iPKey ){ - sqlite3VdbeMemSetInt64(pMem, p->iKey1); - }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){ - if( pMem->flags & MEM_Int ){ - sqlite3VdbeMemRealify(pMem); - } + pMem = *ppValue = &p->pUnpacked->aMem[iIdx]; + if( iIdx==p->pTab->iPKey ){ + tdsqlite3VdbeMemSetInt64(pMem, p->iKey1); + }else if( iIdx>=p->pUnpacked->nField ){ + *ppValue = (tdsqlite3_value *)columnNullValue(); + }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){ + if( pMem->flags & (MEM_Int|MEM_IntReal) ){ + testcase( pMem->flags & MEM_Int ); + testcase( pMem->flags & MEM_IntReal ); + tdsqlite3VdbeMemRealify(pMem); } } preupdate_old_out: - sqlite3Error(db, rc); - return sqlite3ApiExit(db, rc); + tdsqlite3Error(db, rc); + return tdsqlite3ApiExit(db, rc); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ @@ -79932,9 +88016,9 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVa ** This function is called from within a pre-update callback to retrieve ** the number of columns in the row being updated, deleted or inserted. */ -SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){ +SQLITE_API int tdsqlite3_preupdate_count(tdsqlite3 *db){ PreUpdate *p = db->pPreUpdate; - return (p ? p->keyinfo.nField : 0); + return (p ? p->keyinfo.nKeyField : 0); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ @@ -79950,7 +88034,7 @@ SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){ ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL ** or SET DEFAULT action is considered a trigger. */ -SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){ +SQLITE_API int tdsqlite3_preupdate_depth(tdsqlite3 *db){ PreUpdate *p = db->pPreUpdate; return (p ? p->v->nFrame : 0); } @@ -79961,7 +88045,7 @@ SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){ ** This function is called from within a pre-update callback to retrieve ** a field of the row currently being updated or inserted. */ -SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){ +SQLITE_API int tdsqlite3_preupdate_new(tdsqlite3 *db, int iIdx, tdsqlite3_value **ppValue){ PreUpdate *p = db->pPreUpdate; int rc = SQLITE_OK; Mem *pMem; @@ -79970,6 +88054,9 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa rc = SQLITE_MISUSE_BKPT; goto preupdate_new_out; } + if( p->pPk && p->op!=SQLITE_UPDATE ){ + iIdx = tdsqlite3TableColumnToIndex(p->pPk, iIdx); + } if( iIdx>=p->pCsr->nField || iIdx<0 ){ rc = SQLITE_RANGE; goto preupdate_new_out; @@ -79990,13 +88077,11 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa } p->pNewUnpacked = pUnpack; } - if( iIdx>=pUnpack->nField ){ - pMem = (sqlite3_value *)columnNullValue(); - }else{ - pMem = &pUnpack->aMem[iIdx]; - if( iIdx==p->pTab->iPKey ){ - sqlite3VdbeMemSetInt64(pMem, p->iKey2); - } + pMem = &pUnpack->aMem[iIdx]; + if( iIdx==p->pTab->iPKey ){ + tdsqlite3VdbeMemSetInt64(pMem, p->iKey2); + }else if( iIdx>=pUnpack->nField ){ + pMem = (tdsqlite3_value *)columnNullValue(); } }else{ /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required @@ -80006,7 +88091,7 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa */ assert( p->op==SQLITE_UPDATE ); if( !p->aNew ){ - p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField); + p->aNew = (Mem *)tdsqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField); if( !p->aNew ){ rc = SQLITE_NOMEM; goto preupdate_new_out; @@ -80016,9 +88101,9 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa pMem = &p->aNew[iIdx]; if( pMem->flags==0 ){ if( iIdx==p->pTab->iPKey ){ - sqlite3VdbeMemSetInt64(pMem, p->iKey2); + tdsqlite3VdbeMemSetInt64(pMem, p->iKey2); }else{ - rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]); + rc = tdsqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]); if( rc!=SQLITE_OK ) goto preupdate_new_out; } } @@ -80026,8 +88111,8 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa *ppValue = pMem; preupdate_new_out: - sqlite3Error(db, rc); - return sqlite3ApiExit(db, rc); + tdsqlite3Error(db, rc); + return tdsqlite3ApiExit(db, rc); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ @@ -80035,8 +88120,8 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa /* ** Return status data for a single loop within query pStmt. */ -SQLITE_API int sqlite3_stmt_scanstatus( - sqlite3_stmt *pStmt, /* Prepared statement being queried */ +SQLITE_API int tdsqlite3_stmt_scanstatus( + tdsqlite3_stmt *pStmt, /* Prepared statement being queried */ int idx, /* Index of loop to report on */ int iScanStatusOp, /* Which metric to return */ void *pOut /* OUT: Write the answer here */ @@ -80047,11 +88132,11 @@ SQLITE_API int sqlite3_stmt_scanstatus( pScan = &p->aScan[idx]; switch( iScanStatusOp ){ case SQLITE_SCANSTAT_NLOOP: { - *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop]; + *(tdsqlite3_int64*)pOut = p->anExec[pScan->addrLoop]; break; } case SQLITE_SCANSTAT_NVISIT: { - *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit]; + *(tdsqlite3_int64*)pOut = p->anExec[pScan->addrVisit]; break; } case SQLITE_SCANSTAT_EST: { @@ -80061,7 +88146,7 @@ SQLITE_API int sqlite3_stmt_scanstatus( x += 10; r *= 0.5; } - *(double*)pOut = r*sqlite3LogEstToInt(x); + *(double*)pOut = r*tdsqlite3LogEstToInt(x); break; } case SQLITE_SCANSTAT_NAME: { @@ -80092,9 +88177,9 @@ SQLITE_API int sqlite3_stmt_scanstatus( } /* -** Zero all counters associated with the sqlite3_stmt_scanstatus() data. +** Zero all counters associated with the tdsqlite3_stmt_scanstatus() data. */ -SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){ +SQLITE_API void tdsqlite3_stmt_scanstatus_reset(tdsqlite3_stmt *pStmt){ Vdbe *p = (Vdbe*)pStmt; memset(p->anExec, 0, p->nOp * sizeof(i64)); } @@ -80115,7 +88200,7 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){ ************************************************************************* ** ** This file contains code used to insert the values of host parameters -** (aka "wildcards") into the SQL text output by sqlite3_trace(). +** (aka "wildcards") into the SQL text output by tdsqlite3_trace(). ** ** The Vdbe parse-tree explainer is also found here. */ @@ -80137,7 +88222,7 @@ static int findNextHostParameter(const char *zSql, int *pnToken){ *pnToken = 0; while( zSql[0] ){ - n = sqlite3GetToken((u8*)zSql, &tokenType); + n = tdsqlite3GetToken((u8*)zSql, &tokenType); assert( n>0 && tokenType!=TK_ILLEGAL ); if( tokenType==TK_VARIABLE ){ *pnToken = n; @@ -80151,7 +88236,7 @@ static int findNextHostParameter(const char *zSql, int *pnToken){ /* ** This function returns a pointer to a nul-terminated string in memory -** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the +** obtained from tdsqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the ** string contains a copy of zRawSql but with host parameters expanded to ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, ** then the returned string holds a copy of zRawSql with "-- " prepended @@ -80173,11 +88258,11 @@ static int findNextHostParameter(const char *zSql, int *pnToken){ ** parameter index is known, locate the value in p->aVar[]. Then render ** the value as a literal in place of the host parameter name. */ -SQLITE_PRIVATE char *sqlite3VdbeExpandSql( +SQLITE_PRIVATE char *tdsqlite3VdbeExpandSql( Vdbe *p, /* The prepared statement being evaluated */ const char *zRawSql /* Raw text of the SQL statement */ ){ - sqlite3 *db; /* The database connection */ + tdsqlite3 *db; /* The database connection */ int idx = 0; /* Index of a host parameter */ int nextIndex = 1; /* Index of next ? host parameter */ int n; /* Length of a token prefix */ @@ -80186,35 +88271,35 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( Mem *pVar; /* Value of a host parameter */ StrAccum out; /* Accumulate the output here */ #ifndef SQLITE_OMIT_UTF16 - Mem utf8; /* Used to convert UTF16 parameters into UTF8 for display */ + Mem utf8; /* Used to convert UTF16 into UTF8 for display */ #endif char zBase[100]; /* Initial working space */ db = p->db; - sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), + tdsqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), db->aLimit[SQLITE_LIMIT_LENGTH]); if( db->nVdbeExec>1 ){ while( *zRawSql ){ const char *zStart = zRawSql; while( *(zRawSql++)!='\n' && *zRawSql ); - sqlite3StrAccumAppend(&out, "-- ", 3); + tdsqlite3_str_append(&out, "-- ", 3); assert( (zRawSql - zStart) > 0 ); - sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart)); + tdsqlite3_str_append(&out, zStart, (int)(zRawSql-zStart)); } }else if( p->nVar==0 ){ - sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql)); + tdsqlite3_str_append(&out, zRawSql, tdsqlite3Strlen30(zRawSql)); }else{ while( zRawSql[0] ){ n = findNextHostParameter(zRawSql, &nToken); assert( n>0 ); - sqlite3StrAccumAppend(&out, zRawSql, n); + tdsqlite3_str_append(&out, zRawSql, n); zRawSql += n; assert( zRawSql[0] || nToken==0 ); if( nToken==0 ) break; if( zRawSql[0]=='?' ){ if( nToken>1 ){ - assert( sqlite3Isdigit(zRawSql[1]) ); - sqlite3GetInt32(&zRawSql[1], &idx); + assert( tdsqlite3Isdigit(zRawSql[1]) ); + tdsqlite3GetInt32(&zRawSql[1], &idx); }else{ idx = nextIndex; } @@ -80225,7 +88310,7 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( testcase( zRawSql[0]=='$' ); testcase( zRawSql[0]=='@' ); testcase( zRawSql[0]=='#' ); - idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken); + idx = tdsqlite3VdbeParameterIndex(p, zRawSql, nToken); assert( idx>0 ); } zRawSql += nToken; @@ -80233,11 +88318,11 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( assert( idx>0 && idx<=p->nVar ); pVar = &p->aVar[idx-1]; if( pVar->flags & MEM_Null ){ - sqlite3StrAccumAppend(&out, "NULL", 4); - }else if( pVar->flags & MEM_Int ){ - sqlite3XPrintf(&out, "%lld", pVar->u.i); + tdsqlite3_str_append(&out, "NULL", 4); + }else if( pVar->flags & (MEM_Int|MEM_IntReal) ){ + tdsqlite3_str_appendf(&out, "%lld", pVar->u.i); }else if( pVar->flags & MEM_Real ){ - sqlite3XPrintf(&out, "%!.15g", pVar->u.r); + tdsqlite3_str_appendf(&out, "%!.15g", pVar->u.r); }else if( pVar->flags & MEM_Str ){ int nOut; /* Number of bytes of the string text to include in output */ #ifndef SQLITE_OMIT_UTF16 @@ -80245,9 +88330,9 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( if( enc!=SQLITE_UTF8 ){ memset(&utf8, 0, sizeof(utf8)); utf8.db = db; - sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC); - if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){ - out.accError = STRACCUM_NOMEM; + tdsqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC); + if( SQLITE_NOMEM==tdsqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){ + out.accError = SQLITE_NOMEM; out.nAlloc = 0; } pVar = &utf8; @@ -80260,39 +88345,39 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; } } #endif - sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z); + tdsqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z); #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOut<pVar->n ){ - sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); + tdsqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut); } #endif #ifndef SQLITE_OMIT_UTF16 - if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8); + if( enc!=SQLITE_UTF8 ) tdsqlite3VdbeMemRelease(&utf8); #endif }else if( pVar->flags & MEM_Zero ){ - sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero); + tdsqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero); }else{ int nOut; /* Number of bytes of the blob to include in output */ assert( pVar->flags & MEM_Blob ); - sqlite3StrAccumAppend(&out, "x'", 2); + tdsqlite3_str_append(&out, "x'", 2); nOut = pVar->n; #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT; #endif for(i=0; i<nOut; i++){ - sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff); + tdsqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff); } - sqlite3StrAccumAppend(&out, "'", 1); + tdsqlite3_str_append(&out, "'", 1); #ifdef SQLITE_TRACE_SIZE_LIMIT if( nOut<pVar->n ){ - sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); + tdsqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut); } #endif } } } - if( out.accError ) sqlite3StrAccumReset(&out); - return sqlite3StrAccumFinish(&out); + if( out.accError ) tdsqlite3_str_reset(&out); + return tdsqlite3StrAccumFinish(&out); } #endif /* #ifndef SQLITE_OMIT_TRACE */ @@ -80332,7 +88417,7 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( ** like that ever happens. */ #ifdef SQLITE_DEBUG -# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M) +# define memAboutToChange(P,M) tdsqlite3VdbeMemAboutToChange(P,M) #else # define memAboutToChange(P,M) #endif @@ -80345,19 +88430,19 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( ** help verify the correct operation of the library. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_search_count = 0; +SQLITE_API int tdsqlite3_search_count = 0; #endif /* ** When this global variable is positive, it gets decremented once before ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted -** field of the sqlite3 structure is set in order to simulate an interrupt. +** field of the tdsqlite3 structure is set in order to simulate an interrupt. ** ** This facility is used for testing purposes only. It does not function ** in an ordinary build. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_interrupt_count = 0; +SQLITE_API int tdsqlite3_interrupt_count = 0; #endif /* @@ -80368,7 +88453,7 @@ SQLITE_API int sqlite3_interrupt_count = 0; ** library. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_sort_count = 0; +SQLITE_API int tdsqlite3_sort_count = 0; #endif /* @@ -80379,10 +88464,10 @@ SQLITE_API int sqlite3_sort_count = 0; ** help verify the correct operation of the library. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_max_blobsize = 0; +SQLITE_API int tdsqlite3_max_blobsize = 0; static void updateMaxBlobsize(Mem *p){ - if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){ - sqlite3_max_blobsize = p->n; + if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>tdsqlite3_max_blobsize ){ + tdsqlite3_max_blobsize = p->n; } } #endif @@ -80405,62 +88490,118 @@ static void updateMaxBlobsize(Mem *p){ ** library. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_found_count = 0; +SQLITE_API int tdsqlite3_found_count = 0; #endif /* ** Test a register to see if it exceeds the current maximum blob size. ** If it does, record the new maximum blob size. */ -#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST) +#if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE) # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P) #else # define UPDATE_MAX_BLOBSIZE(P) #endif +#ifdef SQLITE_DEBUG +/* This routine provides a convenient place to set a breakpoint during +** tracing with PRAGMA vdbe_trace=on. The breakpoint fires right after +** each opcode is printed. Variables "pc" (program counter) and pOp are +** available to add conditionals to the breakpoint. GDB example: +** +** break test_trace_breakpoint if pc=22 +** +** Other useful labels for breakpoints include: +** test_addop_breakpoint(pc,pOp) +** tdsqlite3CorruptError(lineno) +** tdsqlite3MisuseError(lineno) +** tdsqlite3CantopenError(lineno) +*/ +static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){ + static int n = 0; + n++; +} +#endif + /* ** Invoke the VDBE coverage callback, if that callback is defined. This ** feature is used for test suite validation only and does not appear an ** production builds. ** -** M is an integer, 2 or 3, that indices how many different ways the -** branch can go. It is usually 2. "I" is the direction the branch -** goes. 0 means falls through. 1 means branch is taken. 2 means the -** second alternative branch is taken. +** M is the type of branch. I is the direction taken for this instance of +** the branch. +** +** M: 2 - two-way branch (I=0: fall-thru 1: jump ) +** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL ) +** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3) +** +** In other words, if M is 2, then I is either 0 (for fall-through) or +** 1 (for when the branch is taken). If M is 3, the I is 0 for an +** ordinary fall-through, I is 1 if the branch was taken, and I is 2 +** if the result of comparison is NULL. For M=3, I=2 the jump may or +** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5. +** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2 +** depending on if the operands are less than, equal, or greater than. ** ** iSrcLine is the source code line (from the __LINE__ macro) that -** generated the VDBE instruction. This instrumentation assumes that all -** source code is in a single file (the amalgamation). Special values 1 -** and 2 for the iSrcLine parameter mean that this particular branch is -** always taken or never taken, respectively. +** generated the VDBE instruction combined with flag bits. The source +** code line number is in the lower 24 bits of iSrcLine and the upper +** 8 bytes are flags. The lower three bits of the flags indicate +** values for I that should never occur. For example, if the branch is +** always taken, the flags should be 0x05 since the fall-through and +** alternate branch are never taken. If a branch is never taken then +** flags should be 0x06 since only the fall-through approach is allowed. +** +** Bit 0x08 of the flags indicates an OP_Jump opcode that is only +** interested in equal or not-equal. In other words, I==0 and I==2 +** should be treated as equivalent +** +** Since only a line number is retained, not the filename, this macro +** only works for amalgamation builds. But that is ok, since these macros +** should be no-ops except for special builds used to measure test coverage. */ #if !defined(SQLITE_VDBE_COVERAGE) # define VdbeBranchTaken(I,M) #else # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M) - static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){ - if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){ - M = iSrcLine; - /* Assert the truth of VdbeCoverageAlwaysTaken() and - ** VdbeCoverageNeverTaken() */ - assert( (M & I)==I ); - }else{ - if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/ - sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg, - iSrcLine,I,M); + static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){ + u8 mNever; + assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */ + assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */ + assert( I<M ); /* I can only be 2 if M is 3 or 4 */ + /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */ + I = 1<<I; + /* The upper 8 bits of iSrcLine are flags. The lower three bits of + ** the flags indicate directions that the branch can never go. If + ** a branch really does go in one of those directions, assert right + ** away. */ + mNever = iSrcLine >> 24; + assert( (I & mNever)==0 ); + if( tdsqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/ + /* Invoke the branch coverage callback with three arguments: + ** iSrcLine - the line number of the VdbeCoverage() macro, with + ** flags removed. + ** I - Mask of bits 0x07 indicating which cases are are + ** fulfilled by this instance of the jump. 0x01 means + ** fall-thru, 0x02 means taken, 0x04 means NULL. Any + ** impossible cases (ex: if the comparison is never NULL) + ** are filled in automatically so that the coverage + ** measurement logic does not flag those impossible cases + ** as missed coverage. + ** M - Type of jump. Same as M argument above + */ + I |= mNever; + if( M==2 ) I |= 0x04; + if( M==4 ){ + I |= 0x08; + if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/ } + tdsqlite3GlobalConfig.xVdbeBranch(tdsqlite3GlobalConfig.pVdbeBranchArg, + iSrcLine&0xffffff, I, M); } #endif /* -** Convert the given register into a string if it isn't one -** already. Return non-zero if a malloc() fails. -*/ -#define Stringify(P, enc) \ - if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \ - { goto no_mem; } - -/* ** An ephemeral string value (signified by the MEM_Ephem flag) contains ** a pointer to a dynamically allocated string where some other entity ** is responsible for deallocating that string. Because the register @@ -80473,7 +88614,7 @@ SQLITE_API int sqlite3_found_count = 0; */ #define Deephemeralize(P) \ if( ((P)->flags&MEM_Ephem)!=0 \ - && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} + && tdsqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} /* Return true if the cursor was opened using the OP_OpenSorter opcode. */ #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER) @@ -80500,7 +88641,7 @@ static VdbeCursor *allocateCursor( ** allocations. ** ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can - ** be freed lazily via the sqlite3_release_memory() API. This + ** be freed lazily via the tdsqlite3_release_memory() API. This ** minimizes the number of malloc calls made by the system. ** ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from @@ -80513,16 +88654,21 @@ static VdbeCursor *allocateCursor( VdbeCursor *pCx = 0; nByte = ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + - (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0); + (eCurType==CURTYPE_BTREE?tdsqlite3BtreeCursorSize():0); assert( iCur>=0 && iCur<p->nCursor ); if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/ - sqlite3VdbeFreeCursor(p, p->apCsr[iCur]); + /* Before calling tdsqlite3VdbeFreeCursor(), ensure the isEphemeral flag + ** is clear. Otherwise, if this is an ephemeral cursor created by + ** OP_OpenDup, the cursor will not be closed and will still be part + ** of a BtShared.pCursor list. */ + if( p->apCsr[iCur]->pBtx==0 ) p->apCsr[iCur]->isEphemeral = 0; + tdsqlite3VdbeFreeCursor(p, p->apCsr[iCur]); p->apCsr[iCur] = 0; } - if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){ + if( SQLITE_OK==tdsqlite3VdbeMemClearAndResize(pMem, nByte) ){ p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z; - memset(pCx, 0, sizeof(VdbeCursor)); + memset(pCx, 0, offsetof(VdbeCursor,pAltCursor)); pCx->eCurType = eCurType; pCx->iDb = iDb; pCx->nField = nField; @@ -80530,13 +88676,28 @@ static VdbeCursor *allocateCursor( if( eCurType==CURTYPE_BTREE ){ pCx->uc.pCursor = (BtCursor*) &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField]; - sqlite3BtreeCursorZero(pCx->uc.pCursor); + tdsqlite3BtreeCursorZero(pCx->uc.pCursor); } } return pCx; } /* +** The string in pRec is known to look like an integer and to have a +** floating point value of rValue. Return true and set *piValue to the +** integer value if the string is in range to be an integer. Otherwise, +** return false. +*/ +static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){ + i64 iValue = (double)rValue; + if( tdsqlite3RealSameAsInt(rValue,iValue) ){ + *piValue = iValue; + return 1; + } + return 0==tdsqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc); +} + +/* ** Try to convert a value into a numeric representation if we can ** do so without loss of information. In other words, if the string ** looks like a number, convert it into a number. If it does not @@ -80553,18 +88714,23 @@ static VdbeCursor *allocateCursor( */ static void applyNumericAffinity(Mem *pRec, int bTryForInt){ double rValue; - i64 iValue; u8 enc = pRec->enc; - assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str ); - if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return; - if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){ - pRec->u.i = iValue; + int rc; + assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str ); + rc = tdsqlite3AtoF(pRec->z, &rValue, pRec->n, enc); + if( rc<=0 ) return; + if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){ pRec->flags |= MEM_Int; }else{ pRec->u.r = rValue; pRec->flags |= MEM_Real; - if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec); + if( bTryForInt ) tdsqlite3VdbeIntegerAffinity(pRec); } + /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the + ** string representation after computing a numeric equivalent, because the + ** string representation might not be the canonical representation for the + ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */ + pRec->flags &= ~MEM_Str; } /* @@ -80583,6 +88749,7 @@ static void applyNumericAffinity(Mem *pRec, int bTryForInt){ ** Convert pRec to a text representation. ** ** SQLITE_AFF_BLOB: +** SQLITE_AFF_NONE: ** No-op. pRec is unchanged. */ static void applyAffinity( @@ -80597,7 +88764,7 @@ static void applyAffinity( if( (pRec->flags & MEM_Real)==0 ){ if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1); }else{ - sqlite3VdbeIntegerAffinity(pRec); + tdsqlite3VdbeIntegerAffinity(pRec); } } }else if( affinity==SQLITE_AFF_TEXT ){ @@ -80607,11 +88774,14 @@ static void applyAffinity( ** there is already a string rep, but it is pointless to waste those ** CPU cycles. */ if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/ - if( (pRec->flags&(MEM_Real|MEM_Int)) ){ - sqlite3VdbeMemStringify(pRec, enc, 1); + if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){ + testcase( pRec->flags & MEM_Int ); + testcase( pRec->flags & MEM_Real ); + testcase( pRec->flags & MEM_IntReal ); + tdsqlite3VdbeMemStringify(pRec, enc, 1); } } - pRec->flags &= ~(MEM_Real|MEM_Int); + pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal); } } @@ -80621,22 +88791,22 @@ static void applyAffinity( ** is appropriate. But only do the conversion if it is possible without ** loss of information and return the revised type of the argument. */ -SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){ - int eType = sqlite3_value_type(pVal); +SQLITE_API int tdsqlite3_value_numeric_type(tdsqlite3_value *pVal){ + int eType = tdsqlite3_value_type(pVal); if( eType==SQLITE_TEXT ){ Mem *pMem = (Mem*)pVal; applyNumericAffinity(pMem, 0); - eType = sqlite3_value_type(pVal); + eType = tdsqlite3_value_type(pVal); } return eType; } /* -** Exported version of applyAffinity(). This one works on sqlite3_value*, +** Exported version of applyAffinity(). This one works on tdsqlite3_value*, ** not the internal Mem* type. */ -SQLITE_PRIVATE void sqlite3ValueApplyAffinity( - sqlite3_value *pVal, +SQLITE_PRIVATE void tdsqlite3ValueApplyAffinity( + tdsqlite3_value *pVal, u8 affinity, u8 enc ){ @@ -80650,12 +88820,21 @@ SQLITE_PRIVATE void sqlite3ValueApplyAffinity( ** accordingly. */ static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){ - assert( (pMem->flags & (MEM_Int|MEM_Real))==0 ); + int rc; + tdsqlite3_int64 ix; + assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ); assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ); - if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){ - return 0; - } - if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){ + ExpandBlob(pMem); + rc = tdsqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc); + if( rc<=0 ){ + if( rc==0 && tdsqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){ + pMem->u.i = ix; + return MEM_Int; + }else{ + return MEM_Real; + } + }else if( rc==1 && tdsqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){ + pMem->u.i = ix; return MEM_Int; } return MEM_Real; @@ -80669,10 +88848,15 @@ static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){ ** But it does set pMem->u.r and pMem->u.i appropriately. */ static u16 numericType(Mem *pMem){ - if( pMem->flags & (MEM_Int|MEM_Real) ){ - return pMem->flags & (MEM_Int|MEM_Real); + if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal) ){ + testcase( pMem->flags & MEM_Int ); + testcase( pMem->flags & MEM_Real ); + testcase( pMem->flags & MEM_IntReal ); + return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal); } if( pMem->flags & (MEM_Str|MEM_Blob) ){ + testcase( pMem->flags & MEM_Str ); + testcase( pMem->flags & MEM_Blob ); return computeNumericType(pMem); } return 0; @@ -80683,12 +88867,9 @@ static u16 numericType(Mem *pMem){ ** Write a nice string representation of the contents of cell pMem ** into buffer zBuf, length nBuf. */ -SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){ - char *zCsr = zBuf; +SQLITE_PRIVATE void tdsqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){ int f = pMem->flags; - static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"}; - if( f&MEM_Blob ){ int i; char c; @@ -80704,59 +88885,40 @@ SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){ }else{ c = 's'; } - - sqlite3_snprintf(100, zCsr, "%c", c); - zCsr += sqlite3Strlen30(zCsr); - sqlite3_snprintf(100, zCsr, "%d[", pMem->n); - zCsr += sqlite3Strlen30(zCsr); - for(i=0; i<16 && i<pMem->n; i++){ - sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF)); - zCsr += sqlite3Strlen30(zCsr); + tdsqlite3_str_appendf(pStr, "%cx[", c); + for(i=0; i<25 && i<pMem->n; i++){ + tdsqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF)); } - for(i=0; i<16 && i<pMem->n; i++){ + tdsqlite3_str_appendf(pStr, "|"); + for(i=0; i<25 && i<pMem->n; i++){ char z = pMem->z[i]; - if( z<32 || z>126 ) *zCsr++ = '.'; - else *zCsr++ = z; + tdsqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z); } - - sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]); - zCsr += sqlite3Strlen30(zCsr); + tdsqlite3_str_appendf(pStr,"]"); if( f & MEM_Zero ){ - sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero); - zCsr += sqlite3Strlen30(zCsr); + tdsqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero); } - *zCsr = '\0'; }else if( f & MEM_Str ){ - int j, k; - zBuf[0] = ' '; + int j; + u8 c; if( f & MEM_Dyn ){ - zBuf[1] = 'z'; + c = 'z'; assert( (f & (MEM_Static|MEM_Ephem))==0 ); }else if( f & MEM_Static ){ - zBuf[1] = 't'; + c = 't'; assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); }else if( f & MEM_Ephem ){ - zBuf[1] = 'e'; + c = 'e'; assert( (f & (MEM_Static|MEM_Dyn))==0 ); }else{ - zBuf[1] = 's'; + c = 's'; } - k = 2; - sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n); - k += sqlite3Strlen30(&zBuf[k]); - zBuf[k++] = '['; - for(j=0; j<15 && j<pMem->n; j++){ - u8 c = pMem->z[j]; - if( c>=0x20 && c<0x7f ){ - zBuf[k++] = c; - }else{ - zBuf[k++] = '.'; - } + tdsqlite3_str_appendf(pStr, " %c%d[", c, pMem->n); + for(j=0; j<25 && j<pMem->n; j++){ + c = pMem->z[j]; + tdsqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.'); } - zBuf[k++] = ']'; - sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]); - k += sqlite3Strlen30(&zBuf[k]); - zBuf[k++] = 0; + tdsqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]); } } #endif @@ -80769,32 +88931,52 @@ static void memTracePrint(Mem *p){ if( p->flags & MEM_Undefined ){ printf(" undefined"); }else if( p->flags & MEM_Null ){ - printf(" NULL"); + printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL"); }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ printf(" si:%lld", p->u.i); + }else if( (p->flags & (MEM_IntReal))!=0 ){ + printf(" ir:%lld", p->u.i); }else if( p->flags & MEM_Int ){ printf(" i:%lld", p->u.i); #ifndef SQLITE_OMIT_FLOATING_POINT }else if( p->flags & MEM_Real ){ - printf(" r:%g", p->u.r); + printf(" r:%.17g", p->u.r); #endif - }else if( p->flags & MEM_RowSet ){ + }else if( tdsqlite3VdbeMemIsRowSet(p) ){ printf(" (rowset)"); }else{ - char zBuf[200]; - sqlite3VdbeMemPrettyPrint(p, zBuf); - printf(" %s", zBuf); + StrAccum acc; + char zBuf[1000]; + tdsqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); + tdsqlite3VdbeMemPrettyPrint(p, &acc); + printf(" %s", tdsqlite3StrAccumFinish(&acc)); } if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype); } static void registerTrace(int iReg, Mem *p){ - printf("REG[%d] = ", iReg); + printf("R[%d] = ", iReg); memTracePrint(p); + if( p->pScopyFrom ){ + printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg])); + } printf("\n"); + tdsqlite3VdbeCheckMemInvariants(p); } #endif #ifdef SQLITE_DEBUG +/* +** Show the values of all registers in the virtual machine. Used for +** interactive debugging. +*/ +SQLITE_PRIVATE void tdsqlite3VdbeRegisterDump(Vdbe *v){ + int i; + for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i); +} +#endif /* SQLITE_DEBUG */ + + +#ifdef SQLITE_DEBUG # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M) #else # define REGISTER_TRACE(R,M) @@ -80822,7 +89004,7 @@ static void registerTrace(int iReg, Mem *p){ ****************************************************************************** ** ** This file contains inline asm code for retrieving "high-performance" -** counters for x86 class CPUs. +** counters for x86 and x86_64 class CPUs. */ #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H @@ -80833,12 +89015,13 @@ static void registerTrace(int iReg, Mem *p){ ** processor and returns that value. This can be used for high-res ** profiling. */ -#if (defined(__GNUC__) || defined(_MSC_VER)) && \ - (defined(i386) || defined(__i386__) || defined(_M_IX86)) +#if !defined(__STRICT_ANSI__) && \ + (defined(__GNUC__) || defined(_MSC_VER)) && \ + (defined(i386) || defined(__i386__) || defined(_M_IX86)) #if defined(__GNUC__) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned int lo, hi; __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); return (sqlite_uint64)hi << 32 | lo; @@ -80846,7 +89029,7 @@ static void registerTrace(int iReg, Mem *p){ #elif defined(_MSC_VER) - __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ + __declspec(naked) __inline sqlite_uint64 __cdecl tdsqlite3Hwtime(void){ __asm { rdtsc ret ; return value at EDX:EAX @@ -80855,17 +89038,17 @@ static void registerTrace(int iReg, Mem *p){ #endif -#elif (defined(__GNUC__) && defined(__x86_64__)) +#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__)) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned long val; __asm__ __volatile__ ("rdtsc" : "=A" (val)); return val; } -#elif (defined(__GNUC__) && defined(__ppc__)) +#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__)) - __inline__ sqlite_uint64 sqlite3Hwtime(void){ + __inline__ sqlite_uint64 tdsqlite3Hwtime(void){ unsigned long long retval; unsigned long junk; __asm__ __volatile__ ("\n\ @@ -80880,16 +89063,15 @@ static void registerTrace(int iReg, Mem *p){ #else - #error Need implementation of sqlite3Hwtime() for your platform. - /* - ** To compile without implementing sqlite3Hwtime() for your platform, - ** you can remove the above #error and use the following - ** stub function. You will lose timing support for many - ** of the debugging and testing utilities, but it should at - ** least compile and run. + ** asm() is needed for hardware timing support. Without asm(), + ** disable the tdsqlite3Hwtime() routine. + ** + ** tdsqlite3Hwtime() is only used for some obscure debugging + ** and analysis configurations, not in any deliverable, so this + ** should not be a great loss. */ -SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } +SQLITE_PRIVATE sqlite_uint64 tdsqlite3Hwtime(void){ return ((sqlite_uint64)0); } #endif @@ -80911,7 +89093,7 @@ SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } ** ** assert( checkSavepointCount(db) ); */ -static int checkSavepointCount(sqlite3 *db){ +static int checkSavepointCount(tdsqlite3 *db){ int n = 0; Savepoint *p; for(p=db->pSavepoint; p; p=p->pNext) n++; @@ -80925,7 +89107,7 @@ static int checkSavepointCount(sqlite3 *db){ ** overwritten with an integer value. */ static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){ - sqlite3VdbeMemSetNull(pOut); + tdsqlite3VdbeMemSetNull(pOut); pOut->flags = MEM_Int; return pOut; } @@ -80946,9 +89128,9 @@ static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){ /* ** Execute as much of a VDBE program as we can. -** This is the core of sqlite3_step(). +** This is the core of tdsqlite3_step(). */ -SQLITE_PRIVATE int sqlite3VdbeExec( +SQLITE_PRIVATE int tdsqlite3VdbeExec( Vdbe *p /* The VDBE */ ){ Op *aOp = p->aOp; /* Copy of p->aOp */ @@ -80960,61 +89142,60 @@ SQLITE_PRIVATE int sqlite3VdbeExec( int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */ #endif int rc = SQLITE_OK; /* Value to return */ - sqlite3 *db = p->db; /* The database */ + tdsqlite3 *db = p->db; /* The database */ u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */ u8 encoding = ENC(db); /* The database encoding */ int iCompare = 0; /* Result of last comparison */ unsigned nVmStep = 0; /* Number of virtual machine steps */ #ifndef SQLITE_OMIT_PROGRESS_CALLBACK - unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */ + unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */ #endif Mem *aMem = p->aMem; /* Copy of p->aMem */ Mem *pIn1 = 0; /* 1st input operand */ Mem *pIn2 = 0; /* 2nd input operand */ Mem *pIn3 = 0; /* 3rd input operand */ Mem *pOut = 0; /* Output operand */ - int *aPermute = 0; /* Permutation of columns for OP_Compare */ - i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */ #ifdef VDBE_PROFILE u64 start; /* CPU clock count at start of opcode */ #endif /*** INSERT STACK UNION HERE ***/ - assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ - sqlite3VdbeEnter(p); + assert( p->magic==VDBE_MAGIC_RUN ); /* tdsqlite3_step() verifies this */ + tdsqlite3VdbeEnter(p); +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + if( db->xProgress ){ + u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP]; + assert( 0 < db->nProgressOps ); + nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps); + }else{ + nProgressLimit = 0xffffffff; + } +#endif if( p->rc==SQLITE_NOMEM ){ - /* This happens if a malloc() inside a call to sqlite3_column_text() or - ** sqlite3_column_text16() failed. */ + /* This happens if a malloc() inside a call to tdsqlite3_column_text() or + ** tdsqlite3_column_text16() failed. */ goto no_mem; } assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY ); assert( p->bIsReader || p->readOnly!=0 ); - p->rc = SQLITE_OK; p->iCurrentTime = 0; assert( p->explain==0 ); p->pResultSet = 0; db->busyHandler.nBusy = 0; if( db->u1.isInterrupted ) goto abort_due_to_interrupt; - sqlite3VdbeIOTraceSql(p); -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - if( db->xProgress ){ - u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP]; - assert( 0 < db->nProgressOps ); - nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps); - } -#endif + tdsqlite3VdbeIOTraceSql(p); #ifdef SQLITE_DEBUG - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); if( p->pc==0 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0 ){ int i; int once = 1; - sqlite3VdbePrintSql(p); + tdsqlite3VdbePrintSql(p); if( p->db->flags & SQLITE_VdbeListing ){ printf("VDBE Program Listing:\n"); for(i=0; i<p->nOp; i++){ - sqlite3VdbePrintOp(stdout, i, &aOp[i]); + tdsqlite3VdbePrintOp(stdout, i, &aOp[i]); } } if( p->db->flags & SQLITE_VdbeEQP ){ @@ -81028,7 +89209,7 @@ SQLITE_PRIVATE int sqlite3VdbeExec( } if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n"); } - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); #endif for(pOp=&aOp[p->pc]; 1; pOp++){ /* Errors are detected by individual opcodes, with an immediate @@ -81037,7 +89218,7 @@ SQLITE_PRIVATE int sqlite3VdbeExec( assert( pOp>=aOp && pOp<&aOp[p->nOp]); #ifdef VDBE_PROFILE - start = sqlite3Hwtime(); + start = tdsqlite3NProfileCnt ? tdsqlite3NProfileCnt : tdsqlite3Hwtime(); #endif nVmStep++; #ifdef SQLITE_ENABLE_STMT_SCANSTATUS @@ -81048,7 +89229,8 @@ SQLITE_PRIVATE int sqlite3VdbeExec( */ #ifdef SQLITE_DEBUG if( db->flags & SQLITE_VdbeTrace ){ - sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp); + tdsqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp); + test_trace_breakpoint((int)(pOp - aOp),pOp,p); } #endif @@ -81057,10 +89239,10 @@ SQLITE_PRIVATE int sqlite3VdbeExec( ** if we have a special test build. */ #ifdef SQLITE_TEST - if( sqlite3_interrupt_count>0 ){ - sqlite3_interrupt_count--; - if( sqlite3_interrupt_count==0 ){ - sqlite3_interrupt(db); + if( tdsqlite3_interrupt_count>0 ){ + tdsqlite3_interrupt_count--; + if( tdsqlite3_interrupt_count==0 ){ + tdsqlite3_interrupt(db); } } #endif @@ -81068,26 +89250,26 @@ SQLITE_PRIVATE int sqlite3VdbeExec( /* Sanity checking on other operands */ #ifdef SQLITE_DEBUG { - u8 opProperty = sqlite3OpcodeProperty[pOp->opcode]; + u8 opProperty = tdsqlite3OpcodeProperty[pOp->opcode]; if( (opProperty & OPFLG_IN1)!=0 ){ assert( pOp->p1>0 ); assert( pOp->p1<=(p->nMem+1 - p->nCursor) ); assert( memIsValid(&aMem[pOp->p1]) ); - assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) ); + assert( tdsqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) ); REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]); } if( (opProperty & OPFLG_IN2)!=0 ){ assert( pOp->p2>0 ); assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); assert( memIsValid(&aMem[pOp->p2]) ); - assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) ); + assert( tdsqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) ); REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]); } if( (opProperty & OPFLG_IN3)!=0 ){ assert( pOp->p3>0 ); assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); assert( memIsValid(&aMem[pOp->p3]) ); - assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) ); + assert( tdsqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) ); REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]); } if( (opProperty & OPFLG_OUT2)!=0 ){ @@ -81156,32 +89338,47 @@ SQLITE_PRIVATE int sqlite3VdbeExec( ** to the current line should be indented for EXPLAIN output. */ case OP_Goto: { /* jump */ + +#ifdef SQLITE_DEBUG + /* In debuggging mode, when the p5 flags is set on an OP_Goto, that + ** means we should really jump back to the preceeding OP_ReleaseReg + ** instruction. */ + if( pOp->p5 ){ + assert( pOp->p2 < (int)(pOp - aOp) ); + assert( pOp->p2 > 1 ); + pOp = &aOp[pOp->p2 - 2]; + assert( pOp[1].opcode==OP_ReleaseReg ); + goto check_for_interrupt; + } +#endif + jump_to_p2_and_check_for_interrupt: pOp = &aOp[pOp->p2 - 1]; /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev, - ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon - ** completion. Check to see if sqlite3_interrupt() has been called + ** OP_VNext, or OP_SorterNext) all jump here upon + ** completion. Check to see if tdsqlite3_interrupt() has been called ** or if the progress callback needs to be invoked. ** ** This code uses unstructured "goto" statements and does not look clean. ** But that is not due to sloppy coding habits. The code is written this ** way for performance, to avoid having to run the interrupt and progress - ** checks on every opcode. This helps sqlite3_step() to run about 1.5% + ** checks on every opcode. This helps tdsqlite3_step() to run about 1.5% ** faster according to "valgrind --tool=cachegrind" */ check_for_interrupt: if( db->u1.isInterrupted ) goto abort_due_to_interrupt; #ifndef SQLITE_OMIT_PROGRESS_CALLBACK /* Call the progress callback if it is configured and the required number ** of VDBE ops have been executed (either since this invocation of - ** sqlite3VdbeExec() or since last time the progress callback was called). + ** tdsqlite3VdbeExec() or since last time the progress callback was called). ** If the progress callback returns non-zero, exit the virtual machine with ** a return code SQLITE_ABORT. */ - if( db->xProgress!=0 && nVmStep>=nProgressLimit ){ + while( nVmStep>=nProgressLimit && db->xProgress!=0 ){ assert( db->nProgressOps!=0 ); - nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps); + nProgressLimit += db->nProgressOps; if( db->xProgress(db->pProgressArg) ){ + nProgressLimit = 0xffffffff; rc = SQLITE_INTERRUPT; goto abort_due_to_error; } @@ -81304,6 +89501,9 @@ case OP_Yield: { /* in1, jump */ */ case OP_HaltIfNull: { /* in3 */ pIn3 = &aMem[pOp->p3]; +#ifdef SQLITE_DEBUG + if( pOp->p2==OE_Abort ){ tdsqlite3VdbeAssertAbortable(p); } +#endif if( (pIn3->flags & MEM_Null)==0 ) break; /* Fall through into OP_Halt */ } @@ -81313,8 +89513,8 @@ case OP_HaltIfNull: { /* in3 */ ** Exit immediately. All open cursors, etc are closed ** automatically. ** -** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(), -** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0). +** P1 is the result code returned by tdsqlite3_exec(), tdsqlite3_reset(), +** or tdsqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0). ** For errors, it can be some other value. If P1!=0 then P2 will determine ** whether or not to rollback the current transaction. Do not rollback ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort, @@ -81343,14 +89543,16 @@ case OP_Halt: { int pcx; pcx = (int)(pOp - aOp); +#ifdef SQLITE_DEBUG + if( pOp->p2==OE_Abort ){ tdsqlite3VdbeAssertAbortable(p); } +#endif if( pOp->p1==SQLITE_OK && p->pFrame ){ /* Halt the sub-program. Return control to the parent frame. */ pFrame = p->pFrame; p->pFrame = pFrame->pParent; p->nFrame--; - sqlite3VdbeSetChanges(db, p->nChange); - pcx = sqlite3VdbeFrameRestore(pFrame); - lastRowid = db->lastRowid; + tdsqlite3VdbeSetChanges(db, p->nChange); + pcx = tdsqlite3VdbeFrameRestore(pFrame); if( pOp->p2==OE_Ignore ){ /* Instruction pcx is the OP_Program that invoked the sub-program ** currently being halted. If the p2 instruction of this OP_Halt @@ -81367,7 +89569,7 @@ case OP_Halt: { p->rc = pOp->p1; p->errorAction = (u8)pOp->p2; p->pc = pcx; - assert( pOp->p5>=0 && pOp->p5<=4 ); + assert( pOp->p5<=4 ); if( p->rc ){ if( pOp->p5 ){ static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK", @@ -81376,16 +89578,16 @@ case OP_Halt: { testcase( pOp->p5==2 ); testcase( pOp->p5==3 ); testcase( pOp->p5==4 ); - sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]); + tdsqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]); if( pOp->p4.z ){ - p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z); + p->zErrMsg = tdsqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z); } }else{ - sqlite3VdbeError(p, "%s", pOp->p4.z); + tdsqlite3VdbeError(p, "%s", pOp->p4.z); } - sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg); + tdsqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg); } - rc = sqlite3VdbeHalt(p); + rc = tdsqlite3VdbeHalt(p); assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); if( rc==SQLITE_BUSY ){ p->rc = SQLITE_BUSY; @@ -81431,7 +89633,7 @@ case OP_Int64: { /* out2 */ case OP_Real: { /* same as TK_FLOAT, out2 */ pOut = out2Prerelease(p, pOp); pOut->flags = MEM_Real; - assert( !sqlite3IsNaN(*pOp->p4.pReal) ); + assert( !tdsqlite3IsNaN(*pOp->p4.pReal) ); pOut->u.r = *pOp->p4.pReal; break; } @@ -81448,30 +89650,30 @@ case OP_Real: { /* same as TK_FLOAT, out2 */ case OP_String8: { /* same as TK_STRING, out2 */ assert( pOp->p4.z!=0 ); pOut = out2Prerelease(p, pOp); - pOp->opcode = OP_String; - pOp->p1 = sqlite3Strlen30(pOp->p4.z); + pOp->p1 = tdsqlite3Strlen30(pOp->p4.z); #ifndef SQLITE_OMIT_UTF16 if( encoding!=SQLITE_UTF8 ){ - rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); + rc = tdsqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG ); - if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; + if( rc ) goto too_big; + if( SQLITE_OK!=tdsqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z ); assert( VdbeMemDynamic(pOut)==0 ); pOut->szMalloc = 0; pOut->flags |= MEM_Static; if( pOp->p4type==P4_DYNAMIC ){ - sqlite3DbFree(db, pOp->p4.z); + tdsqlite3DbFree(db, pOp->p4.z); } pOp->p4type = P4_DYNAMIC; pOp->p4.z = pOut->z; pOp->p1 = pOut->n; } - testcase( rc==SQLITE_TOOBIG ); #endif if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } + pOp->opcode = OP_String; assert( rc==SQLITE_OK ); /* Fall through to the next case, OP_String */ } @@ -81527,10 +89729,13 @@ case OP_Null: { /* out2 */ assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null; pOut->n = 0; +#ifdef SQLITE_DEBUG + pOut->uTemp = 0; +#endif while( cnt>0 ){ pOut++; memAboutToChange(p, pOut); - sqlite3VdbeMemSetNull(pOut); + tdsqlite3VdbeMemSetNull(pOut); pOut->flags = nullFlag; pOut->n = 0; cnt--; @@ -81549,7 +89754,7 @@ case OP_Null: { /* out2 */ case OP_SoftNull: { assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); pOut = &aMem[pOp->p1]; - pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined; + pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null; break; } @@ -81562,7 +89767,7 @@ case OP_SoftNull: { case OP_Blob: { /* out2 */ assert( pOp->p1 <= SQLITE_MAX_LENGTH ); pOut = out2Prerelease(p, pOp); - sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); + tdsqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); pOut->enc = encoding; UPDATE_MAX_BLOBSIZE(pOut); break; @@ -81574,19 +89779,22 @@ case OP_Blob: { /* out2 */ ** Transfer the values of bound parameter P1 into register P2 ** ** If the parameter is named, then its name appears in P4. -** The P4 value is used by sqlite3_bind_parameter_name(). +** The P4 value is used by tdsqlite3_bind_parameter_name(). */ case OP_Variable: { /* out2 */ Mem *pVar; /* Value being transferred */ assert( pOp->p1>0 && pOp->p1<=p->nVar ); - assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] ); + assert( pOp->p4.z==0 || pOp->p4.z==tdsqlite3VListNumToName(p->pVList,pOp->p1) ); pVar = &p->aVar[pOp->p1 - 1]; - if( sqlite3VdbeMemTooBig(pVar) ){ + if( tdsqlite3VdbeMemTooBig(pVar) ){ goto too_big; } - pOut = out2Prerelease(p, pOp); - sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static); + pOut = &aMem[pOp->p2]; + if( VdbeMemDynamic(pOut) ) tdsqlite3VdbeMemSetNull(pOut); + memcpy(pOut, pVar, MEMCELLSIZE); + pOut->flags &= ~(MEM_Dyn|MEM_Ephem); + pOut->flags |= MEM_Static|MEM_FromBind; UPDATE_MAX_BLOBSIZE(pOut); break; } @@ -81618,10 +89826,15 @@ case OP_Move: { assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] ); assert( memIsValid(pIn1) ); memAboutToChange(p, pOut); - sqlite3VdbeMemMove(pOut, pIn1); + tdsqlite3VdbeMemMove(pOut, pIn1); #ifdef SQLITE_DEBUG - if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){ - pOut->pScopyFrom += pOp->p2 - p1; + pIn1->pScopyFrom = 0; + { int i; + for(i=1; i<p->nMem; i++){ + if( aMem[i].pScopyFrom==pIn1 ){ + aMem[i].pScopyFrom = pOut; + } + } } #endif Deephemeralize(pOut); @@ -81648,7 +89861,8 @@ case OP_Copy: { pOut = &aMem[pOp->p2]; assert( pOut!=pIn1 ); while( 1 ){ - sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); + memAboutToChange(p, pOut); + tdsqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); Deephemeralize(pOut); #ifdef SQLITE_DEBUG pOut->pScopyFrom = 0; @@ -81678,9 +89892,10 @@ case OP_SCopy: { /* out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; assert( pOut!=pIn1 ); - sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); + tdsqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); #ifdef SQLITE_DEBUG - if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1; + pOut->pScopyFrom = pIn1; + pOut->mScopyFlags = pIn1->flags; #endif break; } @@ -81697,7 +89912,7 @@ case OP_IntCopy: { /* out2 */ pIn1 = &aMem[pOp->p1]; assert( (pIn1->flags & MEM_Int)!=0 ); pOut = &aMem[pOp->p2]; - sqlite3VdbeMemSetInt64(pOut, pIn1->u.i); + tdsqlite3VdbeMemSetInt64(pOut, pIn1->u.i); break; } @@ -81705,8 +89920,8 @@ case OP_IntCopy: { /* out2 */ ** Synopsis: output=r[P1@P2] ** ** The registers P1 through P1+P2-1 contain a single row of -** results. This opcode causes the sqlite3_step() call to terminate -** with an SQLITE_ROW return code and it sets up the sqlite3_stmt +** results. This opcode causes the tdsqlite3_step() call to terminate +** with an SQLITE_ROW return code and it sets up the tdsqlite3_stmt ** structure to provide access to the r(P1)..r(P1+P2-1) values as ** the result row. */ @@ -81717,22 +89932,10 @@ case OP_ResultRow: { assert( pOp->p1>0 ); assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 ); -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - /* Run the progress counter just before returning. - */ - if( db->xProgress!=0 - && nVmStep>=nProgressLimit - && db->xProgress(db->pProgressArg)!=0 - ){ - rc = SQLITE_INTERRUPT; - goto abort_due_to_error; - } -#endif - /* If this statement has violated immediate foreign key constraints, do ** not return the number of rows modified. And do not RELEASE the statement ** transaction. It needs to be rolled back. */ - if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){ + if( SQLITE_OK!=(rc = tdsqlite3VdbeCheckFk(p, 0)) ){ assert( db->flags&SQLITE_CountRows ); assert( p->usesStmtJournal ); goto abort_due_to_error; @@ -81754,7 +89957,7 @@ case OP_ResultRow: { ** the RELEASE call below can never fail. */ assert( p->iStatement==0 || db->flags&SQLITE_CountRows ); - rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE); + rc = tdsqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE); assert( rc==SQLITE_OK ); /* Invalidate all ephemeral cursor row caches */ @@ -81770,8 +89973,16 @@ case OP_ResultRow: { Deephemeralize(&pMem[i]); assert( (pMem[i].flags & MEM_Ephem)==0 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 ); - sqlite3VdbeMemNulTerminate(&pMem[i]); + tdsqlite3VdbeMemNulTerminate(&pMem[i]); REGISTER_TRACE(pOp->p1+i, &pMem[i]); +#ifdef SQLITE_DEBUG + /* The registers in the result will not be used again when the + ** prepared statement restarts. This is because tdsqlite3_column() + ** APIs might have caused type conversions of made other changes to + ** the register values. Therefore, we can go ahead and break any + ** OP_SCopy dependencies. */ + pMem[i].pScopyFrom = 0; +#endif } if( db->mallocFailed ) goto no_mem; @@ -81779,6 +89990,7 @@ case OP_ResultRow: { db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0); } + /* Return SQLITE_ROW */ p->pc = (int)(pOp - aOp) + 1; @@ -81800,33 +90012,57 @@ case OP_ResultRow: { ** to avoid a memcpy(). */ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ - i64 nByte; + i64 nByte; /* Total size of the output string or blob */ + u16 flags1; /* Initial flags for P1 */ + u16 flags2; /* Initial flags for P2 */ pIn1 = &aMem[pOp->p1]; pIn2 = &aMem[pOp->p2]; pOut = &aMem[pOp->p3]; + testcase( pIn1==pIn2 ); + testcase( pOut==pIn2 ); assert( pIn1!=pOut ); - if( (pIn1->flags | pIn2->flags) & MEM_Null ){ - sqlite3VdbeMemSetNull(pOut); + flags1 = pIn1->flags; + testcase( flags1 & MEM_Null ); + testcase( pIn2->flags & MEM_Null ); + if( (flags1 | pIn2->flags) & MEM_Null ){ + tdsqlite3VdbeMemSetNull(pOut); break; } - if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem; - Stringify(pIn1, encoding); - Stringify(pIn2, encoding); + if( (flags1 & (MEM_Str|MEM_Blob))==0 ){ + if( tdsqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem; + flags1 = pIn1->flags & ~MEM_Str; + }else if( (flags1 & MEM_Zero)!=0 ){ + if( tdsqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem; + flags1 = pIn1->flags & ~MEM_Str; + } + flags2 = pIn2->flags; + if( (flags2 & (MEM_Str|MEM_Blob))==0 ){ + if( tdsqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem; + flags2 = pIn2->flags & ~MEM_Str; + }else if( (flags2 & MEM_Zero)!=0 ){ + if( tdsqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem; + flags2 = pIn2->flags & ~MEM_Str; + } nByte = pIn1->n + pIn2->n; if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } - if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){ + if( tdsqlite3VdbeMemGrow(pOut, (int)nByte+3, pOut==pIn2) ){ goto no_mem; } MemSetTypeFlag(pOut, MEM_Str); if( pOut!=pIn2 ){ memcpy(pOut->z, pIn2->z, pIn2->n); + assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) ); + pIn2->flags = flags2; } memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); + assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); + pIn1->flags = flags1; pOut->z[nByte]=0; pOut->z[nByte+1] = 0; + pOut->z[nByte+2] = 0; pOut->flags |= MEM_Term; pOut->n = (int)nByte; pOut->enc = encoding; @@ -81877,7 +90113,6 @@ case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */ case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */ case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */ case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ - char bIntint; /* Started out as two integer operands */ u16 flags; /* Combined MEM_* flags from both inputs */ u16 type1; /* Numeric type of left operand */ u16 type2; /* Numeric type of right operand */ @@ -81892,15 +90127,13 @@ case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ type2 = numericType(pIn2); pOut = &aMem[pOp->p3]; flags = pIn1->flags | pIn2->flags; - if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null; if( (type1 & type2 & MEM_Int)!=0 ){ iA = pIn1->u.i; iB = pIn2->u.i; - bIntint = 1; switch( pOp->opcode ){ - case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break; - case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break; - case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break; + case OP_Add: if( tdsqlite3AddInt64(&iB,iA) ) goto fp_math; break; + case OP_Subtract: if( tdsqlite3SubInt64(&iB,iA) ) goto fp_math; break; + case OP_Multiply: if( tdsqlite3MulInt64(&iB,iA) ) goto fp_math; break; case OP_Divide: { if( iA==0 ) goto arithmetic_result_is_null; if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math; @@ -81916,11 +90149,12 @@ case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ } pOut->u.i = iB; MemSetTypeFlag(pOut, MEM_Int); + }else if( (flags & MEM_Null)!=0 ){ + goto arithmetic_result_is_null; }else{ - bIntint = 0; fp_math: - rA = sqlite3VdbeRealValue(pIn1); - rB = sqlite3VdbeRealValue(pIn2); + rA = tdsqlite3VdbeRealValue(pIn1); + rB = tdsqlite3VdbeRealValue(pIn2); switch( pOp->opcode ){ case OP_Add: rB += rA; break; case OP_Subtract: rB -= rA; break; @@ -81932,8 +90166,8 @@ fp_math: break; } default: { - iA = (i64)rA; - iB = (i64)rB; + iA = tdsqlite3VdbeIntValue(pIn1); + iB = tdsqlite3VdbeIntValue(pIn2); if( iA==0 ) goto arithmetic_result_is_null; if( iA==-1 ) iA = 1; rB = (double)(iB % iA); @@ -81944,27 +90178,24 @@ fp_math: pOut->u.i = rB; MemSetTypeFlag(pOut, MEM_Int); #else - if( sqlite3IsNaN(rB) ){ + if( tdsqlite3IsNaN(rB) ){ goto arithmetic_result_is_null; } pOut->u.r = rB; MemSetTypeFlag(pOut, MEM_Real); - if( ((type1|type2)&MEM_Real)==0 && !bIntint ){ - sqlite3VdbeIntegerAffinity(pOut); - } #endif } break; arithmetic_result_is_null: - sqlite3VdbeMemSetNull(pOut); + tdsqlite3VdbeMemSetNull(pOut); break; } /* Opcode: CollSeq P1 * * P4 ** -** P4 is a pointer to a CollSeq struct. If the next call to a user function -** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will +** P4 is a pointer to a CollSeq object. If the next call to a user function +** or aggregate calls tdsqlite3GetFuncCollSeq(), this collation sequence will ** be returned. This is used by the built-in min(), max() and nullif() ** functions. ** @@ -81979,121 +90210,8 @@ arithmetic_result_is_null: case OP_CollSeq: { assert( pOp->p4type==P4_COLLSEQ ); if( pOp->p1 ){ - sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0); - } - break; -} - -/* Opcode: Function0 P1 P2 P3 P4 P5 -** Synopsis: r[P3]=func(r[P2@P5]) -** -** Invoke a user function (P4 is a pointer to a FuncDef object that -** defines the function) with P5 arguments taken from register P2 and -** successors. The result of the function is stored in register P3. -** Register P3 must not be one of the function inputs. -** -** P1 is a 32-bit bitmask indicating whether or not each argument to the -** function was determined to be constant at compile time. If the first -** argument was constant then bit 0 of P1 is set. This is used to determine -** whether meta data associated with a user function argument using the -** sqlite3_set_auxdata() API may be safely retained until the next -** invocation of this opcode. -** -** See also: Function, AggStep, AggFinal -*/ -/* Opcode: Function P1 P2 P3 P4 P5 -** Synopsis: r[P3]=func(r[P2@P5]) -** -** Invoke a user function (P4 is a pointer to an sqlite3_context object that -** contains a pointer to the function to be run) with P5 arguments taken -** from register P2 and successors. The result of the function is stored -** in register P3. Register P3 must not be one of the function inputs. -** -** P1 is a 32-bit bitmask indicating whether or not each argument to the -** function was determined to be constant at compile time. If the first -** argument was constant then bit 0 of P1 is set. This is used to determine -** whether meta data associated with a user function argument using the -** sqlite3_set_auxdata() API may be safely retained until the next -** invocation of this opcode. -** -** SQL functions are initially coded as OP_Function0 with P4 pointing -** to a FuncDef object. But on first evaluation, the P4 operand is -** automatically converted into an sqlite3_context object and the operation -** changed to this OP_Function opcode. In this way, the initialization of -** the sqlite3_context object occurs only once, rather than once for each -** evaluation of the function. -** -** See also: Function0, AggStep, AggFinal -*/ -case OP_Function0: { - int n; - sqlite3_context *pCtx; - - assert( pOp->p4type==P4_FUNCDEF ); - n = pOp->p5; - assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); - assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) ); - assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n ); - pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*)); - if( pCtx==0 ) goto no_mem; - pCtx->pOut = 0; - pCtx->pFunc = pOp->p4.pFunc; - pCtx->iOp = (int)(pOp - aOp); - pCtx->pVdbe = p; - pCtx->argc = n; - pOp->p4type = P4_FUNCCTX; - pOp->p4.pCtx = pCtx; - pOp->opcode = OP_Function; - /* Fall through into OP_Function */ -} -case OP_Function: { - int i; - sqlite3_context *pCtx; - - assert( pOp->p4type==P4_FUNCCTX ); - pCtx = pOp->p4.pCtx; - - /* If this function is inside of a trigger, the register array in aMem[] - ** might change from one evaluation to the next. The next block of code - ** checks to see if the register array has changed, and if so it - ** reinitializes the relavant parts of the sqlite3_context object */ - pOut = &aMem[pOp->p3]; - if( pCtx->pOut != pOut ){ - pCtx->pOut = pOut; - for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; - } - - memAboutToChange(p, pCtx->pOut); -#ifdef SQLITE_DEBUG - for(i=0; i<pCtx->argc; i++){ - assert( memIsValid(pCtx->argv[i]) ); - REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); - } -#endif - MemSetTypeFlag(pCtx->pOut, MEM_Null); - pCtx->fErrorOrAux = 0; - db->lastRowid = lastRowid; - (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */ - lastRowid = db->lastRowid; /* Remember rowid changes made by xSFunc */ - - /* If the function returned an error, throw an exception */ - if( pCtx->fErrorOrAux ){ - if( pCtx->isError ){ - sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut)); - rc = pCtx->isError; - } - sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1); - if( rc ) goto abort_due_to_error; - } - - /* Copy the result of the function into register P3 */ - if( pOut->flags & (MEM_Str|MEM_Blob) ){ - sqlite3VdbeChangeEncoding(pCtx->pOut, encoding); - if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big; + tdsqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0); } - - REGISTER_TRACE(pOp->p3, pCtx->pOut); - UPDATE_MAX_BLOBSIZE(pCtx->pOut); break; } @@ -82140,11 +90258,11 @@ case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ pIn2 = &aMem[pOp->p2]; pOut = &aMem[pOp->p3]; if( (pIn1->flags | pIn2->flags) & MEM_Null ){ - sqlite3VdbeMemSetNull(pOut); + tdsqlite3VdbeMemSetNull(pOut); break; } - iA = sqlite3VdbeIntValue(pIn2); - iB = sqlite3VdbeIntValue(pIn1); + iA = tdsqlite3VdbeIntValue(pIn2); + iB = tdsqlite3VdbeIntValue(pIn1); op = pOp->opcode; if( op==OP_BitAnd ){ iA &= iB; @@ -82190,7 +90308,7 @@ case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ case OP_AddImm: { /* in1 */ pIn1 = &aMem[pOp->p1]; memAboutToChange(p, pIn1); - sqlite3VdbeMemIntegerify(pIn1); + tdsqlite3VdbeMemIntegerify(pIn1); pIn1->u.i += pOp->p2; break; } @@ -82206,8 +90324,8 @@ case OP_MustBeInt: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; if( (pIn1->flags & MEM_Int)==0 ){ applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); - VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2); if( (pIn1->flags & MEM_Int)==0 ){ + VdbeBranchTaken(1, 2); if( pOp->p2==0 ){ rc = SQLITE_MISMATCH; goto abort_due_to_error; @@ -82216,6 +90334,7 @@ case OP_MustBeInt: { /* jump, in1 */ } } } + VdbeBranchTaken(0, 2); MemSetTypeFlag(pIn1, MEM_Int); break; } @@ -82232,8 +90351,11 @@ case OP_MustBeInt: { /* jump, in1 */ */ case OP_RealAffinity: { /* in1 */ pIn1 = &aMem[pOp->p1]; - if( pIn1->flags & MEM_Int ){ - sqlite3VdbeMemRealify(pIn1); + if( pIn1->flags & (MEM_Int|MEM_IntReal) ){ + testcase( pIn1->flags & MEM_Int ); + testcase( pIn1->flags & MEM_IntReal ); + tdsqlite3VdbeMemRealify(pIn1); + REGISTER_TRACE(pOp->p1, pIn1); } break; } @@ -82246,11 +90368,11 @@ case OP_RealAffinity: { /* in1 */ ** Force the value in register P1 to be the type defined by P2. ** ** <ul> -** <li value="97"> TEXT -** <li value="98"> BLOB -** <li value="99"> NUMERIC -** <li value="100"> INTEGER -** <li value="101"> REAL +** <li> P2=='A' → BLOB +** <li> P2=='B' → TEXT +** <li> P2=='C' → NUMERIC +** <li> P2=='D' → INTEGER +** <li> P2=='E' → REAL ** </ul> ** ** A NULL value is not changed by this routine. It remains NULL. @@ -82265,9 +90387,11 @@ case OP_Cast: { /* in1 */ pIn1 = &aMem[pOp->p1]; memAboutToChange(p, pIn1); rc = ExpandBlob(pIn1); - sqlite3VdbeMemCast(pIn1, pOp->p2, encoding); - UPDATE_MAX_BLOBSIZE(pIn1); if( rc ) goto abort_due_to_error; + rc = tdsqlite3VdbeMemCast(pIn1, pOp->p2, encoding); + if( rc ) goto abort_due_to_error; + UPDATE_MAX_BLOBSIZE(pIn1); + REGISTER_TRACE(pOp->p1, pIn1); break; } #endif /* SQLITE_OMIT_CAST */ @@ -82390,16 +90514,15 @@ case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ ** OP_Eq or OP_Ne) then take the jump or not depending on whether ** or not both operands are null. */ - assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne ); assert( (flags1 & MEM_Cleared)==0 ); - assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 ); - if( (flags1&MEM_Null)!=0 - && (flags3&MEM_Null)!=0 + assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB ); + testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 ); + if( (flags1&flags3&MEM_Null)!=0 && (flags3&MEM_Cleared)==0 ){ res = 0; /* Operands are equal */ }else{ - res = 1; /* Operands are not equal */ + res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */ } }else{ /* SQLITE_NULLEQ is clear and at least one operand is NULL, @@ -82425,17 +90548,17 @@ case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ affinity = pOp->p5 & SQLITE_AFF_MASK; if( affinity>=SQLITE_AFF_NUMERIC ){ if( (flags1 | flags3)&MEM_Str ){ - if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ + if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){ applyNumericAffinity(pIn1,0); - testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */ + testcase( flags3!=pIn3->flags ); flags3 = pIn3->flags; } - if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ + if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){ applyNumericAffinity(pIn3,0); } } /* Handle the common case of integer comparison here, as an - ** optimization, to avoid a call to sqlite3MemCompare() */ + ** optimization, to avoid a call to tdsqlite3MemCompare() */ if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){ if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; } if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; } @@ -82443,45 +90566,56 @@ case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ goto compare_op; } }else if( affinity==SQLITE_AFF_TEXT ){ - if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){ + if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){ testcase( pIn1->flags & MEM_Int ); testcase( pIn1->flags & MEM_Real ); - sqlite3VdbeMemStringify(pIn1, encoding, 1); + testcase( pIn1->flags & MEM_IntReal ); + tdsqlite3VdbeMemStringify(pIn1, encoding, 1); testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) ); flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask); - assert( pIn1!=pIn3 ); + if( pIn1==pIn3 ) flags3 = flags1 | MEM_Str; } - if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){ + if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){ testcase( pIn3->flags & MEM_Int ); testcase( pIn3->flags & MEM_Real ); - sqlite3VdbeMemStringify(pIn3, encoding, 1); + testcase( pIn3->flags & MEM_IntReal ); + tdsqlite3VdbeMemStringify(pIn3, encoding, 1); testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) ); flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask); } } assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 ); - res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); + res = tdsqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); } compare_op: - switch( pOp->opcode ){ - case OP_Eq: res2 = res==0; break; - case OP_Ne: res2 = res; break; - case OP_Lt: res2 = res<0; break; - case OP_Le: res2 = res<=0; break; - case OP_Gt: res2 = res>0; break; - default: res2 = res>=0; break; + /* At this point, res is negative, zero, or positive if reg[P1] is + ** less than, equal to, or greater than reg[P3], respectively. Compute + ** the answer to this operator in res2, depending on what the comparison + ** operator actually is. The next block of code depends on the fact + ** that the 6 comparison operators are consecutive integers in this + ** order: NE, EQ, GT, LE, LT, GE */ + assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 ); + assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 ); + if( res<0 ){ /* ne, eq, gt, le, lt, ge */ + static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 }; + res2 = aLTb[pOp->opcode - OP_Ne]; + }else if( res==0 ){ + static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 }; + res2 = aEQb[pOp->opcode - OP_Ne]; + }else{ + static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 }; + res2 = aGTb[pOp->opcode - OP_Ne]; } /* Undo any changes made by applyAffinity() to the input registers. */ - assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); - pIn1->flags = flags1; assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) ); pIn3->flags = flags3; + assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); + pIn1->flags = flags1; if( pOp->p5 & SQLITE_STOREP2 ){ pOut = &aMem[pOp->p2]; iCompare = res; - res2 = res2!=0; /* For this path res2 must be exactly 0 or 1 */ if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){ /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1 ** and prevents OP_Ne from overwriting NULL with 0. This flag @@ -82503,7 +90637,7 @@ compare_op: pOut->u.i = res2; REGISTER_TRACE(pOp->p2, pOut); }else{ - VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3); + VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3); if( res2 ){ goto jump_to_p2; } @@ -82513,16 +90647,31 @@ compare_op: /* Opcode: ElseNotEq * P2 * * * ** -** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator. -** If result of an OP_Eq comparison on the same two operands -** would have be NULL or false (0), then then jump to P2. -** If the result of an OP_Eq comparison on the two previous operands -** would have been true (1), then fall through. +** This opcode must follow an OP_Lt or OP_Gt comparison operator. There +** can be zero or more OP_ReleaseReg opcodes intervening, but no other +** opcodes are allowed to occur between this instruction and the previous +** OP_Lt or OP_Gt. Furthermore, the prior OP_Lt or OP_Gt must have the +** SQLITE_STOREP2 bit set in the P5 field. +** +** If result of an OP_Eq comparison on the same two operands as the +** prior OP_Lt or OP_Gt would have been NULL or false (0), then then +** jump to P2. If the result of an OP_Eq comparison on the two previous +** operands would have been true (1), then fall through. */ case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */ - assert( pOp>aOp ); - assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt ); - assert( pOp[-1].p5 & SQLITE_STOREP2 ); + +#ifdef SQLITE_DEBUG + /* Verify the preconditions of this opcode - that it follows an OP_Lt or + ** OP_Gt with the SQLITE_STOREP2 flag set, with zero or more intervening + ** OP_ReleaseReg opcodes */ + int iAddr; + for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){ + if( aOp[iAddr].opcode==OP_ReleaseReg ) continue; + assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt ); + assert( aOp[iAddr].p5 & SQLITE_STOREP2 ); + break; + } +#endif /* SQLITE_DEBUG */ VdbeBranchTaken(iCompare!=0, 2); if( iCompare!=0 ) goto jump_to_p2; break; @@ -82531,8 +90680,8 @@ case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */ /* Opcode: Permutation * * * P4 * ** -** Set the permutation used by the OP_Compare operator to be the array -** of integers in P4. +** Set the permutation used by the OP_Compare operator in the next +** instruction. The permutation is stored in the P4 operand. ** ** The permutation is only valid until the next OP_Compare that has ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should @@ -82544,7 +90693,8 @@ case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */ case OP_Permutation: { assert( pOp->p4type==P4_INTARRAY ); assert( pOp->p4.ai ); - aPermute = pOp->p4.ai + 1; + assert( pOp[1].opcode==OP_Compare ); + assert( pOp[1].p5 & OPFLAG_PERMUTE ); break; } @@ -82577,15 +90727,24 @@ case OP_Compare: { int idx; CollSeq *pColl; /* Collating sequence to use on this term */ int bRev; /* True for DESCENDING sort order */ + int *aPermute; /* The permutation */ - if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0; + if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){ + aPermute = 0; + }else{ + assert( pOp>aOp ); + assert( pOp[-1].opcode==OP_Permutation ); + assert( pOp[-1].p4type==P4_INTARRAY ); + aPermute = pOp[-1].p4.ai + 1; + assert( aPermute!=0 ); + } n = pOp->p3; pKeyInfo = pOp->p4.pKeyInfo; assert( n>0 ); assert( pKeyInfo!=0 ); p1 = pOp->p1; p2 = pOp->p2; -#if SQLITE_DEBUG +#ifdef SQLITE_DEBUG if( aPermute ){ int k, mx = 0; for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k]; @@ -82602,16 +90761,20 @@ case OP_Compare: { assert( memIsValid(&aMem[p2+idx]) ); REGISTER_TRACE(p1+idx, &aMem[p1+idx]); REGISTER_TRACE(p2+idx, &aMem[p2+idx]); - assert( i<pKeyInfo->nField ); + assert( i<pKeyInfo->nKeyField ); pColl = pKeyInfo->aColl[i]; - bRev = pKeyInfo->aSortOrder[i]; - iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl); + bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC); + iCompare = tdsqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl); if( iCompare ){ + if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) + && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null)) + ){ + iCompare = -iCompare; + } if( bRev ) iCompare = -iCompare; break; } } - aPermute = 0; break; } @@ -82623,11 +90786,11 @@ case OP_Compare: { */ case OP_Jump: { /* jump */ if( iCompare<0 ){ - VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1]; + VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1]; }else if( iCompare==0 ){ - VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1]; + VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1]; }else{ - VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1]; + VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1]; } break; } @@ -82657,18 +90820,8 @@ case OP_Or: { /* same as TK_OR, in1, in2, out3 */ int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ - pIn1 = &aMem[pOp->p1]; - if( pIn1->flags & MEM_Null ){ - v1 = 2; - }else{ - v1 = sqlite3VdbeIntValue(pIn1)!=0; - } - pIn2 = &aMem[pOp->p2]; - if( pIn2->flags & MEM_Null ){ - v2 = 2; - }else{ - v2 = sqlite3VdbeIntValue(pIn2)!=0; - } + v1 = tdsqlite3VdbeBooleanValue(&aMem[pOp->p1], 2); + v2 = tdsqlite3VdbeBooleanValue(&aMem[pOp->p2], 2); if( pOp->opcode==OP_And ){ static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 }; v1 = and_logic[v1*3+v2]; @@ -82686,6 +90839,35 @@ case OP_Or: { /* same as TK_OR, in1, in2, out3 */ break; } +/* Opcode: IsTrue P1 P2 P3 P4 * +** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 +** +** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and +** IS NOT FALSE operators. +** +** Interpret the value in register P1 as a boolean value. Store that +** boolean (a 0 or 1) in register P2. Or if the value in register P1 is +** NULL, then the P3 is stored in register P2. Invert the answer if P4 +** is 1. +** +** The logic is summarized like this: +** +** <ul> +** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE +** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE +** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE +** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE +** </ul> +*/ +case OP_IsTrue: { /* in1, out2 */ + assert( pOp->p4type==P4_INT32 ); + assert( pOp->p4.i==0 || pOp->p4.i==1 ); + assert( pOp->p3==0 || pOp->p3==1 ); + tdsqlite3VdbeMemSetInt64(&aMem[pOp->p2], + tdsqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i); + break; +} + /* Opcode: Not P1 P2 * * * ** Synopsis: r[P2]= !r[P1] ** @@ -82696,16 +90878,16 @@ case OP_Or: { /* same as TK_OR, in1, in2, out3 */ case OP_Not: { /* same as TK_NOT, in1, out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; - sqlite3VdbeMemSetNull(pOut); if( (pIn1->flags & MEM_Null)==0 ){ - pOut->flags = MEM_Int; - pOut->u.i = !sqlite3VdbeIntValue(pIn1); + tdsqlite3VdbeMemSetInt64(pOut, !tdsqlite3VdbeBooleanValue(pIn1,0)); + }else{ + tdsqlite3VdbeMemSetNull(pOut); } break; } /* Opcode: BitNot P1 P2 * * * -** Synopsis: r[P1]= ~r[P1] +** Synopsis: r[P2]= ~r[P1] ** ** Interpret the content of register P1 as an integer. Store the ** ones-complement of the P1 value into register P2. If P1 holds @@ -82714,29 +90896,49 @@ case OP_Not: { /* same as TK_NOT, in1, out2 */ case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ pIn1 = &aMem[pOp->p1]; pOut = &aMem[pOp->p2]; - sqlite3VdbeMemSetNull(pOut); + tdsqlite3VdbeMemSetNull(pOut); if( (pIn1->flags & MEM_Null)==0 ){ pOut->flags = MEM_Int; - pOut->u.i = ~sqlite3VdbeIntValue(pIn1); + pOut->u.i = ~tdsqlite3VdbeIntValue(pIn1); } break; } /* Opcode: Once P1 P2 * * * ** -** If the P1 value is equal to the P1 value on the OP_Init opcode at -** instruction 0, then jump to P2. If the two P1 values differ, then -** set the P1 value on this opcode to equal the P1 value on the OP_Init -** and fall through. +** Fall through to the next instruction the first time this opcode is +** encountered on each invocation of the byte-code program. Jump to P2 +** on the second and all subsequent encounters during the same invocation. +** +** Top-level programs determine first invocation by comparing the P1 +** operand against the P1 operand on the OP_Init opcode at the beginning +** of the program. If the P1 values differ, then fall through and make +** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are +** the same then take the jump. +** +** For subprograms, there is a bitmask in the VdbeFrame that determines +** whether or not the jump should be taken. The bitmask is necessary +** because the self-altering code trick does not work for recursive +** triggers. */ case OP_Once: { /* jump */ + u32 iAddr; /* Address of this instruction */ assert( p->aOp[0].opcode==OP_Init ); - VdbeBranchTaken(p->aOp[0].p1==pOp->p1, 2); - if( p->aOp[0].p1==pOp->p1 ){ - goto jump_to_p2; + if( p->pFrame ){ + iAddr = (int)(pOp - p->aOp); + if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){ + VdbeBranchTaken(1, 2); + goto jump_to_p2; + } + p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7); }else{ - pOp->p1 = p->aOp[0].p1; + if( p->aOp[0].p1==pOp->p1 ){ + VdbeBranchTaken(1, 2); + goto jump_to_p2; + } } + VdbeBranchTaken(0, 2); + pOp->p1 = p->aOp[0].p1; break; } @@ -82746,30 +90948,25 @@ case OP_Once: { /* jump */ ** is considered true if it is numeric and non-zero. If the value ** in P1 is NULL then take the jump if and only if P3 is non-zero. */ +case OP_If: { /* jump, in1 */ + int c; + c = tdsqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3); + VdbeBranchTaken(c!=0, 2); + if( c ) goto jump_to_p2; + break; +} + /* Opcode: IfNot P1 P2 P3 * * ** ** Jump to P2 if the value in register P1 is False. The value ** is considered false if it has a numeric value of zero. If the value ** in P1 is NULL then take the jump if and only if P3 is non-zero. */ -case OP_If: /* jump, in1 */ case OP_IfNot: { /* jump, in1 */ int c; - pIn1 = &aMem[pOp->p1]; - if( pIn1->flags & MEM_Null ){ - c = pOp->p3; - }else{ -#ifdef SQLITE_OMIT_FLOATING_POINT - c = sqlite3VdbeIntValue(pIn1)!=0; -#else - c = sqlite3VdbeRealValue(pIn1)!=0.0; -#endif - if( pOp->opcode==OP_IfNot ) c = !c; - } + c = !tdsqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3); VdbeBranchTaken(c!=0, 2); - if( c ){ - goto jump_to_p2; - } + if( c ) goto jump_to_p2; break; } @@ -82801,6 +90998,54 @@ case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ break; } +/* Opcode: IfNullRow P1 P2 P3 * * +** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2 +** +** Check the cursor P1 to see if it is currently pointing at a NULL row. +** If it is, then set register P3 to NULL and jump immediately to P2. +** If P1 is not on a NULL row, then fall through without making any +** changes. +*/ +case OP_IfNullRow: { /* jump */ + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + assert( p->apCsr[pOp->p1]!=0 ); + if( p->apCsr[pOp->p1]->nullRow ){ + tdsqlite3VdbeMemSetNull(aMem + pOp->p3); + goto jump_to_p2; + } + break; +} + +#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC +/* Opcode: Offset P1 P2 P3 * * +** Synopsis: r[P3] = sqlite_offset(P1) +** +** Store in register r[P3] the byte offset into the database file that is the +** start of the payload for the record at which that cursor P1 is currently +** pointing. +** +** P2 is the column number for the argument to the sqlite_offset() function. +** This opcode does not use P2 itself, but the P2 value is used by the +** code generator. The P1, P2, and P3 operands to this opcode are the +** same as for OP_Column. +** +** This opcode is only available if SQLite is compiled with the +** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option. +*/ +case OP_Offset: { /* out3 */ + VdbeCursor *pC; /* The VDBE cursor */ + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + pC = p->apCsr[pOp->p1]; + pOut = &p->aMem[pOp->p3]; + if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){ + tdsqlite3VdbeMemSetNull(pOut); + }else{ + tdsqlite3VdbeMemSetInt64(pOut, tdsqlite3BtreeOffset(pC->uc.pCursor)); + } + break; +} +#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */ + /* Opcode: Column P1 P2 P3 P4 P5 ** Synopsis: r[P3]=PX ** @@ -82812,16 +91057,11 @@ case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ ** ** The value extracted is stored in register P3. ** -** If the column contains fewer than P2 fields, then extract a NULL. Or, +** If the record contains fewer than P2 fields, then extract a NULL. Or, ** if the P4 argument is a P4_MEM use the value of the P4 argument as ** the result. ** -** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor, -** then the cache of the cursor is reset prior to extracting the column. -** The first OP_Column against a pseudo-table after the value of the content -** register has changed should have this bit set. -** -** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when +** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then ** the result is guaranteed to only be used as the argument of a length() ** or typeof() function, respectively. The loading of large blobs can be ** skipped for length() and all content loading can be skipped for typeof(). @@ -82838,66 +91078,65 @@ case OP_Column: { const u8 *zData; /* Part of the record being decoded */ const u8 *zHdr; /* Next unparsed byte of the header */ const u8 *zEndHdr; /* Pointer to first byte after the header */ - u32 offset; /* Offset into the data */ u64 offset64; /* 64-bit offset */ - u32 avail; /* Number of bytes of available data */ u32 t; /* A type code from the record header */ Mem *pReg; /* PseudoTable input register */ + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); p2 = pOp->p2; - /* If the cursor cache is stale, bring it up-to-date */ - rc = sqlite3VdbeCursorMoveto(&pC, &p2); + /* If the cursor cache is stale (meaning it is not currently point at + ** the correct row) then bring it up-to-date by doing the necessary + ** B-Tree seek. */ + rc = tdsqlite3VdbeCursorMoveto(&pC, &p2); if( rc ) goto abort_due_to_error; assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pDest = &aMem[pOp->p3]; memAboutToChange(p, pDest); - assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( pC!=0 ); assert( p2<pC->nField ); aOffset = pC->aOffset; assert( pC->eCurType!=CURTYPE_VTAB ); assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); assert( pC->eCurType!=CURTYPE_SORTER ); - pCrsr = pC->uc.pCursor; if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/ if( pC->nullRow ){ if( pC->eCurType==CURTYPE_PSEUDO ){ - assert( pC->uc.pseudoTableReg>0 ); - pReg = &aMem[pC->uc.pseudoTableReg]; + /* For the special case of as pseudo-cursor, the seekResult field + ** identifies the register that holds the record */ + assert( pC->seekResult>0 ); + pReg = &aMem[pC->seekResult]; assert( pReg->flags & MEM_Blob ); assert( memIsValid(pReg) ); - pC->payloadSize = pC->szRow = avail = pReg->n; + pC->payloadSize = pC->szRow = pReg->n; pC->aRow = (u8*)pReg->z; }else{ - sqlite3VdbeMemSetNull(pDest); + tdsqlite3VdbeMemSetNull(pDest); goto op_column_out; } }else{ + pCrsr = pC->uc.pCursor; assert( pC->eCurType==CURTYPE_BTREE ); assert( pCrsr ); - assert( sqlite3BtreeCursorIsValid(pCrsr) ); - pC->payloadSize = sqlite3BtreePayloadSize(pCrsr); - pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail); - assert( avail<=65536 ); /* Maximum page size is 64KiB */ - if( pC->payloadSize <= (u32)avail ){ - pC->szRow = pC->payloadSize; - }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ + assert( tdsqlite3BtreeCursorIsValid(pCrsr) ); + pC->payloadSize = tdsqlite3BtreePayloadSize(pCrsr); + pC->aRow = tdsqlite3BtreePayloadFetch(pCrsr, &pC->szRow); + assert( pC->szRow<=pC->payloadSize ); + assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */ + if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; - }else{ - pC->szRow = avail; } } pC->cacheStatus = p->cacheCtr; - pC->iHdrOffset = getVarint32(pC->aRow, offset); + pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]); pC->nHdrParsed = 0; - aOffset[0] = offset; - if( avail<offset ){ /*OPTIMIZATION-IF-FALSE*/ + if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/ /* pC->aRow does not have to hold the entire row, but it does at least ** need to cover the header of the record. If pC->aRow does not contain ** the complete header, then set it to zero, forcing the header to be @@ -82914,17 +91153,26 @@ case OP_Column: { ** 3-byte type for each of the maximum of 32768 columns plus three ** extra bytes for the header length itself. 32768*3 + 3 = 98307. */ - if( offset > 98307 || offset > pC->payloadSize ){ - rc = SQLITE_CORRUPT_BKPT; - goto abort_due_to_error; + if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){ + goto op_column_corrupt; } - }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/ - /* The following goto is an optimization. It can be omitted and - ** everything will still work. But OP_Column is measurably faster - ** by skipping the subsequent conditional, which is always true. + }else{ + /* This is an optimization. By skipping over the first few tests + ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a + ** measurable performance gain. + ** + ** This branch is taken even if aOffset[0]==0. Such a record is never + ** generated by SQLite, and could be considered corruption, but we + ** accept it for historical reasons. When aOffset[0]==0, the code this + ** branch jumps to reads past the end of the record, but never more + ** than a few bytes. Even if the record occurs at the end of the page + ** content area, the "page header" comes after the page content and so + ** this overread is harmless. Similar overreads can occur for a corrupt + ** database file. */ zData = pC->aRow; assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */ + testcase( aOffset[0]==0 ); goto op_column_read_header; } } @@ -82940,7 +91188,7 @@ case OP_Column: { /* Make sure zData points to enough of the record to cover the header. */ if( pC->aRow==0 ){ memset(&sMem, 0, sizeof(sMem)); - rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem); + rc = tdsqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem); if( rc!=SQLITE_OK ) goto abort_due_to_error; zData = (u8*)sMem.z; }else{ @@ -82953,16 +91201,17 @@ case OP_Column: { offset64 = aOffset[i]; zHdr = zData + pC->iHdrOffset; zEndHdr = zData + aOffset[0]; + testcase( zHdr>=zEndHdr ); do{ - if( (t = zHdr[0])<0x80 ){ + if( (pC->aType[i] = t = zHdr[0])<0x80 ){ zHdr++; - offset64 += sqlite3VdbeOneByteSerialTypeLen(t); + offset64 += tdsqlite3VdbeOneByteSerialTypeLen(t); }else{ - zHdr += sqlite3GetVarint32(zHdr, &t); - offset64 += sqlite3VdbeSerialTypeLen(t); + zHdr += tdsqlite3GetVarint32(zHdr, &t); + pC->aType[i] = t; + offset64 += tdsqlite3VdbeSerialTypeLen(t); } - pC->aType[i++] = t; - aOffset[i] = (u32)(offset64 & 0xffffffff); + aOffset[++i] = (u32)(offset64 & 0xffffffff); }while( i<=p2 && zHdr<zEndHdr ); /* The record is corrupt if any of the following are true: @@ -82973,14 +91222,18 @@ case OP_Column: { if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize)) || (offset64 > pC->payloadSize) ){ - if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); - rc = SQLITE_CORRUPT_BKPT; - goto abort_due_to_error; + if( aOffset[0]==0 ){ + i = 0; + zHdr = zEndHdr; + }else{ + if( pC->aRow==0 ) tdsqlite3VdbeMemRelease(&sMem); + goto op_column_corrupt; + } } pC->nHdrParsed = i; pC->iHdrOffset = (u32)(zHdr - zData); - if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); + if( pC->aRow==0 ) tdsqlite3VdbeMemRelease(&sMem); }else{ t = 0; } @@ -82991,9 +91244,9 @@ case OP_Column: { */ if( pC->nHdrParsed<=p2 ){ if( pOp->p4type==P4_MEM ){ - sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static); + tdsqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static); }else{ - sqlite3VdbeMemSetNull(pDest); + tdsqlite3VdbeMemSetNull(pDest); } goto op_column_out; } @@ -83007,9 +91260,9 @@ case OP_Column: { */ assert( p2<pC->nHdrParsed ); assert( rc==SQLITE_OK ); - assert( sqlite3VdbeCheckMemInvariants(pDest) ); + assert( tdsqlite3VdbeCheckMemInvariants(pDest) ); if( VdbeMemDynamic(pDest) ){ - sqlite3VdbeMemSetNull(pDest); + tdsqlite3VdbeMemSetNull(pDest); } assert( t==pC->aType[p2] ); if( pC->szRow>=aOffset[p2+1] ){ @@ -83017,18 +91270,18 @@ case OP_Column: { ** page - where the content is not on an overflow page */ zData = pC->aRow + aOffset[p2]; if( t<12 ){ - sqlite3VdbeSerialGet(zData, t, pDest); + tdsqlite3VdbeSerialGet(zData, t, pDest); }else{ /* If the column value is a string, we need a persistent value, not ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent - ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize(). + ** to calling tdsqlite3VdbeSerialGet() and tdsqlite3VdbeDeephemeralize(). */ static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term }; pDest->n = len = (t-12)/2; pDest->enc = encoding; if( pDest->szMalloc < len+2 ){ pDest->flags = MEM_Null; - if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem; + if( tdsqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem; }else{ pDest->z = pDest->zMalloc; } @@ -83042,21 +91295,26 @@ case OP_Column: { /* This branch happens only when content is on overflow pages */ if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)) - || (len = sqlite3VdbeSerialTypeLen(t))==0 + || (len = tdsqlite3VdbeSerialTypeLen(t))==0 ){ /* Content is irrelevant for ** 1. the typeof() function, ** 2. the length(X) function if X is a blob, and ** 3. if the content length is zero. ** So we might as well use bogus content rather than reading - ** content from disk. */ - static u8 aZero[8]; /* This is the bogus content */ - sqlite3VdbeSerialGet(aZero, t, pDest); + ** content from disk. + ** + ** Although tdsqlite3VdbeSerialGet() may read at most 8 bytes from the + ** buffer passed to it, debugging function VdbeMemPrettyPrint() may + ** read more. Use the global constant tdsqlite3CtypeMap[] as the array, + ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint()) + ** and it begins with a bunch of zeros. + */ + tdsqlite3VdbeSerialGet((u8*)tdsqlite3CtypeMap, t, pDest); }else{ - rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable, - pDest); + rc = tdsqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest); if( rc!=SQLITE_OK ) goto abort_due_to_error; - sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest); + tdsqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest); pDest->flags &= ~MEM_Ephem; } } @@ -83065,6 +91323,15 @@ op_column_out: UPDATE_MAX_BLOBSIZE(pDest); REGISTER_TRACE(pOp->p3, pDest); break; + +op_column_corrupt: + if( aOp[0].p3>0 ){ + pOp = &aOp[aOp[0].p3-1]; + break; + }else{ + rc = SQLITE_CORRUPT_BKPT; + goto abort_due_to_error; + } } /* Opcode: Affinity P1 P2 * P4 * @@ -83072,22 +91339,43 @@ op_column_out: ** ** Apply affinities to a range of P2 registers starting with P1. ** -** P4 is a string that is P2 characters long. The nth character of the -** string indicates the column affinity that should be used for the nth +** P4 is a string that is P2 characters long. The N-th character of the +** string indicates the column affinity that should be used for the N-th ** memory cell in the range. */ case OP_Affinity: { const char *zAffinity; /* The affinity to be applied */ - char cAff; /* A single character of affinity */ zAffinity = pOp->p4.z; assert( zAffinity!=0 ); + assert( pOp->p2>0 ); assert( zAffinity[pOp->p2]==0 ); pIn1 = &aMem[pOp->p1]; - while( (cAff = *(zAffinity++))!=0 ){ + while( 1 /*exit-by-break*/ ){ assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] ); - assert( memIsValid(pIn1) ); - applyAffinity(pIn1, cAff, encoding); + assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) ); + applyAffinity(pIn1, zAffinity[0], encoding); + if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){ + /* When applying REAL affinity, if the result is still an MEM_Int + ** that will fit in 6 bytes, then change the type to MEM_IntReal + ** so that we keep the high-resolution integer value but know that + ** the type really wants to be REAL. */ + testcase( pIn1->u.i==140737488355328LL ); + testcase( pIn1->u.i==140737488355327LL ); + testcase( pIn1->u.i==-140737488355328LL ); + testcase( pIn1->u.i==-140737488355329LL ); + if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){ + pIn1->flags |= MEM_IntReal; + pIn1->flags &= ~MEM_Int; + }else{ + pIn1->u.r = (double)pIn1->u.i; + pIn1->flags |= MEM_Real; + pIn1->flags &= ~MEM_Int; + } + } + REGISTER_TRACE((int)(pIn1-aMem), pIn1); + zAffinity++; + if( zAffinity[0]==0 ) break; pIn1++; } break; @@ -83100,8 +91388,8 @@ case OP_Affinity: { ** use as a data record in a database table or as a key ** in an index. The OP_Column opcode can decode the record later. ** -** P4 may be a string that is P2 characters long. The nth character of the -** string indicates the column affinity that should be used for the nth +** P4 may be a string that is P2 characters long. The N-th character of the +** string indicates the column affinity that should be used for the N-th ** field of the index key. ** ** The mapping from character to affinity is given by the SQLITE_AFF_ @@ -83110,7 +91398,6 @@ case OP_Affinity: { ** If P4 is NULL then all index fields have the affinity BLOB. */ case OP_MakeRecord: { - u8 *zNewRecord; /* A buffer to hold the data for the new record */ Mem *pRec; /* The new record */ u64 nData; /* Number of bytes of data space */ int nHdr; /* Number of bytes of header space */ @@ -83123,9 +91410,9 @@ case OP_MakeRecord: { int nField; /* Number of fields in the record */ char *zAffinity; /* The affinity string for the record */ int file_format; /* File format to use for encoding */ - int i; /* Space used in zNewRecord[] header */ - int j; /* Space used in zNewRecord[] content */ u32 len; /* Length of a field */ + u8 *zHdr; /* Where to write next byte of the header */ + u8 *zPayload; /* Where to write next byte of the payload */ /* Assuming the record contains N fields, the record format looks ** like this: @@ -83138,7 +91425,7 @@ case OP_MakeRecord: { ** and so forth. ** ** Each type field is a varint representing the serial type of the - ** corresponding data element (see sqlite3VdbeSerialType()). The + ** corresponding data element (see tdsqlite3VdbeSerialType()). The ** hdr-size field is also a varint which is the offset from the beginning ** of the record to data0. */ @@ -83164,30 +91451,147 @@ case OP_MakeRecord: { if( zAffinity ){ pRec = pData0; do{ - applyAffinity(pRec++, *(zAffinity++), encoding); + applyAffinity(pRec, zAffinity[0], encoding); + if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){ + pRec->flags |= MEM_IntReal; + pRec->flags &= ~(MEM_Int); + } + REGISTER_TRACE((int)(pRec-aMem), pRec); + zAffinity++; + pRec++; assert( zAffinity[0]==0 || pRec<=pLast ); }while( zAffinity[0] ); } +#ifdef SQLITE_ENABLE_NULL_TRIM + /* NULLs can be safely trimmed from the end of the record, as long as + ** as the schema format is 2 or more and none of the omitted columns + ** have a non-NULL default value. Also, the record must be left with + ** at least one field. If P5>0 then it will be one more than the + ** index of the right-most column with a non-NULL default value */ + if( pOp->p5 ){ + while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){ + pLast--; + nField--; + } + } +#endif + /* Loop through the elements that will make up the record to figure - ** out how much space is required for the new record. + ** out how much space is required for the new record. After this loop, + ** the Mem.uTemp field of each term should hold the serial-type that will + ** be used for that term in the generated record: + ** + ** Mem.uTemp value type + ** --------------- --------------- + ** 0 NULL + ** 1 1-byte signed integer + ** 2 2-byte signed integer + ** 3 3-byte signed integer + ** 4 4-byte signed integer + ** 5 6-byte signed integer + ** 6 8-byte signed integer + ** 7 IEEE float + ** 8 Integer constant 0 + ** 9 Integer constant 1 + ** 10,11 reserved for expansion + ** N>=12 and even BLOB + ** N>=13 and odd text + ** + ** The following additional values are computed: + ** nHdr Number of bytes needed for the record header + ** nData Number of bytes of data space needed for the record + ** nZero Zero bytes at the end of the record */ pRec = pLast; do{ assert( memIsValid(pRec) ); - pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len); - if( pRec->flags & MEM_Zero ){ - if( nData ){ - if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem; + if( pRec->flags & MEM_Null ){ + if( pRec->flags & MEM_Zero ){ + /* Values with MEM_Null and MEM_Zero are created by xColumn virtual + ** table methods that never invoke tdsqlite3_result_xxxxx() while + ** computing an unchanging column value in an UPDATE statement. + ** Give such values a special internal-use-only serial-type of 10 + ** so that they can be passed through to xUpdate and have + ** a true tdsqlite3_value_nochange(). */ + assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB ); + pRec->uTemp = 10; + }else{ + pRec->uTemp = 0; + } + nHdr++; + }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){ + /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */ + i64 i = pRec->u.i; + u64 uu; + testcase( pRec->flags & MEM_Int ); + testcase( pRec->flags & MEM_IntReal ); + if( i<0 ){ + uu = ~i; + }else{ + uu = i; + } + nHdr++; + testcase( uu==127 ); testcase( uu==128 ); + testcase( uu==32767 ); testcase( uu==32768 ); + testcase( uu==8388607 ); testcase( uu==8388608 ); + testcase( uu==2147483647 ); testcase( uu==2147483648 ); + testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL ); + if( uu<=127 ){ + if( (i&1)==i && file_format>=4 ){ + pRec->uTemp = 8+(u32)uu; + }else{ + nData++; + pRec->uTemp = 1; + } + }else if( uu<=32767 ){ + nData += 2; + pRec->uTemp = 2; + }else if( uu<=8388607 ){ + nData += 3; + pRec->uTemp = 3; + }else if( uu<=2147483647 ){ + nData += 4; + pRec->uTemp = 4; + }else if( uu<=140737488355327LL ){ + nData += 6; + pRec->uTemp = 5; }else{ - nZero += pRec->u.nZero; - len -= pRec->u.nZero; + nData += 8; + if( pRec->flags & MEM_IntReal ){ + /* If the value is IntReal and is going to take up 8 bytes to store + ** as an integer, then we might as well make it an 8-byte floating + ** point value */ + pRec->u.r = (double)pRec->u.i; + pRec->flags &= ~MEM_IntReal; + pRec->flags |= MEM_Real; + pRec->uTemp = 7; + }else{ + pRec->uTemp = 6; + } + } + }else if( pRec->flags & MEM_Real ){ + nHdr++; + nData += 8; + pRec->uTemp = 7; + }else{ + assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) ); + assert( pRec->n>=0 ); + len = (u32)pRec->n; + serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0); + if( pRec->flags & MEM_Zero ){ + serial_type += pRec->u.nZero*2; + if( nData ){ + if( tdsqlite3VdbeMemExpandBlob(pRec) ) goto no_mem; + len += pRec->u.nZero; + }else{ + nZero += pRec->u.nZero; + } } + nData += len; + nHdr += tdsqlite3VarintLen(serial_type); + pRec->uTemp = serial_type; } - nData += len; - testcase( serial_type==127 ); - testcase( serial_type==128 ); - nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type); if( pRec==pData0 ) break; pRec--; }while(1); @@ -83203,52 +91607,59 @@ case OP_MakeRecord: { nHdr += 1; }else{ /* Rare case of a really large header */ - nVarint = sqlite3VarintLen(nHdr); + nVarint = tdsqlite3VarintLen(nHdr); nHdr += nVarint; - if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++; + if( nVarint<tdsqlite3VarintLen(nHdr) ) nHdr++; } nByte = nHdr+nData; - if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } /* Make sure the output register has a buffer large enough to store ** the new record. The output register (pOp->p3) is not allowed to ** be one of the input registers (because the following call to - ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used). + ** tdsqlite3VdbeMemClearAndResize() could clobber the value before it is used). */ - if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){ - goto no_mem; + if( nByte+nZero<=pOut->szMalloc ){ + /* The output register is already large enough to hold the record. + ** No error checks or buffer enlargement is required */ + pOut->z = pOut->zMalloc; + }else{ + /* Need to make sure that the output is not too big and then enlarge + ** the output register to hold the full result */ + if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + goto too_big; + } + if( tdsqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){ + goto no_mem; + } } - zNewRecord = (u8 *)pOut->z; + pOut->n = (int)nByte; + pOut->flags = MEM_Blob; + if( nZero ){ + pOut->u.nZero = nZero; + pOut->flags |= MEM_Zero; + } + UPDATE_MAX_BLOBSIZE(pOut); + zHdr = (u8 *)pOut->z; + zPayload = zHdr + nHdr; /* Write the record */ - i = putVarint32(zNewRecord, nHdr); - j = nHdr; + zHdr += putVarint32(zHdr, nHdr); assert( pData0<=pLast ); pRec = pData0; do{ serial_type = pRec->uTemp; /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more ** additional varints, one per column. */ - i += putVarint32(&zNewRecord[i], serial_type); /* serial type */ + zHdr += putVarint32(zHdr, serial_type); /* serial type */ /* EVIDENCE-OF: R-64536-51728 The values for each column in the record ** immediately follow the header. */ - j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */ + zPayload += tdsqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */ }while( (++pRec)<=pLast ); - assert( i==nHdr ); - assert( j==nByte ); + assert( nHdr==(int)(zHdr - (u8*)pOut->z) ); + assert( nByte==(int)(zPayload - (u8*)pOut->z) ); assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); - pOut->n = (int)nByte; - pOut->flags = MEM_Blob; - if( nZero ){ - pOut->u.nZero = nZero; - pOut->flags |= MEM_Zero; - } - pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */ REGISTER_TRACE(pOp->p3, pOut); - UPDATE_MAX_BLOBSIZE(pOut); break; } @@ -83267,19 +91678,20 @@ case OP_Count: { /* out2 */ pCrsr = p->apCsr[pOp->p1]->uc.pCursor; assert( pCrsr ); nEntry = 0; /* Not needed. Only used to silence a warning. */ - rc = sqlite3BtreeCount(pCrsr, &nEntry); + rc = tdsqlite3BtreeCount(db, pCrsr, &nEntry); if( rc ) goto abort_due_to_error; pOut = out2Prerelease(p, pOp); pOut->u.i = nEntry; - break; + goto check_for_interrupt; } #endif /* Opcode: Savepoint P1 * * P4 * ** ** Open, release or rollback the savepoint named by parameter P4, depending -** on the value of P1. To open a new savepoint, P1==0. To release (commit) an -** existing savepoint, P1==1, or to rollback an existing savepoint P1==2. +** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN). +** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE). +** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK). */ case OP_Savepoint: { int p1; /* Value of P1 operand */ @@ -83308,10 +91720,10 @@ case OP_Savepoint: { /* A new savepoint cannot be created if there are active write ** statements (i.e. open read/write incremental blob handles). */ - sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress"); + tdsqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress"); rc = SQLITE_BUSY; }else{ - nName = sqlite3Strlen30(zName); + nName = tdsqlite3Strlen30(zName); #ifndef SQLITE_OMIT_VIRTUALTABLE /* This call is Ok even if this savepoint is actually a transaction @@ -83319,13 +91731,13 @@ case OP_Savepoint: { ** If this is a transaction savepoint being opened, it is guaranteed ** that the db->aVTrans[] array is empty. */ assert( db->autoCommit==0 || db->nVTrans==0 ); - rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, + rc = tdsqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, db->nStatement+db->nSavepoint); if( rc!=SQLITE_OK ) goto abort_due_to_error; #endif /* Create a new savepoint structure. */ - pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1); + pNew = tdsqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1); if( pNew ){ pNew->zName = (char *)&pNew[1]; memcpy(pNew->zName, zName, nName+1); @@ -83347,25 +91759,26 @@ case OP_Savepoint: { } } }else{ + assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK ); iSavepoint = 0; /* Find the named savepoint. If there is no such savepoint, then an ** an error is returned to the user. */ for( pSavepoint = db->pSavepoint; - pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName); + pSavepoint && tdsqlite3StrICmp(pSavepoint->zName, zName); pSavepoint = pSavepoint->pNext ){ iSavepoint++; } if( !pSavepoint ){ - sqlite3VdbeError(p, "no such savepoint: %s", zName); + tdsqlite3VdbeError(p, "no such savepoint: %s", zName); rc = SQLITE_ERROR; }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){ /* It is not possible to release (commit) a savepoint if there are ** active write statements. */ - sqlite3VdbeError(p, "cannot release savepoint - " + tdsqlite3VdbeError(p, "cannot release savepoint - " "SQL statements in progress"); rc = SQLITE_BUSY; }else{ @@ -83376,51 +91789,57 @@ case OP_Savepoint: { */ int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint; if( isTransaction && p1==SAVEPOINT_RELEASE ){ - if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ + if( (rc = tdsqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ goto vdbe_return; } db->autoCommit = 1; - if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ + if( tdsqlite3VdbeHalt(p)==SQLITE_BUSY ){ p->pc = (int)(pOp - aOp); db->autoCommit = 0; p->rc = rc = SQLITE_BUSY; goto vdbe_return; } - db->isTransactionSavepoint = 0; rc = p->rc; + if( rc ){ + db->autoCommit = 0; + }else{ + db->isTransactionSavepoint = 0; + } }else{ int isSchemaChange; iSavepoint = db->nSavepoint - iSavepoint - 1; if( p1==SAVEPOINT_ROLLBACK ){ - isSchemaChange = (db->flags & SQLITE_InternChanges)!=0; + isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0; for(ii=0; ii<db->nDb; ii++){ - rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, + rc = tdsqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT_ROLLBACK, isSchemaChange==0); if( rc!=SQLITE_OK ) goto abort_due_to_error; } }else{ + assert( p1==SAVEPOINT_RELEASE ); isSchemaChange = 0; } for(ii=0; ii<db->nDb; ii++){ - rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint); + rc = tdsqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } } if( isSchemaChange ){ - sqlite3ExpirePreparedStatements(db); - sqlite3ResetAllSchemasOfConnection(db); - db->flags = (db->flags | SQLITE_InternChanges); + tdsqlite3ExpirePreparedStatements(db, 0); + tdsqlite3ResetAllSchemasOfConnection(db); + db->mDbFlags |= DBFLAG_SchemaChange; } } + if( rc ) goto abort_due_to_error; /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all ** savepoints nested inside of the savepoint being operated on. */ while( db->pSavepoint!=pSavepoint ){ pTmp = db->pSavepoint; db->pSavepoint = pTmp->pNext; - sqlite3DbFree(db, pTmp); + tdsqlite3DbFree(db, pTmp); db->nSavepoint--; } @@ -83431,17 +91850,18 @@ case OP_Savepoint: { if( p1==SAVEPOINT_RELEASE ){ assert( pSavepoint==db->pSavepoint ); db->pSavepoint = pSavepoint->pNext; - sqlite3DbFree(db, pSavepoint); + tdsqlite3DbFree(db, pSavepoint); if( !isTransaction ){ db->nSavepoint--; } }else{ + assert( p1==SAVEPOINT_ROLLBACK ); db->nDeferredCons = pSavepoint->nDeferredCons; db->nDeferredImmCons = pSavepoint->nDeferredImmCons; } if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){ - rc = sqlite3VtabSavepoint(db, p1, iSavepoint); + rc = tdsqlite3VtabSavepoint(db, p1, iSavepoint); if( rc!=SQLITE_OK ) goto abort_due_to_error; } } @@ -83474,29 +91894,28 @@ case OP_AutoCommit: { if( desiredAutoCommit!=db->autoCommit ){ if( iRollback ){ assert( desiredAutoCommit==1 ); - sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); + tdsqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); db->autoCommit = 1; }else if( desiredAutoCommit && db->nVdbeWrite>0 ){ /* If this instruction implements a COMMIT and other VMs are writing ** return an error indicating that the other VMs must complete first. */ - sqlite3VdbeError(p, "cannot commit transaction - " + tdsqlite3VdbeError(p, "cannot commit transaction - " "SQL statements in progress"); rc = SQLITE_BUSY; goto abort_due_to_error; - }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ + }else if( (rc = tdsqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ goto vdbe_return; }else{ db->autoCommit = (u8)desiredAutoCommit; } - if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ + if( tdsqlite3VdbeHalt(p)==SQLITE_BUSY ){ p->pc = (int)(pOp - aOp); db->autoCommit = (u8)(1-desiredAutoCommit); p->rc = rc = SQLITE_BUSY; goto vdbe_return; } - assert( db->nStatement==0 ); - sqlite3CloseSavepoints(db); + tdsqlite3CloseSavepoints(db); if( p->rc==SQLITE_OK ){ rc = SQLITE_DONE; }else{ @@ -83504,7 +91923,7 @@ case OP_AutoCommit: { } goto vdbe_return; }else{ - sqlite3VdbeError(p, + tdsqlite3VdbeError(p, (!desiredAutoCommit)?"cannot start a transaction within a transaction":( (iRollback)?"cannot rollback - no transaction is active": "cannot commit - no transaction is active")); @@ -83512,7 +91931,7 @@ case OP_AutoCommit: { rc = SQLITE_ERROR; goto abort_due_to_error; } - break; + /*NOTREACHED*/ assert(0); } /* Opcode: Transaction P1 P2 P3 P4 P5 @@ -83546,13 +91965,12 @@ case OP_AutoCommit: { ** cookie in P3 differs from the schema cookie in the database header or ** if the schema generation counter in P4 differs from the current ** generation counter, then an SQLITE_SCHEMA error is raised and execution -** halts. The sqlite3_step() wrapper function might then reprepare the +** halts. The tdsqlite3_step() wrapper function might then reprepare the ** statement and rerun it from the beginning. */ case OP_Transaction: { Btree *pBt; - int iMeta; - int iGen; + int iMeta = 0; assert( p->bIsReader ); assert( p->readOnly==0 || pOp->p2==0 ); @@ -83565,7 +91983,7 @@ case OP_Transaction: { pBt = db->aDb[pOp->p1].pBt; if( pBt ){ - rc = sqlite3BtreeBeginTrans(pBt, pOp->p2); + rc = tdsqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta); testcase( rc==SQLITE_BUSY_SNAPSHOT ); testcase( rc==SQLITE_BUSY_RECOVERY ); if( rc!=SQLITE_OK ){ @@ -83577,19 +91995,20 @@ case OP_Transaction: { goto abort_due_to_error; } - if( pOp->p2 && p->usesStmtJournal + if( p->usesStmtJournal + && pOp->p2 && (db->autoCommit==0 || db->nVdbeRead>1) ){ - assert( sqlite3BtreeIsInTrans(pBt) ); + assert( tdsqlite3BtreeIsInTrans(pBt) ); if( p->iStatement==0 ){ assert( db->nStatement>=0 && db->nSavepoint>=0 ); db->nStatement++; p->iStatement = db->nSavepoint + db->nStatement; } - rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1); + rc = tdsqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1); if( rc==SQLITE_OK ){ - rc = sqlite3BtreeBeginStmt(pBt, p->iStatement); + rc = tdsqlite3BtreeBeginStmt(pBt, p->iStatement); } /* Store the current value of the database handles deferred constraint @@ -83598,21 +92017,19 @@ case OP_Transaction: { p->nStmtDefCons = db->nDeferredCons; p->nStmtDefImmCons = db->nDeferredImmCons; } - - /* Gather the schema version number for checking: + } + assert( pOp->p5==0 || pOp->p4type==P4_INT32 ); + if( pOp->p5 + && (iMeta!=pOp->p3 + || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i) + ){ + /* ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema ** version is checked to ensure that the schema has not changed since the ** SQL statement was prepared. */ - sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta); - iGen = db->aDb[pOp->p1].pSchema->iGeneration; - }else{ - iGen = iMeta = 0; - } - assert( pOp->p5==0 || pOp->p4type==P4_INT32 ); - if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){ - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed"); + tdsqlite3DbFree(db, p->zErrMsg); + p->zErrMsg = tdsqlite3DbStrDup(db, "database schema has changed"); /* If the schema-cookie from the database file matches the cookie ** stored with the in-memory representation of the schema, do ** not reload the schema from the database file. @@ -83622,12 +92039,12 @@ case OP_Transaction: { ** are queried from within xNext() and other v-table methods using ** prepared queries. If such a query is out-of-date, we do not want to ** discard the database schema, as the user code implementing the - ** v-table would have to be ready for the sqlite3_vtab structure itself - ** to be invalidated whenever sqlite3_step() is called from within + ** v-table would have to be ready for the tdsqlite3_vtab structure itself + ** to be invalidated whenever tdsqlite3_step() is called from within ** a v-table method. */ if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){ - sqlite3ResetOneSchema(db, pOp->p1); + tdsqlite3ResetOneSchema(db, pOp->p1); } p->expired = 1; rc = SQLITE_SCHEMA; @@ -83661,7 +92078,7 @@ case OP_ReadCookie: { /* out2 */ assert( db->aDb[iDb].pBt!=0 ); assert( DbMaskTest(p->btreeMask, iDb) ); - sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta); + tdsqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta); pOut = out2Prerelease(p, pOp); pOut->u.i = iMeta; break; @@ -83679,19 +92096,21 @@ case OP_ReadCookie: { /* out2 */ */ case OP_SetCookie: { Db *pDb; + + tdsqlite3VdbeIncrWriteCounter(p, 0); assert( pOp->p2<SQLITE_N_BTREE_META ); assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); assert( p->readOnly==0 ); pDb = &db->aDb[pOp->p1]; assert( pDb->pBt!=0 ); - assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, pOp->p1, 0) ); /* See note about index shifting on OP_ReadCookie */ - rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3); + rc = tdsqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3); if( pOp->p2==BTREE_SCHEMA_VERSION ){ /* When the schema cookie changes, record the new cookie internally */ pDb->pSchema->schema_cookie = pOp->p3; - db->flags |= SQLITE_InternChanges; + db->mDbFlags |= DBFLAG_SchemaChange; }else if( pOp->p2==BTREE_FILE_FORMAT ){ /* Record changes in the file format */ pDb->pSchema->file_format = pOp->p3; @@ -83699,7 +92118,7 @@ case OP_SetCookie: { if( pOp->p1==1 ){ /* Invalidate all prepared statements whenever the TEMP database ** schema is changed. Ticket #1644 */ - sqlite3ExpirePreparedStatements(db); + tdsqlite3ExpirePreparedStatements(db, 0); p->expired = 0; } if( rc ) goto abort_due_to_error; @@ -83717,59 +92136,78 @@ case OP_SetCookie: { ** values need not be contiguous but all P1 values should be small integers. ** It is an error for P1 to be negative. ** -** If P5!=0 then use the content of register P2 as the root page, not -** the value of P2 itself. -** -** There will be a read lock on the database whenever there is an -** open cursor. If the database was unlocked prior to this instruction -** then a read lock is acquired as part of this instruction. A read -** lock allows other processes to read the database but prohibits -** any other process from modifying the database. The read lock is -** released when all cursors are closed. If this instruction attempts -** to get a read lock but fails, the script terminates with an -** SQLITE_BUSY error code. +** Allowed P5 bits: +** <ul> +** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for +** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT +** of OP_SeekLE/OP_IdxGT) +** </ul> ** ** The P4 value may be either an integer (P4_INT32) or a pointer to ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo -** structure, then said structure defines the content and collating -** sequence of the index being opened. Otherwise, if P4 is an integer -** value, it is set to the number of columns in the table. +** object, then table being opened must be an [index b-tree] where the +** KeyInfo object defines the content and collating +** sequence of that index b-tree. Otherwise, if P4 is an integer +** value, then the table being opened must be a [table b-tree] with a +** number of columns no less than the value of P4. ** ** See also: OpenWrite, ReopenIdx */ /* Opcode: ReopenIdx P1 P2 P3 P4 P5 ** Synopsis: root=P2 iDb=P3 ** -** The ReopenIdx opcode works exactly like ReadOpen except that it first -** checks to see if the cursor on P1 is already open with a root page -** number of P2 and if it is this opcode becomes a no-op. In other words, +** The ReopenIdx opcode works like OP_OpenRead except that it first +** checks to see if the cursor on P1 is already open on the same +** b-tree and if it is this opcode becomes a no-op. In other words, ** if the cursor is already open, do not reopen it. ** -** The ReopenIdx opcode may only be used with P5==0 and with P4 being -** a P4_KEYINFO object. Furthermore, the P3 value must be the same as -** every other ReopenIdx or OpenRead for the same cursor number. +** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ +** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must +** be the same as every other ReopenIdx or OpenRead for the same cursor +** number. ** -** See the OpenRead opcode documentation for additional information. +** Allowed P5 bits: +** <ul> +** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for +** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT +** of OP_SeekLE/OP_IdxGT) +** </ul> +** +** See also: OP_OpenRead, OP_OpenWrite */ /* Opcode: OpenWrite P1 P2 P3 P4 P5 ** Synopsis: root=P2 iDb=P3 ** ** Open a read/write cursor named P1 on the table or index whose root -** page is P2. Or if P5!=0 use the content of register P2 to find the -** root page. +** page is P2 (or whose root page is held in register P2 if the +** OPFLAG_P2ISREG bit is set in P5 - see below). ** ** The P4 value may be either an integer (P4_INT32) or a pointer to ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo -** structure, then said structure defines the content and collating -** sequence of the index being opened. Otherwise, if P4 is an integer -** value, it is set to the number of columns in the table, or to the -** largest index of any column of the table that is actually used. +** object, then table being opened must be an [index b-tree] where the +** KeyInfo object defines the content and collating +** sequence of that index b-tree. Otherwise, if P4 is an integer +** value, then the table being opened must be a [table b-tree] with a +** number of columns no less than the value of P4. ** -** This instruction works just like OpenRead except that it opens the cursor -** in read/write mode. For a given table, there can be one or more read-only -** cursors or a single read/write cursor but not both. +** Allowed P5 bits: +** <ul> +** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for +** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT +** of OP_SeekLE/OP_IdxGT) +** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek +** and subsequently delete entries in an index btree. This is a +** hint to the storage engine that the storage engine is allowed to +** ignore. The hint is not used by the official SQLite b*tree storage +** engine, but is used by COMDB2. +** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2 +** as the root page, not the value of P2 itself. +** </ul> ** -** See also OpenRead. +** This instruction works like OpenRead except that it opens the cursor +** in read/write mode. +** +** See also: OP_OpenRead, OP_ReopenIdx */ case OP_ReopenIdx: { int nField; @@ -83798,7 +92236,7 @@ case OP_OpenWrite: assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx || p->readOnly==0 ); - if( p->expired ){ + if( p->expired==1 ){ rc = SQLITE_ABORT_ROLLBACK; goto abort_due_to_error; } @@ -83815,7 +92253,7 @@ case OP_OpenWrite: if( pOp->opcode==OP_OpenWrite ){ assert( OPFLAG_FORDELETE==BTREE_FORDELETE ); wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); if( pDb->pSchema->file_format < p->minWriteFileFormat ){ p->minWriteFileFormat = pDb->pSchema->file_format; } @@ -83825,12 +92263,13 @@ case OP_OpenWrite: if( pOp->p5 & OPFLAG_P2ISREG ){ assert( p2>0 ); assert( p2<=(p->nMem+1 - p->nCursor) ); + assert( pOp->opcode==OP_OpenWrite ); pIn2 = &aMem[p2]; assert( memIsValid(pIn2) ); assert( (pIn2->flags & MEM_Int)!=0 ); - sqlite3VdbeMemIntegerify(pIn2); + tdsqlite3VdbeMemIntegerify(pIn2); p2 = (int)pIn2->u.i; - /* The p2 value always comes from a prior OP_CreateTable opcode and + /* The p2 value always comes from a prior OP_CreateBtree opcode and ** that opcode will always set the p2 value to 2 or more or else fail. ** If there were a failure, the prepared statement would have halted ** before reaching this instruction. */ @@ -83840,7 +92279,7 @@ case OP_OpenWrite: pKeyInfo = pOp->p4.pKeyInfo; assert( pKeyInfo->enc==ENC(db) ); assert( pKeyInfo->db==db ); - nField = pKeyInfo->nField+pKeyInfo->nXField; + nField = pKeyInfo->nAllField; }else if( pOp->p4type==P4_INT32 ){ nField = pOp->p4.i; } @@ -83855,7 +92294,7 @@ case OP_OpenWrite: #ifdef SQLITE_DEBUG pCur->wrFlag = wrFlag; #endif - rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor); + rc = tdsqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor); pCur->pKeyInfo = pKeyInfo; /* Set the VdbeCursor.isTable variable. Previous versions of ** SQLite used to check if the root-page flags were sane at this point @@ -83870,12 +92309,46 @@ open_cursor_set_hints: #ifdef SQLITE_ENABLE_CURSOR_HINTS testcase( pOp->p2 & OPFLAG_SEEKEQ ); #endif - sqlite3BtreeCursorHintFlags(pCur->uc.pCursor, + tdsqlite3BtreeCursorHintFlags(pCur->uc.pCursor, (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ))); if( rc ) goto abort_due_to_error; break; } +/* Opcode: OpenDup P1 P2 * * * +** +** Open a new cursor P1 that points to the same ephemeral table as +** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral +** opcode. Only ephemeral cursors may be duplicated. +** +** Duplicate ephemeral cursors are used for self-joins of materialized views. +*/ +case OP_OpenDup: { + VdbeCursor *pOrig; /* The original cursor to be duplicated */ + VdbeCursor *pCx; /* The new cursor */ + + pOrig = p->apCsr[pOp->p2]; + assert( pOrig ); + assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */ + + pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE); + if( pCx==0 ) goto no_mem; + pCx->nullRow = 1; + pCx->isEphemeral = 1; + pCx->pKeyInfo = pOrig->pKeyInfo; + pCx->isTable = pOrig->isTable; + pCx->pgnoRoot = pOrig->pgnoRoot; + pCx->isOrdered = pOrig->isOrdered; + rc = tdsqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR, + pCx->pKeyInfo, pCx->uc.pCursor); + /* The tdsqlite3BtreeCursor() routine can only fail for the first cursor + ** opened for a database. Since there is already an open cursor when this + ** opcode is run, the tdsqlite3BtreeCursor() cannot fail */ + assert( rc==SQLITE_OK ); + break; +} + + /* Opcode: OpenEphemeral P1 P2 * P4 P5 ** Synopsis: nColumn=P2 ** @@ -83884,6 +92357,9 @@ open_cursor_set_hints: ** the main database is read-only. The ephemeral ** table is deleted automatically when the cursor is closed. ** +** If the cursor P1 is already opened on an ephemeral table, the table +** is cleared (all content is erased). +** ** P2 is the number of columns in the ephemeral table. ** The cursor points to a BTree table if P4==0 and to a BTree index ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure @@ -83915,42 +92391,53 @@ case OP_OpenEphemeral: { SQLITE_OPEN_TRANSIENT_DB; assert( pOp->p1>=0 ); assert( pOp->p2>=0 ); - pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE); - if( pCx==0 ) goto no_mem; - pCx->nullRow = 1; - pCx->isEphemeral = 1; - rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt, - BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags); - if( rc==SQLITE_OK ){ - rc = sqlite3BtreeBeginTrans(pCx->pBt, 1); - } - if( rc==SQLITE_OK ){ - /* If a transient index is required, create it by calling - ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before - ** opening it. If a transient table is required, just use the - ** automatically created table with root-page 1 (an BLOB_INTKEY table). - */ - if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){ - int pgno; - assert( pOp->p4type==P4_KEYINFO ); - rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5); - if( rc==SQLITE_OK ){ - assert( pgno==MASTER_ROOT+1 ); - assert( pKeyInfo->db==db ); - assert( pKeyInfo->enc==ENC(db) ); - pCx->pKeyInfo = pKeyInfo; - rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR, - pKeyInfo, pCx->uc.pCursor); + pCx = p->apCsr[pOp->p1]; + if( pCx && pCx->pBtx ){ + /* If the ephermeral table is already open, erase all existing content + ** so that the table is empty again, rather than creating a new table. */ + assert( pCx->isEphemeral ); + pCx->seqCount = 0; + pCx->cacheStatus = CACHE_STALE; + rc = tdsqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0); + }else{ + pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE); + if( pCx==0 ) goto no_mem; + pCx->isEphemeral = 1; + rc = tdsqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, + BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, + vfsFlags); + if( rc==SQLITE_OK ){ + rc = tdsqlite3BtreeBeginTrans(pCx->pBtx, 1, 0); + } + if( rc==SQLITE_OK ){ + /* If a transient index is required, create it by calling + ** tdsqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before + ** opening it. If a transient table is required, just use the + ** automatically created table with root-page 1 (an BLOB_INTKEY table). + */ + if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){ + assert( pOp->p4type==P4_KEYINFO ); + rc = tdsqlite3BtreeCreateTable(pCx->pBtx, (int*)&pCx->pgnoRoot, + BTREE_BLOBKEY | pOp->p5); + if( rc==SQLITE_OK ){ + assert( pCx->pgnoRoot==MASTER_ROOT+1 ); + assert( pKeyInfo->db==db ); + assert( pKeyInfo->enc==ENC(db) ); + rc = tdsqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR, + pKeyInfo, pCx->uc.pCursor); + } + pCx->isTable = 0; + }else{ + pCx->pgnoRoot = MASTER_ROOT; + rc = tdsqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR, + 0, pCx->uc.pCursor); + pCx->isTable = 1; } - pCx->isTable = 0; - }else{ - rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, BTREE_WRCSR, - 0, pCx->uc.pCursor); - pCx->isTable = 1; } + pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); } if( rc ) goto abort_due_to_error; - pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); + pCx->nullRow = 1; break; } @@ -83974,7 +92461,7 @@ case OP_SorterOpen: { pCx->pKeyInfo = pOp->p4.pKeyInfo; assert( pCx->pKeyInfo->db==db ); assert( pCx->pKeyInfo->enc==ENC(db) ); - rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx); + rc = tdsqlite3VdbeSorterInit(db, pOp->p3, pCx); if( rc ) goto abort_due_to_error; break; } @@ -84021,8 +92508,13 @@ case OP_OpenPseudo: { pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO); if( pCx==0 ) goto no_mem; pCx->nullRow = 1; - pCx->uc.pseudoTableReg = pOp->p2; + pCx->seekResult = pOp->p2; pCx->isTable = 1; + /* Give this pseudo-cursor a fake BtCursor pointer so that pCx + ** can be safely passed to tdsqlite3VdbeCursorMoveto(). This avoids a test + ** for pCx->eCurType==CURTYPE_BTREE inside of tdsqlite3VdbeCursorMoveto() + ** which is a performance optimization */ + pCx->uc.pCursor = tdsqlite3BtreeFakeValidCursor(); assert( pOp->p5==0 ); break; } @@ -84034,7 +92526,7 @@ case OP_OpenPseudo: { */ case OP_Close: { assert( pOp->p1>=0 && pOp->p1<p->nCursor ); - sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); + tdsqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); p->apCsr[pOp->p1] = 0; break; } @@ -84145,10 +92637,10 @@ case OP_ColumnsUsed: { ** ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt */ -case OP_SeekLT: /* jump, in3 */ -case OP_SeekLE: /* jump, in3 */ -case OP_SeekGE: /* jump, in3 */ -case OP_SeekGT: { /* jump, in3 */ +case OP_SeekLT: /* jump, in3, group */ +case OP_SeekLE: /* jump, in3, group */ +case OP_SeekGE: /* jump, in3, group */ +case OP_SeekGT: { /* jump, in3, group */ int res; /* Comparison result */ int oc; /* Opcode */ VdbeCursor *pC; /* The cursor to seek */ @@ -84174,28 +92666,39 @@ case OP_SeekGT: { /* jump, in3 */ pC->seekOp = pOp->opcode; #endif + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; if( pC->isTable ){ + u16 flags3, newType; /* The BTREE_SEEK_EQ flag is only set on index cursors */ - assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 ); + assert( tdsqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 + || CORRUPT_DB ); /* The input value in P3 might be of any type: integer, real, string, ** blob, or NULL. But it needs to be an integer before we can do ** the seek, so convert it. */ pIn3 = &aMem[pOp->p3]; - if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ + flags3 = pIn3->flags; + if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){ applyNumericAffinity(pIn3, 0); } - iKey = sqlite3VdbeIntValue(pIn3); + iKey = tdsqlite3VdbeIntValue(pIn3); /* Get the integer key value */ + newType = pIn3->flags; /* Record the type after applying numeric affinity */ + pIn3->flags = flags3; /* But convert the type back to its original */ /* If the P3 value could not be converted into an integer without ** loss of information, then special processing is required... */ - if( (pIn3->flags & MEM_Int)==0 ){ - if( (pIn3->flags & MEM_Real)==0 ){ - /* If the P3 value cannot be converted into any kind of a number, - ** then the seek is not possible, so jump to P2 */ - VdbeBranchTaken(1,2); goto jump_to_p2; - break; - } + if( (newType & (MEM_Int|MEM_IntReal))==0 ){ + if( (newType & MEM_Real)==0 ){ + if( (newType & MEM_Null) || oc>=OP_SeekGE ){ + VdbeBranchTaken(1,2); + goto jump_to_p2; + }else{ + rc = tdsqlite3BtreeLast(pC->uc.pCursor, &res); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + goto seek_not_found; + } + }else /* If the approximation iKey is larger than the actual real search ** term, substitute >= for > and < for <=. e.g. if the search term @@ -84219,8 +92722,8 @@ case OP_SeekGT: { /* jump, in3 */ assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) ); if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++; } - } - rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res); + } + rc = tdsqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res); pC->movetoTarget = iKey; /* Used by OP_Delete */ if( rc!=SQLITE_OK ){ goto abort_due_to_error; @@ -84230,7 +92733,7 @@ case OP_SeekGT: { /* jump, in3 */ ** OP_SeekLE opcodes are allowed, and these must be immediately followed ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key. */ - if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){ + if( tdsqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){ eqOnly = 1; assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE ); assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); @@ -84264,7 +92767,7 @@ case OP_SeekGT: { /* jump, in3 */ { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); } #endif r.eqSeen = 0; - rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res); + rc = tdsqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } @@ -84273,16 +92776,21 @@ case OP_SeekGT: { /* jump, in3 */ goto seek_not_found; } } - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; #ifdef SQLITE_TEST - sqlite3_search_count++; + tdsqlite3_search_count++; #endif if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT ); if( res<0 || (res==0 && oc==OP_SeekGT) ){ res = 0; - rc = sqlite3BtreeNext(pC->uc.pCursor, &res); - if( rc!=SQLITE_OK ) goto abort_due_to_error; + rc = tdsqlite3BtreeNext(pC->uc.pCursor, 0); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + res = 1; + }else{ + goto abort_due_to_error; + } + } }else{ res = 0; } @@ -84290,13 +92798,20 @@ case OP_SeekGT: { /* jump, in3 */ assert( oc==OP_SeekLT || oc==OP_SeekLE ); if( res>0 || (res==0 && oc==OP_SeekLT) ){ res = 0; - rc = sqlite3BtreePrevious(pC->uc.pCursor, &res); - if( rc!=SQLITE_OK ) goto abort_due_to_error; + rc = tdsqlite3BtreePrevious(pC->uc.pCursor, 0); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + res = 1; + }else{ + goto abort_due_to_error; + } + } }else{ /* res might be negative because the table is empty. Check to ** see if this is the case. */ - res = sqlite3BtreeEof(pC->uc.pCursor); + res = tdsqlite3BtreeEof(pC->uc.pCursor); } } seek_not_found: @@ -84311,6 +92826,39 @@ seek_not_found: break; } +/* Opcode: SeekHit P1 P2 * * * +** Synopsis: seekHit=P2 +** +** Set the seekHit flag on cursor P1 to the value in P2. +* The seekHit flag is used by the IfNoHope opcode. +** +** P1 must be a valid b-tree cursor. P2 must be a boolean value, +** either 0 or 1. +*/ +case OP_SeekHit: { + VdbeCursor *pC; + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pOp->p2==0 || pOp->p2==1 ); + pC->seekHit = pOp->p2 & 1; + break; +} + +/* Opcode: IfNotOpen P1 P2 * * * +** Synopsis: if( !csr[P1] ) goto P2 +** +** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through. +*/ +case OP_IfNotOpen: { /* jump */ + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2); + if( !p->apCsr[pOp->p1] ){ + goto jump_to_p2_and_check_for_interrupt; + } + break; +} + /* Opcode: Found P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** @@ -84345,7 +92893,34 @@ seek_not_found: ** advanced in either direction. In other words, the Next and Prev ** opcodes do not work after this operation. ** -** See also: Found, NotExists, NoConflict +** See also: Found, NotExists, NoConflict, IfNoHope +*/ +/* Opcode: IfNoHope P1 P2 P3 P4 * +** Synopsis: key=r[P3@P4] +** +** Register P3 is the first of P4 registers that form an unpacked +** record. +** +** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then +** this opcode is a no-op. But if the seekHit flag of P1 is clear, then +** check to see if there is any entry in P1 that matches the +** prefix identified by P3 and P4. If no entry matches the prefix, +** jump to P2. Otherwise fall through. +** +** This opcode behaves like OP_NotFound if the seekHit +** flag is clear and it behaves like OP_Noop if the seekHit flag is set. +** +** This opcode is used in IN clause processing for a multi-column key. +** If an IN clause is attached to an element of the key other than the +** left-most element, and if there are no matches on the most recent +** seek over the whole key, then it might be that one of the key element +** to the left is prohibiting a match, and hence there is "no hope" of +** any match regardless of how many IN clause elements are checked. +** In such a case, we abandon the IN clause search early, using this +** opcode. The opcode name comes from the fact that the +** jump is taken if there is "no hope" of achieving a match. +** +** See also: NotFound, SeekHit */ /* Opcode: NoConflict P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] @@ -84370,6 +92945,14 @@ seek_not_found: ** ** See also: NotFound, Found, NotExists */ +case OP_IfNoHope: { /* jump, in3 */ + VdbeCursor *pC; + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + if( pC->seekHit ) break; + /* Fall through into OP_NotFound */ +} case OP_NoConflict: /* jump, in3 */ case OP_NotFound: /* jump, in3 */ case OP_Found: { /* jump, in3 */ @@ -84378,13 +92961,12 @@ case OP_Found: { /* jump, in3 */ int ii; VdbeCursor *pC; int res; - char *pFree; + UnpackedRecord *pFree; UnpackedRecord *pIdxKey; UnpackedRecord r; - char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7]; #ifdef SQLITE_TEST - if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++; + if( pOp->opcode!=OP_NoConflict ) tdsqlite3_found_count++; #endif assert( pOp->p1>=0 && pOp->p1<p->nCursor ); @@ -84398,7 +92980,6 @@ case OP_Found: { /* jump, in3 */ assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( pC->isTable==0 ); - pFree = 0; if( pOp->p4.i>0 ){ r.pKeyInfo = pC->pKeyInfo; r.nField = (u16)pOp->p4.i; @@ -84411,14 +92992,15 @@ case OP_Found: { /* jump, in3 */ } #endif pIdxKey = &r; + pFree = 0; }else{ - pIdxKey = sqlite3VdbeAllocUnpackedRecord( - pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree - ); - if( pIdxKey==0 ) goto no_mem; assert( pIn3->flags & MEM_Blob ); - (void)ExpandBlob(pIn3); - sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); + rc = ExpandBlob(pIn3); + assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); + if( rc ) goto no_mem; + pFree = pIdxKey = tdsqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo); + if( pIdxKey==0 ) goto no_mem; + tdsqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); } pIdxKey->default_rc = 0; takeJump = 0; @@ -84433,8 +93015,8 @@ case OP_Found: { /* jump, in3 */ } } } - rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res); - sqlite3DbFree(db, pFree); + rc = tdsqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res); + if( pFree ) tdsqlite3DbFreeNN(db, pFree); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } @@ -84507,27 +93089,40 @@ case OP_SeekRowid: { /* jump, in3 */ u64 iKey; pIn3 = &aMem[pOp->p3]; - if( (pIn3->flags & MEM_Int)==0 ){ - applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding); - if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2; + testcase( pIn3->flags & MEM_Int ); + testcase( pIn3->flags & MEM_IntReal ); + testcase( pIn3->flags & MEM_Real ); + testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str ); + if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){ + /* If pIn3->u.i does not contain an integer, compute iKey as the + ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted + ** into an integer without loss of information. Take care to avoid + ** changing the datatype of pIn3, however, as it is used by other + ** parts of the prepared statement. */ + Mem x = pIn3[0]; + applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding); + if( (x.flags & MEM_Int)==0 ) goto jump_to_p2; + iKey = x.u.i; + goto notExistsWithKey; } /* Fall through into OP_NotExists */ case OP_NotExists: /* jump, in3 */ pIn3 = &aMem[pOp->p3]; - assert( pIn3->flags & MEM_Int ); + assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid ); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + iKey = pIn3->u.i; +notExistsWithKey: pC = p->apCsr[pOp->p1]; assert( pC!=0 ); #ifdef SQLITE_DEBUG - pC->seekOp = 0; + if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid; #endif assert( pC->isTable ); assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; assert( pCrsr!=0 ); res = 0; - iKey = pIn3->u.i; - rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); + rc = tdsqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); assert( rc==SQLITE_OK || res==0 ); pC->movetoTarget = iKey; /* Used by OP_Delete */ pC->nullRow = 0; @@ -84583,7 +93178,7 @@ case OP_Sequence: { /* out2 */ case OP_NewRowid: { /* out2 */ i64 v; /* The new rowid */ VdbeCursor *pC; /* Cursor of table to get the new rowid */ - int res; /* Result of an sqlite3BtreeLast() */ + int res; /* Result of an tdsqlite3BtreeLast() */ int cnt; /* Counter to limit the number of searches */ Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ VdbeFrame *pFrame; /* Root frame of VDBE */ @@ -84594,6 +93189,7 @@ case OP_NewRowid: { /* out2 */ assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); + assert( pC->isTable ); assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); { @@ -84623,15 +93219,15 @@ case OP_NewRowid: { /* out2 */ #endif if( !pC->useRandomRowid ){ - rc = sqlite3BtreeLast(pC->uc.pCursor, &res); + rc = tdsqlite3BtreeLast(pC->uc.pCursor, &res); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } if( res ){ v = 1; /* IMP: R-61914-48074 */ }else{ - assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) ); - v = sqlite3BtreeIntegerKey(pC->uc.pCursor); + assert( tdsqlite3BtreeCursorIsValid(pC->uc.pCursor) ); + v = tdsqlite3BtreeIntegerKey(pC->uc.pCursor); if( v>=MAX_ROWID ){ pC->useRandomRowid = 1; }else{ @@ -84658,10 +93254,10 @@ case OP_NewRowid: { /* out2 */ assert( memIsValid(pMem) ); REGISTER_TRACE(pOp->p3, pMem); - sqlite3VdbeMemIntegerify(pMem); + tdsqlite3VdbeMemIntegerify(pMem); assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){ - rc = SQLITE_FULL; /* IMP: R-12275-61338 */ + rc = SQLITE_FULL; /* IMP: R-17817-00630 */ goto abort_due_to_error; } if( v<pMem->u.i+1 ){ @@ -84679,9 +93275,9 @@ case OP_NewRowid: { /* out2 */ ** an AUTOINCREMENT table. */ cnt = 0; do{ - sqlite3_randomness(sizeof(v), &v); + tdsqlite3_randomness(sizeof(v), &v); v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */ - }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v, + }while( ((rc = tdsqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v, 0, &res))==SQLITE_OK) && (res==0) && (++cnt<100)); @@ -84711,17 +93307,12 @@ case OP_NewRowid: { /* out2 */ ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, ** then rowid is stored for subsequent return by the -** sqlite3_last_insert_rowid() function (otherwise it is unmodified). -** -** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of -** the last seek operation (OP_NotExists or OP_SeekRowid) was a success, -** then this -** operation will not attempt to find the appropriate row before doing -** the insert but will instead overwrite the row that the cursor is -** currently pointing to. Presumably, the prior OP_NotExists or -** OP_SeekRowid opcode -** has already positioned the cursor correctly. This is an optimization -** that boosts performance by avoiding redundant seeks. +** tdsqlite3_last_insert_rowid() function (otherwise it is unmodified). +** +** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might +** run faster by avoiding an unnecessary seek on cursor P1. However, +** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior +** seeks on the cursor or if the most recent seek used a key equal to P3. ** ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an ** UPDATE operation. Otherwise (if the flag is clear) then this opcode @@ -84741,78 +93332,63 @@ case OP_NewRowid: { /* out2 */ ** This instruction only works on tables. The equivalent instruction ** for indices is OP_IdxInsert. */ -/* Opcode: InsertInt P1 P2 P3 P4 P5 -** Synopsis: intkey=P3 data=r[P2] -** -** This works exactly like OP_Insert except that the key is the -** integer value P3, not the value of the integer stored in register P3. -*/ -case OP_Insert: -case OP_InsertInt: { +case OP_Insert: { Mem *pData; /* MEM cell holding data for the record to be inserted */ Mem *pKey; /* MEM cell holding key for the record */ VdbeCursor *pC; /* Cursor to table into which insert is written */ int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ const char *zDb; /* database name - used by the update hook */ Table *pTab; /* Table structure - used by update and pre-update hooks */ - int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */ BtreePayload x; /* Payload to be inserted */ - op = 0; pData = &aMem[pOp->p2]; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( memIsValid(pData) ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); + assert( pC->deferredMoveto==0 ); assert( pC->uc.pCursor!=0 ); - assert( pC->isTable ); + assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable ); assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC ); REGISTER_TRACE(pOp->p2, pData); + tdsqlite3VdbeIncrWriteCounter(p, pC); - if( pOp->opcode==OP_Insert ){ - pKey = &aMem[pOp->p3]; - assert( pKey->flags & MEM_Int ); - assert( memIsValid(pKey) ); - REGISTER_TRACE(pOp->p3, pKey); - x.nKey = pKey->u.i; - }else{ - assert( pOp->opcode==OP_InsertInt ); - x.nKey = pOp->p3; - } + pKey = &aMem[pOp->p3]; + assert( pKey->flags & MEM_Int ); + assert( memIsValid(pKey) ); + REGISTER_TRACE(pOp->p3, pKey); + x.nKey = pKey->u.i; if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ - assert( pC->isTable ); assert( pC->iDb>=0 ); zDb = db->aDb[pC->iDb].zDbSName; pTab = pOp->p4.pTab; - assert( HasRowid(pTab) ); - op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT); + assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) ); }else{ - pTab = 0; /* Not needed. Silence a comiler warning. */ + pTab = 0; zDb = 0; /* Not needed. Silence a compiler warning. */ } #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* Invoke the pre-update hook, if any */ - if( db->xPreUpdateCallback - && pOp->p4type==P4_TABLE - && !(pOp->p5 & OPFLAG_ISUPDATE) - ){ - sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2); + if( pTab ){ + if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){ + tdsqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2); + } + if( db->xUpdateCallback==0 || pTab->aCol==0 ){ + /* Prevent post-update hook from running in cases when it should not */ + pTab = 0; + } } + if( pOp->p5 & OPFLAG_ISNOOP ) break; #endif if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; - if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = x.nKey; - if( pData->flags & MEM_Null ){ - x.pData = 0; - x.nData = 0; - }else{ - assert( pData->flags & (MEM_Blob|MEM_Str) ); - x.pData = pData->z; - x.nData = pData->n; - } + if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey; + assert( pData->flags & (MEM_Blob|MEM_Str) ); + x.pData = pData->z; + x.nData = pData->n; seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0); if( pData->flags & MEM_Zero ){ x.nZero = pData->u.nZero; @@ -84820,16 +93396,20 @@ case OP_InsertInt: { x.nZero = 0; } x.pKey = 0; - rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, - (pOp->p5 & OPFLAG_APPEND)!=0, seekResult + rc = tdsqlite3BtreeInsert(pC->uc.pCursor, &x, + (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult ); pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; /* Invoke the update-hook if required. */ if( rc ) goto abort_due_to_error; - if( db->xUpdateCallback && op ){ - db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey); + if( pTab ){ + assert( db->xUpdateCallback!=0 ); + assert( pTab->aCol!=0 ); + db->xUpdateCallback(db->pUpdateArg, + (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT, + zDb, pTab->zName, x.nKey); } break; } @@ -84882,14 +93462,19 @@ case OP_Delete: { assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); assert( pC->deferredMoveto==0 ); + tdsqlite3VdbeIncrWriteCounter(p, pC); #ifdef SQLITE_DEBUG - if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){ + if( pOp->p4type==P4_TABLE + && HasRowid(pOp->p4.pTab) + && pOp->p5==0 + && tdsqlite3BtreeCursorIsValidNN(pC->uc.pCursor) + ){ /* If p5 is zero, the seek operation that positioned the cursor prior to ** OP_Delete will have also set the pC->movetoTarget field to the rowid of ** the row that is being deleted */ - i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor); - assert( pC->movetoTarget==iKey ); + i64 iKey = tdsqlite3BtreeIntegerKey(pC->uc.pCursor); + assert( CORRUPT_DB || pC->movetoTarget==iKey ); } #endif @@ -84904,7 +93489,7 @@ case OP_Delete: { zDb = db->aDb[pC->iDb].zDbSName; pTab = pOp->p4.pTab; if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){ - pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor); + pC->movetoTarget = tdsqlite3BtreeIntegerKey(pC->uc.pCursor); } }else{ zDb = 0; /* Not needed. Silence a compiler warning. */ @@ -84913,9 +93498,12 @@ case OP_Delete: { #ifdef SQLITE_ENABLE_PREUPDATE_HOOK /* Invoke the pre-update-hook if required. */ - if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){ - assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) ); - sqlite3VdbePreUpdateHook(p, pC, + if( db->xPreUpdateCallback && pOp->p4.pTab ){ + assert( !(opflags & OPFLAG_ISUPDATE) + || HasRowid(pTab)==0 + || (aMem[pOp->p3].flags & MEM_Int) + ); + tdsqlite3VdbePreUpdateHook(p, pC, (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, zDb, pTab, pC->movetoTarget, pOp->p3 @@ -84943,8 +93531,9 @@ case OP_Delete: { } #endif - rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5); + rc = tdsqlite3BtreeDelete(pC->uc.pCursor, pOp->p5); pC->cacheStatus = CACHE_STALE; + pC->seekResult = 0; if( rc ) goto abort_due_to_error; /* Invoke the update-hook if required. */ @@ -84962,12 +93551,12 @@ case OP_Delete: { /* Opcode: ResetCount * * * * * ** ** The value of the change counter is copied to the database handle -** change counter (returned by subsequent calls to sqlite3_changes()). +** change counter (returned by subsequent calls to tdsqlite3_changes()). ** Then the VMs internal change counter resets to 0. ** This is used by trigger programs. */ case OP_ResetCount: { - sqlite3VdbeSetChanges(db, p->nChange); + tdsqlite3VdbeSetChanges(db, p->nChange); p->nChange = 0; break; } @@ -84998,7 +93587,7 @@ case OP_SorterCompare: { pIn3 = &aMem[pOp->p3]; nKeyCol = pOp->p4.i; res = 0; - rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res); + rc = tdsqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res); VdbeBranchTaken(res!=0,2); if( rc ) goto abort_due_to_error; if( res ) goto jump_to_p2; @@ -85023,7 +93612,7 @@ case OP_SorterData: { pOut = &aMem[pOp->p2]; pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); - rc = sqlite3VdbeSorterRowkey(pC, pOut); + rc = tdsqlite3VdbeSorterRowkey(pC, pOut); assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) ); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); if( rc ) goto abort_due_to_error; @@ -85031,81 +93620,73 @@ case OP_SorterData: { break; } -/* Opcode: RowData P1 P2 * * * +/* Opcode: RowData P1 P2 P3 * * ** Synopsis: r[P2]=data ** -** Write into register P2 the complete row data for cursor P1. +** Write into register P2 the complete row content for the row at +** which cursor P1 is currently pointing. ** There is no interpretation of the data. ** It is just copied onto the P2 register exactly as ** it is found in the database file. ** +** If cursor P1 is an index, then the content is the key of the row. +** If cursor P2 is a table, then the content extracted is the data. +** ** If the P1 cursor must be pointing to a valid row (not a NULL row) ** of a real table, not a pseudo-table. -*/ -/* Opcode: RowKey P1 P2 * * * -** Synopsis: r[P2]=key ** -** Write into register P2 the complete row key for cursor P1. -** There is no interpretation of the data. -** The key is copied onto the P2 register exactly as -** it is found in the database file. +** If P3!=0 then this opcode is allowed to make an ephemeral pointer +** into the database page. That means that the content of the output +** register will be invalidated as soon as the cursor moves - including +** moves caused by other cursors that "save" the current cursors +** position in order that they can write to the same table. If P3==0 +** then a copy of the data is made into memory. P3!=0 is faster, but +** P3==0 is safer. ** -** If the P1 cursor must be pointing to a valid row (not a NULL row) -** of a real table, not a pseudo-table. +** If P3!=0 then the content of the P2 register is unsuitable for use +** in OP_Result and any OP_Result will invalidate the P2 register content. +** The P2 register content is invalidated by opcodes like OP_Function or +** by any use of another cursor pointing to the same table. */ -case OP_RowKey: case OP_RowData: { VdbeCursor *pC; BtCursor *pCrsr; u32 n; - pOut = &aMem[pOp->p2]; - memAboutToChange(p, pOut); + pOut = out2Prerelease(p, pOp); - /* Note that RowKey and RowData are really exactly the same instruction */ assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); assert( isSorter(pC)==0 ); - assert( pC->isTable || pOp->opcode!=OP_RowData ); - assert( pC->isTable==0 || pOp->opcode==OP_RowData ); assert( pC->nullRow==0 ); assert( pC->uc.pCursor!=0 ); pCrsr = pC->uc.pCursor; - /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or + /* The OP_RowData opcodes always follow OP_NotExists or ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions ** that might invalidate the cursor. ** If this where not the case, on of the following assert()s ** would fail. Should this ever change (because of changes in the code ** generator) then the fix would be to insert a call to - ** sqlite3VdbeCursorMoveto(). + ** tdsqlite3VdbeCursorMoveto(). */ assert( pC->deferredMoveto==0 ); - assert( sqlite3BtreeCursorIsValid(pCrsr) ); + assert( tdsqlite3BtreeCursorIsValid(pCrsr) ); #if 0 /* Not required due to the previous to assert() statements */ - rc = sqlite3VdbeCursorMoveto(pC); + rc = tdsqlite3VdbeCursorMoveto(pC); if( rc!=SQLITE_OK ) goto abort_due_to_error; #endif - n = sqlite3BtreePayloadSize(pCrsr); + n = tdsqlite3BtreePayloadSize(pCrsr); if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } testcase( n==0 ); - if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){ - goto no_mem; - } - pOut->n = n; - MemSetTypeFlag(pOut, MEM_Blob); - if( pC->isTable==0 ){ - rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z); - }else{ - rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z); - } + rc = tdsqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut); if( rc ) goto abort_due_to_error; - pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */ + if( !pOp->p3 ) Deephemeralize(pOut); UPDATE_MAX_BLOBSIZE(pOut); REGISTER_TRACE(pOp->p2, pOut); break; @@ -85124,8 +93705,8 @@ case OP_RowData: { case OP_Rowid: { /* out2 */ VdbeCursor *pC; i64 v; - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; + tdsqlite3_vtab *pVtab; + const tdsqlite3_module *pModule; pOut = out2Prerelease(p, pOp); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); @@ -85144,19 +93725,19 @@ case OP_Rowid: { /* out2 */ pModule = pVtab->pModule; assert( pModule->xRowid ); rc = pModule->xRowid(pC->uc.pVCur, &v); - sqlite3VtabImportErrmsg(p, pVtab); + tdsqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; #endif /* SQLITE_OMIT_VIRTUALTABLE */ }else{ assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->uc.pCursor!=0 ); - rc = sqlite3VdbeCursorRestore(pC); + rc = tdsqlite3VdbeCursorRestore(pC); if( rc ) goto abort_due_to_error; if( pC->nullRow ){ pOut->flags = MEM_Null; break; } - v = sqlite3BtreeIntegerKey(pC->uc.pCursor); + v = tdsqlite3BtreeIntegerKey(pC->uc.pCursor); } pOut->u.i = v; break; @@ -85178,12 +93759,25 @@ case OP_NullRow: { pC->cacheStatus = CACHE_STALE; if( pC->eCurType==CURTYPE_BTREE ){ assert( pC->uc.pCursor!=0 ); - sqlite3BtreeClearCursor(pC->uc.pCursor); + tdsqlite3BtreeClearCursor(pC->uc.pCursor); } +#ifdef SQLITE_DEBUG + if( pC->seekOp==0 ) pC->seekOp = OP_NullRow; +#endif break; } -/* Opcode: Last P1 P2 P3 * * +/* Opcode: SeekEnd P1 * * * * +** +** Position cursor P1 at the end of the btree for the purpose of +** appending a new entry onto the btree. +** +** It is assumed that the cursor is used only for appending and so +** if the cursor is valid, then the cursor must already be pointing +** at the end of the btree and so no changes are made to +** the cursor. +*/ +/* Opcode: Last P1 P2 * * * ** ** The next use of the Rowid or Column or Prev instruction for P1 ** will refer to the last entry in the database table or index. @@ -85195,6 +93789,7 @@ case OP_NullRow: { ** from the end toward the beginning. In other words, the cursor is ** configured to use Prev, not Next. */ +case OP_SeekEnd: case OP_Last: { /* jump */ VdbeCursor *pC; BtCursor *pCrsr; @@ -85207,14 +93802,20 @@ case OP_Last: { /* jump */ pCrsr = pC->uc.pCursor; res = 0; assert( pCrsr!=0 ); - rc = sqlite3BtreeLast(pCrsr, &res); +#ifdef SQLITE_DEBUG + pC->seekOp = pOp->opcode; +#endif + if( pOp->opcode==OP_SeekEnd ){ + assert( pOp->p2==0 ); + pC->seekResult = -1; + if( tdsqlite3BtreeCursorIsValidNN(pCrsr) ){ + break; + } + } + rc = tdsqlite3BtreeLast(pCrsr, &res); pC->nullRow = (u8)res; pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; - pC->seekResult = pOp->p3; -#ifdef SQLITE_DEBUG - pC->seekOp = OP_Last; -#endif if( rc ) goto abort_due_to_error; if( pOp->p2>0 ){ VdbeBranchTaken(res!=0,2); @@ -85223,7 +93824,43 @@ case OP_Last: { /* jump */ break; } +/* Opcode: IfSmaller P1 P2 P3 * * +** +** Estimate the number of rows in the table P1. Jump to P2 if that +** estimate is less than approximately 2**(0.1*P3). +*/ +case OP_IfSmaller: { /* jump */ + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + i64 sz; + + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + pCrsr = pC->uc.pCursor; + assert( pCrsr ); + rc = tdsqlite3BtreeFirst(pCrsr, &res); + if( rc ) goto abort_due_to_error; + if( res==0 ){ + sz = tdsqlite3BtreeRowCountEst(pCrsr); + if( ALWAYS(sz>=0) && tdsqlite3LogEst((u64)sz)<pOp->p3 ) res = 1; + } + VdbeBranchTaken(res!=0,2); + if( res ) goto jump_to_p2; + break; +} + +/* Opcode: SorterSort P1 P2 * * * +** +** After all records have been inserted into the Sorter object +** identified by P1, invoke this opcode to actually do the sorting. +** Jump to P2 if there are no records to be sorted. +** +** This opcode is an alias for OP_Sort and OP_Rewind that is used +** for Sorter objects. +*/ /* Opcode: Sort P1 P2 * * * ** ** This opcode does exactly the same thing as OP_Rewind except that @@ -85239,8 +93876,8 @@ case OP_Last: { /* jump */ case OP_SorterSort: /* jump */ case OP_Sort: { /* jump */ #ifdef SQLITE_TEST - sqlite3_sort_count++; - sqlite3_search_count--; + tdsqlite3_sort_count++; + tdsqlite3_search_count--; #endif p->aCounter[SQLITE_STMTSTATUS_SORT]++; /* Fall through into OP_Rewind */ @@ -85263,6 +93900,7 @@ case OP_Rewind: { /* jump */ int res; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + assert( pOp->p5==0 ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) ); @@ -85271,12 +93909,12 @@ case OP_Rewind: { /* jump */ pC->seekOp = OP_Rewind; #endif if( isSorter(pC) ){ - rc = sqlite3VdbeSorterRewind(pC, &res); + rc = tdsqlite3VdbeSorterRewind(pC, &res); }else{ assert( pC->eCurType==CURTYPE_BTREE ); pCrsr = pC->uc.pCursor; assert( pCrsr ); - rc = sqlite3BtreeFirst(pCrsr, &res); + rc = tdsqlite3BtreeFirst(pCrsr, &res); pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; } @@ -85308,17 +93946,12 @@ case OP_Rewind: { /* jump */ ** always either 0 or 1. ** ** P4 is always of type P4_ADVANCE. The function pointer points to -** sqlite3BtreeNext(). +** tdsqlite3BtreeNext(). ** ** If P5 is positive and the jump is taken, then event counter ** number P5-1 in the prepared statement is incremented. ** -** See also: Prev, NextIfOpen -*/ -/* Opcode: NextIfOpen P1 P2 P3 P4 P5 -** -** This opcode works just like Next except that if cursor P1 is not -** open it behaves a no-op. +** See also: Prev */ /* Opcode: Prev P1 P2 P3 P4 P5 ** @@ -85341,93 +93974,101 @@ case OP_Rewind: { /* jump */ ** always either 0 or 1. ** ** P4 is always of type P4_ADVANCE. The function pointer points to -** sqlite3BtreePrevious(). +** tdsqlite3BtreePrevious(). ** ** If P5 is positive and the jump is taken, then event counter ** number P5-1 in the prepared statement is incremented. */ -/* Opcode: PrevIfOpen P1 P2 P3 P4 P5 +/* Opcode: SorterNext P1 P2 * * P5 ** -** This opcode works just like Prev except that if cursor P1 is not -** open it behaves a no-op. +** This opcode works just like OP_Next except that P1 must be a +** sorter object for which the OP_SorterSort opcode has been +** invoked. This opcode advances the cursor to the next sorted +** record, or jumps to P2 if there are no more sorted records. */ case OP_SorterNext: { /* jump */ VdbeCursor *pC; - int res; pC = p->apCsr[pOp->p1]; assert( isSorter(pC) ); - res = 0; - rc = sqlite3VdbeSorterNext(db, pC, &res); + rc = tdsqlite3VdbeSorterNext(db, pC); goto next_tail; -case OP_PrevIfOpen: /* jump */ -case OP_NextIfOpen: /* jump */ - if( p->apCsr[pOp->p1]==0 ) break; - /* Fall through */ case OP_Prev: /* jump */ case OP_Next: /* jump */ assert( pOp->p1>=0 && pOp->p1<p->nCursor ); assert( pOp->p5<ArraySize(p->aCounter) ); pC = p->apCsr[pOp->p1]; - res = pOp->p3; assert( pC!=0 ); assert( pC->deferredMoveto==0 ); assert( pC->eCurType==CURTYPE_BTREE ); - assert( res==0 || (res==1 && pC->isTable==0) ); - testcase( res==1 ); - assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext ); - assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious ); - assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext ); - assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious); - - /* The Next opcode is only used after SeekGT, SeekGE, and Rewind. + assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==tdsqlite3BtreeNext ); + assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==tdsqlite3BtreePrevious ); + + /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */ - assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen + assert( pOp->opcode!=OP_Next || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE - || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found); - assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen + || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found + || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid + || pC->seekOp==OP_IfNoHope); + assert( pOp->opcode!=OP_Prev || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE - || pC->seekOp==OP_Last ); + || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope + || pC->seekOp==OP_NullRow); - rc = pOp->p4.xAdvance(pC->uc.pCursor, &res); + rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3); next_tail: pC->cacheStatus = CACHE_STALE; - VdbeBranchTaken(res==0,2); - if( rc ) goto abort_due_to_error; - if( res==0 ){ + VdbeBranchTaken(rc==SQLITE_OK,2); + if( rc==SQLITE_OK ){ pC->nullRow = 0; p->aCounter[pOp->p5]++; #ifdef SQLITE_TEST - sqlite3_search_count++; + tdsqlite3_search_count++; #endif goto jump_to_p2_and_check_for_interrupt; - }else{ - pC->nullRow = 1; } + if( rc!=SQLITE_DONE ) goto abort_due_to_error; + rc = SQLITE_OK; + pC->nullRow = 1; goto check_for_interrupt; } -/* Opcode: IdxInsert P1 P2 P3 * P5 +/* Opcode: IdxInsert P1 P2 P3 P4 P5 ** Synopsis: key=r[P2] ** ** Register P2 holds an SQL index key made using the ** MakeRecord instructions. This opcode writes that key ** into the index P1. Data for the entry is nil. ** -** P3 is a flag that provides a hint to the b-tree layer that this -** insert is likely to be an append. +** If P4 is not zero, then it is the number of values in the unpacked +** key of reg(P2). In that case, P3 is the index of the first register +** for the unpacked key. The availability of the unpacked key can sometimes +** be an optimization. +** +** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer +** that this insert is likely to be an append. ** ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear, ** then the change counter is unchanged. ** -** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have -** just done a seek to the spot where the new entry is to be inserted. -** This flag avoids doing an extra seek. +** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might +** run faster by avoiding an unnecessary seek on cursor P1. However, +** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior +** seeks on the cursor or if the most recent seek used a key equivalent +** to P2. ** ** This instruction only works for indices. The equivalent instruction ** for tables is OP_Insert. */ +/* Opcode: SorterInsert P1 P2 * * * +** Synopsis: key=r[P2] +** +** Register P2 holds an SQL index key made using the +** MakeRecord instructions. This opcode writes that key +** into the sorter P1. Data for the entry is nil. +*/ case OP_SorterInsert: /* in2 */ case OP_IdxInsert: { /* in2 */ VdbeCursor *pC; @@ -85435,6 +94076,7 @@ case OP_IdxInsert: { /* in2 */ assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; + tdsqlite3VdbeIncrWriteCounter(p, pC); assert( pC!=0 ); assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) ); pIn2 = &aMem[pOp->p2]; @@ -85445,11 +94087,14 @@ case OP_IdxInsert: { /* in2 */ rc = ExpandBlob(pIn2); if( rc ) goto abort_due_to_error; if( pOp->opcode==OP_SorterInsert ){ - rc = sqlite3VdbeSorterWrite(pC, pIn2); + rc = tdsqlite3VdbeSorterWrite(pC, pIn2); }else{ x.nKey = pIn2->n; x.pKey = pIn2->z; - rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, pOp->p3, + x.aMem = aMem + pOp->p3; + x.nMem = (u16)pOp->p4.i; + rc = tdsqlite3BtreeInsert(pC->uc.pCursor, &x, + (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) ); assert( pC->deferredMoveto==0 ); @@ -85478,6 +94123,7 @@ case OP_IdxDelete: { pC = p->apCsr[pOp->p1]; assert( pC!=0 ); assert( pC->eCurType==CURTYPE_BTREE ); + tdsqlite3VdbeIncrWriteCounter(p, pC); pCrsr = pC->uc.pCursor; assert( pCrsr!=0 ); assert( pOp->p5==0 ); @@ -85485,19 +94131,20 @@ case OP_IdxDelete: { r.nField = (u16)pOp->p3; r.default_rc = 0; r.aMem = &aMem[pOp->p2]; - rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res); + rc = tdsqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res); if( rc ) goto abort_due_to_error; if( res==0 ){ - rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE); + rc = tdsqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE); if( rc ) goto abort_due_to_error; } assert( pC->deferredMoveto==0 ); pC->cacheStatus = CACHE_STALE; + pC->seekResult = 0; break; } -/* Opcode: Seek P1 * P3 P4 * -** Synopsis: Move P3 to P1.rowid +/* Opcode: DeferredSeek P1 * P3 P4 * +** Synopsis: Move P3 to P1.rowid if needed ** ** P1 is an open index cursor and P3 is a cursor on the corresponding ** table. This opcode does a deferred seek of the P3 table cursor @@ -85524,11 +94171,11 @@ case OP_IdxDelete: { ** ** See also: Rowid, MakeRecord. */ -case OP_Seek: -case OP_IdxRowid: { /* out2 */ - VdbeCursor *pC; /* The P1 index cursor */ - VdbeCursor *pTabCur; /* The P2 table cursor (OP_Seek only) */ - i64 rowid; /* Rowid that P1 current points to */ +case OP_DeferredSeek: +case OP_IdxRowid: { /* out2 */ + VdbeCursor *pC; /* The P1 index cursor */ + VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */ + i64 rowid; /* Rowid that P1 current points to */ assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; @@ -85540,21 +94187,21 @@ case OP_IdxRowid: { /* out2 */ assert( !pC->nullRow || pOp->opcode==OP_IdxRowid ); /* The IdxRowid and Seek opcodes are combined because of the commonality - ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */ - rc = sqlite3VdbeCursorRestore(pC); + ** of tdsqlite3VdbeCursorRestore() and tdsqlite3VdbeIdxRowid(). */ + rc = tdsqlite3VdbeCursorRestore(pC); - /* sqlite3VbeCursorRestore() can only fail if the record has been deleted + /* tdsqlite3VbeCursorRestore() can only fail if the record has been deleted ** out from under the cursor. That will never happens for an IdxRowid ** or Seek opcode */ if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; if( !pC->nullRow ){ rowid = 0; /* Not needed. Only used to silence a warning. */ - rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid); + rc = tdsqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } - if( pOp->opcode==OP_Seek ){ + if( pOp->opcode==OP_DeferredSeek ){ assert( pOp->p3>=0 && pOp->p3<p->nCursor ); pTabCur = p->apCsr[pOp->p3]; assert( pTabCur!=0 ); @@ -85570,11 +94217,28 @@ case OP_IdxRowid: { /* out2 */ }else{ pOut = out2Prerelease(p, pOp); pOut->u.i = rowid; - pOut->flags = MEM_Int; } }else{ assert( pOp->opcode==OP_IdxRowid ); - sqlite3VdbeMemSetNull(&aMem[pOp->p2]); + tdsqlite3VdbeMemSetNull(&aMem[pOp->p2]); + } + break; +} + +/* Opcode: FinishSeek P1 * * * * +** +** If cursor P1 was previously moved via OP_DeferredSeek, complete that +** seek operation now, without further delay. If the cursor seek has +** already occurred, this instruction is a no-op. +*/ +case OP_FinishSeek: { + VdbeCursor *pC; /* The P1 index cursor */ + + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + pC = p->apCsr[pOp->p1]; + if( pC->deferredMoveto ){ + rc = tdsqlite3VdbeFinishMoveto(pC); + if( rc ) goto abort_due_to_error; } break; } @@ -85651,10 +94315,16 @@ case OP_IdxGE: { /* jump */ } r.aMem = &aMem[pOp->p3]; #ifdef SQLITE_DEBUG - { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); } + { + int i; + for(i=0; i<r.nField; i++){ + assert( memIsValid(&r.aMem[i]) ); + REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]); + } + } #endif res = 0; /* Not needed. Only used to silence a warning. */ - rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res); + rc = tdsqlite3VdbeIdxKeyCompare(db, pC, &r, &res); assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) ); if( (pOp->opcode&1)==(OP_IdxLT&1) ){ assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT ); @@ -85682,10 +94352,17 @@ case OP_IdxGE: { /* jump */ ** might be moved into the newly deleted root page in order to keep all ** root pages contiguous at the beginning of the database. The former ** value of the root page that moved - its value before the move occurred - -** is stored in register P2. If no page -** movement was required (because the table being dropped was already -** the last one in the database) then a zero is stored in register P2. -** If AUTOVACUUM is disabled then a zero is stored in register P2. +** is stored in register P2. If no page movement was required (because the +** table being dropped was already the last one in the database) then a +** zero is stored in register P2. If AUTOVACUUM is disabled then a zero +** is stored in register P2. +** +** This opcode throws an error if there are any active reader VMs when +** it is invoked. This is done to avoid the difficulty associated with +** updating existing cursors when a root page is moved in an AUTOVACUUM +** database. This error is thrown even if the database is not an AUTOVACUUM +** db in order to avoid introducing an incompatibility between autovacuum +** and non-autovacuum modes. ** ** See also: Clear */ @@ -85693,6 +94370,7 @@ case OP_Destroy: { /* out2 */ int iMoved; int iDb; + tdsqlite3VdbeIncrWriteCounter(p, 0); assert( p->readOnly==0 ); assert( pOp->p1>1 ); pOut = out2Prerelease(p, pOp); @@ -85705,13 +94383,13 @@ case OP_Destroy: { /* out2 */ iDb = pOp->p3; assert( DbMaskTest(p->btreeMask, iDb) ); iMoved = 0; /* Not needed. Only to silence a warning. */ - rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved); + rc = tdsqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved); pOut->flags = MEM_Int; pOut->u.i = iMoved; if( rc ) goto abort_due_to_error; #ifndef SQLITE_OMIT_AUTOVACUUM if( iMoved!=0 ){ - sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1); + tdsqlite3RootPageMoved(db, iDb, iMoved, pOp->p1); /* All OP_Destroy operations occur on the same btree */ assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 ); resetSchemaOnFault = iDb+1; @@ -85742,10 +94420,11 @@ case OP_Destroy: { /* out2 */ case OP_Clear: { int nChange; + tdsqlite3VdbeIncrWriteCounter(p, 0); nChange = 0; assert( p->readOnly==0 ); assert( DbMaskTest(p->btreeMask, pOp->p2) ); - rc = sqlite3BtreeClearTable( + rc = tdsqlite3BtreeClearTable( db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0) ); if( pOp->p3 ){ @@ -85775,69 +94454,62 @@ case OP_ResetSorter: { pC = p->apCsr[pOp->p1]; assert( pC!=0 ); if( isSorter(pC) ){ - sqlite3VdbeSorterReset(db, pC->uc.pSorter); + tdsqlite3VdbeSorterReset(db, pC->uc.pSorter); }else{ assert( pC->eCurType==CURTYPE_BTREE ); assert( pC->isEphemeral ); - rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor); + rc = tdsqlite3BtreeClearTableOfCursor(pC->uc.pCursor); if( rc ) goto abort_due_to_error; } break; } -/* Opcode: CreateTable P1 P2 * * * -** Synopsis: r[P2]=root iDb=P1 -** -** Allocate a new table in the main database file if P1==0 or in the -** auxiliary database file if P1==1 or in an attached database if -** P1>1. Write the root page number of the new table into -** register P2 -** -** The difference between a table and an index is this: A table must -** have a 4-byte integer key and can have arbitrary data. An index -** has an arbitrary key but no data. +/* Opcode: CreateBtree P1 P2 P3 * * +** Synopsis: r[P2]=root iDb=P1 flags=P3 ** -** See also: CreateIndex +** Allocate a new b-tree in the main database file if P1==0 or in the +** TEMP database file if P1==1 or in an attached database if +** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table +** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table. +** The root page number of the new b-tree is stored in register P2. */ -/* Opcode: CreateIndex P1 P2 * * * -** Synopsis: r[P2]=root iDb=P1 -** -** Allocate a new index in the main database file if P1==0 or in the -** auxiliary database file if P1==1 or in an attached database if -** P1>1. Write the root page number of the new table into -** register P2. -** -** See documentation on OP_CreateTable for additional information. -*/ -case OP_CreateIndex: /* out2 */ -case OP_CreateTable: { /* out2 */ +case OP_CreateBtree: { /* out2 */ int pgno; - int flags; Db *pDb; + tdsqlite3VdbeIncrWriteCounter(p, 0); pOut = out2Prerelease(p, pOp); pgno = 0; + assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY ); assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( DbMaskTest(p->btreeMask, pOp->p1) ); assert( p->readOnly==0 ); pDb = &db->aDb[pOp->p1]; assert( pDb->pBt!=0 ); - if( pOp->opcode==OP_CreateTable ){ - /* flags = BTREE_INTKEY; */ - flags = BTREE_INTKEY; - }else{ - flags = BTREE_BLOBKEY; - } - rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags); + rc = tdsqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3); if( rc ) goto abort_due_to_error; pOut->u.i = pgno; break; } +/* Opcode: SqlExec * * * P4 * +** +** Run the SQL statement or statements specified in the P4 string. +*/ +case OP_SqlExec: { + tdsqlite3VdbeIncrWriteCounter(p, 0); + db->nSqlExec++; + rc = tdsqlite3_exec(db, pOp->p4.z, 0, 0, 0); + db->nSqlExec--; + if( rc ) goto abort_due_to_error; + break; +} + /* Opcode: ParseSchema P1 * * P4 * ** ** Read and parse all entries from the SQLITE_MASTER table of database P1 -** that match the WHERE clause P4. +** that match the WHERE clause P4. If P4 is a NULL pointer, then the +** entire schema for P1 is reparsed. ** ** This opcode invokes the parser to create a new virtual machine, ** then runs the new virtual machine. It is thus a re-entrant opcode. @@ -85850,24 +94522,35 @@ case OP_ParseSchema: { /* Any prepared statement that invokes this opcode will hold mutexes ** on every btree. This is a prerequisite for invoking - ** sqlite3InitCallback(). + ** tdsqlite3InitCallback(). */ #ifdef SQLITE_DEBUG for(iDb=0; iDb<db->nDb; iDb++){ - assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); + assert( iDb==1 || tdsqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); } #endif iDb = pOp->p1; assert( iDb>=0 && iDb<db->nDb ); assert( DbHasProperty(db, iDb, DB_SchemaLoaded) ); - /* Used to be a conditional */ { - zMaster = SCHEMA_TABLE(iDb); + +#ifndef SQLITE_OMIT_ALTERTABLE + if( pOp->p4.z==0 ){ + tdsqlite3SchemaClear(db->aDb[iDb].pSchema); + db->mDbFlags &= ~DBFLAG_SchemaKnownOk; + rc = tdsqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable); + db->mDbFlags |= DBFLAG_SchemaChange; + p->expired = 0; + }else +#endif + { + zMaster = MASTER_NAME; initData.db = db; - initData.iDb = pOp->p1; + initData.iDb = iDb; initData.pzErrMsg = &p->zErrMsg; - zSql = sqlite3MPrintf(db, - "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid", + initData.mInitFlags = 0; + zSql = tdsqlite3MPrintf(db, + "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid", db->aDb[iDb].zDbSName, zMaster, pOp->p4.z); if( zSql==0 ){ rc = SQLITE_NOMEM_BKPT; @@ -85875,15 +94558,22 @@ case OP_ParseSchema: { assert( db->init.busy==0 ); db->init.busy = 1; initData.rc = SQLITE_OK; + initData.nInitRow = 0; assert( !db->mallocFailed ); - rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); + rc = tdsqlite3_exec(db, zSql, tdsqlite3InitCallback, &initData, 0); if( rc==SQLITE_OK ) rc = initData.rc; - sqlite3DbFree(db, zSql); + if( rc==SQLITE_OK && initData.nInitRow==0 ){ + /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse + ** at least one SQL statement. Any less than that indicates that + ** the sqlite_master table is corrupt. */ + rc = SQLITE_CORRUPT_BKPT; + } + tdsqlite3DbFreeNN(db, zSql); db->init.busy = 0; } } if( rc ){ - sqlite3ResetAllSchemasOfConnection(db); + tdsqlite3ResetAllSchemasOfConnection(db); if( rc==SQLITE_NOMEM ){ goto no_mem; } @@ -85901,7 +94591,7 @@ case OP_ParseSchema: { */ case OP_LoadAnalysis: { assert( pOp->p1>=0 && pOp->p1<db->nDb ); - rc = sqlite3AnalysisLoad(db, pOp->p1); + rc = tdsqlite3AnalysisLoad(db, pOp->p1); if( rc ) goto abort_due_to_error; break; } @@ -85916,7 +94606,8 @@ case OP_LoadAnalysis: { ** schema consistent with what is on disk. */ case OP_DropTable: { - sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); + tdsqlite3VdbeIncrWriteCounter(p, 0); + tdsqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); break; } @@ -85929,7 +94620,8 @@ case OP_DropTable: { ** schema consistent with what is on disk. */ case OP_DropIndex: { - sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); + tdsqlite3VdbeIncrWriteCounter(p, 0); + tdsqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); break; } @@ -85942,7 +94634,8 @@ case OP_DropIndex: { ** schema consistent with what is on disk. */ case OP_DropTrigger: { - sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); + tdsqlite3VdbeIncrWriteCounter(p, 0); + tdsqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); break; } @@ -85954,7 +94647,7 @@ case OP_DropTrigger: { ** register P1 the text of an error message describing any problems. ** If no problems are found, store a NULL in register P1. ** -** The register P3 contains the maximum number of allowed errors. +** The register P3 contains one less than the maximum number of allowed errors. ** At most reg(P3) errors will be reported. ** In other words, the analysis stops as soon as reg(P1) errors are ** seen. Reg(P1) is updated with the number of errors remaining. @@ -85978,7 +94671,7 @@ case OP_IntegrityCk: { nRoot = pOp->p2; aRoot = pOp->p4.ai; assert( nRoot>0 ); - assert( aRoot[nRoot]==0 ); + assert( aRoot[0]==nRoot ); assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); pnErr = &aMem[pOp->p3]; assert( (pnErr->flags & MEM_Int)!=0 ); @@ -85986,27 +94679,27 @@ case OP_IntegrityCk: { pIn1 = &aMem[pOp->p1]; assert( pOp->p5<db->nDb ); assert( DbMaskTest(p->btreeMask, pOp->p5) ); - z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot, - (int)pnErr->u.i, &nErr); - pnErr->u.i -= nErr; - sqlite3VdbeMemSetNull(pIn1); + z = tdsqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot, + (int)pnErr->u.i+1, &nErr); + tdsqlite3VdbeMemSetNull(pIn1); if( nErr==0 ){ assert( z==0 ); }else if( z==0 ){ goto no_mem; }else{ - sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free); + pnErr->u.i -= nErr-1; + tdsqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, tdsqlite3_free); } UPDATE_MAX_BLOBSIZE(pIn1); - sqlite3VdbeChangeEncoding(pIn1, encoding); - break; + tdsqlite3VdbeChangeEncoding(pIn1, encoding); + goto check_for_interrupt; } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ /* Opcode: RowSetAdd P1 P2 * * * ** Synopsis: rowset(P1)=r[P2] ** -** Insert the integer value held by register P2 into a boolean index +** Insert the integer value held by register P2 into a RowSet object ** held in register P1. ** ** An assertion fails if P2 is not an integer. @@ -86015,36 +94708,38 @@ case OP_RowSetAdd: { /* in1, in2 */ pIn1 = &aMem[pOp->p1]; pIn2 = &aMem[pOp->p2]; assert( (pIn2->flags & MEM_Int)!=0 ); - if( (pIn1->flags & MEM_RowSet)==0 ){ - sqlite3VdbeMemSetRowSet(pIn1); - if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; + if( (pIn1->flags & MEM_Blob)==0 ){ + if( tdsqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem; } - sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i); + assert( tdsqlite3VdbeMemIsRowSet(pIn1) ); + tdsqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i); break; } /* Opcode: RowSetRead P1 P2 P3 * * ** Synopsis: r[P3]=rowset(P1) ** -** Extract the smallest value from boolean index P1 and put that value into -** register P3. Or, if boolean index P1 is initially empty, leave P3 +** Extract the smallest value from the RowSet object in P1 +** and put that value into register P3. +** Or, if RowSet object P1 is initially empty, leave P3 ** unchanged and jump to instruction P2. */ case OP_RowSetRead: { /* jump, in1, out3 */ i64 val; pIn1 = &aMem[pOp->p1]; - if( (pIn1->flags & MEM_RowSet)==0 - || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0 + assert( (pIn1->flags & MEM_Blob)==0 || tdsqlite3VdbeMemIsRowSet(pIn1) ); + if( (pIn1->flags & MEM_Blob)==0 + || tdsqlite3RowSetNext((RowSet*)pIn1->z, &val)==0 ){ /* The boolean index is empty */ - sqlite3VdbeMemSetNull(pIn1); + tdsqlite3VdbeMemSetNull(pIn1); VdbeBranchTaken(1,2); goto jump_to_p2_and_check_for_interrupt; }else{ /* A value was pulled from the index */ VdbeBranchTaken(0,2); - sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val); + tdsqlite3VdbeMemSetInt64(&aMem[pOp->p3], val); } goto check_for_interrupt; } @@ -86058,15 +94753,14 @@ case OP_RowSetRead: { /* jump, in1, out3 */ ** integer in P3 into the RowSet and continue on to the ** next opcode. ** -** The RowSet object is optimized for the case where successive sets -** of integers, where each set contains no duplicates. Each set -** of values is identified by a unique P4 value. The first set -** must have P4==0, the final set P4=-1. P4 must be either -1 or -** non-negative. For non-negative values of P4 only the lower 4 -** bits are significant. +** The RowSet object is optimized for the case where sets of integers +** are inserted in distinct phases, which each set contains no duplicates. +** Each set is identified by a unique P4 value. The first set +** must have P4==0, the final set must have P4==-1, and for all other sets +** must have P4>0. ** ** This allows optimizations: (a) when P4==0 there is no need to test -** the rowset object for P3, as it is guaranteed not to contain it, +** the RowSet object for P3, as it is guaranteed not to contain it, ** (b) when P4==-1 there is no need to insert the value, as it will ** never be tested for, and (c) when a value that is part of set X is ** inserted, there is no need to search to see if the same value was @@ -86085,20 +94779,19 @@ case OP_RowSetTest: { /* jump, in1, in3 */ /* If there is anything other than a rowset object in memory cell P1, ** delete it now and initialize P1 with an empty rowset */ - if( (pIn1->flags & MEM_RowSet)==0 ){ - sqlite3VdbeMemSetRowSet(pIn1); - if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; + if( (pIn1->flags & MEM_Blob)==0 ){ + if( tdsqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem; } - + assert( tdsqlite3VdbeMemIsRowSet(pIn1) ); assert( pOp->p4type==P4_INT32 ); assert( iSet==-1 || iSet>=0 ); if( iSet ){ - exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i); + exists = tdsqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i); VdbeBranchTaken(exists!=0,2); if( exists ) goto jump_to_p2; } if( iSet>=0 ){ - sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i); + tdsqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i); } break; } @@ -86154,7 +94847,7 @@ case OP_Program: { /* jump */ if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ rc = SQLITE_ERROR; - sqlite3VdbeError(p, "too many levels of trigger recursion"); + tdsqlite3VdbeError(p, "too many levels of trigger recursion"); goto abort_due_to_error; } @@ -86162,7 +94855,7 @@ case OP_Program: { /* jump */ ** of the current program, and the memory required at runtime to execute ** the trigger program. If this trigger has been fired before, then pRt ** is already allocated. Otherwise, it must be initialized. */ - if( (pRt->flags&MEM_Frame)==0 ){ + if( (pRt->flags&MEM_Blob)==0 ){ /* SubProgram.nMem is set to the number of memory cells used by the ** program stored in SubProgram.aOp. As well as these, one memory ** cell is required for each cursor used by the program. Set local @@ -86173,14 +94866,17 @@ case OP_Program: { /* jump */ if( pProgram->nCsr==0 ) nMem++; nByte = ROUND8(sizeof(VdbeFrame)) + nMem * sizeof(Mem) - + pProgram->nCsr * sizeof(VdbeCursor *); - pFrame = sqlite3DbMallocZero(db, nByte); + + pProgram->nCsr * sizeof(VdbeCursor*) + + (pProgram->nOp + 7)/8; + pFrame = tdsqlite3DbMallocZero(db, nByte); if( !pFrame ){ goto no_mem; } - sqlite3VdbeMemRelease(pRt); - pRt->flags = MEM_Frame; - pRt->u.pFrame = pFrame; + tdsqlite3VdbeMemRelease(pRt); + pRt->flags = MEM_Blob|MEM_Dyn; + pRt->z = (char*)pFrame; + pRt->n = nByte; + pRt->xDel = tdsqlite3VdbeFrameMemDel; pFrame->v = p; pFrame->nChildMem = nMem; @@ -86196,6 +94892,9 @@ case OP_Program: { /* jump */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS pFrame->anExec = p->anExec; #endif +#ifdef SQLITE_DEBUG + pFrame->iFrameMagic = SQLITE_FRAME_MAGIC; +#endif pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem]; for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){ @@ -86203,7 +94902,8 @@ case OP_Program: { /* jump */ pMem->db = db; } }else{ - pFrame = pRt->u.pFrame; + pFrame = (VdbeFrame*)pRt->z; + assert( pRt->xDel==tdsqlite3VdbeFrameMemDel ); assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) ); assert( pProgram->nCsr==pFrame->nChildCsr ); @@ -86212,7 +94912,7 @@ case OP_Program: { /* jump */ p->nFrame++; pFrame->pParent = p->pFrame; - pFrame->lastRowid = lastRowid; + pFrame->lastRowid = db->lastRowid; pFrame->nChange = p->nChange; pFrame->nDbChange = p->db->nChange; assert( pFrame->pAuxData==0 ); @@ -86224,14 +94924,26 @@ case OP_Program: { /* jump */ p->nMem = pFrame->nChildMem; p->nCursor = (u16)pFrame->nChildCsr; p->apCsr = (VdbeCursor **)&aMem[p->nMem]; + pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr]; + memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8); p->aOp = aOp = pProgram->aOp; p->nOp = pProgram->nOp; #ifdef SQLITE_ENABLE_STMT_SCANSTATUS p->anExec = 0; #endif +#ifdef SQLITE_DEBUG + /* Verify that second and subsequent executions of the same trigger do not + ** try to reuse register values from the first use. */ + { + int i; + for(i=0; i<p->nMem; i++){ + aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */ + aMem[i].flags |= MEM_Undefined; /* Cause a fault if this reg is reused */ + } + } +#endif pOp = &aOp[-1]; - - break; + goto check_for_interrupt; } /* Opcode: Param P1 P2 * * * @@ -86252,7 +94964,7 @@ case OP_Param: { /* out2 */ pOut = out2Prerelease(p, pOp); pFrame = p->pFrame; pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1]; - sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem); + tdsqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem); break; } @@ -86323,9 +95035,9 @@ case OP_MemMax: { /* in2 */ pIn1 = &aMem[pOp->p1]; } assert( memIsValid(pIn1) ); - sqlite3VdbeMemIntegerify(pIn1); + tdsqlite3VdbeMemIntegerify(pIn1); pIn2 = &aMem[pOp->p2]; - sqlite3VdbeMemIntegerify(pIn2); + tdsqlite3VdbeMemIntegerify(pIn2); if( pIn1->u.i<pIn2->u.i){ pIn1->u.i = pIn2->u.i; } @@ -86373,29 +95085,42 @@ case OP_IfPos: { /* jump, in1 */ ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3]. */ case OP_OffsetLimit: { /* in1, out2, in3 */ + i64 x; pIn1 = &aMem[pOp->p1]; pIn3 = &aMem[pOp->p3]; pOut = out2Prerelease(p, pOp); assert( pIn1->flags & MEM_Int ); assert( pIn3->flags & MEM_Int ); - pOut->u.i = pIn1->u.i<=0 ? -1 : pIn1->u.i+(pIn3->u.i>0?pIn3->u.i:0); + x = pIn1->u.i; + if( x<=0 || tdsqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){ + /* If the LIMIT is less than or equal to zero, loop forever. This + ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then + ** also loop forever. This is undocumented. In fact, one could argue + ** that the loop should terminate. But assuming 1 billion iterations + ** per second (far exceeding the capabilities of any current hardware) + ** it would take nearly 300 years to actually reach the limit. So + ** looping forever is a reasonable approximation. */ + pOut->u.i = -1; + }else{ + pOut->u.i = x; + } break; } -/* Opcode: IfNotZero P1 P2 P3 * * -** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 +/* Opcode: IfNotZero P1 P2 * * * +** Synopsis: if r[P1]!=0 then r[P1]--, goto P2 ** ** Register P1 must contain an integer. If the content of register P1 is -** initially nonzero, then subtract P3 from the value in register P1 and -** jump to P2. If register P1 is initially zero, leave it unchanged -** and fall through. +** initially greater than zero, then decrement the value in register P1. +** If it is non-zero (negative or positive) and then also jump to P2. +** If register P1 is initially zero, leave it unchanged and fall through. */ case OP_IfNotZero: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags&MEM_Int ); VdbeBranchTaken(pIn1->u.i<0, 2); if( pIn1->u.i ){ - pIn1->u.i -= pOp->p3; + if( pIn1->u.i>0 ) pIn1->u.i--; goto jump_to_p2; } break; @@ -86404,82 +95129,113 @@ case OP_IfNotZero: { /* jump, in1 */ /* Opcode: DecrJumpZero P1 P2 * * * ** Synopsis: if (--r[P1])==0 goto P2 ** -** Register P1 must hold an integer. Decrement the value in register P1 -** then jump to P2 if the new value is exactly zero. +** Register P1 must hold an integer. Decrement the value in P1 +** and jump to P2 if the new value is exactly zero. */ case OP_DecrJumpZero: { /* jump, in1 */ pIn1 = &aMem[pOp->p1]; assert( pIn1->flags&MEM_Int ); - pIn1->u.i--; + if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--; VdbeBranchTaken(pIn1->u.i==0, 2); if( pIn1->u.i==0 ) goto jump_to_p2; break; } -/* Opcode: AggStep0 * P2 P3 P4 P5 +/* Opcode: AggStep * P2 P3 P4 P5 ** Synopsis: accum=r[P3] step(r[P2@P5]) ** -** Execute the step function for an aggregate. The -** function has P5 arguments. P4 is a pointer to the FuncDef -** structure that specifies the function. Register P3 is the +** Execute the xStep function for an aggregate. +** The function has P5 arguments. P4 is a pointer to the +** FuncDef structure that specifies the function. Register P3 is the ** accumulator. ** ** The P5 arguments are taken from register P2 and its ** successors. */ -/* Opcode: AggStep * P2 P3 P4 P5 +/* Opcode: AggInverse * P2 P3 P4 P5 +** Synopsis: accum=r[P3] inverse(r[P2@P5]) +** +** Execute the xInverse function for an aggregate. +** The function has P5 arguments. P4 is a pointer to the +** FuncDef structure that specifies the function. Register P3 is the +** accumulator. +** +** The P5 arguments are taken from register P2 and its +** successors. +*/ +/* Opcode: AggStep1 P1 P2 P3 P4 P5 ** Synopsis: accum=r[P3] step(r[P2@P5]) ** -** Execute the step function for an aggregate. The -** function has P5 arguments. P4 is a pointer to an sqlite3_context -** object that is used to run the function. Register P3 is -** as the accumulator. +** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an +** aggregate. The function has P5 arguments. P4 is a pointer to the +** FuncDef structure that specifies the function. Register P3 is the +** accumulator. ** ** The P5 arguments are taken from register P2 and its ** successors. ** ** This opcode is initially coded as OP_AggStep0. On first evaluation, -** the FuncDef stored in P4 is converted into an sqlite3_context and +** the FuncDef stored in P4 is converted into an tdsqlite3_context and ** the opcode is changed. In this way, the initialization of the -** sqlite3_context only happens once, instead of on each call to the +** tdsqlite3_context only happens once, instead of on each call to the ** step function. */ -case OP_AggStep0: { +case OP_AggInverse: +case OP_AggStep: { int n; - sqlite3_context *pCtx; + tdsqlite3_context *pCtx; assert( pOp->p4type==P4_FUNCDEF ); n = pOp->p5; assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) ); assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n ); - pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*)); + pCtx = tdsqlite3DbMallocRawNN(db, n*sizeof(tdsqlite3_value*) + + (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(tdsqlite3_value*))); if( pCtx==0 ) goto no_mem; pCtx->pMem = 0; + pCtx->pOut = (Mem*)&(pCtx->argv[n]); + tdsqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null); pCtx->pFunc = pOp->p4.pFunc; pCtx->iOp = (int)(pOp - aOp); pCtx->pVdbe = p; + pCtx->skipFlag = 0; + pCtx->isError = 0; pCtx->argc = n; pOp->p4type = P4_FUNCCTX; pOp->p4.pCtx = pCtx; - pOp->opcode = OP_AggStep; + + /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */ + assert( pOp->p1==(pOp->opcode==OP_AggInverse) ); + + pOp->opcode = OP_AggStep1; /* Fall through into OP_AggStep */ } -case OP_AggStep: { +case OP_AggStep1: { int i; - sqlite3_context *pCtx; + tdsqlite3_context *pCtx; Mem *pMem; - Mem t; assert( pOp->p4type==P4_FUNCCTX ); pCtx = pOp->p4.pCtx; pMem = &aMem[pOp->p3]; +#ifdef SQLITE_DEBUG + if( pOp->p1 ){ + /* This is an OP_AggInverse call. Verify that xStep has always + ** been called at least once prior to any xInverse call. */ + assert( pMem->uTemp==0x1122e0e3 ); + }else{ + /* This is an OP_AggStep call. Mark it as such. */ + pMem->uTemp = 0x1122e0e3; + } +#endif + /* If this function is inside of a trigger, the register array in aMem[] ** might change from one evaluation to the next. The next block of code ** checks to see if the register array has changed, and if so it - ** reinitializes the relavant parts of the sqlite3_context object */ + ** reinitializes the relavant parts of the tdsqlite3_context object */ if( pCtx->pMem != pMem ){ pCtx->pMem = pMem; for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; @@ -86493,55 +95249,88 @@ case OP_AggStep: { #endif pMem->n++; - sqlite3VdbeMemInit(&t, db, MEM_Null); - pCtx->pOut = &t; - pCtx->fErrorOrAux = 0; - pCtx->skipFlag = 0; + assert( pCtx->pOut->flags==MEM_Null ); + assert( pCtx->isError==0 ); + assert( pCtx->skipFlag==0 ); +#ifndef SQLITE_OMIT_WINDOWFUNC + if( pOp->p1 ){ + (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv); + }else +#endif (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */ - if( pCtx->fErrorOrAux ){ - if( pCtx->isError ){ - sqlite3VdbeError(p, "%s", sqlite3_value_text(&t)); + + if( pCtx->isError ){ + if( pCtx->isError>0 ){ + tdsqlite3VdbeError(p, "%s", tdsqlite3_value_text(pCtx->pOut)); rc = pCtx->isError; } - sqlite3VdbeMemRelease(&t); + if( pCtx->skipFlag ){ + assert( pOp[-1].opcode==OP_CollSeq ); + i = pOp[-1].p1; + if( i ) tdsqlite3VdbeMemSetInt64(&aMem[i], 1); + pCtx->skipFlag = 0; + } + tdsqlite3VdbeMemRelease(pCtx->pOut); + pCtx->pOut->flags = MEM_Null; + pCtx->isError = 0; if( rc ) goto abort_due_to_error; - }else{ - assert( t.flags==MEM_Null ); - } - if( pCtx->skipFlag ){ - assert( pOp[-1].opcode==OP_CollSeq ); - i = pOp[-1].p1; - if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1); } + assert( pCtx->pOut->flags==MEM_Null ); + assert( pCtx->skipFlag==0 ); break; } /* Opcode: AggFinal P1 P2 * P4 * ** Synopsis: accum=r[P1] N=P2 ** -** Execute the finalizer function for an aggregate. P1 is -** the memory location that is the accumulator for the aggregate. +** P1 is the memory location that is the accumulator for an aggregate +** or window function. Execute the finalizer function +** for an aggregate and store the result in P1. ** ** P2 is the number of arguments that the step function takes and ** P4 is a pointer to the FuncDef for this function. The P2 ** argument is not used by this opcode. It is only there to disambiguate ** functions that can take varying numbers of arguments. The -** P4 argument is only needed for the degenerate case where +** P4 argument is only needed for the case where ** the step function was not previously called. */ +/* Opcode: AggValue * P2 P3 P4 * +** Synopsis: r[P3]=value N=P2 +** +** Invoke the xValue() function and store the result in register P3. +** +** P2 is the number of arguments that the step function takes and +** P4 is a pointer to the FuncDef for this function. The P2 +** argument is not used by this opcode. It is only there to disambiguate +** functions that can take varying numbers of arguments. The +** P4 argument is only needed for the case where +** the step function was not previously called. +*/ +case OP_AggValue: case OP_AggFinal: { Mem *pMem; assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); + assert( pOp->p3==0 || pOp->opcode==OP_AggValue ); pMem = &aMem[pOp->p1]; assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); - rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); +#ifndef SQLITE_OMIT_WINDOWFUNC + if( pOp->p3 ){ + memAboutToChange(p, &aMem[pOp->p3]); + rc = tdsqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc); + pMem = &aMem[pOp->p3]; + }else +#endif + { + rc = tdsqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); + } + if( rc ){ - sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem)); + tdsqlite3VdbeError(p, "%s", tdsqlite3_value_text(pMem)); goto abort_due_to_error; } - sqlite3VdbeChangeEncoding(pMem, encoding); + tdsqlite3VdbeChangeEncoding(pMem, encoding); UPDATE_MAX_BLOBSIZE(pMem); - if( sqlite3VdbeMemTooBig(pMem) ){ + if( tdsqlite3VdbeMemTooBig(pMem) ){ goto too_big; } break; @@ -86572,14 +95361,14 @@ case OP_Checkpoint: { || pOp->p2==SQLITE_CHECKPOINT_RESTART || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE ); - rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); + rc = tdsqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); if( rc ){ if( rc!=SQLITE_BUSY ) goto abort_due_to_error; rc = SQLITE_OK; aRes[0] = 1; } for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){ - sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]); + tdsqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]); } break; }; @@ -86620,20 +95409,20 @@ case OP_JournalMode: { /* out2 */ assert( p->readOnly==0 ); pBt = db->aDb[pOp->p1].pBt; - pPager = sqlite3BtreePager(pBt); - eOld = sqlite3PagerGetJournalMode(pPager); + pPager = tdsqlite3BtreePager(pBt); + eOld = tdsqlite3PagerGetJournalMode(pPager); if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld; - if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld; + if( !tdsqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld; #ifndef SQLITE_OMIT_WAL - zFilename = sqlite3PagerFilename(pPager, 1); + zFilename = tdsqlite3PagerFilename(pPager, 1); /* Do not allow a transition to journal_mode=WAL for a database ** in temporary storage or if the VFS does not support shared memory */ if( eNew==PAGER_JOURNALMODE_WAL - && (sqlite3Strlen30(zFilename)==0 /* Temp file */ - || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */ + && (tdsqlite3Strlen30(zFilename)==0 /* Temp file */ + || !tdsqlite3PagerWalSupported(pPager)) /* No shared-memory support */ ){ eNew = eOld; } @@ -86643,7 +95432,7 @@ case OP_JournalMode: { /* out2 */ ){ if( !db->autoCommit || db->nVdbeRead>1 ){ rc = SQLITE_ERROR; - sqlite3VdbeError(p, + tdsqlite3VdbeError(p, "cannot change %s wal mode from within a transaction", (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of") ); @@ -86656,49 +95445,54 @@ case OP_JournalMode: { /* out2 */ ** file. An EXCLUSIVE lock may still be held on the database file ** after a successful return. */ - rc = sqlite3PagerCloseWal(pPager); + rc = tdsqlite3PagerCloseWal(pPager, db); if( rc==SQLITE_OK ){ - sqlite3PagerSetJournalMode(pPager, eNew); + tdsqlite3PagerSetJournalMode(pPager, eNew); } }else if( eOld==PAGER_JOURNALMODE_MEMORY ){ /* Cannot transition directly from MEMORY to WAL. Use mode OFF ** as an intermediate */ - sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF); + tdsqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF); } /* Open a transaction on the database file. Regardless of the journal ** mode, this transaction always uses a rollback journal. */ - assert( sqlite3BtreeIsInTrans(pBt)==0 ); + assert( tdsqlite3BtreeIsInTrans(pBt)==0 ); if( rc==SQLITE_OK ){ - rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1)); + rc = tdsqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1)); } } } #endif /* ifndef SQLITE_OMIT_WAL */ if( rc ) eNew = eOld; - eNew = sqlite3PagerSetJournalMode(pPager, eNew); + eNew = tdsqlite3PagerSetJournalMode(pPager, eNew); pOut->flags = MEM_Str|MEM_Static|MEM_Term; - pOut->z = (char *)sqlite3JournalModename(eNew); - pOut->n = sqlite3Strlen30(pOut->z); + pOut->z = (char *)tdsqlite3JournalModename(eNew); + pOut->n = tdsqlite3Strlen30(pOut->z); pOut->enc = SQLITE_UTF8; - sqlite3VdbeChangeEncoding(pOut, encoding); + tdsqlite3VdbeChangeEncoding(pOut, encoding); if( rc ) goto abort_due_to_error; break; }; #endif /* SQLITE_OMIT_PRAGMA */ #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) -/* Opcode: Vacuum P1 * * * * +/* Opcode: Vacuum P1 P2 * * * ** ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more ** for an attached database. The "temp" database may not be vacuumed. +** +** If P2 is not zero, then it is a register holding a string which is +** the file into which the result of vacuum should be written. When +** P2 is zero, the vacuum overwrites the original database. */ case OP_Vacuum: { assert( p->readOnly==0 ); - rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1); + rc = tdsqlite3RunVacuum(&p->zErrMsg, db, pOp->p1, + pOp->p2 ? &aMem[pOp->p2] : 0); if( rc ) goto abort_due_to_error; break; } @@ -86718,7 +95512,7 @@ case OP_IncrVacuum: { /* jump */ assert( DbMaskTest(p->btreeMask, pOp->p1) ); assert( p->readOnly==0 ); pBt = db->aDb[pOp->p1].pBt; - rc = sqlite3BtreeIncrVacuum(pBt); + rc = tdsqlite3BtreeIncrVacuum(pBt); VdbeBranchTaken(rc==SQLITE_DONE,2); if( rc ){ if( rc!=SQLITE_DONE ) goto abort_due_to_error; @@ -86729,25 +95523,62 @@ case OP_IncrVacuum: { /* jump */ } #endif -/* Opcode: Expire P1 * * * * +/* Opcode: Expire P1 P2 * * * ** ** Cause precompiled statements to expire. When an expired statement -** is executed using sqlite3_step() it will either automatically -** reprepare itself (if it was originally created using sqlite3_prepare_v2()) +** is executed using tdsqlite3_step() it will either automatically +** reprepare itself (if it was originally created using tdsqlite3_prepare_v2()) ** or it will fail with SQLITE_SCHEMA. ** ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, ** then only the currently executing statement is expired. +** +** If P2 is 0, then SQL statements are expired immediately. If P2 is 1, +** then running SQL statements are allowed to continue to run to completion. +** The P2==1 case occurs when a CREATE INDEX or similar schema change happens +** that might help the statement run faster but which does not affect the +** correctness of operation. */ case OP_Expire: { + assert( pOp->p2==0 || pOp->p2==1 ); if( !pOp->p1 ){ - sqlite3ExpirePreparedStatements(db); + tdsqlite3ExpirePreparedStatements(db, pOp->p2); }else{ - p->expired = 1; + p->expired = pOp->p2+1; } break; } +/* Opcode: CursorLock P1 * * * * +** +** Lock the btree to which cursor P1 is pointing so that the btree cannot be +** written by an other cursor. +*/ +case OP_CursorLock: { + VdbeCursor *pC; + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->eCurType==CURTYPE_BTREE ); + tdsqlite3BtreeCursorPin(pC->uc.pCursor); + break; +} + +/* Opcode: CursorUnlock P1 * * * * +** +** Unlock the btree to which cursor P1 is pointing so that it can be +** written by other cursors. +*/ +case OP_CursorUnlock: { + VdbeCursor *pC; + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->eCurType==CURTYPE_BTREE ); + tdsqlite3BtreeCursorUnpin(pC->uc.pCursor); + break; +} + #ifndef SQLITE_OMIT_SHARED_CACHE /* Opcode: TableLock P1 P2 P3 P4 * ** Synopsis: iDb=P1 root=P2 write=P3 @@ -86766,16 +95597,16 @@ case OP_Expire: { */ case OP_TableLock: { u8 isWriteLock = (u8)pOp->p3; - if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){ + if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){ int p1 = pOp->p1; assert( p1>=0 && p1<db->nDb ); assert( DbMaskTest(p->btreeMask, p1) ); assert( isWriteLock==0 || isWriteLock==1 ); - rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock); + rc = tdsqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock); if( rc ){ if( (rc&0xFF)==SQLITE_LOCKED ){ const char *z = pOp->p4.z; - sqlite3VdbeError(p, "database table is locked: %s", z); + tdsqlite3VdbeError(p, "database table is locked: %s", z); } goto abort_due_to_error; } @@ -86787,7 +95618,7 @@ case OP_TableLock: { #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VBegin * * * P4 * ** -** P4 may be a pointer to an sqlite3_vtab structure. If so, call the +** P4 may be a pointer to an tdsqlite3_vtab structure. If so, call the ** xBegin method for that table. ** ** Also, whether or not P4 is set, check that this is not being called from @@ -86797,8 +95628,8 @@ case OP_TableLock: { case OP_VBegin: { VTable *pVTab; pVTab = pOp->p4.pVtab; - rc = sqlite3VtabBegin(db, pVTab); - if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab); + rc = tdsqlite3VtabBegin(db, pVTab); + if( pVTab ) tdsqlite3VtabImportErrmsg(p, pVTab->pVtab); if( rc ) goto abort_due_to_error; break; } @@ -86817,17 +95648,17 @@ case OP_VCreate: { memset(&sMem, 0, sizeof(sMem)); sMem.db = db; /* Because P2 is always a static string, it is impossible for the - ** sqlite3VdbeMemCopy() to fail */ + ** tdsqlite3VdbeMemCopy() to fail */ assert( (aMem[pOp->p2].flags & MEM_Str)!=0 ); assert( (aMem[pOp->p2].flags & MEM_Static)!=0 ); - rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]); + rc = tdsqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]); assert( rc==SQLITE_OK ); - zTab = (const char*)sqlite3_value_text(&sMem); + zTab = (const char*)tdsqlite3_value_text(&sMem); assert( zTab || db->mallocFailed ); if( zTab ){ - rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg); + rc = tdsqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg); } - sqlite3VdbeMemRelease(&sMem); + tdsqlite3VdbeMemRelease(&sMem); if( rc ) goto abort_due_to_error; break; } @@ -86841,8 +95672,9 @@ case OP_VCreate: { */ case OP_VDestroy: { db->nVDestroy++; - rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); + rc = tdsqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); db->nVDestroy--; + assert( p->errorAction==OE_Abort && p->usesStmtJournal ); if( rc ) goto abort_due_to_error; break; } @@ -86851,15 +95683,15 @@ case OP_VDestroy: { #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VOpen P1 * * P4 * ** -** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. +** P4 is a pointer to a virtual table object, an tdsqlite3_vtab structure. ** P1 is a cursor number. This opcode opens a cursor to the virtual ** table and stores that cursor in P1. */ case OP_VOpen: { VdbeCursor *pCur; - sqlite3_vtab_cursor *pVCur; - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; + tdsqlite3_vtab_cursor *pVCur; + tdsqlite3_vtab *pVtab; + const tdsqlite3_module *pModule; assert( p->bIsReader ); pCur = 0; @@ -86871,10 +95703,10 @@ case OP_VOpen: { } pModule = pVtab->pModule; rc = pModule->xOpen(pVtab, &pVCur); - sqlite3VtabImportErrmsg(p, pVtab); + tdsqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; - /* Initialize sqlite3_vtab_cursor base class */ + /* Initialize tdsqlite3_vtab_cursor base class */ pVCur->pVtab = pVtab; /* Initialize vdbe cursor object */ @@ -86914,11 +95746,11 @@ case OP_VOpen: { case OP_VFilter: { /* jump */ int nArg; int iQuery; - const sqlite3_module *pModule; + const tdsqlite3_module *pModule; Mem *pQuery; Mem *pArgc; - sqlite3_vtab_cursor *pVCur; - sqlite3_vtab *pVtab; + tdsqlite3_vtab_cursor *pVCur; + tdsqlite3_vtab *pVtab; VdbeCursor *pCur; int res; int i; @@ -86946,7 +95778,7 @@ case OP_VFilter: { /* jump */ apArg[i] = &pArgc[i+1]; } rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg); - sqlite3VtabImportErrmsg(p, pVtab); + tdsqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; res = pModule->xEof(pVCur); pCur->nullRow = 0; @@ -86957,18 +95789,25 @@ case OP_VFilter: { /* jump */ #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VColumn P1 P2 P3 * * +/* Opcode: VColumn P1 P2 P3 * P5 ** Synopsis: r[P3]=vcolumn(P2) ** -** Store the value of the P2-th column of -** the row of the virtual-table that the -** P1 cursor is pointing to into register P3. +** Store in register P3 the value of the P2-th column of +** the current row of the virtual-table of cursor P1. +** +** If the VColumn opcode is being used to fetch the value of +** an unchanging column during an UPDATE operation, then the P5 +** value is OPFLAG_NOCHNG. This will cause the tdsqlite3_vtab_nochange() +** function to return true inside the xColumn method of the virtual +** table implementation. The P5 column might also contain other +** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are +** unused by OP_VColumn. */ case OP_VColumn: { - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; + tdsqlite3_vtab *pVtab; + const tdsqlite3_module *pModule; Mem *pDest; - sqlite3_context sContext; + tdsqlite3_context sContext; VdbeCursor *pCur = p->apCsr[pOp->p1]; assert( pCur->eCurType==CURTYPE_VTAB ); @@ -86976,7 +95815,7 @@ case OP_VColumn: { pDest = &aMem[pOp->p3]; memAboutToChange(p, pDest); if( pCur->nullRow ){ - sqlite3VdbeMemSetNull(pDest); + tdsqlite3VdbeMemSetNull(pDest); break; } pVtab = pCur->uc.pVCur->pVtab; @@ -86984,17 +95823,25 @@ case OP_VColumn: { assert( pModule->xColumn ); memset(&sContext, 0, sizeof(sContext)); sContext.pOut = pDest; - MemSetTypeFlag(pDest, MEM_Null); + assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 ); + if( pOp->p5 & OPFLAG_NOCHNG ){ + tdsqlite3VdbeMemSetNull(pDest); + pDest->flags = MEM_Null|MEM_Zero; + pDest->u.nZero = 0; + }else{ + MemSetTypeFlag(pDest, MEM_Null); + } rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2); - sqlite3VtabImportErrmsg(p, pVtab); - if( sContext.isError ){ + tdsqlite3VtabImportErrmsg(p, pVtab); + if( sContext.isError>0 ){ + tdsqlite3VdbeError(p, "%s", tdsqlite3_value_text(pDest)); rc = sContext.isError; } - sqlite3VdbeChangeEncoding(pDest, encoding); + tdsqlite3VdbeChangeEncoding(pDest, encoding); REGISTER_TRACE(pOp->p3, pDest); UPDATE_MAX_BLOBSIZE(pDest); - if( sqlite3VdbeMemTooBig(pDest) ){ + if( tdsqlite3VdbeMemTooBig(pDest) ){ goto too_big; } if( rc ) goto abort_due_to_error; @@ -87010,8 +95857,8 @@ case OP_VColumn: { ** the end of its result set, then fall through to the next instruction. */ case OP_VNext: { /* jump */ - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; + tdsqlite3_vtab *pVtab; + const tdsqlite3_module *pModule; int res; VdbeCursor *pCur; @@ -87032,7 +95879,7 @@ case OP_VNext: { /* jump */ ** some other method is next invoked on the save virtual table cursor. */ rc = pModule->xNext(pCur->uc.pVCur); - sqlite3VtabImportErrmsg(p, pVtab); + tdsqlite3VtabImportErrmsg(p, pVtab); if( rc ) goto abort_due_to_error; res = pModule->xEof(pCur->uc.pVCur); VdbeBranchTaken(!res,2); @@ -87047,14 +95894,17 @@ case OP_VNext: { /* jump */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Opcode: VRename P1 * * P4 * ** -** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. +** P4 is a pointer to a virtual table object, an tdsqlite3_vtab structure. ** This opcode invokes the corresponding xRename method. The value ** in register P1 is passed as the zName argument to the xRename method. */ case OP_VRename: { - sqlite3_vtab *pVtab; + tdsqlite3_vtab *pVtab; Mem *pName; - + int isLegacy; + + isLegacy = (db->flags & SQLITE_LegacyAlter); + db->flags |= SQLITE_LegacyAlter; pVtab = pOp->p4.pVtab->pVtab; pName = &aMem[pOp->p1]; assert( pVtab->pModule->xRename ); @@ -87065,10 +95915,11 @@ case OP_VRename: { testcase( pName->enc==SQLITE_UTF8 ); testcase( pName->enc==SQLITE_UTF16BE ); testcase( pName->enc==SQLITE_UTF16LE ); - rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8); + rc = tdsqlite3VdbeChangeEncoding(pName, SQLITE_UTF8); if( rc ) goto abort_due_to_error; rc = pVtab->pModule->xRename(pVtab, pName->z); - sqlite3VtabImportErrmsg(p, pVtab); + if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter; + tdsqlite3VtabImportErrmsg(p, pVtab); p->expired = 0; if( rc ) goto abort_due_to_error; break; @@ -87079,7 +95930,7 @@ case OP_VRename: { /* Opcode: VUpdate P1 P2 P3 P4 P5 ** Synopsis: data=r[P3@P2] ** -** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. +** P4 is a pointer to a virtual table object, an tdsqlite3_vtab structure. ** This opcode invokes the corresponding xUpdate method. P2 values ** are contiguous memory cells starting at P3 to pass to the xUpdate ** invocation. The value in register (P3+P2-1) corresponds to the @@ -87097,15 +95948,15 @@ case OP_VRename: { ** a row to delete. ** ** P1 is a boolean flag. If it is set to true and the xUpdate call -** is successful, then the value returned by sqlite3_last_insert_rowid() +** is successful, then the value returned by tdsqlite3_last_insert_rowid() ** is set to the value of the rowid for the row just inserted. ** ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to ** apply in the case of a constraint failure on an insert or update. */ case OP_VUpdate: { - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; + tdsqlite3_vtab *pVtab; + const tdsqlite3_module *pModule; int nArg; int i; sqlite_int64 rowid; @@ -87116,6 +95967,8 @@ case OP_VUpdate: { || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace ); assert( p->readOnly==0 ); + if( db->mallocFailed ) goto no_mem; + tdsqlite3VdbeIncrWriteCounter(p, 0); pVtab = pOp->p4.pVtab->pVtab; if( pVtab==0 || NEVER(pVtab->pModule==0) ){ rc = SQLITE_LOCKED; @@ -87137,10 +95990,10 @@ case OP_VUpdate: { db->vtabOnConflict = pOp->p5; rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid); db->vtabOnConflict = vtabOnConflict; - sqlite3VtabImportErrmsg(p, pVtab); + tdsqlite3VtabImportErrmsg(p, pVtab); if( rc==SQLITE_OK && pOp->p1 ){ assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) ); - db->lastRowid = lastRowid = rowid; + db->lastRowid = rowid; } if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){ if( pOp->p5==OE_Ignore ){ @@ -87164,7 +96017,7 @@ case OP_VUpdate: { */ case OP_Pagecount: { /* out2 */ pOut = out2Prerelease(p, pOp); - pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt); + pOut->u.i = tdsqlite3BtreeLastPage(db->aDb[pOp->p1].pBt); break; } #endif @@ -87187,45 +96040,158 @@ case OP_MaxPgcnt: { /* out2 */ pBt = db->aDb[pOp->p1].pBt; newMax = 0; if( pOp->p3 ){ - newMax = sqlite3BtreeLastPage(pBt); + newMax = tdsqlite3BtreeLastPage(pBt); if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3; } - pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax); + pOut->u.i = tdsqlite3BtreeMaxPageCount(pBt, newMax); break; } #endif +/* Opcode: Function P1 P2 P3 P4 * +** Synopsis: r[P3]=func(r[P2@P5]) +** +** Invoke a user function (P4 is a pointer to an tdsqlite3_context object that +** contains a pointer to the function to be run) with arguments taken +** from register P2 and successors. The number of arguments is in +** the tdsqlite3_context object that P4 points to. +** The result of the function is stored +** in register P3. Register P3 must not be one of the function inputs. +** +** P1 is a 32-bit bitmask indicating whether or not each argument to the +** function was determined to be constant at compile time. If the first +** argument was constant then bit 0 of P1 is set. This is used to determine +** whether meta data associated with a user function argument using the +** tdsqlite3_set_auxdata() API may be safely retained until the next +** invocation of this opcode. +** +** See also: AggStep, AggFinal, PureFunc +*/ +/* Opcode: PureFunc P1 P2 P3 P4 * +** Synopsis: r[P3]=func(r[P2@P5]) +** +** Invoke a user function (P4 is a pointer to an tdsqlite3_context object that +** contains a pointer to the function to be run) with arguments taken +** from register P2 and successors. The number of arguments is in +** the tdsqlite3_context object that P4 points to. +** The result of the function is stored +** in register P3. Register P3 must not be one of the function inputs. +** +** P1 is a 32-bit bitmask indicating whether or not each argument to the +** function was determined to be constant at compile time. If the first +** argument was constant then bit 0 of P1 is set. This is used to determine +** whether meta data associated with a user function argument using the +** tdsqlite3_set_auxdata() API may be safely retained until the next +** invocation of this opcode. +** +** This opcode works exactly like OP_Function. The only difference is in +** its name. This opcode is used in places where the function must be +** purely non-deterministic. Some built-in date/time functions can be +** either determinitic of non-deterministic, depending on their arguments. +** When those function are used in a non-deterministic way, they will check +** to see if they were called using OP_PureFunc instead of OP_Function, and +** if they were, they throw an error. +** +** See also: AggStep, AggFinal, Function +*/ +case OP_PureFunc: /* group */ +case OP_Function: { /* group */ + int i; + tdsqlite3_context *pCtx; + + assert( pOp->p4type==P4_FUNCCTX ); + pCtx = pOp->p4.pCtx; + + /* If this function is inside of a trigger, the register array in aMem[] + ** might change from one evaluation to the next. The next block of code + ** checks to see if the register array has changed, and if so it + ** reinitializes the relavant parts of the tdsqlite3_context object */ + pOut = &aMem[pOp->p3]; + if( pCtx->pOut != pOut ){ + pCtx->pVdbe = p; + pCtx->pOut = pOut; + for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; + } + assert( pCtx->pVdbe==p ); + + memAboutToChange(p, pOut); +#ifdef SQLITE_DEBUG + for(i=0; i<pCtx->argc; i++){ + assert( memIsValid(pCtx->argv[i]) ); + REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); + } +#endif + MemSetTypeFlag(pOut, MEM_Null); + assert( pCtx->isError==0 ); + (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */ + + /* If the function returned an error, throw an exception */ + if( pCtx->isError ){ + if( pCtx->isError>0 ){ + tdsqlite3VdbeError(p, "%s", tdsqlite3_value_text(pOut)); + rc = pCtx->isError; + } + tdsqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1); + pCtx->isError = 0; + if( rc ) goto abort_due_to_error; + } -/* Opcode: Init P1 P2 * P4 * + /* Copy the result of the function into register P3 */ + if( pOut->flags & (MEM_Str|MEM_Blob) ){ + tdsqlite3VdbeChangeEncoding(pOut, encoding); + if( tdsqlite3VdbeMemTooBig(pOut) ) goto too_big; + } + + REGISTER_TRACE(pOp->p3, pOut); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Trace P1 P2 * P4 * +** +** Write P4 on the statement trace output if statement tracing is +** enabled. +** +** Operand P1 must be 0x7fffffff and P2 must positive. +*/ +/* Opcode: Init P1 P2 P3 P4 * ** Synopsis: Start at P2 ** ** Programs contain a single instance of this opcode as the very first ** opcode. ** -** If tracing is enabled (by the sqlite3_trace()) interface, then +** If tracing is enabled (by the tdsqlite3_trace()) interface, then ** the UTF-8 string contained in P4 is emitted on the trace callback. -** Or if P4 is blank, use the string returned by sqlite3_sql(). +** Or if P4 is blank, use the string returned by tdsqlite3_sql(). ** ** If P2 is not zero, jump to instruction P2. ** ** Increment the value of P1 so that OP_Once opcodes will jump the ** first time they are evaluated for this run. +** +** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT +** error is encountered. */ +case OP_Trace: case OP_Init: { /* jump */ - char *zTrace; int i; +#ifndef SQLITE_OMIT_TRACE + char *zTrace; +#endif /* If the P4 argument is not NULL, then it must be an SQL comment string. ** The "--" string is broken up to prevent false-positives with srcck1.c. ** ** This assert() provides evidence for: ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that - ** would have been returned by the legacy sqlite3_trace() interface by + ** would have been returned by the legacy tdsqlite3_trace() interface by ** using the X argument when X begins with "--" and invoking - ** sqlite3_expanded_sql(P) otherwise. + ** tdsqlite3_expanded_sql(P) otherwise. */ assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 ); - assert( pOp==p->aOp ); /* Always instruction 0 */ + + /* OP_Init is always instruction 0 */ + assert( pOp==p->aOp || pOp->opcode==OP_Trace ); #ifndef SQLITE_OMIT_TRACE if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0 @@ -87235,12 +96201,16 @@ case OP_Init: { /* jump */ #ifndef SQLITE_OMIT_DEPRECATED if( db->mTrace & SQLITE_TRACE_LEGACY ){ void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace; - char *z = sqlite3VdbeExpandSql(p, zTrace); + char *z = tdsqlite3VdbeExpandSql(p, zTrace); x(db->pTraceArg, z); - sqlite3_free(z); + tdsqlite3_free(z); }else #endif - { + if( db->nVdbeExec>1 ){ + char *z = tdsqlite3MPrintf(db, "-- %s", zTrace); + (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z); + tdsqlite3DbFree(db, z); + }else{ (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace); } } @@ -87250,7 +96220,7 @@ case OP_Init: { /* jump */ int j; for(j=0; j<db->nDb; j++){ if( DbMaskTest(p->btreeMask, j)==0 ) continue; - sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace); + tdsqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace); } } #endif /* SQLITE_USE_FCNTL_TRACE */ @@ -87258,18 +96228,20 @@ case OP_Init: { /* jump */ if( (db->flags & SQLITE_SqlTrace)!=0 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){ - sqlite3DebugPrintf("SQL-trace: %s\n", zTrace); + tdsqlite3DebugPrintf("SQL-trace: %s\n", zTrace); } #endif /* SQLITE_DEBUG */ #endif /* SQLITE_OMIT_TRACE */ assert( pOp->p2>0 ); - if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){ + if( pOp->p1>=tdsqlite3GlobalConfig.iOnceResetThreshold ){ + if( pOp->opcode==OP_Trace ) break; for(i=1; i<p->nOp; i++){ if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0; } pOp->p1 = 0; } pOp->p1++; + p->aCounter[SQLITE_STMTSTATUS_RUN]++; goto jump_to_p2; } @@ -87289,13 +96261,78 @@ case OP_CursorHint: { pC = p->apCsr[pOp->p1]; if( pC ){ assert( pC->eCurType==CURTYPE_BTREE ); - sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE, + tdsqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE, pOp->p4.pExpr, aMem); } break; } #endif /* SQLITE_ENABLE_CURSOR_HINTS */ +#ifdef SQLITE_DEBUG +/* Opcode: Abortable * * * * * +** +** Verify that an Abort can happen. Assert if an Abort at this point +** might cause database corruption. This opcode only appears in debugging +** builds. +** +** An Abort is safe if either there have been no writes, or if there is +** an active statement journal. +*/ +case OP_Abortable: { + tdsqlite3VdbeAssertAbortable(p); + break; +} +#endif + +#ifdef SQLITE_DEBUG +/* Opcode: ReleaseReg P1 P2 P3 * P5 +** Synopsis: release r[P1@P2] mask P3 +** +** Release registers from service. Any content that was in the +** the registers is unreliable after this opcode completes. +** +** The registers released will be the P2 registers starting at P1, +** except if bit ii of P3 set, then do not release register P1+ii. +** In other words, P3 is a mask of registers to preserve. +** +** Releasing a register clears the Mem.pScopyFrom pointer. That means +** that if the content of the released register was set using OP_SCopy, +** a change to the value of the source register for the OP_SCopy will no longer +** generate an assertion fault in tdsqlite3VdbeMemAboutToChange(). +** +** If P5 is set, then all released registers have their type set +** to MEM_Undefined so that any subsequent attempt to read the released +** register (before it is reinitialized) will generate an assertion fault. +** +** P5 ought to be set on every call to this opcode. +** However, there are places in the code generator will release registers +** before their are used, under the (valid) assumption that the registers +** will not be reallocated for some other purpose before they are used and +** hence are safe to release. +** +** This opcode is only available in testing and debugging builds. It is +** not generated for release builds. The purpose of this opcode is to help +** validate the generated bytecode. This opcode does not actually contribute +** to computing an answer. +*/ +case OP_ReleaseReg: { + Mem *pMem; + int i; + u32 constMask; + assert( pOp->p1>0 ); + assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 ); + pMem = &aMem[pOp->p1]; + constMask = pOp->p3; + for(i=0; i<pOp->p2; i++, pMem++){ + if( i>=32 || (constMask & MASKBIT32(i))==0 ){ + pMem->pScopyFrom = 0; + if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined); + } + } + break; +} +#endif + /* Opcode: Noop * * * * * ** ** Do nothing. This instruction is often useful as a jump @@ -87307,8 +96344,9 @@ case OP_CursorHint: { ** This opcode records information from the optimizer. It is the ** the same as a no-op. This opcodesnever appears in a real VM program. */ -default: { /* This is really OP_Noop and OP_Explain */ +default: { /* This is really OP_Noop, OP_Explain */ assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain ); + break; } @@ -87322,7 +96360,7 @@ default: { /* This is really OP_Noop and OP_Explain */ #ifdef VDBE_PROFILE { - u64 endTime = sqlite3Hwtime(); + u64 endTime = tdsqlite3NProfileCnt ? tdsqlite3NProfileCnt : tdsqlite3Hwtime(); if( endTime>start ) pOrigOp->cycles += endTime - start; pOrigOp->cnt++; } @@ -87338,7 +96376,7 @@ default: { /* This is really OP_Noop and OP_Explain */ #ifdef SQLITE_DEBUG if( db->flags & SQLITE_VdbeTrace ){ - u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode]; + u8 opProperty = tdsqlite3OpcodeProperty[pOrigOp->opcode]; if( rc!=0 ) printf("rc=%d\n",rc); if( opProperty & (OPFLG_OUT2) ){ registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]); @@ -87346,6 +96384,12 @@ default: { /* This is really OP_Noop and OP_Explain */ if( opProperty & OPFLG_OUT3 ){ registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]); } + if( opProperty==0xff ){ + /* Never happens. This code exists to avoid a harmless linkage + ** warning aboud tdsqlite3VdbeRegisterDump() being defined but not + ** used. */ + tdsqlite3VdbeRegisterDump(p); + } } #endif /* SQLITE_DEBUG */ #endif /* NDEBUG */ @@ -87358,30 +96402,38 @@ abort_due_to_error: if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT; assert( rc ); if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){ - sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); + tdsqlite3VdbeError(p, "%s", tdsqlite3ErrStr(rc)); } p->rc = rc; - sqlite3SystemError(db, rc); - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(rc, "statement aborts at %d: [%s] %s", + tdsqlite3SystemError(db, rc); + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + tdsqlite3_log(rc, "statement aborts at %d: [%s] %s", (int)(pOp - aOp), p->zSql, p->zErrMsg); - sqlite3VdbeHalt(p); - if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db); + tdsqlite3VdbeHalt(p); + if( rc==SQLITE_IOERR_NOMEM ) tdsqlite3OomFault(db); rc = SQLITE_ERROR; if( resetSchemaOnFault>0 ){ - sqlite3ResetOneSchema(db, resetSchemaOnFault-1); + tdsqlite3ResetOneSchema(db, resetSchemaOnFault-1); } /* This is the only way out of this procedure. We have to ** release the mutexes on btrees that were acquired at the ** top. */ vdbe_return: - db->lastRowid = lastRowid; - testcase( nVmStep>0 ); +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + while( nVmStep>=nProgressLimit && db->xProgress!=0 ){ + nProgressLimit += db->nProgressOps; + if( db->xProgress(db->pProgressArg) ){ + nProgressLimit = 0xffffffff; + rc = SQLITE_INTERRUPT; + goto abort_due_to_error; + } + } +#endif p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep; - sqlite3VdbeLeave(p); + tdsqlite3VdbeLeave(p); assert( rc!=SQLITE_OK || nExtraDelete==0 - || sqlite3_strlike("DELETE%",p->zSql,0)!=0 + || tdsqlite3_strlike("DELETE%",p->zSql,0)!=0 ); return rc; @@ -87389,26 +96441,26 @@ vdbe_return: ** is encountered. */ too_big: - sqlite3VdbeError(p, "string or blob too big"); + tdsqlite3VdbeError(p, "string or blob too big"); rc = SQLITE_TOOBIG; goto abort_due_to_error; /* Jump to here if a malloc() fails. */ no_mem: - sqlite3OomFault(db); - sqlite3VdbeError(p, "out of memory"); + tdsqlite3OomFault(db); + tdsqlite3VdbeError(p, "out of memory"); rc = SQLITE_NOMEM_BKPT; goto abort_due_to_error; - /* Jump to here if the sqlite3_interrupt() API sets the interrupt + /* Jump to here if the tdsqlite3_interrupt() API sets the interrupt ** flag. */ abort_due_to_interrupt: assert( db->u1.isInterrupted ); rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; p->rc = rc; - sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); + tdsqlite3VdbeError(p, "%s", tdsqlite3ErrStr(rc)); goto abort_due_to_error; } @@ -87436,17 +96488,16 @@ abort_due_to_interrupt: #ifndef SQLITE_OMIT_INCRBLOB /* -** Valid sqlite3_blob* handles point to Incrblob structures. +** Valid tdsqlite3_blob* handles point to Incrblob structures. */ typedef struct Incrblob Incrblob; struct Incrblob { - int flags; /* Copy of "flags" passed to sqlite3_blob_open() */ int nByte; /* Size of open blob, in bytes */ int iOffset; /* Byte offset of blob in cursor data */ - int iCol; /* Table column this handle is open on */ + u16 iCol; /* Table column this handle is open on */ BtCursor *pCsr; /* Cursor pointing at blob row */ - sqlite3_stmt *pStmt; /* Statement holding cursor open */ - sqlite3 *db; /* The associated database */ + tdsqlite3_stmt *pStmt; /* Statement holding cursor open */ + tdsqlite3 *db; /* The associated database */ char *zDb; /* Database name */ Table *pTab; /* Table object */ }; @@ -87456,60 +96507,71 @@ struct Incrblob { ** This function is used by both blob_open() and blob_reopen(). It seeks ** the b-tree cursor associated with blob handle p to point to row iRow. ** If successful, SQLITE_OK is returned and subsequent calls to -** sqlite3_blob_read() or sqlite3_blob_write() access the specified row. +** tdsqlite3_blob_read() or tdsqlite3_blob_write() access the specified row. ** ** If an error occurs, or if the specified row does not exist or does not ** contain a value of type TEXT or BLOB in the column nominated when the ** blob handle was opened, then an error code is returned and *pzErr may ** be set to point to a buffer containing an error message. It is the ** responsibility of the caller to free the error message buffer using -** sqlite3DbFree(). +** tdsqlite3DbFree(). ** ** If an error does occur, then the b-tree cursor is closed. All subsequent -** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will +** calls to tdsqlite3_blob_read(), blob_write() or blob_reopen() will ** immediately return SQLITE_ABORT. */ -static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){ +static int blobSeekToRow(Incrblob *p, tdsqlite3_int64 iRow, char **pzErr){ int rc; /* Error code */ char *zErr = 0; /* Error message */ Vdbe *v = (Vdbe *)p->pStmt; - /* Set the value of the SQL statements only variable to integer iRow. - ** This is done directly instead of using sqlite3_bind_int64() to avoid - ** triggering asserts related to mutexes. + /* Set the value of register r[1] in the SQL statement to integer iRow. + ** This is done directly as a performance optimization */ - assert( v->aVar[0].flags&MEM_Int ); - v->aVar[0].u.i = iRow; + v->aMem[1].flags = MEM_Int; + v->aMem[1].u.i = iRow; - rc = sqlite3_step(p->pStmt); + /* If the statement has been run before (and is paused at the OP_ResultRow) + ** then back it up to the point where it does the OP_NotExists. This could + ** have been down with an extra OP_Goto, but simply setting the program + ** counter is faster. */ + if( v->pc>4 ){ + v->pc = 4; + assert( v->aOp[v->pc].opcode==OP_NotExists ); + rc = tdsqlite3VdbeExec(v); + }else{ + rc = tdsqlite3_step(p->pStmt); + } if( rc==SQLITE_ROW ){ VdbeCursor *pC = v->apCsr[0]; - u32 type = pC->aType[p->iCol]; + u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0; + testcase( pC->nHdrParsed==p->iCol ); + testcase( pC->nHdrParsed==p->iCol+1 ); if( type<12 ){ - zErr = sqlite3MPrintf(p->db, "cannot open value of type %s", + zErr = tdsqlite3MPrintf(p->db, "cannot open value of type %s", type==0?"null": type==7?"real": "integer" ); rc = SQLITE_ERROR; - sqlite3_finalize(p->pStmt); + tdsqlite3_finalize(p->pStmt); p->pStmt = 0; }else{ p->iOffset = pC->aType[p->iCol + pC->nField]; - p->nByte = sqlite3VdbeSerialTypeLen(type); + p->nByte = tdsqlite3VdbeSerialTypeLen(type); p->pCsr = pC->uc.pCursor; - sqlite3BtreeIncrblobCursor(p->pCsr); + tdsqlite3BtreeIncrblobCursor(p->pCsr); } } if( rc==SQLITE_ROW ){ rc = SQLITE_OK; }else if( p->pStmt ){ - rc = sqlite3_finalize(p->pStmt); + rc = tdsqlite3_finalize(p->pStmt); p->pStmt = 0; if( rc==SQLITE_OK ){ - zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow); + zErr = tdsqlite3MPrintf(p->db, "no such rowid: %lld", iRow); rc = SQLITE_ERROR; }else{ - zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db)); + zErr = tdsqlite3MPrintf(p->db, "%s", tdsqlite3_errmsg(p->db)); } } @@ -87523,22 +96585,22 @@ static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){ /* ** Open a blob handle. */ -SQLITE_API int sqlite3_blob_open( - sqlite3* db, /* The database connection */ +SQLITE_API int tdsqlite3_blob_open( + tdsqlite3* db, /* The database connection */ const char *zDb, /* The attached database containing the blob */ const char *zTable, /* The table containing the blob */ const char *zColumn, /* The column containing the blob */ sqlite_int64 iRow, /* The row containing the glob */ - int flags, /* True -> read/write access, false -> read-only */ - sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */ + int wrFlag, /* True -> read/write access, false -> read-only */ + tdsqlite3_blob **ppBlob /* Handle for accessing the blob returned here */ ){ int nAttempt = 0; int iCol; /* Index of zColumn in row-record */ int rc = SQLITE_OK; char *zErr = 0; Table *pTab; - Parse *pParse = 0; Incrblob *pBlob = 0; + Parse sParse; #ifdef SQLITE_ENABLE_API_ARMOR if( ppBlob==0 ){ @@ -87547,73 +96609,69 @@ SQLITE_API int sqlite3_blob_open( #endif *ppBlob = 0; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zTable==0 ){ + if( !tdsqlite3SafetyCheckOk(db) || zTable==0 ){ return SQLITE_MISUSE_BKPT; } #endif - flags = !!flags; /* flags = (flags ? 1 : 0); */ + wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */ - sqlite3_mutex_enter(db->mutex); - - pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob)); - if( !pBlob ) goto blob_open_out; - pParse = sqlite3StackAllocRaw(db, sizeof(*pParse)); - if( !pParse ) goto blob_open_out; + tdsqlite3_mutex_enter(db->mutex); + pBlob = (Incrblob *)tdsqlite3DbMallocZero(db, sizeof(Incrblob)); do { - memset(pParse, 0, sizeof(Parse)); - pParse->db = db; - sqlite3DbFree(db, zErr); + memset(&sParse, 0, sizeof(Parse)); + if( !pBlob ) goto blob_open_out; + sParse.db = db; + tdsqlite3DbFree(db, zErr); zErr = 0; - sqlite3BtreeEnterAll(db); - pTab = sqlite3LocateTable(pParse, 0, zTable, zDb); + tdsqlite3BtreeEnterAll(db); + pTab = tdsqlite3LocateTable(&sParse, 0, zTable, zDb); if( pTab && IsVirtual(pTab) ){ pTab = 0; - sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable); + tdsqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable); } if( pTab && !HasRowid(pTab) ){ pTab = 0; - sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable); + tdsqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable); } #ifndef SQLITE_OMIT_VIEW if( pTab && pTab->pSelect ){ pTab = 0; - sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable); + tdsqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable); } #endif if( !pTab ){ - if( pParse->zErrMsg ){ - sqlite3DbFree(db, zErr); - zErr = pParse->zErrMsg; - pParse->zErrMsg = 0; + if( sParse.zErrMsg ){ + tdsqlite3DbFree(db, zErr); + zErr = sParse.zErrMsg; + sParse.zErrMsg = 0; } rc = SQLITE_ERROR; - sqlite3BtreeLeaveAll(db); + tdsqlite3BtreeLeaveAll(db); goto blob_open_out; } pBlob->pTab = pTab; - pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName; + pBlob->zDb = db->aDb[tdsqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName; /* Now search pTab for the exact column. */ for(iCol=0; iCol<pTab->nCol; iCol++) { - if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){ + if( tdsqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){ break; } } if( iCol==pTab->nCol ){ - sqlite3DbFree(db, zErr); - zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn); + tdsqlite3DbFree(db, zErr); + zErr = tdsqlite3MPrintf(db, "no such column: \"%s\"", zColumn); rc = SQLITE_ERROR; - sqlite3BtreeLeaveAll(db); + tdsqlite3BtreeLeaveAll(db); goto blob_open_out; } /* If the value is being opened for writing, check that the ** column is not indexed, and that it is not part of a foreign key. - ** It is against the rules to open a column to which either of these - ** descriptions applies for writing. */ - if( flags ){ + */ + if( wrFlag ){ const char *zFault = 0; Index *pIdx; #ifndef SQLITE_OMIT_FOREIGN_KEY @@ -87643,15 +96701,15 @@ SQLITE_API int sqlite3_blob_open( } } if( zFault ){ - sqlite3DbFree(db, zErr); - zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault); + tdsqlite3DbFree(db, zErr); + zErr = tdsqlite3MPrintf(db, "cannot open %s column for writing", zFault); rc = SQLITE_ERROR; - sqlite3BtreeLeaveAll(db); + tdsqlite3BtreeLeaveAll(db); goto blob_open_out; } } - pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse); + pBlob->pStmt = (tdsqlite3_stmt *)tdsqlite3VdbeCreate(&sParse); assert( pBlob->pStmt || db->mallocFailed ); if( pBlob->pStmt ){ @@ -87666,7 +96724,7 @@ SQLITE_API int sqlite3_blob_open( ** uses it to implement the blob_read(), blob_write() and ** blob_bytes() functions. ** - ** The sqlite3_blob_close() function finalizes the vdbe program, + ** The tdsqlite3_blob_close() function finalizes the vdbe program, ** which closes the b-tree cursor and (possibly) commits the ** transaction. */ @@ -87674,26 +96732,25 @@ SQLITE_API int sqlite3_blob_open( static const VdbeOpList openBlob[] = { {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */ {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */ - {OP_Variable, 1, 1, 0}, /* 2: Move ?1 into reg[1] */ - {OP_NotExists, 0, 7, 1}, /* 3: Seek the cursor */ - {OP_Column, 0, 0, 1}, /* 4 */ - {OP_ResultRow, 1, 0, 0}, /* 5 */ - {OP_Goto, 0, 2, 0}, /* 6 */ - {OP_Close, 0, 0, 0}, /* 7 */ - {OP_Halt, 0, 0, 0}, /* 8 */ + /* blobSeekToRow() will initialize r[1] to the desired rowid */ + {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */ + {OP_Column, 0, 0, 1}, /* 3 */ + {OP_ResultRow, 1, 0, 0}, /* 4 */ + {OP_Halt, 0, 0, 0}, /* 5 */ }; Vdbe *v = (Vdbe *)pBlob->pStmt; - int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + int iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); VdbeOp *aOp; - sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags, + tdsqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag, pTab->pSchema->schema_cookie, pTab->pSchema->iGeneration); - sqlite3VdbeChangeP5(v, 1); - aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn); + tdsqlite3VdbeChangeP5(v, 1); + assert( tdsqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed ); + aOp = tdsqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn); /* Make sure a mutex is held on the table to be accessed */ - sqlite3VdbeUsesBtree(v, iDb); + tdsqlite3VdbeUsesBtree(v, iDb); if( db->mallocFailed==0 ){ assert( aOp!=0 ); @@ -87703,15 +96760,15 @@ SQLITE_API int sqlite3_blob_open( #else aOp[0].p1 = iDb; aOp[0].p2 = pTab->tnum; - aOp[0].p3 = flags; - sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT); + aOp[0].p3 = wrFlag; + tdsqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT); } if( db->mallocFailed==0 ){ #endif /* Remove either the OP_OpenWrite or OpenRead. Set the P2 ** parameter of the other to pTab->tnum. */ - if( flags ) aOp[1].opcode = OP_OpenWrite; + if( wrFlag ) aOp[1].opcode = OP_OpenWrite; aOp[1].p2 = pTab->tnum; aOp[1].p3 = iDb; @@ -87724,57 +96781,55 @@ SQLITE_API int sqlite3_blob_open( */ aOp[1].p4type = P4_INT32; aOp[1].p4.i = pTab->nCol+1; - aOp[4].p2 = pTab->nCol; + aOp[3].p2 = pTab->nCol; - pParse->nVar = 1; - pParse->nMem = 1; - pParse->nTab = 1; - sqlite3VdbeMakeReady(v, pParse); + sParse.nVar = 0; + sParse.nMem = 1; + sParse.nTab = 1; + tdsqlite3VdbeMakeReady(v, &sParse); } } - pBlob->flags = flags; pBlob->iCol = iCol; pBlob->db = db; - sqlite3BtreeLeaveAll(db); + tdsqlite3BtreeLeaveAll(db); if( db->mallocFailed ){ goto blob_open_out; } - sqlite3_bind_int64(pBlob->pStmt, 1, iRow); rc = blobSeekToRow(pBlob, iRow, &zErr); } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA ); blob_open_out: if( rc==SQLITE_OK && db->mallocFailed==0 ){ - *ppBlob = (sqlite3_blob *)pBlob; + *ppBlob = (tdsqlite3_blob *)pBlob; }else{ - if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt); - sqlite3DbFree(db, pBlob); + if( pBlob && pBlob->pStmt ) tdsqlite3VdbeFinalize((Vdbe *)pBlob->pStmt); + tdsqlite3DbFree(db, pBlob); } - sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); - sqlite3DbFree(db, zErr); - sqlite3ParserReset(pParse); - sqlite3StackFree(db, pParse); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + tdsqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); + tdsqlite3DbFree(db, zErr); + tdsqlite3ParserReset(&sParse); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } /* ** Close a blob handle that was previously created using -** sqlite3_blob_open(). +** tdsqlite3_blob_open(). */ -SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){ +SQLITE_API int tdsqlite3_blob_close(tdsqlite3_blob *pBlob){ Incrblob *p = (Incrblob *)pBlob; int rc; - sqlite3 *db; + tdsqlite3 *db; if( p ){ + tdsqlite3_stmt *pStmt = p->pStmt; db = p->db; - sqlite3_mutex_enter(db->mutex); - rc = sqlite3_finalize(p->pStmt); - sqlite3DbFree(db, p); - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_enter(db->mutex); + tdsqlite3DbFree(db, p); + tdsqlite3_mutex_leave(db->mutex); + rc = tdsqlite3_finalize(pStmt); }else{ rc = SQLITE_OK; } @@ -87785,7 +96840,7 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){ ** Perform a read or write operation on a blob */ static int blobReadWrite( - sqlite3_blob *pBlob, + tdsqlite3_blob *pBlob, void *z, int n, int iOffset, @@ -87794,14 +96849,14 @@ static int blobReadWrite( int rc; Incrblob *p = (Incrblob *)pBlob; Vdbe *v; - sqlite3 *db; + tdsqlite3 *db; if( p==0 ) return SQLITE_MISUSE_BKPT; db = p->db; - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); v = (Vdbe*)p->pStmt; - if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){ + if( n<0 || iOffset<0 || ((tdsqlite3_int64)iOffset+n)>p->nByte ){ /* Request is out of range. Return a transient error. */ rc = SQLITE_ERROR; }else if( v==0 ){ @@ -87814,10 +96869,10 @@ static int blobReadWrite( ** returned, clean-up the statement handle. */ assert( db == v->db ); - sqlite3BtreeEnterCursor(p->pCsr); + tdsqlite3BtreeEnterCursor(p->pCsr); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK - if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){ + if( xCall==tdsqlite3BtreePutData && db->xPreUpdateCallback ){ /* If a pre-update hook is registered and this is a write cursor, ** invoke it here. ** @@ -87831,41 +96886,41 @@ static int blobReadWrite( ** using the incremental-blob API, this works. For the sessions module ** anyhow. */ - sqlite3_int64 iKey; - iKey = sqlite3BtreeIntegerKey(p->pCsr); - sqlite3VdbePreUpdateHook( + tdsqlite3_int64 iKey; + iKey = tdsqlite3BtreeIntegerKey(p->pCsr); + tdsqlite3VdbePreUpdateHook( v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1 ); } #endif rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); - sqlite3BtreeLeaveCursor(p->pCsr); + tdsqlite3BtreeLeaveCursor(p->pCsr); if( rc==SQLITE_ABORT ){ - sqlite3VdbeFinalize(v); + tdsqlite3VdbeFinalize(v); p->pStmt = 0; }else{ v->rc = rc; } } - sqlite3Error(db, rc); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + tdsqlite3Error(db, rc); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } /* ** Read data from a blob handle. */ -SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){ - return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData); +SQLITE_API int tdsqlite3_blob_read(tdsqlite3_blob *pBlob, void *z, int n, int iOffset){ + return blobReadWrite(pBlob, z, n, iOffset, tdsqlite3BtreePayloadChecked); } /* ** Write data to a blob handle. */ -SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){ - return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData); +SQLITE_API int tdsqlite3_blob_write(tdsqlite3_blob *pBlob, const void *z, int n, int iOffset){ + return blobReadWrite(pBlob, (void *)z, n, iOffset, tdsqlite3BtreePutData); } /* @@ -87874,7 +96929,7 @@ SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob ** so no mutex is required for access. */ -SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){ +SQLITE_API int tdsqlite3_blob_bytes(tdsqlite3_blob *pBlob){ Incrblob *p = (Incrblob *)pBlob; return (p && p->pStmt) ? p->nByte : 0; } @@ -87886,17 +96941,17 @@ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){ ** If an error occurs, or if the specified row does not exist or does not ** contain a blob or text value, then an error code is returned and the ** database handle error code and message set. If this happens, then all -** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) +** subsequent calls to tdsqlite3_blob_xxx() functions (except blob_close()) ** immediately return SQLITE_ABORT. */ -SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){ +SQLITE_API int tdsqlite3_blob_reopen(tdsqlite3_blob *pBlob, tdsqlite3_int64 iRow){ int rc; Incrblob *p = (Incrblob *)pBlob; - sqlite3 *db; + tdsqlite3 *db; if( p==0 ) return SQLITE_MISUSE_BKPT; db = p->db; - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); if( p->pStmt==0 ){ /* If there is no statement handle, then the blob-handle has @@ -87907,15 +96962,15 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){ char *zErr; rc = blobSeekToRow(p, iRow, &zErr); if( rc!=SQLITE_OK ){ - sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); - sqlite3DbFree(db, zErr); + tdsqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); + tdsqlite3DbFree(db, zErr); } assert( rc!=SQLITE_SCHEMA ); } - rc = sqlite3ApiExit(db, rc); + rc = tdsqlite3ApiExit(db, rc); assert( rc==SQLITE_OK || p->pStmt==0 ); - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -87946,9 +97001,9 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){ ** Here is the (internal, non-API) interface between this module and the ** rest of the SQLite system: ** -** sqlite3VdbeSorterInit() Create a new VdbeSorter object. +** tdsqlite3VdbeSorterInit() Create a new VdbeSorter object. ** -** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter +** tdsqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter ** object. The row is a binary blob in the ** OP_MakeRecord format that contains both ** the ORDER BY key columns and result columns @@ -87956,27 +97011,27 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){ ** the complete record for an index entry ** in the case of a CREATE INDEX. ** -** sqlite3VdbeSorterRewind() Sort all content previously added. +** tdsqlite3VdbeSorterRewind() Sort all content previously added. ** Position the read cursor on the ** first sorted element. ** -** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted +** tdsqlite3VdbeSorterNext() Advance the read cursor to the next sorted ** element. ** -** sqlite3VdbeSorterRowkey() Return the complete binary blob for the +** tdsqlite3VdbeSorterRowkey() Return the complete binary blob for the ** row currently under the read cursor. ** -** sqlite3VdbeSorterCompare() Compare the binary blob for the row +** tdsqlite3VdbeSorterCompare() Compare the binary blob for the row ** currently under the read cursor against ** another binary blob X and report if ** X is strictly less than the read cursor. ** Used to enforce uniqueness in a ** CREATE UNIQUE INDEX statement. ** -** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim +** tdsqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim ** all resources. ** -** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This +** tdsqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This ** is like Close() followed by Init() only ** much faster. ** @@ -88096,7 +97151,7 @@ typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */ ** stored in the file. */ struct SorterFile { - sqlite3_file *pFd; /* File handle */ + tdsqlite3_file *pFd; /* File handle */ i64 iEof; /* Bytes of data stored in pFd */ }; @@ -88209,7 +97264,7 @@ struct MergeEngine { ** to block until it finishes). ** ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call -** to sqlite3ThreadJoin() is likely to block. Cases that are likely to +** to tdsqlite3ThreadJoin() is likely to block. Cases that are likely to ** block provoke debugging output. ** ** In both cases, the effects of the main thread seeing (bDone==0) even @@ -88235,7 +97290,7 @@ struct SortSubtask { ** sorter cursor created by the VDBE. ** ** mxKeysize: -** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(), +** As records are added to the sorter by calls to tdsqlite3VdbeSorterWrite(), ** this variable is updated so as to be set to the size on disk of the ** largest record in the sorter. */ @@ -88246,7 +97301,7 @@ struct VdbeSorter { int pgsz; /* Main database page size */ PmaReader *pReader; /* Readr data from here after Rewind() */ MergeEngine *pMerger; /* Or here, if bUseThreads==0 */ - sqlite3 *db; /* Database connection */ + tdsqlite3 *db; /* Database connection */ KeyInfo *pKeyInfo; /* How to compare records */ UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */ SorterList list; /* List of in-memory records */ @@ -88277,7 +97332,7 @@ struct PmaReader { i64 iEof; /* 1 byte past EOF for this PmaReader */ int nAlloc; /* Bytes of space at aAlloc */ int nKey; /* Number of bytes in key */ - sqlite3_file *pFd; /* File handle we are reading from */ + tdsqlite3_file *pFd; /* File handle we are reading from */ u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */ u8 *aKey; /* Pointer to current key */ u8 *aBuffer; /* Current read buffer */ @@ -88343,7 +97398,7 @@ struct PmaWriter { int iBufStart; /* First byte of buffer to write */ int iBufEnd; /* Last byte of buffer to write */ i64 iWriteOff; /* Offset of start of buffer in file */ - sqlite3_file *pFd; /* File handle to write to */ + tdsqlite3_file *pFd; /* File handle to write to */ }; /* @@ -88358,7 +97413,7 @@ struct PmaWriter { ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0), ** then while records are being accumulated the list is linked using the ** SorterRecord.u.iNext offset. This is because the aMemory[] array may -** be sqlite3Realloc()ed while records are being accumulated. Once the VM +** be tdsqlite3Realloc()ed while records are being accumulated. Once the VM ** has finished passing records to the sorter, or when the in-memory buffer ** is full, the list is sorted. As part of the sorting process, it is ** converted to use the SorterRecord.u.pNext pointers. See function @@ -88392,9 +97447,9 @@ static void vdbeIncrFree(IncrMerger *); ** argument. All structure fields are set to zero before returning. */ static void vdbePmaReaderClear(PmaReader *pReadr){ - sqlite3_free(pReadr->aAlloc); - sqlite3_free(pReadr->aBuffer); - if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); + tdsqlite3_free(pReadr->aAlloc); + tdsqlite3_free(pReadr->aBuffer); + if( pReadr->aMap ) tdsqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); vdbeIncrFree(pReadr->pIncr); memset(pReadr, 0, sizeof(PmaReader)); } @@ -88430,7 +97485,7 @@ static int vdbePmaReadBlob( iBuf = p->iReadOff % p->nBuffer; if( iBuf==0 ){ int nRead; /* Bytes to read from disk */ - int rc; /* sqlite3OsRead() return code */ + int rc; /* tdsqlite3OsRead() return code */ /* Determine how many bytes of data to read. */ if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){ @@ -88441,7 +97496,7 @@ static int vdbePmaReadBlob( assert( nRead>0 ); /* Readr data from the file. Return early if an error occurs. */ - rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff); + rc = tdsqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff); assert( rc!=SQLITE_IOERR_SHORT_READ ); if( rc!=SQLITE_OK ) return rc; } @@ -88462,9 +97517,9 @@ static int vdbePmaReadBlob( /* Extend the p->aAlloc[] allocation if required. */ if( p->nAlloc<nByte ){ u8 *aNew; - int nNew = MAX(128, p->nAlloc*2); + tdsqlite3_int64 nNew = MAX(128, 2*(tdsqlite3_int64)p->nAlloc); while( nByte>nNew ) nNew = nNew*2; - aNew = sqlite3Realloc(p->aAlloc, nNew); + aNew = tdsqlite3Realloc(p->aAlloc, nNew); if( !aNew ) return SQLITE_NOMEM_BKPT; p->nAlloc = nNew; p->aAlloc = aNew; @@ -88506,11 +97561,11 @@ static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){ int iBuf; if( p->aMap ){ - p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut); + p->iReadOff += tdsqlite3GetVarint(&p->aMap[p->iReadOff], pnOut); }else{ iBuf = p->iReadOff % p->nBuffer; if( iBuf && (p->nBuffer-iBuf)>=9 ){ - p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut); + p->iReadOff += tdsqlite3GetVarint(&p->aBuffer[iBuf], pnOut); }else{ u8 aVarint[16], *a; int i = 0, rc; @@ -88519,7 +97574,7 @@ static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){ if( rc ) return rc; aVarint[(i++)&0xf] = a[0]; }while( (a[0]&0x80)!=0 ); - sqlite3GetVarint(aVarint, pnOut); + tdsqlite3GetVarint(aVarint, pnOut); } } @@ -88538,9 +97593,9 @@ static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){ static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){ int rc = SQLITE_OK; if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){ - sqlite3_file *pFd = pFile->pFd; + tdsqlite3_file *pFd = pFile->pFd; if( pFd->pMethods->iVersion>=3 ){ - rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp); + rc = tdsqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp); testcase( rc!=SQLITE_OK ); } } @@ -88562,9 +97617,9 @@ static int vdbePmaReaderSeek( assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 ); - if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ; + if( tdsqlite3FaultSim(201) ) return SQLITE_IOERR_READ; if( pReadr->aMap ){ - sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); + tdsqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); pReadr->aMap = 0; } pReadr->iReadOff = iOff; @@ -88576,7 +97631,7 @@ static int vdbePmaReaderSeek( int pgsz = pTask->pSorter->pgsz; int iBuf = pReadr->iReadOff % pgsz; if( pReadr->aBuffer==0 ){ - pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz); + pReadr->aBuffer = (u8*)tdsqlite3Malloc(pgsz); if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT; pReadr->nBuffer = pgsz; } @@ -88585,7 +97640,7 @@ static int vdbePmaReaderSeek( if( (pReadr->iReadOff + nRead) > pReadr->iEof ){ nRead = (int)(pReadr->iEof - pReadr->iReadOff); } - rc = sqlite3OsRead( + rc = tdsqlite3OsRead( pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff ); testcase( rc!=SQLITE_OK ); @@ -88687,10 +97742,10 @@ static int vdbeSorterCompareTail( ){ UnpackedRecord *r2 = pTask->pUnpacked; if( *pbKey2Cached==0 ){ - sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); + tdsqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); *pbKey2Cached = 1; } - return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1); + return tdsqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1); } /* @@ -88714,10 +97769,10 @@ static int vdbeSorterCompare( ){ UnpackedRecord *r2 = pTask->pUnpacked; if( !*pbKey2Cached ){ - sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); + tdsqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); *pbKey2Cached = 1; } - return sqlite3VdbeRecordCompare(nKey1, pKey1, r2); + return tdsqlite3VdbeRecordCompare(nKey1, pKey1, r2); } /* @@ -88740,21 +97795,22 @@ static int vdbeSorterCompareText( int n2; int res; - getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2; - getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2; - res = memcmp(v1, v2, MIN(n1, n2)); + getVarint32(&p1[1], n1); + getVarint32(&p2[1], n2); + res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2); if( res==0 ){ res = n1 - n2; } if( res==0 ){ - if( pTask->pSorter->pKeyInfo->nField>1 ){ + if( pTask->pSorter->pKeyInfo->nKeyField>1 ){ res = vdbeSorterCompareTail( pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 ); } }else{ - if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){ + assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) ); + if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){ res = res * -1; } } @@ -88783,47 +97839,47 @@ static int vdbeSorterCompareInt( assert( (s1>0 && s1<7) || s1==8 || s1==9 ); assert( (s2>0 && s2<7) || s2==8 || s2==9 ); - if( s1>7 && s2>7 ){ - res = s1 - s2; - }else{ - if( s1==s2 ){ - if( (*v1 ^ *v2) & 0x80 ){ - /* The two values have different signs */ - res = (*v1 & 0x80) ? -1 : +1; - }else{ - /* The two values have the same sign. Compare using memcmp(). */ - static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 }; - int i; - res = 0; - for(i=0; i<aLen[s1]; i++){ - if( (res = v1[i] - v2[i]) ) break; + if( s1==s2 ){ + /* The two values have the same sign. Compare using memcmp(). */ + static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 }; + const u8 n = aLen[s1]; + int i; + res = 0; + for(i=0; i<n; i++){ + if( (res = v1[i] - v2[i])!=0 ){ + if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){ + res = v1[0] & 0x80 ? -1 : +1; } + break; } + } + }else if( s1>7 && s2>7 ){ + res = s1 - s2; + }else{ + if( s2>7 ){ + res = +1; + }else if( s1>7 ){ + res = -1; }else{ - if( s2>7 ){ - res = +1; - }else if( s1>7 ){ - res = -1; - }else{ - res = s1 - s2; - } - assert( res!=0 ); + res = s1 - s2; + } + assert( res!=0 ); - if( res>0 ){ - if( *v1 & 0x80 ) res = -1; - }else{ - if( *v2 & 0x80 ) res = +1; - } + if( res>0 ){ + if( *v1 & 0x80 ) res = -1; + }else{ + if( *v2 & 0x80 ) res = +1; } } if( res==0 ){ - if( pTask->pSorter->pKeyInfo->nField>1 ){ + if( pTask->pSorter->pKeyInfo->nKeyField>1 ){ res = vdbeSorterCompareTail( pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 ); } - }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){ + }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){ + assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) ); res = res * -1; } @@ -88833,7 +97889,7 @@ static int vdbeSorterCompareInt( /* ** Initialize the temporary index cursor just opened as a sorter cursor. ** -** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField) +** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField) ** to determine the number of fields that should be compared from the ** records being sorted. However, if the value passed as argument nField ** is non-zero and the sorter is able to guarantee a stable sort, nField @@ -88849,8 +97905,8 @@ static int vdbeSorterCompareInt( ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ -SQLITE_PRIVATE int sqlite3VdbeSorterInit( - sqlite3 *db, /* Database connection (for malloc()) */ +SQLITE_PRIVATE int tdsqlite3VdbeSorterInit( + tdsqlite3 *db, /* Database connection (for malloc()) */ int nField, /* Number of key fields in each record */ VdbeCursor *pCsr /* Cursor that holds the new sorter */ ){ @@ -88869,7 +97925,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( /* Initialize the upper limit on the number of worker threads */ #if SQLITE_MAX_WORKER_THREADS>0 - if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){ + if( tdsqlite3TempInMemory(db) || tdsqlite3GlobalConfig.bCoreMutex==0 ){ nWorker = 0; }else{ nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS]; @@ -88884,12 +97940,12 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( } #endif - assert( pCsr->pKeyInfo && pCsr->pBt==0 ); + assert( pCsr->pKeyInfo && pCsr->pBtx==0 ); assert( pCsr->eCurType==CURTYPE_SORTER ); - szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*); + szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*); sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask); - pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo); + pSorter = (VdbeSorter*)tdsqlite3DbMallocZero(db, sz + szKeyInfo); pCsr->uc.pSorter = pSorter; if( pSorter==0 ){ rc = SQLITE_NOMEM_BKPT; @@ -88898,10 +97954,9 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo); pKeyInfo->db = 0; if( nField && nWorker==0 ){ - pKeyInfo->nXField += (pKeyInfo->nField - nField); - pKeyInfo->nField = nField; + pKeyInfo->nKeyField = nField; } - pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt); + pSorter->pgsz = pgsz = tdsqlite3BtreeGetPageSize(db->aDb[0].pBt); pSorter->nTask = nWorker + 1; pSorter->iPrev = (u8)(nWorker - 1); pSorter->bUseThreads = (pSorter->nTask>1); @@ -88911,9 +97966,9 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( pTask->pSorter = pSorter; } - if( !sqlite3TempInMemory(db) ){ + if( !tdsqlite3TempInMemory(db) ){ i64 mxCache; /* Cache size in bytes*/ - u32 szPma = sqlite3GlobalConfig.szPma; + u32 szPma = tdsqlite3GlobalConfig.szPma; pSorter->mnPmaSize = szPma * pgsz; mxCache = db->aDb[0].pSchema->cache_size; @@ -88927,20 +97982,19 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( mxCache = MIN(mxCache, SQLITE_MAX_PMASZ); pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache); - /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of - ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary - ** large heap allocations. - */ - if( sqlite3GlobalConfig.pScratch==0 ){ + /* Avoid large memory allocations if the application has requested + ** SQLITE_CONFIG_SMALL_MALLOC. */ + if( tdsqlite3GlobalConfig.bSmallMalloc==0 ){ assert( pSorter->iMemory==0 ); pSorter->nMemory = pgsz; - pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz); + pSorter->list.aMemory = (u8*)tdsqlite3Malloc(pgsz); if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT; } } - if( (pKeyInfo->nField+pKeyInfo->nXField)<13 + if( pKeyInfo->nAllField<13 && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl) + && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0 ){ pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT; } @@ -88953,12 +98007,12 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( /* ** Free the list of sorted records starting at pRecord. */ -static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){ +static void vdbeSorterRecordFree(tdsqlite3 *db, SorterRecord *pRecord){ SorterRecord *p; SorterRecord *pNext; for(p=pRecord; p; p=pNext){ pNext = p->u.pNext; - sqlite3DbFree(db, p); + tdsqlite3DbFree(db, p); } } @@ -88966,13 +98020,13 @@ static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){ ** Free all resources owned by the object indicated by argument pTask. All ** fields of *pTask are zeroed before returning. */ -static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){ - sqlite3DbFree(db, pTask->pUnpacked); +static void vdbeSortSubtaskCleanup(tdsqlite3 *db, SortSubtask *pTask){ + tdsqlite3DbFree(db, pTask->pUnpacked); #if SQLITE_MAX_WORKER_THREADS>0 /* pTask->list.aMemory can only be non-zero if it was handed memory ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */ if( pTask->list.aMemory ){ - sqlite3_free(pTask->list.aMemory); + tdsqlite3_free(pTask->list.aMemory); }else #endif { @@ -88980,10 +98034,10 @@ static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){ vdbeSorterRecordFree(0, pTask->list.pList); } if( pTask->file.pFd ){ - sqlite3OsCloseFree(pTask->file.pFd); + tdsqlite3OsCloseFree(pTask->file.pFd); } if( pTask->file2.pFd ){ - sqlite3OsCloseFree(pTask->file2.pFd); + tdsqlite3OsCloseFree(pTask->file2.pFd); } memset(pTask, 0, sizeof(SortSubtask)); } @@ -88992,12 +98046,12 @@ static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){ static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){ i64 t; int iTask = (pTask - pTask->pSorter->aTask); - sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); + tdsqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent); } static void vdbeSorterRewindDebug(const char *zEvent){ i64 t; - sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t); + tdsqlite3OsCurrentTimeInt64(tdsqlite3_vfs_find(0), &t); fprintf(stderr, "%lld:X %s\n", t, zEvent); } static void vdbeSorterPopulateDebug( @@ -89006,7 +98060,7 @@ static void vdbeSorterPopulateDebug( ){ i64 t; int iTask = (pTask - pTask->pSorter->aTask); - sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); + tdsqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent); } static void vdbeSorterBlockDebug( @@ -89016,7 +98070,7 @@ static void vdbeSorterBlockDebug( ){ if( bBlocked ){ i64 t; - sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); + tdsqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); fprintf(stderr, "%lld:main %s\n", t, zEvent); } } @@ -89039,7 +98093,7 @@ static int vdbeSorterJoinThread(SortSubtask *pTask){ #endif void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR); vdbeSorterBlockDebug(pTask, !bDone, "enter"); - (void)sqlite3ThreadJoin(pTask->pThread, &pRet); + (void)tdsqlite3ThreadJoin(pTask->pThread, &pRet); vdbeSorterBlockDebug(pTask, !bDone, "exit"); rc = SQLITE_PTR_TO_INT(pRet); assert( pTask->bDone==1 ); @@ -89058,7 +98112,7 @@ static int vdbeSorterCreateThread( void *pIn /* Argument passed into xTask() */ ){ assert( pTask->pThread==0 && pTask->bDone==0 ); - return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn); + return tdsqlite3ThreadCreate(&pTask->pThread, xTask, pIn); } /* @@ -89105,7 +98159,7 @@ static MergeEngine *vdbeMergeEngineNew(int nReader){ while( N<nReader ) N += N; nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader)); - pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte); + pNew = tdsqlite3FaultSim(100) ? 0 : (MergeEngine*)tdsqlite3MallocZero(nByte); if( pNew ){ pNew->nTree = N; pNew->pTask = 0; @@ -89125,7 +98179,7 @@ static void vdbeMergeEngineFree(MergeEngine *pMerger){ vdbePmaReaderClear(&pMerger->aReadr[i]); } } - sqlite3_free(pMerger); + tdsqlite3_free(pMerger); } /* @@ -89137,26 +98191,26 @@ static void vdbeIncrFree(IncrMerger *pIncr){ #if SQLITE_MAX_WORKER_THREADS>0 if( pIncr->bUseThread ){ vdbeSorterJoinThread(pIncr->pTask); - if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd); - if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd); + if( pIncr->aFile[0].pFd ) tdsqlite3OsCloseFree(pIncr->aFile[0].pFd); + if( pIncr->aFile[1].pFd ) tdsqlite3OsCloseFree(pIncr->aFile[1].pFd); } #endif vdbeMergeEngineFree(pIncr->pMerger); - sqlite3_free(pIncr); + tdsqlite3_free(pIncr); } } /* ** Reset a sorting cursor back to its original empty state. */ -SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){ +SQLITE_PRIVATE void tdsqlite3VdbeSorterReset(tdsqlite3 *db, VdbeSorter *pSorter){ int i; (void)vdbeSorterJoinAll(pSorter, SQLITE_OK); assert( pSorter->bUseThreads || pSorter->pReader==0 ); #if SQLITE_MAX_WORKER_THREADS>0 if( pSorter->pReader ){ vdbePmaReaderClear(pSorter->pReader); - sqlite3DbFree(db, pSorter->pReader); + tdsqlite3DbFree(db, pSorter->pReader); pSorter->pReader = 0; } #endif @@ -89175,21 +98229,21 @@ SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){ pSorter->bUsePMA = 0; pSorter->iMemory = 0; pSorter->mxKeysize = 0; - sqlite3DbFree(db, pSorter->pUnpacked); + tdsqlite3DbFree(db, pSorter->pUnpacked); pSorter->pUnpacked = 0; } /* -** Free any cursor components allocated by sqlite3VdbeSorterXXX routines. +** Free any cursor components allocated by tdsqlite3VdbeSorterXXX routines. */ -SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){ +SQLITE_PRIVATE void tdsqlite3VdbeSorterClose(tdsqlite3 *db, VdbeCursor *pCsr){ VdbeSorter *pSorter; assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; if( pSorter ){ - sqlite3VdbeSorterReset(db, pSorter); - sqlite3_free(pSorter->list.aMemory); - sqlite3DbFree(db, pSorter); + tdsqlite3VdbeSorterReset(db, pSorter); + tdsqlite3_free(pSorter->list.aMemory); + tdsqlite3DbFree(db, pSorter); pCsr->uc.pSorter = 0; } } @@ -89204,14 +98258,14 @@ SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){ ** Whether or not the file does end up memory mapped of course depends on ** the specific VFS implementation. */ -static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){ +static void vdbeSorterExtendFile(tdsqlite3 *db, tdsqlite3_file *pFd, i64 nByte){ if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){ void *p = 0; int chunksize = 4*1024; - sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize); - sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte); - sqlite3OsFetch(pFd, 0, (int)nByte, &p); - sqlite3OsUnfetch(pFd, 0, p); + tdsqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize); + tdsqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte); + tdsqlite3OsFetch(pFd, 0, (int)nByte, &p); + tdsqlite3OsUnfetch(pFd, 0, p); } } #else @@ -89224,20 +98278,20 @@ static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){ ** Otherwise, set *ppFd to 0 and return an SQLite error code. */ static int vdbeSorterOpenTempFile( - sqlite3 *db, /* Database handle doing sort */ + tdsqlite3 *db, /* Database handle doing sort */ i64 nExtend, /* Attempt to extend file to this size */ - sqlite3_file **ppFd + tdsqlite3_file **ppFd ){ int rc; - if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS; - rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd, + if( tdsqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS; + rc = tdsqlite3OsOpenMalloc(db->pVfs, 0, ppFd, SQLITE_OPEN_TEMP_JOURNAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc ); if( rc==SQLITE_OK ){ i64 max = SQLITE_MAX_MMAP_SIZE; - sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max); + tdsqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max); if( nExtend>0 ){ vdbeSorterExtendFile(db, *ppFd, nExtend); } @@ -89252,13 +98306,9 @@ static int vdbeSorterOpenTempFile( */ static int vdbeSortAllocUnpacked(SortSubtask *pTask){ if( pTask->pUnpacked==0 ){ - char *pFree; - pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord( - pTask->pSorter->pKeyInfo, 0, 0, &pFree - ); - assert( pTask->pUnpacked==(UnpackedRecord*)pFree ); - if( pFree==0 ) return SQLITE_NOMEM_BKPT; - pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField; + pTask->pUnpacked = tdsqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo); + if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT; + pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField; pTask->pUnpacked->errCode = 0; } return SQLITE_OK; @@ -89326,20 +98376,16 @@ static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){ */ static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){ int i; - SorterRecord **aSlot; SorterRecord *p; int rc; + SorterRecord *aSlot[64]; rc = vdbeSortAllocUnpacked(pTask); if( rc!=SQLITE_OK ) return rc; p = pList->pList; pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter); - - aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *)); - if( !aSlot ){ - return SQLITE_NOMEM_BKPT; - } + memset(aSlot, 0, sizeof(aSlot)); while( p ){ SorterRecord *pNext; @@ -89347,7 +98393,7 @@ static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){ if( (u8*)p==pList->aMemory ){ pNext = 0; }else{ - assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) ); + assert( p->u.iNext<tdsqlite3MallocSize(pList->aMemory) ); pNext = (SorterRecord*)&pList->aMemory[p->u.iNext]; } }else{ @@ -89364,13 +98410,12 @@ static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){ } p = 0; - for(i=0; i<64; i++){ + for(i=0; i<ArraySize(aSlot); i++){ if( aSlot[i]==0 ) continue; p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i]; } pList->pList = p; - sqlite3_free(aSlot); assert( pTask->pUnpacked->errCode==SQLITE_OK || pTask->pUnpacked->errCode==SQLITE_NOMEM ); @@ -89381,13 +98426,13 @@ static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){ ** Initialize a PMA-writer object. */ static void vdbePmaWriterInit( - sqlite3_file *pFd, /* File handle to write to */ + tdsqlite3_file *pFd, /* File handle to write to */ PmaWriter *p, /* Object to populate */ int nBuf, /* Buffer size */ i64 iStart /* Offset of pFd to begin writing at */ ){ memset(p, 0, sizeof(PmaWriter)); - p->aBuffer = (u8*)sqlite3Malloc(nBuf); + p->aBuffer = (u8*)tdsqlite3Malloc(nBuf); if( !p->aBuffer ){ p->eFWErr = SQLITE_NOMEM_BKPT; }else{ @@ -89413,7 +98458,7 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){ memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy); p->iBufEnd += nCopy; if( p->iBufEnd==p->nBuffer ){ - p->eFWErr = sqlite3OsWrite(p->pFd, + p->eFWErr = tdsqlite3OsWrite(p->pFd, &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, p->iWriteOff + p->iBufStart ); @@ -89438,13 +98483,13 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){ static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){ int rc; if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){ - p->eFWErr = sqlite3OsWrite(p->pFd, + p->eFWErr = tdsqlite3OsWrite(p->pFd, &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, p->iWriteOff + p->iBufStart ); } *piEof = (p->iWriteOff + p->iBufEnd); - sqlite3_free(p->aBuffer); + tdsqlite3_free(p->aBuffer); rc = p->eFWErr; memset(p, 0, sizeof(PmaWriter)); return rc; @@ -89457,7 +98502,7 @@ static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){ static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){ int nByte; u8 aByte[10]; - nByte = sqlite3PutVarint(aByte, iVal); + nByte = tdsqlite3PutVarint(aByte, iVal); vdbePmaWriteBlob(p, aByte, nByte); } @@ -89476,14 +98521,14 @@ static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){ ** key). The varint is the number of bytes in the blob of data. */ static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){ - sqlite3 *db = pTask->pSorter->db; + tdsqlite3 *db = pTask->pSorter->db; int rc = SQLITE_OK; /* Return code */ PmaWriter writer; /* Object used to write to the file */ #ifdef SQLITE_DEBUG /* Set iSz to the expected size of file pTask->file after writing the PMA. ** This is used by an assert() statement at the end of this function. */ - i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof; + i64 iSz = pList->szPMA + tdsqlite3VarintLen(pList->szPMA) + pTask->file.iEof; #endif vdbeSorterWorkDebug(pTask, "enter"); @@ -89520,7 +98565,7 @@ static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){ pNext = p->u.pNext; vdbePmaWriteVarint(&writer, p->nVal); vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal); - if( pList->aMemory==0 ) sqlite3_free(p); + if( pList->aMemory==0 ) tdsqlite3_free(p); } pList->pList = p; rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof); @@ -89661,22 +98706,25 @@ static int vdbeSorterFlushPMA(VdbeSorter *pSorter){ rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list); }else{ /* Launch a background thread for this operation */ - u8 *aMem = pTask->list.aMemory; - void *pCtx = (void*)pTask; + u8 *aMem; + void *pCtx; + assert( pTask!=0 ); assert( pTask->pThread==0 && pTask->bDone==0 ); assert( pTask->list.pList==0 ); assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 ); + aMem = pTask->list.aMemory; + pCtx = (void*)pTask; pSorter->iPrev = (u8)(pTask - pSorter->aTask); pTask->list = pSorter->list; pSorter->list.pList = 0; pSorter->list.szPMA = 0; if( aMem ){ pSorter->list.aMemory = aMem; - pSorter->nMemory = sqlite3MallocSize(aMem); + pSorter->nMemory = tdsqlite3MallocSize(aMem); }else if( pSorter->list.aMemory ){ - pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory); + pSorter->list.aMemory = tdsqlite3Malloc(pSorter->nMemory); if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT; } @@ -89691,7 +98739,7 @@ static int vdbeSorterFlushPMA(VdbeSorter *pSorter){ /* ** Add a record to the sorter. */ -SQLITE_PRIVATE int sqlite3VdbeSorterWrite( +SQLITE_PRIVATE int tdsqlite3VdbeSorterWrite( const VdbeCursor *pCsr, /* Sorter cursor */ Mem *pVal /* Memory cell containing record */ ){ @@ -89730,17 +98778,17 @@ SQLITE_PRIVATE int sqlite3VdbeSorterWrite( ** than (page-size * cache-size), or ** ** * The total memory allocated for the in-memory list is greater - ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true. + ** than (page-size * 10) and tdsqlite3HeapNearlyFull() returns true. */ nReq = pVal->n + sizeof(SorterRecord); - nPMA = pVal->n + sqlite3VarintLen(pVal->n); + nPMA = pVal->n + tdsqlite3VarintLen(pVal->n); if( pSorter->mxPmaSize ){ if( pSorter->list.aMemory ){ bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize; }else{ bFlush = ( (pSorter->list.szPMA > pSorter->mxPmaSize) - || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull()) + || (pSorter->list.szPMA > pSorter->mnPmaSize && tdsqlite3HeapNearlyFull()) ); } if( bFlush ){ @@ -89761,15 +98809,19 @@ SQLITE_PRIVATE int sqlite3VdbeSorterWrite( if( nMin>pSorter->nMemory ){ u8 *aNew; - int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory; - int nNew = pSorter->nMemory * 2; + tdsqlite3_int64 nNew = 2 * (tdsqlite3_int64)pSorter->nMemory; + int iListOff = -1; + if( pSorter->list.pList ){ + iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory; + } while( nNew < nMin ) nNew = nNew*2; if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize; if( nNew < nMin ) nNew = nMin; - - aNew = sqlite3Realloc(pSorter->list.aMemory, nNew); + aNew = tdsqlite3Realloc(pSorter->list.aMemory, nNew); if( !aNew ) return SQLITE_NOMEM_BKPT; - pSorter->list.pList = (SorterRecord*)&aNew[iListOff]; + if( iListOff>=0 ){ + pSorter->list.pList = (SorterRecord*)&aNew[iListOff]; + } pSorter->list.aMemory = aNew; pSorter->nMemory = nNew; } @@ -89780,7 +98832,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterWrite( pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory); } }else{ - pNew = (SorterRecord *)sqlite3Malloc(nReq); + pNew = (SorterRecord *)tdsqlite3Malloc(nReq); if( pNew==0 ){ return SQLITE_NOMEM_BKPT; } @@ -89821,7 +98873,7 @@ static int vdbeIncrPopulate(IncrMerger *pIncr){ /* Check if the output file is full or if the input has been exhausted. ** In either case exit the loop. */ if( pReader->pFd==0 ) break; - if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break; + if( (iEof + nKey + tdsqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break; /* Write the next key to the output. */ vdbePmaWriteVarint(&writer, nKey); @@ -89921,7 +98973,7 @@ static int vdbeIncrMergerNew( ){ int rc = SQLITE_OK; IncrMerger *pIncr = *ppOut = (IncrMerger*) - (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr))); + (tdsqlite3FaultSim(100) ? 0 : tdsqlite3MallocZero(sizeof(*pIncr))); if( pIncr ){ pIncr->pMerger = pMerger; pIncr->pTask = pTask; @@ -90040,7 +99092,11 @@ static int vdbeMergeEngineInit( ){ int rc = SQLITE_OK; /* Return code */ int i; /* For looping over PmaReader objects */ - int nTree = pMerger->nTree; + int nTree; /* Number of subtrees to merge */ + + /* Failure to allocate the merge would have been detected prior to + ** invoking this routine */ + assert( pMerger!=0 ); /* eMode is always INCRINIT_NORMAL in single-threaded mode */ assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); @@ -90049,6 +99105,7 @@ static int vdbeMergeEngineInit( assert( pMerger->pTask==0 ); pMerger->pTask = pTask; + nTree = pMerger->nTree; for(i=0; i<nTree; i++){ if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){ /* PmaReaders should be normally initialized in order, as if they are @@ -90108,7 +99165,7 @@ static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){ int rc = SQLITE_OK; IncrMerger *pIncr = pReadr->pIncr; SortSubtask *pTask = pIncr->pTask; - sqlite3 *db = pTask->pSorter->db; + tdsqlite3 *db = pTask->pSorter->db; /* eMode is always INCRINIT_NORMAL in single-threaded mode */ assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); @@ -90406,7 +99463,7 @@ static int vdbeSorterMergeTreeBuild( } /* -** This function is called as part of an sqlite3VdbeSorterRewind() operation +** This function is called as part of an tdsqlite3VdbeSorterRewind() operation ** on a sorter that has written two or more PMAs to temporary files. It sets ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader ** (for multi-threaded sorters) so that it can be used to iterate through @@ -90419,7 +99476,7 @@ static int vdbeSorterSetupMerge(VdbeSorter *pSorter){ SortSubtask *pTask0 = &pSorter->aTask[0]; MergeEngine *pMain = 0; #if SQLITE_MAX_WORKER_THREADS - sqlite3 *db = pTask0->pSorter->db; + tdsqlite3 *db = pTask0->pSorter->db; int i; SorterCompare xCompare = vdbeSorterGetCompare(pSorter); for(i=0; i<pSorter->nTask; i++){ @@ -90437,7 +99494,7 @@ static int vdbeSorterSetupMerge(VdbeSorter *pSorter){ SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1]; rc = vdbeSortAllocUnpacked(pLast); if( rc==SQLITE_OK ){ - pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader)); + pReadr = (PmaReader*)tdsqlite3DbMallocZero(db, sizeof(PmaReader)); pSorter->pReader = pReadr; if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT; } @@ -90492,11 +99549,11 @@ static int vdbeSorterSetupMerge(VdbeSorter *pSorter){ /* -** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite, +** Once the sorter has been populated by calls to tdsqlite3VdbeSorterWrite, ** this function is called to prepare for iterating through the records ** in sorted order. */ -SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){ +SQLITE_PRIVATE int tdsqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){ VdbeSorter *pSorter; int rc = SQLITE_OK; /* Return code */ @@ -90542,9 +99599,13 @@ SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){ } /* -** Advance to the next element in the sorter. +** Advance to the next element in the sorter. Return value: +** +** SQLITE_OK success +** SQLITE_DONE end of data +** otherwise some kind of error. */ -SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){ +SQLITE_PRIVATE int tdsqlite3VdbeSorterNext(tdsqlite3 *db, const VdbeCursor *pCsr){ VdbeSorter *pSorter; int rc; /* Return code */ @@ -90558,21 +99619,22 @@ SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, in #if SQLITE_MAX_WORKER_THREADS>0 if( pSorter->bUseThreads ){ rc = vdbePmaReaderNext(pSorter->pReader); - *pbEof = (pSorter->pReader->pFd==0); + if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE; }else #endif /*if( !pSorter->bUseThreads )*/ { + int res = 0; assert( pSorter->pMerger!=0 ); assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) ); - rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof); + rc = vdbeMergeEngineStep(pSorter->pMerger, &res); + if( rc==SQLITE_OK && res ) rc = SQLITE_DONE; } }else{ SorterRecord *pFree = pSorter->list.pList; pSorter->list.pList = pFree->u.pNext; pFree->u.pNext = 0; if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree); - *pbEof = !pSorter->list.pList; - rc = SQLITE_OK; + rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE; } return rc; } @@ -90608,14 +99670,14 @@ static void *vdbeSorterRowkey( /* ** Copy the current sorter key into the memory cell pOut. */ -SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ +SQLITE_PRIVATE int tdsqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ VdbeSorter *pSorter; void *pKey; int nKey; /* Sorter key to copy into pOut */ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; pKey = vdbeSorterRowkey(pSorter, &nKey); - if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){ + if( tdsqlite3VdbeMemClearAndResize(pOut, nKey) ){ return SQLITE_NOMEM_BKPT; } pOut->n = nKey; @@ -90641,7 +99703,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ ** This routine forms the core of the OP_SorterCompare opcode, which in ** turn is used to verify uniqueness when constructing a UNIQUE INDEX. */ -SQLITE_PRIVATE int sqlite3VdbeSorterCompare( +SQLITE_PRIVATE int tdsqlite3VdbeSorterCompare( const VdbeCursor *pCsr, /* Sorter cursor */ Mem *pVal, /* Value to compare to current sorter key */ int nKeyCol, /* Compare this many columns */ @@ -90658,16 +99720,14 @@ SQLITE_PRIVATE int sqlite3VdbeSorterCompare( r2 = pSorter->pUnpacked; pKeyInfo = pCsr->pKeyInfo; if( r2==0 ){ - char *p; - r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p); - assert( pSorter->pUnpacked==(UnpackedRecord*)p ); + r2 = pSorter->pUnpacked = tdsqlite3VdbeAllocUnpackedRecord(pKeyInfo); if( r2==0 ) return SQLITE_NOMEM_BKPT; r2->nField = nKeyCol; } assert( r2->nField==nKeyCol ); pKey = vdbeSorterRowkey(pSorter, &nKey); - sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2); + tdsqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2); for(i=0; i<nKeyCol; i++){ if( r2->aMem[i].flags & MEM_Null ){ *pRes = -1; @@ -90675,7 +99735,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterCompare( } } - *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2); + *pRes = tdsqlite3VdbeRecordCompare(pVal->n, pVal->z, r2); return SQLITE_OK; } @@ -90740,16 +99800,16 @@ struct FileChunk { ** The cursor can be either for reading or writing. */ struct FilePoint { - sqlite3_int64 iOffset; /* Offset from the beginning of the file */ + tdsqlite3_int64 iOffset; /* Offset from the beginning of the file */ FileChunk *pChunk; /* Specific chunk into which cursor points */ }; /* -** This structure is a subclass of sqlite3_file. Each open memory-journal +** This structure is a subclass of tdsqlite3_file. Each open memory-journal ** is an instance of this class. */ struct MemJournal { - const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */ + const tdsqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */ int nChunkSize; /* In-memory chunk-size */ int nSpill; /* Bytes of data before flushing */ @@ -90759,16 +99819,16 @@ struct MemJournal { FilePoint readpoint; /* Pointer to the end of the last xRead() */ int flags; /* xOpen flags */ - sqlite3_vfs *pVfs; /* The "real" underlying VFS */ + tdsqlite3_vfs *pVfs; /* The "real" underlying VFS */ const char *zJournal; /* Name of the journal file */ }; /* ** Read data from the in-memory journal file. This is the implementation -** of the sqlite3_vfs.xRead method. +** of the tdsqlite3_vfs.xRead method. */ static int memjrnlRead( - sqlite3_file *pJfd, /* The journal file from which to read */ + tdsqlite3_file *pJfd, /* The journal file from which to read */ void *zBuf, /* Put the results here */ int iAmt, /* Number of bytes to read */ sqlite_int64 iOfst /* Begin reading at this offset */ @@ -90779,16 +99839,12 @@ static int memjrnlRead( int iChunkOffset; FileChunk *pChunk; -#ifdef SQLITE_ENABLE_ATOMIC_WRITE if( (iAmt+iOfst)>p->endpoint.iOffset ){ return SQLITE_IOERR_SHORT_READ; } -#endif - - assert( (iAmt+iOfst)<=p->endpoint.iOffset ); assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 ); if( p->readpoint.iOffset!=iOfst || iOfst==0 ){ - sqlite3_int64 iOff = 0; + tdsqlite3_int64 iOff = 0; for(pChunk=p->pFirst; ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst; pChunk=pChunk->pNext @@ -90823,7 +99879,7 @@ static void memjrnlFreeChunks(MemJournal *p){ FileChunk *pNext; for(pIter=p->pFirst; pIter; pIter=pNext){ pNext = pIter->pNext; - sqlite3_free(pIter); + tdsqlite3_free(pIter); } p->pFirst = 0; } @@ -90833,11 +99889,11 @@ static void memjrnlFreeChunks(MemJournal *p){ */ static int memjrnlCreateFile(MemJournal *p){ int rc; - sqlite3_file *pReal = (sqlite3_file*)p; + tdsqlite3_file *pReal = (tdsqlite3_file*)p; MemJournal copy = *p; memset(p, 0, sizeof(MemJournal)); - rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0); + rc = tdsqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0); if( rc==SQLITE_OK ){ int nChunk = copy.nChunkSize; i64 iOff = 0; @@ -90846,7 +99902,7 @@ static int memjrnlCreateFile(MemJournal *p){ if( iOff + nChunk > copy.endpoint.iOffset ){ nChunk = copy.endpoint.iOffset - iOff; } - rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff); + rc = tdsqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff); if( rc ) break; iOff += nChunk; } @@ -90860,7 +99916,7 @@ static int memjrnlCreateFile(MemJournal *p){ ** the original before returning. This way, SQLite uses the in-memory ** journal data to roll back changes made to the internal page-cache ** before this function was called. */ - sqlite3OsClose(pReal); + tdsqlite3OsClose(pReal); *p = copy; } return rc; @@ -90871,7 +99927,7 @@ static int memjrnlCreateFile(MemJournal *p){ ** Write data to the file. */ static int memjrnlWrite( - sqlite3_file *pJfd, /* The journal file into which to write */ + tdsqlite3_file *pJfd, /* The journal file into which to write */ const void *zBuf, /* Take data to be written from here */ int iAmt, /* Number of bytes to write */ sqlite_int64 iOfst /* Begin writing at this offset into the file */ @@ -90885,7 +99941,7 @@ static int memjrnlWrite( if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){ int rc = memjrnlCreateFile(p); if( rc==SQLITE_OK ){ - rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst); + rc = tdsqlite3OsWrite(pJfd, zBuf, iAmt, iOfst); } return rc; } @@ -90898,7 +99954,8 @@ static int memjrnlWrite( ** atomic-write optimization. In this case the first 28 bytes of the ** journal file may be written as part of committing the transaction. */ assert( iOfst==p->endpoint.iOffset || iOfst==0 ); -#ifdef SQLITE_ENABLE_ATOMIC_WRITE +#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \ + || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) if( iOfst==0 && p->pFirst ){ assert( p->nChunkSize>iAmt ); memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt); @@ -90914,7 +99971,7 @@ static int memjrnlWrite( if( iChunkOffset==0 ){ /* New chunk is required to extend the file. */ - FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize)); + FileChunk *pNew = tdsqlite3_malloc(fileChunkSize(p->nChunkSize)); if( !pNew ){ return SQLITE_IOERR_NOMEM_BKPT; } @@ -90948,7 +100005,7 @@ static int memjrnlWrite( ** is still in main memory but is being truncated to zero bytes in size, ** ignore */ -static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){ +static int memjrnlTruncate(tdsqlite3_file *pJfd, sqlite_int64 size){ MemJournal *p = (MemJournal *)pJfd; if( ALWAYS(size==0) ){ memjrnlFreeChunks(p); @@ -90964,7 +100021,7 @@ static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){ /* ** Close the file. */ -static int memjrnlClose(sqlite3_file *pJfd){ +static int memjrnlClose(tdsqlite3_file *pJfd){ MemJournal *p = (MemJournal *)pJfd; memjrnlFreeChunks(p); return SQLITE_OK; @@ -90976,7 +100033,7 @@ static int memjrnlClose(sqlite3_file *pJfd){ ** If the real file has been created, call its xSync method. Otherwise, ** syncing an in-memory journal is a no-op. */ -static int memjrnlSync(sqlite3_file *pJfd, int flags){ +static int memjrnlSync(tdsqlite3_file *pJfd, int flags){ UNUSED_PARAMETER2(pJfd, flags); return SQLITE_OK; } @@ -90984,16 +100041,16 @@ static int memjrnlSync(sqlite3_file *pJfd, int flags){ /* ** Query the size of the file in bytes. */ -static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){ +static int memjrnlFileSize(tdsqlite3_file *pJfd, sqlite_int64 *pSize){ MemJournal *p = (MemJournal *)pJfd; *pSize = (sqlite_int64) p->endpoint.iOffset; return SQLITE_OK; } /* -** Table of methods for MemJournal sqlite3_file object. +** Table of methods for MemJournal tdsqlite3_file object. */ -static const struct sqlite3_io_methods MemJournalMethods = { +static const struct tdsqlite3_io_methods MemJournalMethods = { 1, /* iVersion */ memjrnlClose, /* xClose */ memjrnlRead, /* xRead */ @@ -91025,24 +100082,24 @@ static const struct sqlite3_io_methods MemJournalMethods = { ** positive value, then the journal file is initially created in-memory ** but may be flushed to disk later on. In this case the journal file is ** flushed to disk either when it grows larger than nSpill bytes in size, -** or when sqlite3JournalCreate() is called. +** or when tdsqlite3JournalCreate() is called. */ -SQLITE_PRIVATE int sqlite3JournalOpen( - sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */ +SQLITE_PRIVATE int tdsqlite3JournalOpen( + tdsqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */ const char *zName, /* Name of the journal file */ - sqlite3_file *pJfd, /* Preallocated, blank file handle */ + tdsqlite3_file *pJfd, /* Preallocated, blank file handle */ int flags, /* Opening flags */ int nSpill /* Bytes buffered before opening the file */ ){ MemJournal *p = (MemJournal*)pJfd; /* Zero the file-handle object. If nSpill was passed zero, initialize - ** it using the sqlite3OsOpen() function of the underlying VFS. In this + ** it using the tdsqlite3OsOpen() function of the underlying VFS. In this ** case none of the code in this module is executed as a result of calls ** made on the journal file-handle. */ memset(p, 0, sizeof(MemJournal)); if( nSpill==0 ){ - return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0); + return tdsqlite3OsOpen(pVfs, zName, pJfd, flags, 0); } if( nSpill>0 ){ @@ -91052,7 +100109,7 @@ SQLITE_PRIVATE int sqlite3JournalOpen( assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) ); } - p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods; + p->pMethod = (const tdsqlite3_io_methods*)&MemJournalMethods; p->nSpill = nSpill; p->flags = flags; p->zJournal = zName; @@ -91063,21 +100120,35 @@ SQLITE_PRIVATE int sqlite3JournalOpen( /* ** Open an in-memory journal file. */ -SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){ - sqlite3JournalOpen(0, 0, pJfd, 0, -1); +SQLITE_PRIVATE void tdsqlite3MemJournalOpen(tdsqlite3_file *pJfd){ + tdsqlite3JournalOpen(0, 0, pJfd, 0, -1); } -#ifdef SQLITE_ENABLE_ATOMIC_WRITE +#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \ + || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) /* ** If the argument p points to a MemJournal structure that is not an ** in-memory-only journal file (i.e. is one that was opened with a +ve -** nSpill parameter), and the underlying file has not yet been created, -** create it now. +** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying +** file has not yet been created, create it now. */ -SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){ +SQLITE_PRIVATE int tdsqlite3JournalCreate(tdsqlite3_file *pJfd){ int rc = SQLITE_OK; - if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){ - rc = memjrnlCreateFile((MemJournal*)p); + MemJournal *p = (MemJournal*)pJfd; + if( p->pMethod==&MemJournalMethods && ( +#ifdef SQLITE_ENABLE_ATOMIC_WRITE + p->nSpill>0 +#else + /* While this appears to not be possible without ATOMIC_WRITE, the + ** paths are complex, so it seems prudent to leave the test in as + ** a NEVER(), in case our analysis is subtly flawed. */ + NEVER(p->nSpill>0) +#endif +#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE + || (p->flags & SQLITE_OPEN_MAIN_JOURNAL) +#endif + )){ + rc = memjrnlCreateFile(p); } return rc; } @@ -91088,7 +100159,7 @@ SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){ ** Return true if this "journal file" is currently stored in heap memory, ** or false otherwise. */ -SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){ +SQLITE_PRIVATE int tdsqlite3JournalIsInMemory(tdsqlite3_file *p){ return p->pMethods==&MemJournalMethods; } @@ -91096,7 +100167,7 @@ SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){ ** Return the number of bytes required to store a JournalFile that uses vfs ** pVfs to create the underlying on-disk files. */ -SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){ +SQLITE_PRIVATE int tdsqlite3JournalSize(tdsqlite3_vfs *pVfs){ return MAX(pVfs->szOsFile, (int)sizeof(MemJournal)); } @@ -91121,6 +100192,35 @@ SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){ /* #include <string.h> */ +#if !defined(SQLITE_OMIT_WINDOWFUNC) +/* +** Walk all expressions linked into the list of Window objects passed +** as the second argument. +*/ +static int walkWindowList(Walker *pWalker, Window *pList){ + Window *pWin; + for(pWin=pList; pWin; pWin=pWin->pNextWin){ + int rc; + rc = tdsqlite3WalkExprList(pWalker, pWin->pOrderBy); + if( rc ) return WRC_Abort; + rc = tdsqlite3WalkExprList(pWalker, pWin->pPartition); + if( rc ) return WRC_Abort; + rc = tdsqlite3WalkExpr(pWalker, pWin->pFilter); + if( rc ) return WRC_Abort; + + /* The next two are purely for calls to tdsqlite3RenameExprUnmap() + ** within tdsqlite3WindowOffsetExpr(). Because of constraints imposed + ** by tdsqlite3WindowOffsetExpr(), they can never fail. The results do + ** not matter anyhow. */ + rc = tdsqlite3WalkExpr(pWalker, pWin->pStart); + if( NEVER(rc) ) return WRC_Abort; + rc = tdsqlite3WalkExpr(pWalker, pWin->pEnd); + if( NEVER(rc) ) return WRC_Abort; + } + return WRC_Continue; +} +#endif + /* ** Walk an expression tree. Invoke the callback once for each node ** of the expression, while descending. (In other words, the callback @@ -91131,11 +100231,11 @@ SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){ ** ** WRC_Continue Continue descending down the tree. ** -** WRC_Prune Do not descend into child nodes. But allow +** WRC_Prune Do not descend into child nodes, but allow ** the walk to continue with sibling nodes. ** ** WRC_Abort Do no more callbacks. Unwind the stack and -** return the top-level walk call. +** return from the top-level walk call. ** ** The return value from this routine is WRC_Abort to abandon the tree walk ** and WRC_Continue to continue. @@ -91144,33 +100244,48 @@ static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){ int rc; testcase( ExprHasProperty(pExpr, EP_TokenOnly) ); testcase( ExprHasProperty(pExpr, EP_Reduced) ); - rc = pWalker->xExprCallback(pWalker, pExpr); - if( rc || ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){ - return rc & WRC_Abort; - } - if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort; - if( pExpr->pRight && walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort; - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort; - }else if( pExpr->x.pList ){ - if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort; + while(1){ + rc = pWalker->xExprCallback(pWalker, pExpr); + if( rc ) return rc & WRC_Abort; + if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){ + assert( pExpr->x.pList==0 || pExpr->pRight==0 ); + if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort; + if( pExpr->pRight ){ + assert( !ExprHasProperty(pExpr, EP_WinFunc) ); + pExpr = pExpr->pRight; + continue; + }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + assert( !ExprHasProperty(pExpr, EP_WinFunc) ); + if( tdsqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort; + }else{ + if( pExpr->x.pList ){ + if( tdsqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort; + } +#ifndef SQLITE_OMIT_WINDOWFUNC + if( ExprHasProperty(pExpr, EP_WinFunc) ){ + if( walkWindowList(pWalker, pExpr->y.pWin) ) return WRC_Abort; + } +#endif + } + } + break; } return WRC_Continue; } -SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){ +SQLITE_PRIVATE int tdsqlite3WalkExpr(Walker *pWalker, Expr *pExpr){ return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue; } /* -** Call sqlite3WalkExpr() for every expression in list p or until +** Call tdsqlite3WalkExpr() for every expression in list p or until ** an abort request is seen. */ -SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){ +SQLITE_PRIVATE int tdsqlite3WalkExprList(Walker *pWalker, ExprList *p){ int i; struct ExprList_item *pItem; if( p ){ for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){ - if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort; + if( tdsqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort; } } return WRC_Continue; @@ -91182,14 +100297,24 @@ SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){ ** any expr callbacks and SELECT callbacks that come from subqueries. ** Return WRC_Abort or WRC_Continue. */ -SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){ - if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort; - if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort; - if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort; +SQLITE_PRIVATE int tdsqlite3WalkSelectExpr(Walker *pWalker, Select *p){ + if( tdsqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort; + if( tdsqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort; + if( tdsqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort; + if( tdsqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort; + if( tdsqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort; + if( tdsqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort; +#if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE) + { + Parse *pParse = pWalker->pParse; + if( pParse && IN_RENAME_OBJECT ){ + /* The following may return WRC_Abort if there are unresolvable + ** symbols (e.g. a table that does not exist) in a window definition. */ + int rc = walkWindowList(pWalker, p->pWinDefn); + return rc; + } + } +#endif return WRC_Continue; } @@ -91200,36 +100325,36 @@ SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){ ** and on any subqueries further down in the tree. Return ** WRC_Abort or WRC_Continue; */ -SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){ +SQLITE_PRIVATE int tdsqlite3WalkSelectFrom(Walker *pWalker, Select *p){ SrcList *pSrc; int i; struct SrcList_item *pItem; pSrc = p->pSrc; - if( ALWAYS(pSrc) ){ - for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ - if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){ - return WRC_Abort; - } - if( pItem->fg.isTabFunc - && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg) - ){ - return WRC_Abort; - } + assert( pSrc!=0 ); + for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ + if( pItem->pSelect && tdsqlite3WalkSelect(pWalker, pItem->pSelect) ){ + return WRC_Abort; + } + if( pItem->fg.isTabFunc + && tdsqlite3WalkExprList(pWalker, pItem->u1.pFuncArg) + ){ + return WRC_Abort; } } return WRC_Continue; } /* -** Call sqlite3WalkExpr() for every expression in Select statement p. -** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and +** Call tdsqlite3WalkExpr() for every expression in Select statement p. +** Invoke tdsqlite3WalkSelect() for subqueries in the FROM clause and ** on the compound select chain, p->pPrior. ** ** If it is not NULL, the xSelectCallback() callback is invoked before ** the walk of the expressions and FROM clause. The xSelectCallback2() -** method, if it is not NULL, is invoked following the walk of the -** expressions and FROM clause. +** method is invoked following the walk of the expressions and FROM clause, +** but only if both xSelectCallback and xSelectCallback2 are both non-NULL +** and if the expressions and FROM clause both return WRC_Continue; ** ** Return WRC_Continue under normal conditions. Return WRC_Abort if ** there is an abort request. @@ -91237,31 +100362,24 @@ SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){ ** If the Walker does not have an xSelectCallback() then this routine ** is a no-op returning WRC_Continue. */ -SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){ +SQLITE_PRIVATE int tdsqlite3WalkSelect(Walker *pWalker, Select *p){ int rc; - if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){ - return WRC_Continue; - } - rc = WRC_Continue; - pWalker->walkerDepth++; - while( p ){ - if( pWalker->xSelectCallback ){ - rc = pWalker->xSelectCallback(pWalker, p); - if( rc ) break; - } - if( sqlite3WalkSelectExpr(pWalker, p) - || sqlite3WalkSelectFrom(pWalker, p) + if( p==0 ) return WRC_Continue; + if( pWalker->xSelectCallback==0 ) return WRC_Continue; + do{ + rc = pWalker->xSelectCallback(pWalker, p); + if( rc ) return rc & WRC_Abort; + if( tdsqlite3WalkSelectExpr(pWalker, p) + || tdsqlite3WalkSelectFrom(pWalker, p) ){ - pWalker->walkerDepth--; return WRC_Abort; } if( pWalker->xSelectCallback2 ){ pWalker->xSelectCallback2(pWalker, p); } p = p->pPrior; - } - pWalker->walkerDepth--; - return rc & WRC_Abort; + }while( p!=0 ); + return WRC_Continue; } /************** End of walker.c **********************************************/ @@ -91283,8 +100401,6 @@ SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){ ** table and column. */ /* #include "sqliteInt.h" */ -/* #include <stdlib.h> */ -/* #include <string.h> */ /* ** Walk the expression tree pExpr and increase the aggregate function @@ -91305,7 +100421,7 @@ static void incrAggFunctionDepth(Expr *pExpr, int N){ memset(&w, 0, sizeof(w)); w.xExprCallback = incrAggDepth; w.u.n = N; - sqlite3WalkExpr(&w, pExpr); + tdsqlite3WalkExpr(&w, pExpr); } } @@ -91338,36 +100454,44 @@ static void resolveAlias( ){ Expr *pOrig; /* The iCol-th column of the result set */ Expr *pDup; /* Copy of pOrig */ - sqlite3 *db; /* The database connection */ + tdsqlite3 *db; /* The database connection */ assert( iCol>=0 && iCol<pEList->nExpr ); pOrig = pEList->a[iCol].pExpr; assert( pOrig!=0 ); db = pParse->db; - pDup = sqlite3ExprDup(db, pOrig, 0); - if( pDup==0 ) return; - if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery); - if( pExpr->op==TK_COLLATE ){ - pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); - } - ExprSetProperty(pDup, EP_Alias); + pDup = tdsqlite3ExprDup(db, pOrig, 0); + if( pDup!=0 ){ + if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery); + if( pExpr->op==TK_COLLATE ){ + pDup = tdsqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); + } - /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This - ** prevents ExprDelete() from deleting the Expr structure itself, - ** allowing it to be repopulated by the memcpy() on the following line. - ** The pExpr->u.zToken might point into memory that will be freed by the - ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to - ** make a copy of the token before doing the sqlite3DbFree(). - */ - ExprSetProperty(pExpr, EP_Static); - sqlite3ExprDelete(db, pExpr); - memcpy(pExpr, pDup, sizeof(*pExpr)); - if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ - assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); - pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken); - pExpr->flags |= EP_MemToken; + /* Before calling tdsqlite3ExprDelete(), set the EP_Static flag. This + ** prevents ExprDelete() from deleting the Expr structure itself, + ** allowing it to be repopulated by the memcpy() on the following line. + ** The pExpr->u.zToken might point into memory that will be freed by the + ** tdsqlite3DbFree(db, pDup) on the last line of this block, so be sure to + ** make a copy of the token before doing the tdsqlite3DbFree(). + */ + ExprSetProperty(pExpr, EP_Static); + tdsqlite3ExprDelete(db, pExpr); + memcpy(pExpr, pDup, sizeof(*pExpr)); + if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ + assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); + pExpr->u.zToken = tdsqlite3DbStrDup(db, pExpr->u.zToken); + pExpr->flags |= EP_MemToken; + } + if( ExprHasProperty(pExpr, EP_WinFunc) ){ + if( pExpr->y.pWin!=0 ){ + pExpr->y.pWin->pOwner = pExpr; + }else{ + assert( db->mallocFailed ); + } + } + tdsqlite3DbFree(db, pDup); } - sqlite3DbFree(db, pDup); + ExprSetProperty(pExpr, EP_Alias); } @@ -91381,7 +100505,7 @@ static int nameInUsingClause(IdList *pUsing, const char *zCol){ if( pUsing ){ int k; for(k=0; k<pUsing->nId; k++){ - if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1; + if( tdsqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1; } } return 0; @@ -91394,30 +100518,50 @@ static int nameInUsingClause(IdList *pUsing, const char *zCol){ ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will ** match anything. */ -SQLITE_PRIVATE int sqlite3MatchSpanName( - const char *zSpan, +SQLITE_PRIVATE int tdsqlite3MatchEName( + const struct ExprList_item *pItem, const char *zCol, const char *zTab, const char *zDb ){ int n; + const char *zSpan; + if( NEVER(pItem->eEName!=ENAME_TAB) ) return 0; + zSpan = pItem->zEName; for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} - if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ + if( zDb && (tdsqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ return 0; } zSpan += n+1; for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} - if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ + if( zTab && (tdsqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ return 0; } zSpan += n+1; - if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){ + if( zCol && tdsqlite3StrICmp(zSpan, zCol)!=0 ){ return 0; } return 1; } /* +** Return TRUE if the double-quoted string mis-feature should be supported. +*/ +static int areDoubleQuotedStringsEnabled(tdsqlite3 *db, NameContext *pTopNC){ + if( db->init.busy ) return 1; /* Always support for legacy schemas */ + if( pTopNC->ncFlags & NC_IsDDL ){ + /* Currently parsing a DDL statement */ + if( tdsqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){ + return 1; + } + return (db->flags & SQLITE_DqsDDL)!=0; + }else{ + /* Currently parsing a DML statement */ + return (db->flags & SQLITE_DqsDML)!=0; + } +} + +/* ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up ** that name in the set of source tables in pSrcList and make the pExpr ** expression node refer back to that source column. The following changes @@ -91427,7 +100571,7 @@ SQLITE_PRIVATE int sqlite3MatchSpanName( ** (even if X is implied). ** pExpr->iTable Set to the cursor number for the table obtained ** from pSrcList. -** pExpr->pTab Points to the Table structure of X.Y (even if +** pExpr->y.pTab Points to the Table structure of X.Y (even if ** X and/or Y are implied.) ** pExpr->iColumn Set to the column number within the table. ** pExpr->op Set to TK_COLUMN. @@ -91456,12 +100600,12 @@ static int lookupName( int cnt = 0; /* Number of matching column names */ int cntTab = 0; /* Number of matching table names */ int nSubquery = 0; /* How many levels of subquery */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ struct SrcList_item *pItem; /* Use for looping over pSrcList items */ struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ NameContext *pTopNC = pNC; /* First namecontext in the list */ Schema *pSchema = 0; /* Schema of the expression */ - int isTrigger = 0; /* True if resolved to a trigger column */ + int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ Table *pTab = 0; /* Table hold the row */ Column *pCol; /* A column of pTab */ @@ -91471,7 +100615,6 @@ static int lookupName( /* Initialize the node to no-match */ pExpr->iTable = -1; - pExpr->pTab = 0; ExprSetVVAProperty(pExpr, EP_NoReduce); /* Translate the schema name in zDb into a pointer to the corresponding @@ -91490,7 +100633,7 @@ static int lookupName( }else{ for(i=0; i<db->nDb; i++){ assert( db->aDb[i].zDbSName ); - if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ + if( tdsqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ pSchema = db->aDb[i].pSchema; break; } @@ -91499,7 +100642,8 @@ static int lookupName( } /* Start at the inner-most context and move outward until a match is found */ - while( pNC && cnt==0 ){ + assert( pNC && cnt==0 ); + do{ ExprList *pEList; SrcList *pSrcList = pNC->pSrcList; @@ -91512,7 +100656,7 @@ static int lookupName( int hit = 0; pEList = pItem->pSelect->pEList; for(j=0; j<pEList->nExpr; j++){ - if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ + if( tdsqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){ cnt++; cntTab = 2; pMatch = pItem; @@ -91528,15 +100672,18 @@ static int lookupName( if( zTab ){ const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; assert( zTabName!=0 ); - if( sqlite3StrICmp(zTabName, zTab)!=0 ){ + if( tdsqlite3StrICmp(zTabName, zTab)!=0 ){ continue; } + if( IN_RENAME_OBJECT && pItem->zAlias ){ + tdsqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); + } } if( 0==(cntTab++) ){ pMatch = pItem; } for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ - if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ + if( tdsqlite3StrICmp(pCol->zName, zCol)==0 ){ /* If there has been exactly one prior match and this match ** is for the right-hand table of a NATURAL JOIN or is in a ** USING clause, then skip this match. @@ -91555,69 +100702,100 @@ static int lookupName( } if( pMatch ){ pExpr->iTable = pMatch->iCursor; - pExpr->pTab = pMatch->pTab; + pExpr->y.pTab = pMatch->pTab; /* RIGHT JOIN not (yet) supported */ assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ ExprSetProperty(pExpr, EP_CanBeNull); } - pSchema = pExpr->pTab->pSchema; + pSchema = pExpr->y.pTab->pSchema; } } /* if( pSrcList ) */ -#ifndef SQLITE_OMIT_TRIGGER +#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) /* If we have not already resolved the name, then maybe - ** it is a new.* or old.* trigger argument reference + ** it is a new.* or old.* trigger argument reference. Or + ** maybe it is an excluded.* from an upsert. */ - if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){ - int op = pParse->eTriggerOp; - assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); - if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ - pExpr->iTable = 1; - pTab = pParse->pTriggerTab; - }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ - pExpr->iTable = 0; - pTab = pParse->pTriggerTab; - }else{ - pTab = 0; + if( zDb==0 && zTab!=0 && cntTab==0 ){ + pTab = 0; +#ifndef SQLITE_OMIT_TRIGGER + if( pParse->pTriggerTab!=0 ){ + int op = pParse->eTriggerOp; + assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); + if( op!=TK_DELETE && tdsqlite3StrICmp("new",zTab) == 0 ){ + pExpr->iTable = 1; + pTab = pParse->pTriggerTab; + }else if( op!=TK_INSERT && tdsqlite3StrICmp("old",zTab)==0 ){ + pExpr->iTable = 0; + pTab = pParse->pTriggerTab; + } + } +#endif /* SQLITE_OMIT_TRIGGER */ +#ifndef SQLITE_OMIT_UPSERT + if( (pNC->ncFlags & NC_UUpsert)!=0 ){ + Upsert *pUpsert = pNC->uNC.pUpsert; + if( pUpsert && tdsqlite3StrICmp("excluded",zTab)==0 ){ + pTab = pUpsert->pUpsertSrc->a[0].pTab; + pExpr->iTable = 2; + } } +#endif /* SQLITE_OMIT_UPSERT */ if( pTab ){ int iCol; pSchema = pTab->pSchema; cntTab++; for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ - if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ + if( tdsqlite3StrICmp(pCol->zName, zCol)==0 ){ if( iCol==pTab->iPKey ){ iCol = -1; } break; } } - if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ + if( iCol>=pTab->nCol && tdsqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ /* IMP: R-51414-32910 */ iCol = -1; } if( iCol<pTab->nCol ){ cnt++; - if( iCol<0 ){ - pExpr->affinity = SQLITE_AFF_INTEGER; - }else if( pExpr->iTable==0 ){ - testcase( iCol==31 ); - testcase( iCol==32 ); - pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); - }else{ - testcase( iCol==31 ); - testcase( iCol==32 ); - pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); +#ifndef SQLITE_OMIT_UPSERT + if( pExpr->iTable==2 ){ + testcase( iCol==(-1) ); + if( IN_RENAME_OBJECT ){ + pExpr->iColumn = iCol; + pExpr->y.pTab = pTab; + eNewExprOp = TK_COLUMN; + }else{ + pExpr->iTable = pNC->uNC.pUpsert->regData + iCol; + eNewExprOp = TK_REGISTER; + ExprSetProperty(pExpr, EP_Alias); + } + }else +#endif /* SQLITE_OMIT_UPSERT */ + { +#ifndef SQLITE_OMIT_TRIGGER + if( iCol<0 ){ + pExpr->affExpr = SQLITE_AFF_INTEGER; + }else if( pExpr->iTable==0 ){ + testcase( iCol==31 ); + testcase( iCol==32 ); + pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); + }else{ + testcase( iCol==31 ); + testcase( iCol==32 ); + pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); + } + pExpr->y.pTab = pTab; + pExpr->iColumn = (i16)iCol; + eNewExprOp = TK_TRIGGER; +#endif /* SQLITE_OMIT_TRIGGER */ } - pExpr->iColumn = (i16)iCol; - pExpr->pTab = pTab; - isTrigger = 1; } } } -#endif /* !defined(SQLITE_OMIT_TRIGGER) */ +#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */ /* ** Perhaps the name is a reference to the ROWID @@ -91625,13 +100803,13 @@ static int lookupName( if( cnt==0 && cntTab==1 && pMatch - && (pNC->ncFlags & NC_IdxExpr)==0 - && sqlite3IsRowid(zCol) + && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0 + && tdsqlite3IsRowid(zCol) && VisibleRowid(pMatch->pTab) ){ cnt = 1; pExpr->iColumn = -1; - pExpr->affinity = SQLITE_AFF_INTEGER; + pExpr->affExpr = SQLITE_AFF_INTEGER; } /* @@ -91650,32 +100828,45 @@ static int lookupName( ** or HAVING clauses, or as part of a larger expression in the ORDER BY ** clause is not standard SQL. This is a (goofy) SQLite extension, that ** is supported for backwards compatibility only. Hence, we issue a warning - ** on sqlite3_log() whenever the capability is used. + ** on tdsqlite3_log() whenever the capability is used. */ - if( (pEList = pNC->pEList)!=0 - && zTab==0 + if( (pNC->ncFlags & NC_UEList)!=0 && cnt==0 + && zTab==0 ){ + pEList = pNC->uNC.pEList; + assert( pEList!=0 ); for(j=0; j<pEList->nExpr; j++){ - char *zAs = pEList->a[j].zName; - if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ + char *zAs = pEList->a[j].zEName; + if( pEList->a[j].eEName==ENAME_NAME + && tdsqlite3_stricmp(zAs, zCol)==0 + ){ Expr *pOrig; assert( pExpr->pLeft==0 && pExpr->pRight==0 ); assert( pExpr->x.pList==0 ); assert( pExpr->x.pSelect==0 ); pOrig = pEList->a[j].pExpr; if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ - sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); + tdsqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); + return WRC_Abort; + } + if( ExprHasProperty(pOrig, EP_Win) + && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC ) + ){ + tdsqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs); return WRC_Abort; } - if( sqlite3ExprVectorSize(pOrig)!=1 ){ - sqlite3ErrorMsg(pParse, "row value misused"); + if( tdsqlite3ExprVectorSize(pOrig)!=1 ){ + tdsqlite3ErrorMsg(pParse, "row value misused"); return WRC_Abort; } resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); cnt = 1; pMatch = 0; assert( zTab==0 && zDb==0 ); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); + } goto lookupname_end; } } @@ -91684,11 +100875,11 @@ static int lookupName( /* Advance to the next name context. The loop will exit when either ** we have a match (cnt>0) or when we run out of name contexts. */ - if( cnt==0 ){ - pNC = pNC->pNext; - nSubquery++; - } - } + if( cnt ) break; + pNC = pNC->pNext; + nSubquery++; + }while( pNC ); + /* ** If X and Y are NULL (in other words if only the column name Z is @@ -91700,10 +100891,37 @@ static int lookupName( ** Because no reference was made to outer contexts, the pNC->nRef ** fields are not changed in any context. */ - if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){ - pExpr->op = TK_STRING; - pExpr->pTab = 0; - return WRC_Prune; + if( cnt==0 && zTab==0 ){ + assert( pExpr->op==TK_ID ); + if( ExprHasProperty(pExpr,EP_DblQuoted) + && areDoubleQuotedStringsEnabled(db, pTopNC) + ){ + /* If a double-quoted identifier does not match any known column name, + ** then treat it as a string. + ** + ** This hack was added in the early days of SQLite in a misguided attempt + ** to be compatible with MySQL 3.x, which used double-quotes for strings. + ** I now sorely regret putting in this hack. The effect of this hack is + ** that misspelled identifier names are silently converted into strings + ** rather than causing an error, to the frustration of countless + ** programmers. To all those frustrated programmers, my apologies. + ** + ** Someday, I hope to get rid of this hack. Unfortunately there is + ** a huge amount of legacy SQL that uses it. So for now, we just + ** issue a warning. + */ + tdsqlite3_log(SQLITE_WARNING, + "double-quoted string literal: \"%w\"", zCol); +#ifdef SQLITE_ENABLE_NORMALIZE + tdsqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol); +#endif + pExpr->op = TK_STRING; + pExpr->y.pTab = 0; + return WRC_Prune; + } + if( tdsqlite3ExprIdToTrueFalse(pExpr) ){ + return WRC_Prune; + } } /* @@ -91714,11 +100932,11 @@ static int lookupName( const char *zErr; zErr = cnt==0 ? "no such column" : "ambiguous column name"; if( zDb ){ - sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); + tdsqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); }else if( zTab ){ - sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); + tdsqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); }else{ - sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); + tdsqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); } pParse->checkSchema = 1; pTopNC->nErr++; @@ -91726,32 +100944,50 @@ static int lookupName( /* If a column from a table in pSrcList is referenced, then record ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes - ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the - ** column number is greater than the number of bits in the bitmask - ** then set the high-order bit of the bitmask. + ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is + ** set if the 63rd or any subsequent column is used. + ** + ** The colUsed mask is an optimization used to help determine if an + ** index is a covering index. The correct answer is still obtained + ** if the mask contains extra set bits. However, it is important to + ** avoid setting bits beyond the maximum column number of the table. + ** (See ticket [b92e5e8ec2cdbaa1]). + ** + ** If a generated column is referenced, set bits for every column + ** of the table. */ if( pExpr->iColumn>=0 && pMatch!=0 ){ int n = pExpr->iColumn; - testcase( n==BMS-1 ); - if( n>=BMS ){ - n = BMS-1; - } + Table *pExTab = pExpr->y.pTab; + assert( pExTab!=0 ); assert( pMatch->iCursor==pExpr->iTable ); - pMatch->colUsed |= ((Bitmask)1)<<n; + if( (pExTab->tabFlags & TF_HasGenerated)!=0 + && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0 + ){ + testcase( pExTab->nCol==BMS-1 ); + testcase( pExTab->nCol==BMS ); + pMatch->colUsed = pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1; + }else{ + testcase( n==BMS-1 ); + testcase( n==BMS ); + if( n>=BMS ) n = BMS-1; + pMatch->colUsed |= ((Bitmask)1)<<n; + } } /* Clean up and return */ - sqlite3ExprDelete(db, pExpr->pLeft); + tdsqlite3ExprDelete(db, pExpr->pLeft); pExpr->pLeft = 0; - sqlite3ExprDelete(db, pExpr->pRight); + tdsqlite3ExprDelete(db, pExpr->pRight); pExpr->pRight = 0; - pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN); + pExpr->op = eNewExprOp; + ExprSetProperty(pExpr, EP_Leaf); lookupname_end: if( cnt==1 ){ assert( pNC!=0 ); if( !ExprHasProperty(pExpr, EP_Alias) ){ - sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); + tdsqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); } /* Increment the nRef value on all name contexts from TopNC up to ** the point where the name matched. */ @@ -91771,21 +101007,28 @@ lookupname_end: ** Allocate and return a pointer to an expression to load the column iCol ** from datasource iSrc in SrcList pSrc. */ -SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ - Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0); +SQLITE_PRIVATE Expr *tdsqlite3CreateColumnExpr(tdsqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ + Expr *p = tdsqlite3ExprAlloc(db, TK_COLUMN, 0, 0); if( p ){ struct SrcList_item *pItem = &pSrc->a[iSrc]; - p->pTab = pItem->pTab; + Table *pTab = p->y.pTab = pItem->pTab; p->iTable = pItem->iCursor; - if( p->pTab->iPKey==iCol ){ + if( p->y.pTab->iPKey==iCol ){ p->iColumn = -1; }else{ p->iColumn = (ynVar)iCol; - testcase( iCol==BMS ); - testcase( iCol==BMS-1 ); - pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); + if( (pTab->tabFlags & TF_HasGenerated)!=0 + && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0 + ){ + testcase( pTab->nCol==63 ); + testcase( pTab->nCol==64 ); + pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1; + }else{ + testcase( iCol==BMS ); + testcase( iCol==BMS-1 ); + pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); + } } - ExprSetProperty(p, EP_Resolved); } return p; } @@ -91793,23 +101036,39 @@ SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSr /* ** Report an error that an expression is not valid for some set of ** pNC->ncFlags values determined by validMask. -*/ -static void notValid( - Parse *pParse, /* Leave error message here */ - NameContext *pNC, /* The name context */ - const char *zMsg, /* Type of error */ - int validMask /* Set of contexts for which prohibited */ -){ - assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 ); - if( (pNC->ncFlags & validMask)!=0 ){ - const char *zIn = "partial index WHERE clauses"; - if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions"; +** +** static void notValid( +** Parse *pParse, // Leave error message here +** NameContext *pNC, // The name context +** const char *zMsg, // Type of error +** int validMask, // Set of contexts for which prohibited +** Expr *pExpr // Invalidate this expression on error +** ){...} +** +** As an optimization, since the conditional is almost always false +** (because errors are rare), the conditional is moved outside of the +** function call using a macro. +*/ +static void notValidImpl( + Parse *pParse, /* Leave error message here */ + NameContext *pNC, /* The name context */ + const char *zMsg, /* Type of error */ + Expr *pExpr /* Invalidate this expression on error */ +){ + const char *zIn = "partial index WHERE clauses"; + if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions"; #ifndef SQLITE_OMIT_CHECK - else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints"; + else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints"; #endif - sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn); - } +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns"; +#endif + tdsqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn); + if( pExpr ) pExpr->op = TK_NULL; } +#define tdsqlite3ResolveNotValid(P,N,M,X,E) \ + assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \ + if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E); /* ** Expression p should encode a floating point value between 1.0 and 0.0. @@ -91819,14 +101078,14 @@ static void notValid( static int exprProbability(Expr *p){ double r = -1.0; if( p->op!=TK_FLOAT ) return -1; - sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); + tdsqlite3AtoF(p->u.zToken, &r, tdsqlite3Strlen30(p->u.zToken), SQLITE_UTF8); assert( r>=0.0 ); if( r>1.0 ) return -1; return (int)(r*134217728.0); } /* -** This routine is callback for sqlite3WalkExpr(). +** This routine is callback for tdsqlite3WalkExpr(). ** ** Resolve symbolic names into TK_COLUMN operators for the current ** node in the expression tree. Return 0 to continue the search down @@ -91845,8 +101104,6 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ pParse = pNC->pParse; assert( pParse==pWalker->pParse ); - if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune; - ExprSetProperty(pExpr, EP_Resolved); #ifndef NDEBUG if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ SrcList *pSrcList = pNC->pSrcList; @@ -91867,44 +101124,58 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ SrcList *pSrcList = pNC->pSrcList; struct SrcList_item *pItem; assert( pSrcList && pSrcList->nSrc==1 ); - pItem = pSrcList->a; + pItem = pSrcList->a; + assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 ); pExpr->op = TK_COLUMN; - pExpr->pTab = pItem->pTab; + pExpr->y.pTab = pItem->pTab; pExpr->iTable = pItem->iCursor; pExpr->iColumn = -1; - pExpr->affinity = SQLITE_AFF_INTEGER; + pExpr->affExpr = SQLITE_AFF_INTEGER; break; } #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ - /* A lone identifier is the name of a column. - */ - case TK_ID: { - return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr); - } - - /* A table name and column name: ID.ID + /* A column name: ID + ** Or table name and column name: ID.ID ** Or a database, table and column: ID.ID.ID + ** + ** The TK_ID and TK_OUT cases are combined so that there will only + ** be one call to lookupName(). Then the compiler will in-line + ** lookupName() for a size reduction and performance increase. */ + case TK_ID: case TK_DOT: { const char *zColumn; const char *zTable; const char *zDb; Expr *pRight; - /* if( pSrcList==0 ) break; */ - notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr); - pRight = pExpr->pRight; - if( pRight->op==TK_ID ){ + if( pExpr->op==TK_ID ){ zDb = 0; - zTable = pExpr->pLeft->u.zToken; - zColumn = pRight->u.zToken; + zTable = 0; + zColumn = pExpr->u.zToken; }else{ - assert( pRight->op==TK_DOT ); - zDb = pExpr->pLeft->u.zToken; - zTable = pRight->pLeft->u.zToken; - zColumn = pRight->pRight->u.zToken; + Expr *pLeft = pExpr->pLeft; + testcase( pNC->ncFlags & NC_IdxExpr ); + testcase( pNC->ncFlags & NC_GenCol ); + tdsqlite3ResolveNotValid(pParse, pNC, "the \".\" operator", + NC_IdxExpr|NC_GenCol, 0); + pRight = pExpr->pRight; + if( pRight->op==TK_ID ){ + zDb = 0; + }else{ + assert( pRight->op==TK_DOT ); + zDb = pLeft->u.zToken; + pLeft = pRight->pLeft; + pRight = pRight->pRight; + } + zTable = pLeft->u.zToken; + zColumn = pRight->u.zToken; + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight); + tdsqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft); + } } return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); } @@ -91921,13 +101192,16 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ const char *zId; /* The function name. */ FuncDef *pDef; /* Information about the function */ u8 enc = ENC(pParse->db); /* The database encoding */ - + int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin)); +#ifndef SQLITE_OMIT_WINDOWFUNC + Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0); +#endif assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); zId = pExpr->u.zToken; - nId = sqlite3Strlen30(zId); - pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0); + nId = tdsqlite3Strlen30(zId); + pDef = tdsqlite3FindFunction(pParse->db, zId, n, enc, 0); if( pDef==0 ){ - pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0); + pDef = tdsqlite3FindFunction(pParse->db, zId, -2, enc, 0); if( pDef==0 ){ no_such_func = 1; }else{ @@ -91936,11 +101210,11 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ }else{ is_agg = pDef->xFinalize!=0; if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ - ExprSetProperty(pExpr, EP_Unlikely|EP_Skip); + ExprSetProperty(pExpr, EP_Unlikely); if( n==2 ){ pExpr->iTable = exprProbability(pList->a[1].pExpr); if( pExpr->iTable<0 ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "second argument to likelihood() must be a " "constant between 0.0 and 1.0"); pNC->nErr++; @@ -91960,10 +101234,10 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ } #ifndef SQLITE_OMIT_AUTHORIZATION { - int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0); + int auth = tdsqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0); if( auth!=SQLITE_OK ){ if( auth==SQLITE_DENY ){ - sqlite3ErrorMsg(pParse, "not authorized to use function: %s", + tdsqlite3ErrorMsg(pParse, "not authorized to use function: %s", pDef->zName); pNC->nErr++; } @@ -91975,51 +101249,150 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ /* For the purposes of the EP_ConstFunc flag, date and time ** functions and other functions that change slowly are considered - ** constant because they are constant for the duration of one query */ + ** constant because they are constant for the duration of one query. + ** This allows them to be factored out of inner loops. */ ExprSetProperty(pExpr,EP_ConstFunc); } if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){ - /* Date/time functions that use 'now', and other functions like + /* Clearly non-deterministic functions like random(), but also + ** date/time functions that use 'now', and other functions like ** sqlite_version() that might change over time cannot be used - ** in an index. */ - notValid(pParse, pNC, "non-deterministic functions", - NC_IdxExpr|NC_PartIdx); + ** in an index or generated column. Curiously, they can be used + ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all + ** all this. */ + tdsqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions", + NC_IdxExpr|NC_PartIdx|NC_GenCol, 0); + }else{ + assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */ + pExpr->op2 = pNC->ncFlags & NC_SelfRef; + if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL); + } + if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 + && pParse->nested==0 + && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0 + ){ + /* Internal-use-only functions are disallowed unless the + ** SQL is being compiled using tdsqlite3NestedParse() or + ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be + ** used to activate internal functionsn for testing purposes */ + no_such_func = 1; + pDef = 0; + }else + if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 + && !IN_RENAME_OBJECT + ){ + tdsqlite3ExprFunctionUsable(pParse, pExpr, pDef); } } - if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){ - sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId); - pNC->nErr++; - is_agg = 0; - }else if( no_such_func && pParse->db->init.busy==0 + + if( 0==IN_RENAME_OBJECT ){ +#ifndef SQLITE_OMIT_WINDOWFUNC + assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX) + || (pDef->xValue==0 && pDef->xInverse==0) + || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize) + ); + if( pDef && pDef->xValue==0 && pWin ){ + tdsqlite3ErrorMsg(pParse, + "%.*s() may not be used as a window function", nId, zId + ); + pNC->nErr++; + }else if( + (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) + || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin) + || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0) + ){ + const char *zType; + if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){ + zType = "window"; + }else{ + zType = "aggregate"; + } + tdsqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId); + pNC->nErr++; + is_agg = 0; + } +#else + if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){ + tdsqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId); + pNC->nErr++; + is_agg = 0; + } +#endif + else if( no_such_func && pParse->db->init.busy==0 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION - && pParse->explain==0 + && pParse->explain==0 +#endif + ){ + tdsqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); + pNC->nErr++; + }else if( wrong_num_args ){ + tdsqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", + nId, zId); + pNC->nErr++; + } +#ifndef SQLITE_OMIT_WINDOWFUNC + else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){ + tdsqlite3ErrorMsg(pParse, + "FILTER may not be used with non-aggregate %.*s()", + nId, zId + ); + pNC->nErr++; + } +#endif + if( is_agg ){ + /* Window functions may not be arguments of aggregate functions. + ** Or arguments of other window functions. But aggregate functions + ** may be arguments for window functions. */ +#ifndef SQLITE_OMIT_WINDOWFUNC + pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0)); +#else + pNC->ncFlags &= ~NC_AllowAgg; #endif - ){ - sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); - pNC->nErr++; - }else if( wrong_num_args ){ - sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", - nId, zId); - pNC->nErr++; - } - if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg; - sqlite3WalkExprList(pWalker, pList); - if( is_agg ){ - NameContext *pNC2 = pNC; - pExpr->op = TK_AGG_FUNCTION; - pExpr->op2 = 0; - while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ - pExpr->op2++; - pNC2 = pNC2->pNext; } - assert( pDef!=0 ); - if( pNC2 ){ - assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); - testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); - pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX); + } +#ifndef SQLITE_OMIT_WINDOWFUNC + else if( ExprHasProperty(pExpr, EP_WinFunc) ){ + is_agg = 1; + } +#endif + tdsqlite3WalkExprList(pWalker, pList); + if( is_agg ){ +#ifndef SQLITE_OMIT_WINDOWFUNC + if( pWin ){ + Select *pSel = pNC->pWinSelect; + assert( pWin==pExpr->y.pWin ); + if( IN_RENAME_OBJECT==0 ){ + tdsqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef); + } + tdsqlite3WalkExprList(pWalker, pWin->pPartition); + tdsqlite3WalkExprList(pWalker, pWin->pOrderBy); + tdsqlite3WalkExpr(pWalker, pWin->pFilter); + tdsqlite3WindowLink(pSel, pWin); + pNC->ncFlags |= NC_HasWin; + }else +#endif /* SQLITE_OMIT_WINDOWFUNC */ + { + NameContext *pNC2 = pNC; + pExpr->op = TK_AGG_FUNCTION; + pExpr->op2 = 0; +#ifndef SQLITE_OMIT_WINDOWFUNC + if( ExprHasProperty(pExpr, EP_WinFunc) ){ + tdsqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter); + } +#endif + while( pNC2 && !tdsqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ + pExpr->op2++; + pNC2 = pNC2->pNext; + } + assert( pDef!=0 || IN_RENAME_OBJECT ); + if( pNC2 && pDef ){ + assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); + testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); + pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX); + } } - pNC->ncFlags |= NC_AllowAgg; + pNC->ncFlags |= savedAllowFlags; } /* FIX ME: Compute pExpr->affinity based on the expected return ** type of the function @@ -92034,8 +101407,13 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ testcase( pExpr->op==TK_IN ); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ int nRef = pNC->nRef; - notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr); - sqlite3WalkSelect(pWalker, pExpr->x.pSelect); + testcase( pNC->ncFlags & NC_IsCheck ); + testcase( pNC->ncFlags & NC_PartIdx ); + testcase( pNC->ncFlags & NC_IdxExpr ); + testcase( pNC->ncFlags & NC_GenCol ); + tdsqlite3ResolveNotValid(pParse, pNC, "subqueries", + NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr); + tdsqlite3WalkSelect(pWalker, pExpr->x.pSelect); assert( pNC->nRef>=nRef ); if( nRef!=pNC->nRef ){ ExprSetProperty(pExpr, EP_VarSelect); @@ -92045,30 +101423,50 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ break; } case TK_VARIABLE: { - notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr); + testcase( pNC->ncFlags & NC_IsCheck ); + testcase( pNC->ncFlags & NC_PartIdx ); + testcase( pNC->ncFlags & NC_IdxExpr ); + testcase( pNC->ncFlags & NC_GenCol ); + tdsqlite3ResolveNotValid(pParse, pNC, "parameters", + NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr); break; } + case TK_IS: + case TK_ISNOT: { + Expr *pRight = tdsqlite3ExprSkipCollateAndLikely(pExpr->pRight); + assert( !ExprHasProperty(pExpr, EP_Reduced) ); + /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE", + ** and "x IS NOT FALSE". */ + if( pRight->op==TK_ID ){ + int rc = resolveExprStep(pWalker, pRight); + if( rc==WRC_Abort ) return WRC_Abort; + if( pRight->op==TK_TRUEFALSE ){ + pExpr->op2 = pExpr->op; + pExpr->op = TK_TRUTH; + return WRC_Continue; + } + } + /* Fall thru */ + } case TK_BETWEEN: case TK_EQ: case TK_NE: case TK_LT: case TK_LE: case TK_GT: - case TK_GE: - case TK_IS: - case TK_ISNOT: { + case TK_GE: { int nLeft, nRight; if( pParse->db->mallocFailed ) break; assert( pExpr->pLeft!=0 ); - nLeft = sqlite3ExprVectorSize(pExpr->pLeft); + nLeft = tdsqlite3ExprVectorSize(pExpr->pLeft); if( pExpr->op==TK_BETWEEN ){ - nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr); + nRight = tdsqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr); if( nRight==nLeft ){ - nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr); + nRight = tdsqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr); } }else{ assert( pExpr->pRight!=0 ); - nRight = sqlite3ExprVectorSize(pExpr->pRight); + nRight = tdsqlite3ExprVectorSize(pExpr->pRight); } if( nLeft!=nRight ){ testcase( pExpr->op==TK_EQ ); @@ -92080,7 +101478,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ testcase( pExpr->op==TK_IS ); testcase( pExpr->op==TK_ISNOT ); testcase( pExpr->op==TK_BETWEEN ); - sqlite3ErrorMsg(pParse, "row value misused"); + tdsqlite3ErrorMsg(pParse, "row value misused"); } break; } @@ -92112,8 +101510,9 @@ static int resolveAsName( if( pE->op==TK_ID ){ char *zCol = pE->u.zToken; for(i=0; i<pEList->nExpr; i++){ - char *zAs = pEList->a[i].zName; - if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ + if( pEList->a[i].eEName==ENAME_NAME + && tdsqlite3_stricmp(pEList->a[i].zEName, zCol)==0 + ){ return i+1; } } @@ -92147,11 +101546,11 @@ static int resolveOrderByTermToExprList( int i; /* Loop counter */ ExprList *pEList; /* The columns of the result set */ NameContext nc; /* Name context for resolving pE */ - sqlite3 *db; /* Database connection */ + tdsqlite3 *db; /* Database connection */ int rc; /* Return code from subprocedures */ u8 savedSuppErr; /* Saved value of db->suppressErr */ - assert( sqlite3ExprIsInteger(pE, &i)==0 ); + assert( tdsqlite3ExprIsInteger(pE, &i)==0 ); pEList = pSelect->pEList; /* Resolve all names in the ORDER BY term expression @@ -92159,13 +101558,13 @@ static int resolveOrderByTermToExprList( memset(&nc, 0, sizeof(nc)); nc.pParse = pParse; nc.pSrcList = pSelect->pSrc; - nc.pEList = pEList; - nc.ncFlags = NC_AllowAgg; + nc.uNC.pEList = pEList; + nc.ncFlags = NC_AllowAgg|NC_UEList; nc.nErr = 0; db = pParse->db; savedSuppErr = db->suppressErr; db->suppressErr = 1; - rc = sqlite3ResolveExprNames(&nc, pE); + rc = tdsqlite3ResolveExprNames(&nc, pE); db->suppressErr = savedSuppErr; if( rc ) return 0; @@ -92174,7 +101573,7 @@ static int resolveOrderByTermToExprList( ** result-set entry. */ for(i=0; i<pEList->nExpr; i++){ - if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){ + if( tdsqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){ return i+1; } } @@ -92192,7 +101591,7 @@ static void resolveOutOfRangeError( int i, /* The index (1-based) of the term out of range */ int mx /* Largest permissible value of i */ ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "%r %s BY term out of range - should be " "between 1 and %d", i, zType, mx); } @@ -92219,18 +101618,16 @@ static int resolveCompoundOrderBy( int i; ExprList *pOrderBy; ExprList *pEList; - sqlite3 *db; + tdsqlite3 *db; int moreToDo = 1; pOrderBy = pSelect->pOrderBy; if( pOrderBy==0 ) return 0; db = pParse->db; -#if SQLITE_MAX_COLUMN if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); + tdsqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); return 1; } -#endif for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } @@ -92248,8 +101645,8 @@ static int resolveCompoundOrderBy( int iCol = -1; Expr *pE, *pDup; if( pItem->done ) continue; - pE = sqlite3ExprSkipCollate(pItem->pExpr); - if( sqlite3ExprIsInteger(pE, &iCol) ){ + pE = tdsqlite3ExprSkipCollateAndLikely(pItem->pExpr); + if( tdsqlite3ExprIsInteger(pE, &iCol) ){ if( iCol<=0 || iCol>pEList->nExpr ){ resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr); return 1; @@ -92257,32 +101654,53 @@ static int resolveCompoundOrderBy( }else{ iCol = resolveAsName(pParse, pEList, pE); if( iCol==0 ){ - pDup = sqlite3ExprDup(db, pE, 0); + /* Now test if expression pE matches one of the values returned + ** by pSelect. In the usual case this is done by duplicating the + ** expression, resolving any symbols in it, and then comparing + ** it against each expression returned by the SELECT statement. + ** Once the comparisons are finished, the duplicate expression + ** is deleted. + ** + ** Or, if this is running as part of an ALTER TABLE operation, + ** resolve the symbols in the actual expression, not a duplicate. + ** And, if one of the comparisons is successful, leave the expression + ** as is instead of transforming it to an integer as in the usual + ** case. This allows the code in alter.c to modify column + ** refererences within the ORDER BY expression as required. */ + if( IN_RENAME_OBJECT ){ + pDup = pE; + }else{ + pDup = tdsqlite3ExprDup(db, pE, 0); + } if( !db->mallocFailed ){ assert(pDup); iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); } - sqlite3ExprDelete(db, pDup); + if( !IN_RENAME_OBJECT ){ + tdsqlite3ExprDelete(db, pDup); + } } } if( iCol>0 ){ /* Convert the ORDER BY term into an integer column number iCol, ** taking care to preserve the COLLATE clause if it exists */ - Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); - if( pNew==0 ) return 1; - pNew->flags |= EP_IntValue; - pNew->u.iValue = iCol; - if( pItem->pExpr==pE ){ - pItem->pExpr = pNew; - }else{ - Expr *pParent = pItem->pExpr; - assert( pParent->op==TK_COLLATE ); - while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft; - assert( pParent->pLeft==pE ); - pParent->pLeft = pNew; + if( !IN_RENAME_OBJECT ){ + Expr *pNew = tdsqlite3Expr(db, TK_INTEGER, 0); + if( pNew==0 ) return 1; + pNew->flags |= EP_IntValue; + pNew->u.iValue = iCol; + if( pItem->pExpr==pE ){ + pItem->pExpr = pNew; + }else{ + Expr *pParent = pItem->pExpr; + assert( pParent->op==TK_COLLATE ); + while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft; + assert( pParent->pLeft==pE ); + pParent->pLeft = pNew; + } + tdsqlite3ExprDelete(db, pE); + pItem->u.x.iOrderByCol = (u16)iCol; } - sqlite3ExprDelete(db, pE); - pItem->u.x.iOrderByCol = (u16)iCol; pItem->done = 1; }else{ moreToDo = 1; @@ -92292,7 +101710,7 @@ static int resolveCompoundOrderBy( } for(i=0; i<pOrderBy->nExpr; i++){ if( pOrderBy->a[i].done==0 ){ - sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " + tdsqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " "column in the result set", i+1); return 1; } @@ -92310,26 +101728,24 @@ static int resolveCompoundOrderBy( ** If any errors are detected, add an error message to pParse and ** return non-zero. Return zero if no errors are seen. */ -SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy( +SQLITE_PRIVATE int tdsqlite3ResolveOrderGroupBy( Parse *pParse, /* Parsing context. Leave error messages here */ Select *pSelect, /* The SELECT statement containing the clause */ ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ const char *zType /* "ORDER" or "GROUP" */ ){ int i; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; ExprList *pEList; struct ExprList_item *pItem; - if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; -#if SQLITE_MAX_COLUMN + if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0; if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); + tdsqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); return 1; } -#endif pEList = pSelect->pEList; - assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ + assert( pEList!=0 ); /* tdsqlite3SelectNew() guarantees this */ for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ if( pItem->u.x.iOrderByCol ){ if( pItem->u.x.iOrderByCol>pEList->nExpr ){ @@ -92343,6 +101759,36 @@ SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy( return 0; } +#ifndef SQLITE_OMIT_WINDOWFUNC +/* +** Walker callback for windowRemoveExprFromSelect(). +*/ +static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){ + UNUSED_PARAMETER(pWalker); + if( ExprHasProperty(pExpr, EP_WinFunc) ){ + Window *pWin = pExpr->y.pWin; + tdsqlite3WindowUnlinkFromSelect(pWin); + } + return WRC_Continue; +} + +/* +** Remove any Window objects owned by the expression pExpr from the +** Select.pWin list of Select object pSelect. +*/ +static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){ + if( pSelect->pWin ){ + Walker sWalker; + memset(&sWalker, 0, sizeof(Walker)); + sWalker.xExprCallback = resolveRemoveWindowsCb; + sWalker.u.pSelect = pSelect; + tdsqlite3WalkExpr(&sWalker, pExpr); + } +} +#else +# define windowRemoveExprFromSelect(a, b) +#endif /* SQLITE_OMIT_WINDOWFUNC */ + /* ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. ** The Name context of the SELECT statement is pNC. zType is either @@ -92355,7 +101801,7 @@ SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy( ** the order-by term is an identifier that corresponds to the AS-name of ** a result-set expression, then the term resolves to a copy of the ** result-set expression. Otherwise, the expression is resolved in -** the usual way - using sqlite3ResolveExprNames(). +** the usual way - using tdsqlite3ResolveExprNames(). ** ** This routine returns the number of errors. If errors occur, then ** an appropriate error message might be left in pParse. (OOM errors @@ -92378,21 +101824,21 @@ static int resolveOrderGroupBy( pParse = pNC->pParse; for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ Expr *pE = pItem->pExpr; - Expr *pE2 = sqlite3ExprSkipCollate(pE); + Expr *pE2 = tdsqlite3ExprSkipCollateAndLikely(pE); if( zType[0]!='G' ){ iCol = resolveAsName(pParse, pSelect->pEList, pE2); if( iCol>0 ){ /* If an AS-name match is found, mark this ORDER BY column as being ** a copy of the iCol-th result-set column. The subsequent call to - ** sqlite3ResolveOrderGroupBy() will convert the expression to a + ** tdsqlite3ResolveOrderGroupBy() will convert the expression to a ** copy of the iCol-th result-set expression. */ pItem->u.x.iOrderByCol = (u16)iCol; continue; } } - if( sqlite3ExprIsInteger(pE2, &iCol) ){ + if( tdsqlite3ExprIsInteger(pE2, &iCol) ){ /* The ORDER BY term is an integer constant. Again, set the column - ** number so that sqlite3ResolveOrderGroupBy() will convert the + ** number so that tdsqlite3ResolveOrderGroupBy() will convert the ** order-by term to a copy of the result-set expression */ if( iCol<1 || iCol>0xffff ){ resolveOutOfRangeError(pParse, zType, i+1, nResult); @@ -92404,16 +101850,20 @@ static int resolveOrderGroupBy( /* Otherwise, treat the ORDER BY term as an ordinary expression */ pItem->u.x.iOrderByCol = 0; - if( sqlite3ResolveExprNames(pNC, pE) ){ + if( tdsqlite3ResolveExprNames(pNC, pE) ){ return 1; } for(j=0; j<pSelect->pEList->nExpr; j++){ - if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ + if( tdsqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ + /* Since this expresion is being changed into a reference + ** to an identical expression in the result set, remove all Window + ** objects belonging to the expression from the Select.pWin list. */ + windowRemoveExprFromSelect(pSelect, pE); pItem->u.x.iOrderByCol = j+1; } } } - return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); + return tdsqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); } /* @@ -92428,7 +101878,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ int i; /* Loop counter */ ExprList *pGroupBy; /* The GROUP BY clause */ Select *pLeftmost; /* Left-most of SELECT of a compound */ - sqlite3 *db; /* Database connection */ + tdsqlite3 *db; /* Database connection */ assert( p!=0 ); @@ -92439,16 +101889,16 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ pParse = pWalker->pParse; db = pParse->db; - /* Normally sqlite3SelectExpand() will be called first and will have + /* Normally tdsqlite3SelectExpand() will be called first and will have ** already expanded this SELECT. However, if this is a subquery within - ** an expression, sqlite3ResolveExprNames() will be called without a - ** prior call to sqlite3SelectExpand(). When that happens, let - ** sqlite3SelectPrep() do all of the processing for this SELECT. - ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and + ** an expression, tdsqlite3ResolveExprNames() will be called without a + ** prior call to tdsqlite3SelectExpand(). When that happens, let + ** tdsqlite3SelectPrep() do all of the processing for this SELECT. + ** tdsqlite3SelectPrep() will invoke both tdsqlite3SelectExpand() and ** this routine in the correct order. */ if( (p->selFlags & SF_Expanded)==0 ){ - sqlite3SelectPrep(pParse, p, pOuterNC); + tdsqlite3SelectPrep(pParse, p, pOuterNC); return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune; } @@ -92465,8 +101915,8 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; - if( sqlite3ResolveExprNames(&sNC, p->pLimit) || - sqlite3ResolveExprNames(&sNC, p->pOffset) ){ + sNC.pWinSelect = p; + if( tdsqlite3ResolveExprNames(&sNC, p->pLimit) ){ return WRC_Abort; } @@ -92488,7 +101938,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ */ for(i=0; i<p->pSrc->nSrc; i++){ struct SrcList_item *pItem = &p->pSrc->a[i]; - if( pItem->pSelect ){ + if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){ NameContext *pNC; /* Used to iterate name contexts */ int nRef = 0; /* Refcount for pOuterNC and outer contexts */ const char *zSavedContext = pParse->zAuthContext; @@ -92501,7 +101951,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef; if( pItem->zName ) pParse->zAuthContext = pItem->zName; - sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); + tdsqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); pParse->zAuthContext = zSavedContext; if( pParse->nErr || db->mallocFailed ) return WRC_Abort; @@ -92511,15 +101961,16 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ } } - /* Set up the local name-context to pass to sqlite3ResolveExprNames() to + /* Set up the local name-context to pass to tdsqlite3ResolveExprNames() to ** resolve the result-set expression list. */ - sNC.ncFlags = NC_AllowAgg; + sNC.ncFlags = NC_AllowAgg|NC_AllowWin; sNC.pSrcList = p->pSrc; sNC.pNext = pOuterNC; /* Resolve names in the result set. */ - if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort; + if( tdsqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort; + sNC.ncFlags &= ~NC_AllowWin; /* If there are no aggregate functions in the result-set, and no GROUP BY ** expression, do not allow aggregates in any of the other expressions. @@ -92536,7 +101987,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ /* If a HAVING clause is present, then there must be a GROUP BY clause. */ if( p->pHaving && !pGroupBy ){ - sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); + tdsqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); return WRC_Abort; } @@ -92548,15 +101999,17 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ ** Minor point: If this is the case, then the expression will be ** re-evaluated for each reference to it. */ - sNC.pEList = p->pEList; - if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; - if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; + assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 ); + sNC.uNC.pEList = p->pEList; + sNC.ncFlags |= NC_UEList; + if( tdsqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; + if( tdsqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; /* Resolve names in table-valued-function arguments */ for(i=0; i<p->pSrc->nSrc; i++){ struct SrcList_item *pItem = &p->pSrc->a[i]; if( pItem->fg.isTabFunc - && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) + && tdsqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) ){ return WRC_Abort; } @@ -92566,7 +102019,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ ** outer queries */ sNC.pNext = 0; - sNC.ncFlags |= NC_AllowAgg; + sNC.ncFlags |= NC_AllowAgg|NC_AllowWin; /* If this is a converted compound query, move the ORDER BY clause from ** the sub-query back to the parent query. At this point each term @@ -92597,6 +102050,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ if( db->mallocFailed ){ return WRC_Abort; } + sNC.ncFlags &= ~NC_AllowWin; /* Resolve the GROUP BY clause. At the same time, make sure ** the GROUP BY clause does not contain aggregate functions. @@ -92609,17 +102063,30 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ } for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ - sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " + tdsqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " "the GROUP BY clause"); return WRC_Abort; } } } +#ifndef SQLITE_OMIT_WINDOWFUNC + if( IN_RENAME_OBJECT ){ + Window *pWin; + for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){ + if( tdsqlite3ResolveExprListNames(&sNC, pWin->pOrderBy) + || tdsqlite3ResolveExprListNames(&sNC, pWin->pPartition) + ){ + return WRC_Abort; + } + } + } +#endif + /* If this is part of a compound SELECT, check that it has the right ** number of expressions in the select list. */ if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){ - sqlite3SelectWrongNumTermsError(pParse, p->pNext); + tdsqlite3SelectWrongNumTermsError(pParse, p->pNext); return WRC_Abort; } @@ -92687,59 +102154,53 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ ** An error message is left in pParse if anything is amiss. The number ** if errors is returned. */ -SQLITE_PRIVATE int sqlite3ResolveExprNames( +SQLITE_PRIVATE int tdsqlite3ResolveExprNames( NameContext *pNC, /* Namespace to resolve expressions in. */ Expr *pExpr /* The expression to be analyzed. */ ){ - u16 savedHasAgg; + int savedHasAgg; Walker w; - if( pExpr==0 ) return 0; -#if SQLITE_MAX_EXPR_DEPTH>0 - { - Parse *pParse = pNC->pParse; - if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){ - return 1; - } - pParse->nHeight += pExpr->nHeight; - } -#endif - savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg); - pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg); + if( pExpr==0 ) return SQLITE_OK; + savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin); + pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin); w.pParse = pNC->pParse; w.xExprCallback = resolveExprStep; w.xSelectCallback = resolveSelectStep; w.xSelectCallback2 = 0; - w.walkerDepth = 0; - w.eCode = 0; w.u.pNC = pNC; - sqlite3WalkExpr(&w, pExpr); #if SQLITE_MAX_EXPR_DEPTH>0 - pNC->pParse->nHeight -= pExpr->nHeight; -#endif - if( pNC->nErr>0 || w.pParse->nErr>0 ){ - ExprSetProperty(pExpr, EP_Error); - } - if( pNC->ncFlags & NC_HasAgg ){ - ExprSetProperty(pExpr, EP_Agg); + w.pParse->nHeight += pExpr->nHeight; + if( tdsqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){ + return SQLITE_ERROR; } +#endif + tdsqlite3WalkExpr(&w, pExpr); +#if SQLITE_MAX_EXPR_DEPTH>0 + w.pParse->nHeight -= pExpr->nHeight; +#endif + assert( EP_Agg==NC_HasAgg ); + assert( EP_Win==NC_HasWin ); + testcase( pNC->ncFlags & NC_HasAgg ); + testcase( pNC->ncFlags & NC_HasWin ); + ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) ); pNC->ncFlags |= savedHasAgg; - return ExprHasProperty(pExpr, EP_Error); + return pNC->nErr>0 || w.pParse->nErr>0; } /* ** Resolve all names for all expression in an expression list. This is -** just like sqlite3ResolveExprNames() except that it works for an expression +** just like tdsqlite3ResolveExprNames() except that it works for an expression ** list rather than a single expression. */ -SQLITE_PRIVATE int sqlite3ResolveExprListNames( +SQLITE_PRIVATE int tdsqlite3ResolveExprListNames( NameContext *pNC, /* Namespace to resolve expressions in. */ ExprList *pList /* The expression list to be analyzed. */ ){ int i; if( pList ){ for(i=0; i<pList->nExpr; i++){ - if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort; + if( tdsqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort; } } return WRC_Continue; @@ -92751,13 +102212,13 @@ SQLITE_PRIVATE int sqlite3ResolveExprListNames( ** subqueries in expressions, and subqueries used as FROM clause ** terms. ** -** See sqlite3ResolveExprNames() for a description of the kinds of +** See tdsqlite3ResolveExprNames() for a description of the kinds of ** transformations that occur. ** ** All SELECT statements should have been expanded using -** sqlite3SelectExpand() prior to invoking this routine. +** tdsqlite3SelectExpand() prior to invoking this routine. */ -SQLITE_PRIVATE void sqlite3ResolveSelectNames( +SQLITE_PRIVATE void tdsqlite3ResolveSelectNames( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ NameContext *pOuterNC /* Name context for parent SELECT statement */ @@ -92765,47 +102226,65 @@ SQLITE_PRIVATE void sqlite3ResolveSelectNames( Walker w; assert( p!=0 ); - memset(&w, 0, sizeof(w)); w.xExprCallback = resolveExprStep; w.xSelectCallback = resolveSelectStep; + w.xSelectCallback2 = 0; w.pParse = pParse; w.u.pNC = pOuterNC; - sqlite3WalkSelect(&w, p); + tdsqlite3WalkSelect(&w, p); } /* -** Resolve names in expressions that can only reference a single table: +** Resolve names in expressions that can only reference a single table +** or which cannot reference any tables at all. Examples: ** -** * CHECK constraints -** * WHERE clauses on partial indices +** "type" flag +** ------------ +** (1) CHECK constraints NC_IsCheck +** (2) WHERE clauses on partial indices NC_PartIdx +** (3) Expressions in indexes on expressions NC_IdxExpr +** (4) Expression arguments to VACUUM INTO. 0 +** (5) GENERATED ALWAYS as expressions NC_GenCol ** -** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression -** is set to -1 and the Expr.iColumn value is set to the column number. +** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN +** nodes of the expression is set to -1 and the Expr.iColumn value is +** set to the column number. In case (4), TK_COLUMN nodes cause an error. ** ** Any errors cause an error message to be set in pParse. */ -SQLITE_PRIVATE void sqlite3ResolveSelfReference( - Parse *pParse, /* Parsing context */ - Table *pTab, /* The table being referenced */ - int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */ - Expr *pExpr, /* Expression to resolve. May be NULL. */ - ExprList *pList /* Expression list to resolve. May be NUL. */ +SQLITE_PRIVATE int tdsqlite3ResolveSelfReference( + Parse *pParse, /* Parsing context */ + Table *pTab, /* The table being referenced, or NULL */ + int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */ + Expr *pExpr, /* Expression to resolve. May be NULL. */ + ExprList *pList /* Expression list to resolve. May be NULL. */ ){ SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ NameContext sNC; /* Name context for pParse->pNewTable */ + int rc; - assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr ); + assert( type==0 || pTab!=0 ); + assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr + || type==NC_GenCol || pTab==0 ); memset(&sNC, 0, sizeof(sNC)); memset(&sSrc, 0, sizeof(sSrc)); - sSrc.nSrc = 1; - sSrc.a[0].zName = pTab->zName; - sSrc.a[0].pTab = pTab; - sSrc.a[0].iCursor = -1; + if( pTab ){ + sSrc.nSrc = 1; + sSrc.a[0].zName = pTab->zName; + sSrc.a[0].pTab = pTab; + sSrc.a[0].iCursor = -1; + if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){ + /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP + ** schema elements */ + type |= NC_FromDDL; + } + } sNC.pParse = pParse; sNC.pSrcList = &sSrc; - sNC.ncFlags = type; - if( sqlite3ResolveExprNames(&sNC, pExpr) ) return; - if( pList ) sqlite3ResolveExprListNames(&sNC, pList); + sNC.ncFlags = type | NC_IsDDL; + if( (rc = tdsqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc; + if( pList ) rc = tdsqlite3ResolveExprListNames(&sNC, pList); + return rc; } /************** End of resolve.c *********************************************/ @@ -92833,7 +102312,7 @@ static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree); /* ** Return the affinity character for a single column of a table. */ -SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){ +SQLITE_PRIVATE char tdsqlite3TableColumnAffinity(Table *pTab, int iCol){ assert( iCol<pTab->nCol ); return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER; } @@ -92854,32 +102333,38 @@ SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){ ** SELECT a AS b FROM t1 WHERE b; ** SELECT * FROM t1 WHERE (select a from t1); */ -SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){ +SQLITE_PRIVATE char tdsqlite3ExprAffinity(Expr *pExpr){ int op; - pExpr = sqlite3ExprSkipCollate(pExpr); - if( pExpr->flags & EP_Generic ) return 0; + while( ExprHasProperty(pExpr, EP_Skip) ){ + assert( pExpr->op==TK_COLLATE ); + pExpr = pExpr->pLeft; + assert( pExpr!=0 ); + } op = pExpr->op; if( op==TK_SELECT ){ assert( pExpr->flags&EP_xIsSelect ); - return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); + return tdsqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); } if( op==TK_REGISTER ) op = pExpr->op2; #ifndef SQLITE_OMIT_CAST if( op==TK_CAST ){ assert( !ExprHasProperty(pExpr, EP_IntValue) ); - return sqlite3AffinityType(pExpr->u.zToken, 0); + return tdsqlite3AffinityType(pExpr->u.zToken, 0); } #endif - if( op==TK_AGG_COLUMN || op==TK_COLUMN ){ - return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn); + if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){ + return tdsqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); } if( op==TK_SELECT_COLUMN ){ assert( pExpr->pLeft->flags&EP_xIsSelect ); - return sqlite3ExprAffinity( + return tdsqlite3ExprAffinity( pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr ); } - return pExpr->affinity; + if( op==TK_VECTOR ){ + return tdsqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr); + } + return pExpr->affExpr; } /* @@ -92890,14 +102375,14 @@ SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){ ** If a memory allocation error occurs, that fact is recorded in pParse->db ** and the pExpr parameter is returned unchanged. */ -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken( +SQLITE_PRIVATE Expr *tdsqlite3ExprAddCollateToken( Parse *pParse, /* Parsing context */ Expr *pExpr, /* Add the "COLLATE" clause to this expression */ const Token *pCollName, /* Name of collating sequence */ int dequote /* True to dequote pCollName */ ){ if( pCollName->n>0 ){ - Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); + Expr *pNew = tdsqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); if( pNew ){ pNew->pLeft = pExpr; pNew->flags |= EP_Collate|EP_Skip; @@ -92906,19 +102391,31 @@ SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken( } return pExpr; } -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){ +SQLITE_PRIVATE Expr *tdsqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){ Token s; assert( zC!=0 ); - sqlite3TokenInit(&s, (char*)zC); - return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0); + tdsqlite3TokenInit(&s, (char*)zC); + return tdsqlite3ExprAddCollateToken(pParse, pExpr, &s, 0); } /* -** Skip over any TK_COLLATE operators and any unlikely() -** or likelihood() function at the root of an expression. +** Skip over any TK_COLLATE operators. */ -SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){ +SQLITE_PRIVATE Expr *tdsqlite3ExprSkipCollate(Expr *pExpr){ while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ + assert( pExpr->op==TK_COLLATE ); + pExpr = pExpr->pLeft; + } + return pExpr; +} + +/* +** Skip over any TK_COLLATE operators and/or any unlikely() +** or likelihood() or likely() functions at the root of an +** expression. +*/ +SQLITE_PRIVATE Expr *tdsqlite3ExprSkipCollateAndLikely(Expr *pExpr){ + while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){ if( ExprHasProperty(pExpr, EP_Unlikely) ){ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); assert( pExpr->x.pList->nExpr>0 ); @@ -92936,39 +102433,47 @@ SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){ ** Return the collation sequence for the expression pExpr. If ** there is no defined collating sequence, return NULL. ** +** See also: tdsqlite3ExprNNCollSeq() +** +** The tdsqlite3ExprNNCollSeq() works the same exact that it returns the +** default collation if pExpr has no defined collation. +** ** The collating sequence might be determined by a COLLATE operator ** or by the presence of a column with a defined collating sequence. ** COLLATE operators take first precedence. Left operands take ** precedence over right operands. */ -SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ - sqlite3 *db = pParse->db; +SQLITE_PRIVATE CollSeq *tdsqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ + tdsqlite3 *db = pParse->db; CollSeq *pColl = 0; Expr *p = pExpr; while( p ){ int op = p->op; - if( p->flags & EP_Generic ) break; - if( op==TK_CAST || op==TK_UPLUS ){ - p = p->pLeft; - continue; - } - if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){ - pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); - break; - } - if( (op==TK_AGG_COLUMN || op==TK_COLUMN - || op==TK_REGISTER || op==TK_TRIGGER) - && p->pTab!=0 + if( op==TK_REGISTER ) op = p->op2; + if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER) + && p->y.pTab!=0 ){ - /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally + /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally ** a TK_COLUMN but was previously evaluated and cached in a register */ int j = p->iColumn; if( j>=0 ){ - const char *zColl = p->pTab->aCol[j].zColl; - pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); + const char *zColl = p->y.pTab->aCol[j].zColl; + pColl = tdsqlite3FindCollSeq(db, ENC(db), zColl, 0); } break; } + if( op==TK_CAST || op==TK_UPLUS ){ + p = p->pLeft; + continue; + } + if( op==TK_VECTOR ){ + p = p->x.pList->a[0].pExpr; + continue; + } + if( op==TK_COLLATE ){ + pColl = tdsqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); + break; + } if( p->flags & EP_Collate ){ if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){ p = p->pLeft; @@ -92976,12 +102481,12 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ Expr *pNext = p->pRight; /* The Expr.x union is never used at the same time as Expr.pRight */ assert( p->x.pList==0 || p->pRight==0 ); - /* p->flags holds EP_Collate and p->pLeft->flags does not. And - ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at - ** least one EP_Collate. Thus the following two ALWAYS. */ - if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){ + if( p->x.pList!=0 + && !db->mallocFailed + && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) + ){ int i; - for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){ + for(i=0; i<p->x.pList->nExpr; i++){ if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){ pNext = p->x.pList->a[i].pExpr; break; @@ -92994,37 +102499,58 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ break; } } - if( sqlite3CheckCollSeq(pParse, pColl) ){ + if( tdsqlite3CheckCollSeq(pParse, pColl) ){ pColl = 0; } return pColl; } /* +** Return the collation sequence for the expression pExpr. If +** there is no defined collating sequence, return a pointer to the +** defautl collation sequence. +** +** See also: tdsqlite3ExprCollSeq() +** +** The tdsqlite3ExprCollSeq() routine works the same except that it +** returns NULL if there is no defined collation. +*/ +SQLITE_PRIVATE CollSeq *tdsqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){ + CollSeq *p = tdsqlite3ExprCollSeq(pParse, pExpr); + if( p==0 ) p = pParse->db->pDfltColl; + assert( p!=0 ); + return p; +} + +/* +** Return TRUE if the two expressions have equivalent collating sequences. +*/ +SQLITE_PRIVATE int tdsqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){ + CollSeq *pColl1 = tdsqlite3ExprNNCollSeq(pParse, pE1); + CollSeq *pColl2 = tdsqlite3ExprNNCollSeq(pParse, pE2); + return tdsqlite3StrICmp(pColl1->zName, pColl2->zName)==0; +} + +/* ** pExpr is an operand of a comparison operator. aff2 is the ** type affinity of the other operand. This routine returns the ** type affinity that should be used for the comparison operator. */ -SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){ - char aff1 = sqlite3ExprAffinity(pExpr); - if( aff1 && aff2 ){ +SQLITE_PRIVATE char tdsqlite3CompareAffinity(Expr *pExpr, char aff2){ + char aff1 = tdsqlite3ExprAffinity(pExpr); + if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){ /* Both sides of the comparison are columns. If one has numeric ** affinity, use that. Otherwise use no affinity. */ - if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ + if( tdsqlite3IsNumericAffinity(aff1) || tdsqlite3IsNumericAffinity(aff2) ){ return SQLITE_AFF_NUMERIC; }else{ return SQLITE_AFF_BLOB; } - }else if( !aff1 && !aff2 ){ - /* Neither side of the comparison is a column. Compare the - ** results directly. - */ - return SQLITE_AFF_BLOB; }else{ /* One side is a column, the other is not. Use the columns affinity. */ - assert( aff1==0 || aff2==0 ); - return (aff1 + aff2); + assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE ); + return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE; } } @@ -93038,12 +102564,12 @@ static char comparisonAffinity(Expr *pExpr){ pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); assert( pExpr->pLeft ); - aff = sqlite3ExprAffinity(pExpr->pLeft); + aff = tdsqlite3ExprAffinity(pExpr->pLeft); if( pExpr->pRight ){ - aff = sqlite3CompareAffinity(pExpr->pRight, aff); + aff = tdsqlite3CompareAffinity(pExpr->pRight, aff); }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); - }else if( NEVER(aff==0) ){ + aff = tdsqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); + }else if( aff==0 ){ aff = SQLITE_AFF_BLOB; } return aff; @@ -93055,16 +102581,15 @@ static char comparisonAffinity(Expr *pExpr){ ** if the index with affinity idx_affinity may be used to implement ** the comparison in pExpr. */ -SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ +SQLITE_PRIVATE int tdsqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ char aff = comparisonAffinity(pExpr); - switch( aff ){ - case SQLITE_AFF_BLOB: - return 1; - case SQLITE_AFF_TEXT: - return idx_affinity==SQLITE_AFF_TEXT; - default: - return sqlite3IsNumericAffinity(idx_affinity); + if( aff<SQLITE_AFF_TEXT ){ + return 1; + } + if( aff==SQLITE_AFF_TEXT ){ + return idx_affinity==SQLITE_AFF_TEXT; } + return tdsqlite3IsNumericAffinity(idx_affinity); } /* @@ -93072,8 +102597,8 @@ SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. */ static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ - u8 aff = (char)sqlite3ExprAffinity(pExpr2); - aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; + u8 aff = (char)tdsqlite3ExprAffinity(pExpr2); + aff = (u8)tdsqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; return aff; } @@ -93089,7 +102614,7 @@ static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ ** Argument pRight (but not pLeft) may be a null pointer. In this case, ** it is not considered. */ -SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq( +SQLITE_PRIVATE CollSeq *tdsqlite3BinaryCompareCollSeq( Parse *pParse, Expr *pLeft, Expr *pRight @@ -93097,18 +102622,34 @@ SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq( CollSeq *pColl; assert( pLeft ); if( pLeft->flags & EP_Collate ){ - pColl = sqlite3ExprCollSeq(pParse, pLeft); + pColl = tdsqlite3ExprCollSeq(pParse, pLeft); }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ - pColl = sqlite3ExprCollSeq(pParse, pRight); + pColl = tdsqlite3ExprCollSeq(pParse, pRight); }else{ - pColl = sqlite3ExprCollSeq(pParse, pLeft); + pColl = tdsqlite3ExprCollSeq(pParse, pLeft); if( !pColl ){ - pColl = sqlite3ExprCollSeq(pParse, pRight); + pColl = tdsqlite3ExprCollSeq(pParse, pRight); } } return pColl; } +/* Expresssion p is a comparison operator. Return a collation sequence +** appropriate for the comparison operator. +** +** This is normally just a wrapper around tdsqlite3BinaryCompareCollSeq(). +** However, if the OP_Commuted flag is set, then the order of the operands +** is reversed in the tdsqlite3BinaryCompareCollSeq() call so that the +** correct collating sequence is found. +*/ +SQLITE_PRIVATE CollSeq *tdsqlite3ExprCompareCollSeq(Parse *pParse, Expr *p){ + if( ExprHasProperty(p, EP_Commuted) ){ + return tdsqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft); + }else{ + return tdsqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight); + } +} + /* ** Generate code for a comparison operator. */ @@ -93119,17 +102660,23 @@ static int codeCompare( int opcode, /* The comparison opcode */ int in1, int in2, /* Register holding operands */ int dest, /* Jump here if true. */ - int jumpIfNull /* If true, jump if either operand is NULL */ + int jumpIfNull, /* If true, jump if either operand is NULL */ + int isCommuted /* The comparison has been commuted */ ){ int p5; int addr; CollSeq *p4; - p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); + if( pParse->nErr ) return 0; + if( isCommuted ){ + p4 = tdsqlite3BinaryCompareCollSeq(pParse, pRight, pLeft); + }else{ + p4 = tdsqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); + } p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); - addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, + addr = tdsqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, (void*)p4, P4_COLLSEQ); - sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); + tdsqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); return addr; } @@ -93142,8 +102689,8 @@ static int codeCompare( ** But a TK_SELECT might be either a vector or a scalar. It is only ** considered a vector if it has two or more result columns. */ -SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){ - return sqlite3ExprVectorSize(pExpr)>1; +SQLITE_PRIVATE int tdsqlite3ExprIsVector(Expr *pExpr){ + return tdsqlite3ExprVectorSize(pExpr)>1; } /* @@ -93152,7 +102699,7 @@ SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){ ** is a sub-select, return the number of columns in the sub-select. For ** any other type of expression, return 1. */ -SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){ +SQLITE_PRIVATE int tdsqlite3ExprVectorSize(Expr *pExpr){ u8 op = pExpr->op; if( op==TK_REGISTER ) op = pExpr->op2; if( op==TK_VECTOR ){ @@ -93164,7 +102711,6 @@ SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){ } } -#ifndef SQLITE_OMIT_SUBQUERY /* ** Return a pointer to a subexpression of pVector that is the i-th ** column of the vector (numbered starting with 0). The caller must @@ -93180,9 +102726,9 @@ SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){ ** not be ready for evaluation because the table cursor has not yet ** been positioned. */ -SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ - assert( i<sqlite3ExprVectorSize(pVector) ); - if( sqlite3ExprIsVector(pVector) ){ +SQLITE_PRIVATE Expr *tdsqlite3VectorFieldSubexpr(Expr *pVector, int i){ + assert( i<tdsqlite3ExprVectorSize(pVector) ); + if( tdsqlite3ExprIsVector(pVector) ){ assert( pVector->op2==0 || pVector->op==TK_REGISTER ); if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){ return pVector->x.pSelect->pEList->a[i].pExpr; @@ -93192,16 +102738,14 @@ SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ } return pVector; } -#endif /* !defined(SQLITE_OMIT_SUBQUERY) */ -#ifndef SQLITE_OMIT_SUBQUERY /* ** Compute and return a new Expr object which when passed to -** sqlite3ExprCode() will generate all necessary code to compute +** tdsqlite3ExprCode() will generate all necessary code to compute ** the iField-th column of the vector expression pVector. ** ** It is ok for pVector to be a scalar (as long as iField==0). -** In that case, this routine works like sqlite3ExprDup(). +** In that case, this routine works like tdsqlite3ExprDup(). ** ** The caller owns the returned Expr object and is responsible for ** ensuring that the returned value eventually gets freed. @@ -93216,7 +102760,7 @@ SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ ** the returned Expr object is to attach the pVector to the pRight field ** of the returned TK_SELECT_COLUMN Expr object. */ -SQLITE_PRIVATE Expr *sqlite3ExprForVectorField( +SQLITE_PRIVATE Expr *tdsqlite3ExprForVectorField( Parse *pParse, /* Parsing context */ Expr *pVector, /* The vector. List of expressions or a sub-SELECT */ int iField /* Which column of the vector to return */ @@ -93226,20 +102770,21 @@ SQLITE_PRIVATE Expr *sqlite3ExprForVectorField( assert( pVector->flags & EP_xIsSelect ); /* The TK_SELECT_COLUMN Expr node: ** - ** pLeft: pVector containing TK_SELECT + ** pLeft: pVector containing TK_SELECT. Not deleted. ** pRight: not used. But recursively deleted. ** iColumn: Index of a column in pVector + ** iTable: 0 or the number of columns on the LHS of an assignment ** pLeft->iTable: First in an array of register holding result, or 0 ** if the result is not yet computed. ** - ** sqlite3ExprDelete() specifically skips the recursive delete of + ** tdsqlite3ExprDelete() specifically skips the recursive delete of ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector ** can be attached to pRight to cause this node to take ownership of ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes ** with the same pLeft pointer to the pVector, but only one of them ** will own the pVector. */ - pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0, 0); + pRet = tdsqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0); if( pRet ){ pRet->iColumn = iField; pRet->pLeft = pVector; @@ -93247,11 +102792,11 @@ SQLITE_PRIVATE Expr *sqlite3ExprForVectorField( assert( pRet==0 || pRet->iTable==0 ); }else{ if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr; - pRet = sqlite3ExprDup(pParse->db, pVector, 0); + pRet = tdsqlite3ExprDup(pParse->db, pVector, 0); + tdsqlite3RenameTokenRemap(pParse, pRet, pVector); } return pRet; } -#endif /* !define(SQLITE_OMIT_SUBQUERY) */ /* ** If expression pExpr is of type TK_SELECT, generate code to evaluate @@ -93265,7 +102810,7 @@ static int exprCodeSubselect(Parse *pParse, Expr *pExpr){ int reg = 0; #ifndef SQLITE_OMIT_SUBQUERY if( pExpr->op==TK_SELECT ){ - reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0); + reg = tdsqlite3CodeSubselect(pParse, pExpr); } #endif return reg; @@ -93300,7 +102845,7 @@ static int exprVectorRegister( u8 op = pVector->op; assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT ); if( op==TK_REGISTER ){ - *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField); + *ppExpr = tdsqlite3VectorFieldSubexpr(pVector, iField); return pVector->iTable+iField; } if( op==TK_SELECT ){ @@ -93308,7 +102853,7 @@ static int exprVectorRegister( return regSelect+iField; } *ppExpr = pVector->x.pList->a[iField].pExpr; - return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree); + return tdsqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree); } /* @@ -93332,14 +102877,19 @@ static void codeVectorCompare( Vdbe *v = pParse->pVdbe; Expr *pLeft = pExpr->pLeft; Expr *pRight = pExpr->pRight; - int nLeft = sqlite3ExprVectorSize(pLeft); + int nLeft = tdsqlite3ExprVectorSize(pLeft); int i; int regLeft = 0; int regRight = 0; u8 opx = op; - int addrDone = sqlite3VdbeMakeLabel(v); + int addrDone = tdsqlite3VdbeMakeLabel(pParse); + int isCommuted = ExprHasProperty(pExpr,EP_Commuted); - assert( nLeft==sqlite3ExprVectorSize(pRight) ); + if( pParse->nErr ) return; + if( nLeft!=tdsqlite3ExprVectorSize(pRight) ){ + tdsqlite3ErrorMsg(pParse, "row value misused"); + return; + } assert( pExpr->op==TK_EQ || pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT || pExpr->op==TK_LT || pExpr->op==TK_GT @@ -93362,31 +102912,29 @@ static void codeVectorCompare( Expr *pL, *pR; int r1, r2; assert( i>=0 && i<nLeft ); - if( i>0 ) sqlite3ExprCachePush(pParse); r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, ®Free1); r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, ®Free2); - codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5); + codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); - if( i>0 ) sqlite3ExprCachePop(pParse); + tdsqlite3ReleaseTempReg(pParse, regFree1); + tdsqlite3ReleaseTempReg(pParse, regFree2); if( i==nLeft-1 ){ break; } if( opx==TK_EQ ){ - sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v); p5 |= SQLITE_KEEPNULL; }else if( opx==TK_NE ){ - sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v); p5 |= SQLITE_KEEPNULL; }else{ assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE ); - sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone); + tdsqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone); VdbeCoverageIf(v, op==TK_LT); VdbeCoverageIf(v, op==TK_GT); VdbeCoverageIf(v, op==TK_LE); @@ -93394,7 +102942,7 @@ static void codeVectorCompare( if( i==nLeft-2 ) opx = op; } } - sqlite3VdbeResolveLabel(v, addrDone); + tdsqlite3VdbeResolveLabel(v, addrDone); } #if SQLITE_MAX_EXPR_DEPTH>0 @@ -93403,11 +102951,11 @@ static void codeVectorCompare( ** expression depth allowed. If it is not, leave an error message in ** pParse. */ -SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ +SQLITE_PRIVATE int tdsqlite3ExprCheckHeight(Parse *pParse, int nHeight){ int rc = SQLITE_OK; int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; if( nHeight>mxHeight ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "Expression tree is too large (maximum depth %d)", mxHeight ); rc = SQLITE_ERROR; @@ -93439,16 +102987,15 @@ static void heightOfExprList(ExprList *p, int *pnHeight){ } } } -static void heightOfSelect(Select *p, int *pnHeight){ - if( p ){ +static void heightOfSelect(Select *pSelect, int *pnHeight){ + Select *p; + for(p=pSelect; p; p=p->pPrior){ heightOfExpr(p->pWhere, pnHeight); heightOfExpr(p->pHaving, pnHeight); heightOfExpr(p->pLimit, pnHeight); - heightOfExpr(p->pOffset, pnHeight); heightOfExprList(p->pEList, pnHeight); heightOfExprList(p->pGroupBy, pnHeight); heightOfExprList(p->pOrderBy, pnHeight); - heightOfSelect(p->pPrior, pnHeight); } } @@ -93470,7 +103017,7 @@ static void exprSetHeight(Expr *p){ heightOfSelect(p->x.pSelect, &nHeight); }else if( p->x.pList ){ heightOfExprList(p->x.pList, &nHeight); - p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); + p->flags |= EP_Propagate & tdsqlite3ExprListFlags(p->x.pList); } p->nHeight = nHeight + 1; } @@ -93483,17 +103030,17 @@ static void exprSetHeight(Expr *p){ ** Also propagate all EP_Propagate flags from the Expr.x.pList into ** Expr.flags. */ -SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ +SQLITE_PRIVATE void tdsqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ if( pParse->nErr ) return; exprSetHeight(p); - sqlite3ExprCheckHeight(pParse, p->nHeight); + tdsqlite3ExprCheckHeight(pParse, p->nHeight); } /* ** Return the maximum height of any expression tree referenced ** by the select statement passed as an argument. */ -SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){ +SQLITE_PRIVATE int tdsqlite3SelectExprHeight(Select *p){ int nHeight = 0; heightOfSelect(p, &nHeight); return nHeight; @@ -93503,9 +103050,9 @@ SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){ ** Propagate all EP_Propagate flags from the Expr.x.pList into ** Expr.flags. */ -SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ +SQLITE_PRIVATE void tdsqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){ - p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); + p->flags |= EP_Propagate & tdsqlite3ExprListFlags(p->x.pList); } } #define exprSetHeight(y) @@ -93516,7 +103063,7 @@ SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ ** ** Construct a new expression node and return a pointer to it. Memory ** for this node and for the pToken argument is a single allocation -** obtained from sqlite3DbMalloc(). The calling function +** obtained from tdsqlite3DbMalloc(). The calling function ** is responsible for making sure the node eventually gets freed. ** ** If dequote is true, then the token (if it exists) is dequoted. @@ -93531,8 +103078,8 @@ SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ ** into u.iValue and the EP_IntValue flag is set. No extra storage ** is allocated to hold the integer text and the dequote flag is ignored. */ -SQLITE_PRIVATE Expr *sqlite3ExprAlloc( - sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */ +SQLITE_PRIVATE Expr *tdsqlite3ExprAlloc( + tdsqlite3 *db, /* Handle for tdsqlite3DbMallocRawNN() */ int op, /* Expression opcode */ const Token *pToken, /* Token argument. Might be NULL */ int dequote /* True to dequote */ @@ -93544,28 +103091,27 @@ SQLITE_PRIVATE Expr *sqlite3ExprAlloc( assert( db!=0 ); if( pToken ){ if( op!=TK_INTEGER || pToken->z==0 - || sqlite3GetInt32(pToken->z, &iValue)==0 ){ + || tdsqlite3GetInt32(pToken->z, &iValue)==0 ){ nExtra = pToken->n+1; assert( iValue>=0 ); } } - pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); + pNew = tdsqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); if( pNew ){ memset(pNew, 0, sizeof(Expr)); pNew->op = (u8)op; pNew->iAgg = -1; if( pToken ){ if( nExtra==0 ){ - pNew->flags |= EP_IntValue; + pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse); pNew->u.iValue = iValue; }else{ pNew->u.zToken = (char*)&pNew[1]; assert( pToken->z!=0 || pToken->n==0 ); if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); pNew->u.zToken[pToken->n] = 0; - if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ - if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted; - sqlite3Dequote(pNew->u.zToken); + if( dequote && tdsqlite3Isquote(pNew->u.zToken[0]) ){ + tdsqlite3DequoteExpr(pNew); } } } @@ -93580,15 +103126,15 @@ SQLITE_PRIVATE Expr *sqlite3ExprAlloc( ** Allocate a new expression node from a zero-terminated token that has ** already been dequoted. */ -SQLITE_PRIVATE Expr *sqlite3Expr( - sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ +SQLITE_PRIVATE Expr *tdsqlite3Expr( + tdsqlite3 *db, /* Handle for tdsqlite3DbMallocZero() (may be null) */ int op, /* Expression opcode */ const char *zToken /* Token argument. Might be NULL */ ){ Token x; x.z = zToken; - x.n = zToken ? sqlite3Strlen30(zToken) : 0; - return sqlite3ExprAlloc(db, op, &x, 0); + x.n = tdsqlite3Strlen30(zToken); + return tdsqlite3ExprAlloc(db, op, &x, 0); } /* @@ -93597,16 +103143,16 @@ SQLITE_PRIVATE Expr *sqlite3Expr( ** If pRoot==NULL that means that a memory allocation error has occurred. ** In that case, delete the subtrees pLeft and pRight. */ -SQLITE_PRIVATE void sqlite3ExprAttachSubtrees( - sqlite3 *db, +SQLITE_PRIVATE void tdsqlite3ExprAttachSubtrees( + tdsqlite3 *db, Expr *pRoot, Expr *pLeft, Expr *pRight ){ if( pRoot==0 ){ assert( db->mallocFailed ); - sqlite3ExprDelete(db, pLeft); - sqlite3ExprDelete(db, pRight); + tdsqlite3ExprDelete(db, pLeft); + tdsqlite3ExprDelete(db, pRight); }else{ if( pRight ){ pRoot->pRight = pRight; @@ -93627,23 +103173,23 @@ SQLITE_PRIVATE void sqlite3ExprAttachSubtrees( ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, ** free the subtrees and return NULL. */ -SQLITE_PRIVATE Expr *sqlite3PExpr( +SQLITE_PRIVATE Expr *tdsqlite3PExpr( Parse *pParse, /* Parsing context */ int op, /* Expression opcode */ Expr *pLeft, /* Left operand */ - Expr *pRight, /* Right operand */ - const Token *pToken /* Argument token */ + Expr *pRight /* Right operand */ ){ Expr *p; - if( op==TK_AND && pParse->nErr==0 ){ - /* Take advantage of short-circuit false optimization for AND */ - p = sqlite3ExprAnd(pParse->db, pLeft, pRight); + p = tdsqlite3DbMallocRawNN(pParse->db, sizeof(Expr)); + if( p ){ + memset(p, 0, sizeof(Expr)); + p->op = op & 0xff; + p->iAgg = -1; + tdsqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); + tdsqlite3ExprCheckHeight(pParse, p->nHeight); }else{ - p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1); - sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); - } - if( p ) { - sqlite3ExprCheckHeight(pParse, p->nHeight); + tdsqlite3ExprDelete(pParse->db, pLeft); + tdsqlite3ExprDelete(pParse->db, pRight); } return p; } @@ -93652,46 +103198,19 @@ SQLITE_PRIVATE Expr *sqlite3PExpr( ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due ** do a memory allocation failure) then delete the pSelect object. */ -SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){ +SQLITE_PRIVATE void tdsqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){ if( pExpr ){ pExpr->x.pSelect = pSelect; ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery); - sqlite3ExprSetHeightAndFlags(pParse, pExpr); + tdsqlite3ExprSetHeightAndFlags(pParse, pExpr); }else{ assert( pParse->db->mallocFailed ); - sqlite3SelectDelete(pParse->db, pSelect); + tdsqlite3SelectDelete(pParse->db, pSelect); } } /* -** If the expression is always either TRUE or FALSE (respectively), -** then return 1. If one cannot determine the truth value of the -** expression at compile-time return 0. -** -** This is an optimization. If is OK to return 0 here even if -** the expression really is always false or false (a false negative). -** But it is a bug to return 1 if the expression might have different -** boolean values in different circumstances (a false positive.) -** -** Note that if the expression is part of conditional for a -** LEFT JOIN, then we cannot determine at compile-time whether or not -** is it true or false, so always return 0. -*/ -static int exprAlwaysTrue(Expr *p){ - int v = 0; - if( ExprHasProperty(p, EP_FromJoin) ) return 0; - if( !sqlite3ExprIsInteger(p, &v) ) return 0; - return v!=0; -} -static int exprAlwaysFalse(Expr *p){ - int v = 0; - if( ExprHasProperty(p, EP_FromJoin) ) return 0; - if( !sqlite3ExprIsInteger(p, &v) ) return 0; - return v==0; -} - -/* ** Join two expressions using an AND operator. If either expression is ** NULL, then just return the other expression. ** @@ -93699,19 +103218,20 @@ static int exprAlwaysFalse(Expr *p){ ** of returning an AND expression, just return a constant expression with ** a value of false. */ -SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){ - if( pLeft==0 ){ +SQLITE_PRIVATE Expr *tdsqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){ + tdsqlite3 *db = pParse->db; + if( pLeft==0 ){ return pRight; }else if( pRight==0 ){ return pLeft; - }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){ - sqlite3ExprDelete(db, pLeft); - sqlite3ExprDelete(db, pRight); - return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0); + }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight)) + && !IN_RENAME_OBJECT + ){ + tdsqlite3ExprDelete(db, pLeft); + tdsqlite3ExprDelete(db, pRight); + return tdsqlite3Expr(db, TK_INTEGER, "0"); }else{ - Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0); - sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight); - return pNew; + return tdsqlite3PExpr(pParse, TK_AND, pLeft, pRight); } } @@ -93719,22 +103239,66 @@ SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){ ** Construct a new expression node for a function with multiple ** arguments. */ -SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){ +SQLITE_PRIVATE Expr *tdsqlite3ExprFunction( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* Argument list */ + Token *pToken, /* Name of the function */ + int eDistinct /* SF_Distinct or SF_ALL or 0 */ +){ Expr *pNew; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; assert( pToken ); - pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); + pNew = tdsqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); if( pNew==0 ){ - sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ + tdsqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ return 0; } + if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ + tdsqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken); + } pNew->x.pList = pList; + ExprSetProperty(pNew, EP_HasFunc); assert( !ExprHasProperty(pNew, EP_xIsSelect) ); - sqlite3ExprSetHeightAndFlags(pParse, pNew); + tdsqlite3ExprSetHeightAndFlags(pParse, pNew); + if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct); return pNew; } /* +** Check to see if a function is usable according to current access +** rules: +** +** SQLITE_FUNC_DIRECT - Only usable from top-level SQL +** +** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from +** top-level SQL +** +** If the function is not usable, create an error. +*/ +SQLITE_PRIVATE void tdsqlite3ExprFunctionUsable( + Parse *pParse, /* Parsing and code generating context */ + Expr *pExpr, /* The function invocation */ + FuncDef *pDef /* The function being invoked */ +){ + assert( !IN_RENAME_OBJECT ); + assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 ); + if( ExprHasProperty(pExpr, EP_FromDDL) ){ + if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0 + || (pParse->db->flags & SQLITE_TrustedSchema)==0 + ){ + /* Functions prohibited in triggers and views if: + ** (1) tagged with SQLITE_DIRECTONLY + ** (2) not tagged with SQLITE_INNOCUOUS (which means it + ** is tagged with SQLITE_FUNC_UNSAFE) and + ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning + ** that the schema is possibly tainted). + */ + tdsqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName); + } + } +} + +/* ** Assign a variable number to an expression that encodes a wildcard ** in the original SQL statement. ** @@ -93742,7 +103306,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token * ** variable number. ** ** Wildcards of the form "?nnn" are assigned the number "nnn". We make -** sure "nnn" is not too be to avoid a denial of service attack when +** sure "nnn" is not too big to avoid a denial of service attack when ** the SQL statement comes from an external source. ** ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number @@ -93750,82 +103314,82 @@ SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token * ** instance of the wildcard, the next sequential variable number is ** assigned. */ -SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){ - sqlite3 *db = pParse->db; +SQLITE_PRIVATE void tdsqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){ + tdsqlite3 *db = pParse->db; const char *z; + ynVar x; if( pExpr==0 ) return; assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); z = pExpr->u.zToken; assert( z!=0 ); assert( z[0]!=0 ); - assert( n==sqlite3Strlen30(z) ); + assert( n==(u32)tdsqlite3Strlen30(z) ); if( z[1]==0 ){ /* Wildcard of the form "?". Assign the next variable number */ assert( z[0]=='?' ); - pExpr->iColumn = (ynVar)(++pParse->nVar); + x = (ynVar)(++pParse->nVar); }else{ - ynVar x; + int doAdd = 0; if( z[0]=='?' ){ /* Wildcard of the form "?nnn". Convert "nnn" to an integer and ** use it as the variable number */ i64 i; - int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); - x = (ynVar)i; + int bOk; + if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/ + i = z[1]-'0'; /* The common case of ?N for a single digit N */ + bOk = 1; + }else{ + bOk = 0==tdsqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); + } testcase( i==0 ); testcase( i==1 ); testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ - sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", + tdsqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); return; } - if( i>pParse->nVar ){ - pParse->nVar = (int)i; + x = (ynVar)i; + if( x>pParse->nVar ){ + pParse->nVar = (int)x; + doAdd = 1; + }else if( tdsqlite3VListNumToName(pParse->pVList, x)==0 ){ + doAdd = 1; } }else{ /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable ** number as the prior appearance of the same name, or if the name ** has never appeared before, reuse the same variable number */ - ynVar i; - for(i=x=0; i<pParse->nzVar; i++){ - if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){ - x = (ynVar)i+1; - break; - } + x = (ynVar)tdsqlite3VListNameToNum(pParse->pVList, z, n); + if( x==0 ){ + x = (ynVar)(++pParse->nVar); + doAdd = 1; } - if( x==0 ) x = (ynVar)(++pParse->nVar); } - pExpr->iColumn = x; - if( x>pParse->nzVar ){ - char **a; - a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0])); - if( a==0 ){ - assert( db->mallocFailed ); /* Error reported through mallocFailed */ - return; - } - pParse->azVar = a; - memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0])); - pParse->nzVar = x; - } - if( pParse->azVar[x-1]==0 ){ - pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n); + if( doAdd ){ + pParse->pVList = tdsqlite3VListAdd(db, pParse->pVList, z, n, x); } - } - if( pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ - sqlite3ErrorMsg(pParse, "too many SQL variables"); + } + pExpr->iColumn = x; + if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ + tdsqlite3ErrorMsg(pParse, "too many SQL variables"); } } /* ** Recursively delete an expression tree. */ -static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){ +static SQLITE_NOINLINE void tdsqlite3ExprDeleteNN(tdsqlite3 *db, Expr *p){ assert( p!=0 ); /* Sanity check: Assert that the IntValue is non-negative if it exists */ assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 ); + + assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed ); + assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced) + || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) ); #ifdef SQLITE_DEBUG if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){ assert( p->pLeft==0 ); @@ -93836,21 +103400,41 @@ static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){ if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){ /* The Expr.x union is never used at the same time as Expr.pRight */ assert( p->x.pList==0 || p->pRight==0 ); - if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft); - sqlite3ExprDelete(db, p->pRight); - if( ExprHasProperty(p, EP_xIsSelect) ){ - sqlite3SelectDelete(db, p->x.pSelect); + if( p->pLeft && p->op!=TK_SELECT_COLUMN ) tdsqlite3ExprDeleteNN(db, p->pLeft); + if( p->pRight ){ + assert( !ExprHasProperty(p, EP_WinFunc) ); + tdsqlite3ExprDeleteNN(db, p->pRight); + }else if( ExprHasProperty(p, EP_xIsSelect) ){ + assert( !ExprHasProperty(p, EP_WinFunc) ); + tdsqlite3SelectDelete(db, p->x.pSelect); }else{ - sqlite3ExprListDelete(db, p->x.pList); + tdsqlite3ExprListDelete(db, p->x.pList); +#ifndef SQLITE_OMIT_WINDOWFUNC + if( ExprHasProperty(p, EP_WinFunc) ){ + tdsqlite3WindowDelete(db, p->y.pWin); + } +#endif } } - if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken); + if( ExprHasProperty(p, EP_MemToken) ) tdsqlite3DbFree(db, p->u.zToken); if( !ExprHasProperty(p, EP_Static) ){ - sqlite3DbFree(db, p); + tdsqlite3DbFreeNN(db, p); } } -SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){ - if( p ) sqlite3ExprDeleteNN(db, p); +SQLITE_PRIVATE void tdsqlite3ExprDelete(tdsqlite3 *db, Expr *p){ + if( p ) tdsqlite3ExprDeleteNN(db, p); +} + +/* Invoke tdsqlite3RenameExprUnmap() and tdsqlite3ExprDelete() on the +** expression. +*/ +SQLITE_PRIVATE void tdsqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){ + if( p ){ + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameExprUnmap(pParse, p); + } + tdsqlite3ExprDeleteNN(pParse->db, p); + } } /* @@ -93891,7 +103475,7 @@ static int exprStructSize(Expr *p){ ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size ** (unreduced) Expr objects as they or originally constructed by the parser. ** During expression analysis, extra information is computed and moved into -** later parts of teh Expr object and that extra information might get chopped +** later parts of the Expr object and that extra information might get chopped ** off if the expression is reduced. Note also that it does not work to ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal ** to reduce a pristine expression tree from the parser. The implementation @@ -93903,7 +103487,11 @@ static int dupedExprStructSize(Expr *p, int flags){ assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ assert( EXPR_FULLSIZE<=0xfff ); assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); - if( 0==flags ){ + if( 0==flags || p->op==TK_SELECT_COLUMN +#ifndef SQLITE_OMIT_WINDOWFUNC + || ExprHasProperty(p, EP_WinFunc) +#endif + ){ nSize = EXPR_FULLSIZE; }else{ assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); @@ -93928,7 +103516,7 @@ static int dupedExprStructSize(Expr *p, int flags){ static int dupedExprNodeSize(Expr *p, int flags){ int nByte = dupedExprStructSize(p, flags) & 0xfff; if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ - nByte += sqlite3Strlen30(p->u.zToken)+1; + nByte += tdsqlite3Strlen30NN(p->u.zToken)+1; } return ROUND8(nByte); } @@ -93958,14 +103546,14 @@ static int dupedExprSize(Expr *p, int flags){ } /* -** This function is similar to sqlite3ExprDup(), except that if pzBuffer +** This function is similar to tdsqlite3ExprDup(), except that if pzBuffer ** is not NULL then *pzBuffer is assumed to point to a buffer large enough ** to store the copy of expression p, the copies of p->u.zToken ** (if applicable), and the copies of the p->pLeft and p->pRight expressions, ** if any. Before returning, *pzBuffer is set to the first byte past the ** portion of the buffer copied into by this function. */ -static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ +static Expr *exprDup(tdsqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ Expr *pNew; /* Value to return */ u8 *zAlloc; /* Memory space from which to build Expr object */ u32 staticFlag; /* EP_Static if space not obtained from malloc */ @@ -93980,7 +103568,7 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ zAlloc = *pzBuffer; staticFlag = EP_Static; }else{ - zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags)); + zAlloc = tdsqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags)); staticFlag = 0; } pNew = (Expr *)zAlloc; @@ -93995,7 +103583,7 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ const int nNewSize = nStructSize & 0xfff; int nToken; if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ - nToken = sqlite3Strlen30(p->u.zToken) + 1; + nToken = tdsqlite3Strlen30(p->u.zToken) + 1; }else{ nToken = 0; } @@ -94024,14 +103612,14 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){ /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ if( ExprHasProperty(p, EP_xIsSelect) ){ - pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags); + pNew->x.pSelect = tdsqlite3SelectDup(db, p->x.pSelect, dupFlags); }else{ - pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags); + pNew->x.pList = tdsqlite3ExprListDup(db, p->x.pList, dupFlags); } } /* Fill in pNew->pLeft and pNew->pRight. */ - if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){ + if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){ zAlloc += dupedExprNodeSize(p, dupFlags); if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){ pNew->pLeft = p->pLeft ? @@ -94039,6 +103627,12 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ pNew->pRight = p->pRight ? exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0; } +#ifndef SQLITE_OMIT_WINDOWFUNC + if( ExprHasProperty(p, EP_WinFunc) ){ + pNew->y.pWin = tdsqlite3WindowDup(db, pNew, p->y.pWin); + assert( ExprHasProperty(pNew, EP_WinFunc) ); + } +#endif /* SQLITE_OMIT_WINDOWFUNC */ if( pzBuffer ){ *pzBuffer = zAlloc; } @@ -94046,10 +103640,12 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ if( pNew->op==TK_SELECT_COLUMN ){ pNew->pLeft = p->pLeft; + assert( p->iColumn==0 || p->pRight==0 ); + assert( p->pRight==0 || p->pRight==p->pLeft ); }else{ - pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); + pNew->pLeft = tdsqlite3ExprDup(db, p->pLeft, 0); } - pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); + pNew->pRight = tdsqlite3ExprDup(db, p->pRight, 0); } } } @@ -94062,18 +103658,18 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ ** and the db->mallocFailed flag set. */ #ifndef SQLITE_OMIT_CTE -static With *withDup(sqlite3 *db, With *p){ +static With *withDup(tdsqlite3 *db, With *p){ With *pRet = 0; if( p ){ - int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1); - pRet = sqlite3DbMallocZero(db, nByte); + tdsqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1); + pRet = tdsqlite3DbMallocZero(db, nByte); if( pRet ){ int i; pRet->nCte = p->nCte; for(i=0; i<p->nCte; i++){ - pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0); - pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0); - pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName); + pRet->a[i].pSelect = tdsqlite3SelectDup(db, p->a[i].pSelect, 0); + pRet->a[i].pCols = tdsqlite3ExprListDup(db, p->a[i].pCols, 0); + pRet->a[i].zName = tdsqlite3DbStrDup(db, p->a[i].zName); } } } @@ -94083,14 +103679,47 @@ static With *withDup(sqlite3 *db, With *p){ # define withDup(x,y) 0 #endif +#ifndef SQLITE_OMIT_WINDOWFUNC +/* +** The gatherSelectWindows() procedure and its helper routine +** gatherSelectWindowsCallback() are used to scan all the expressions +** an a newly duplicated SELECT statement and gather all of the Window +** objects found there, assembling them onto the linked list at Select->pWin. +*/ +static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){ + if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){ + Select *pSelect = pWalker->u.pSelect; + Window *pWin = pExpr->y.pWin; + assert( pWin ); + assert( IsWindowFunc(pExpr) ); + assert( pWin->ppThis==0 ); + tdsqlite3WindowLink(pSelect, pWin); + } + return WRC_Continue; +} +static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){ + return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune; +} +static void gatherSelectWindows(Select *p){ + Walker w; + w.xExprCallback = gatherSelectWindowsCallback; + w.xSelectCallback = gatherSelectWindowsSelectCallback; + w.xSelectCallback2 = 0; + w.pParse = 0; + w.u.pSelect = p; + tdsqlite3WalkSelect(&w, p); +} +#endif + + /* ** The following group of routines make deep copies of expressions, ** expression lists, ID lists, and select statements. The copies can ** be deleted (by being passed to their respective ...Delete() routines) ** without effecting the originals. ** -** The expression list, ID, and source lists return by sqlite3ExprListDup(), -** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded +** The expression list, ID, and source lists return by tdsqlite3ExprListDup(), +** tdsqlite3IdListDup(), and tdsqlite3SrcListDup() can not be further expanded ** by subsequent calls to sqlite*ListAppend() routines. ** ** Any tables that the SrcList might point to are not duplicated. @@ -94100,34 +103729,48 @@ static With *withDup(sqlite3 *db, With *p){ ** truncated version of the usual Expr structure that will be stored as ** part of the in-memory representation of the database schema. */ -SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){ +SQLITE_PRIVATE Expr *tdsqlite3ExprDup(tdsqlite3 *db, Expr *p, int flags){ assert( flags==0 || flags==EXPRDUP_REDUCE ); return p ? exprDup(db, p, flags, 0) : 0; } -SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){ +SQLITE_PRIVATE ExprList *tdsqlite3ExprListDup(tdsqlite3 *db, ExprList *p, int flags){ ExprList *pNew; struct ExprList_item *pItem, *pOldItem; int i; + Expr *pPriorSelectCol = 0; assert( db!=0 ); if( p==0 ) return 0; - pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); + pNew = tdsqlite3DbMallocRawNN(db, tdsqlite3DbMallocSize(db, p)); if( pNew==0 ) return 0; - pNew->nExpr = i = p->nExpr; - if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){} - pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) ); - if( pItem==0 ){ - sqlite3DbFree(db, pNew); - return 0; - } + pNew->nExpr = p->nExpr; + pItem = pNew->a; pOldItem = p->a; for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){ Expr *pOldExpr = pOldItem->pExpr; - pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); - pItem->zName = sqlite3DbStrDup(db, pOldItem->zName); - pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan); - pItem->sortOrder = pOldItem->sortOrder; + Expr *pNewExpr; + pItem->pExpr = tdsqlite3ExprDup(db, pOldExpr, flags); + if( pOldExpr + && pOldExpr->op==TK_SELECT_COLUMN + && (pNewExpr = pItem->pExpr)!=0 + ){ + assert( pNewExpr->iColumn==0 || i>0 ); + if( pNewExpr->iColumn==0 ){ + assert( pOldExpr->pLeft==pOldExpr->pRight ); + pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight; + }else{ + assert( i>0 ); + assert( pItem[-1].pExpr!=0 ); + assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 ); + assert( pPriorSelectCol==pItem[-1].pExpr->pLeft ); + pNewExpr->pLeft = pPriorSelectCol; + } + } + pItem->zEName = tdsqlite3DbStrDup(db, pOldItem->zEName); + pItem->sortFlags = pOldItem->sortFlags; + pItem->eEName = pOldItem->eEName; pItem->done = 0; - pItem->bSpanIsTab = pOldItem->bSpanIsTab; + pItem->bNulls = pOldItem->bNulls; + pItem->bSorterRef = pOldItem->bSorterRef; pItem->u = pOldItem->u; } return pNew; @@ -94136,19 +103779,19 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags) /* ** If cursors, triggers, views and subqueries are all omitted from ** the build, then none of the following routines, except for -** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes +** tdsqlite3SelectDup(), can be called. tdsqlite3SelectDup() is sometimes ** called with a NULL argument. */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ || !defined(SQLITE_OMIT_SUBQUERY) -SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ +SQLITE_PRIVATE SrcList *tdsqlite3SrcListDup(tdsqlite3 *db, SrcList *p, int flags){ SrcList *pNew; int i; int nByte; assert( db!=0 ); if( p==0 ) return 0; nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); - pNew = sqlite3DbMallocRawNN(db, nByte ); + pNew = tdsqlite3DbMallocRawNN(db, nByte ); if( pNew==0 ) return 0; pNew->nSrc = pNew->nAlloc = p->nSrc; for(i=0; i<p->nSrc; i++){ @@ -94156,86 +103799,98 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ struct SrcList_item *pOldItem = &p->a[i]; Table *pTab; pNewItem->pSchema = pOldItem->pSchema; - pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); - pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); - pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); + pNewItem->zDatabase = tdsqlite3DbStrDup(db, pOldItem->zDatabase); + pNewItem->zName = tdsqlite3DbStrDup(db, pOldItem->zName); + pNewItem->zAlias = tdsqlite3DbStrDup(db, pOldItem->zAlias); pNewItem->fg = pOldItem->fg; pNewItem->iCursor = pOldItem->iCursor; pNewItem->addrFillSub = pOldItem->addrFillSub; pNewItem->regReturn = pOldItem->regReturn; if( pNewItem->fg.isIndexedBy ){ - pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy); + pNewItem->u1.zIndexedBy = tdsqlite3DbStrDup(db, pOldItem->u1.zIndexedBy); } pNewItem->pIBIndex = pOldItem->pIBIndex; if( pNewItem->fg.isTabFunc ){ pNewItem->u1.pFuncArg = - sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags); + tdsqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags); } pTab = pNewItem->pTab = pOldItem->pTab; if( pTab ){ - pTab->nRef++; + pTab->nTabRef++; } - pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); - pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags); - pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); + pNewItem->pSelect = tdsqlite3SelectDup(db, pOldItem->pSelect, flags); + pNewItem->pOn = tdsqlite3ExprDup(db, pOldItem->pOn, flags); + pNewItem->pUsing = tdsqlite3IdListDup(db, pOldItem->pUsing); pNewItem->colUsed = pOldItem->colUsed; } return pNew; } -SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ +SQLITE_PRIVATE IdList *tdsqlite3IdListDup(tdsqlite3 *db, IdList *p){ IdList *pNew; int i; assert( db!=0 ); if( p==0 ) return 0; - pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); + pNew = tdsqlite3DbMallocRawNN(db, sizeof(*pNew) ); if( pNew==0 ) return 0; pNew->nId = p->nId; - pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) ); + pNew->a = tdsqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) ); if( pNew->a==0 ){ - sqlite3DbFree(db, pNew); + tdsqlite3DbFreeNN(db, pNew); return 0; } /* Note that because the size of the allocation for p->a[] is not - ** necessarily a power of two, sqlite3IdListAppend() may not be called + ** necessarily a power of two, tdsqlite3IdListAppend() may not be called ** on the duplicate created by this function. */ for(i=0; i<p->nId; i++){ struct IdList_item *pNewItem = &pNew->a[i]; struct IdList_item *pOldItem = &p->a[i]; - pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); + pNewItem->zName = tdsqlite3DbStrDup(db, pOldItem->zName); pNewItem->idx = pOldItem->idx; } return pNew; } -SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ - Select *pNew, *pPrior; +SQLITE_PRIVATE Select *tdsqlite3SelectDup(tdsqlite3 *db, Select *pDup, int flags){ + Select *pRet = 0; + Select *pNext = 0; + Select **pp = &pRet; + Select *p; + assert( db!=0 ); - if( p==0 ) return 0; - pNew = sqlite3DbMallocRawNN(db, sizeof(*p) ); - if( pNew==0 ) return 0; - pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); - pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); - pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); - pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); - pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); - pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); - pNew->op = p->op; - pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags); - if( pPrior ) pPrior->pNext = pNew; - pNew->pNext = 0; - pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); - pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags); - pNew->iLimit = 0; - pNew->iOffset = 0; - pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; - pNew->addrOpenEphm[0] = -1; - pNew->addrOpenEphm[1] = -1; - pNew->nSelectRow = p->nSelectRow; - pNew->pWith = withDup(db, p->pWith); - sqlite3SelectSetName(pNew, p->zSelName); - return pNew; + for(p=pDup; p; p=p->pPrior){ + Select *pNew = tdsqlite3DbMallocRawNN(db, sizeof(*p) ); + if( pNew==0 ) break; + pNew->pEList = tdsqlite3ExprListDup(db, p->pEList, flags); + pNew->pSrc = tdsqlite3SrcListDup(db, p->pSrc, flags); + pNew->pWhere = tdsqlite3ExprDup(db, p->pWhere, flags); + pNew->pGroupBy = tdsqlite3ExprListDup(db, p->pGroupBy, flags); + pNew->pHaving = tdsqlite3ExprDup(db, p->pHaving, flags); + pNew->pOrderBy = tdsqlite3ExprListDup(db, p->pOrderBy, flags); + pNew->op = p->op; + pNew->pNext = pNext; + pNew->pPrior = 0; + pNew->pLimit = tdsqlite3ExprDup(db, p->pLimit, flags); + pNew->iLimit = 0; + pNew->iOffset = 0; + pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; + pNew->addrOpenEphm[0] = -1; + pNew->addrOpenEphm[1] = -1; + pNew->nSelectRow = p->nSelectRow; + pNew->pWith = withDup(db, p->pWith); +#ifndef SQLITE_OMIT_WINDOWFUNC + pNew->pWin = 0; + pNew->pWinDefn = tdsqlite3WindowListDup(db, p->pWinDefn); + if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew); +#endif + pNew->selId = p->selId; + *pp = pNew; + pp = &pNew->pPrior; + pNext = pNew; + } + + return pRet; } #else -SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ +SQLITE_PRIVATE Select *tdsqlite3SelectDup(tdsqlite3 *db, Select *p, int flags){ assert( p==0 ); return 0; } @@ -94246,46 +103901,51 @@ SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ ** Add a new element to the end of an expression list. If pList is ** initially NULL, then create a new expression list. ** +** The pList argument must be either NULL or a pointer to an ExprList +** obtained from a prior call to tdsqlite3ExprListAppend(). This routine +** may not be used with an ExprList obtained from tdsqlite3ExprListDup(). +** Reason: This routine assumes that the number of slots in pList->a[] +** is a power of two. That is true for tdsqlite3ExprListAppend() returns +** but is not necessarily true from the return value of tdsqlite3ExprListDup(). +** ** If a memory allocation error occurs, the entire list is freed and ** NULL is returned. If non-NULL is returned, then it is guaranteed ** that the new entry was successfully appended. */ -SQLITE_PRIVATE ExprList *sqlite3ExprListAppend( +SQLITE_PRIVATE ExprList *tdsqlite3ExprListAppend( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to append. Might be NULL */ Expr *pExpr /* Expression to be appended. Might be NULL */ ){ - sqlite3 *db = pParse->db; + struct ExprList_item *pItem; + tdsqlite3 *db = pParse->db; assert( db!=0 ); if( pList==0 ){ - pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) ); + pList = tdsqlite3DbMallocRawNN(db, sizeof(ExprList) ); if( pList==0 ){ goto no_mem; } pList->nExpr = 0; - pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0])); - if( pList->a==0 ) goto no_mem; }else if( (pList->nExpr & (pList->nExpr-1))==0 ){ - struct ExprList_item *a; - assert( pList->nExpr>0 ); - a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0])); - if( a==0 ){ + ExprList *pNew; + pNew = tdsqlite3DbRealloc(db, pList, + sizeof(*pList)+(2*(tdsqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0])); + if( pNew==0 ){ goto no_mem; } - pList->a = a; - } - assert( pList->a!=0 ); - if( 1 ){ - struct ExprList_item *pItem = &pList->a[pList->nExpr++]; - memset(pItem, 0, sizeof(*pItem)); - pItem->pExpr = pExpr; + pList = pNew; } + pItem = &pList->a[pList->nExpr++]; + assert( offsetof(struct ExprList_item,zEName)==sizeof(pItem->pExpr) ); + assert( offsetof(struct ExprList_item,pExpr)==0 ); + memset(&pItem->zEName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zEName)); + pItem->pExpr = pExpr; return pList; no_mem: /* Avoid leaking memory if malloc has failed. */ - sqlite3ExprDelete(db, pExpr); - sqlite3ExprListDelete(db, pList); + tdsqlite3ExprDelete(db, pExpr); + tdsqlite3ExprListDelete(db, pList); return 0; } @@ -94297,16 +103957,16 @@ no_mem: ** Or: (a,b,c) = (SELECT x,y,z FROM ....) ** ** For each term of the vector assignment, append new entries to the -** expression list pList. In the case of a subquery on the LHS, append +** expression list pList. In the case of a subquery on the RHS, append ** TK_SELECT_COLUMN expressions. */ -SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector( +SQLITE_PRIVATE ExprList *tdsqlite3ExprListAppendVector( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to append. Might be NULL */ IdList *pColumns, /* List of names of LHS of the assignment */ Expr *pExpr /* Vector expression to be appended. Might be NULL */ ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; int n; int i; int iFirst = pList ? pList->nExpr : 0; @@ -94314,58 +103974,95 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector( ** exit prior to this routine being invoked */ if( NEVER(pColumns==0) ) goto vector_append_error; if( pExpr==0 ) goto vector_append_error; - n = sqlite3ExprVectorSize(pExpr); - if( pColumns->nId!=n ){ - sqlite3ErrorMsg(pParse, "%d columns assigned %d values", + + /* If the RHS is a vector, then we can immediately check to see that + ** the size of the RHS and LHS match. But if the RHS is a SELECT, + ** wildcards ("*") in the result set of the SELECT must be expanded before + ** we can do the size check, so defer the size check until code generation. + */ + if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=tdsqlite3ExprVectorSize(pExpr)) ){ + tdsqlite3ErrorMsg(pParse, "%d columns assigned %d values", pColumns->nId, n); goto vector_append_error; } - for(i=0; i<n; i++){ - Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i); - pList = sqlite3ExprListAppend(pParse, pList, pSubExpr); + + for(i=0; i<pColumns->nId; i++){ + Expr *pSubExpr = tdsqlite3ExprForVectorField(pParse, pExpr, i); + assert( pSubExpr!=0 || db->mallocFailed ); + assert( pSubExpr==0 || pSubExpr->iTable==0 ); + if( pSubExpr==0 ) continue; + pSubExpr->iTable = pColumns->nId; + pList = tdsqlite3ExprListAppend(pParse, pList, pSubExpr); if( pList ){ assert( pList->nExpr==iFirst+i+1 ); - pList->a[pList->nExpr-1].zName = pColumns->a[i].zName; + pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName; pColumns->a[i].zName = 0; } } - if( pExpr->op==TK_SELECT ){ - if( pList && pList->a[iFirst].pExpr ){ - assert( pList->a[iFirst].pExpr->op==TK_SELECT_COLUMN ); - pList->a[iFirst].pExpr->pRight = pExpr; - pExpr = 0; - } + + if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){ + Expr *pFirst = pList->a[iFirst].pExpr; + assert( pFirst!=0 ); + assert( pFirst->op==TK_SELECT_COLUMN ); + + /* Store the SELECT statement in pRight so it will be deleted when + ** tdsqlite3ExprListDelete() is called */ + pFirst->pRight = pExpr; + pExpr = 0; + + /* Remember the size of the LHS in iTable so that we can check that + ** the RHS and LHS sizes match during code generation. */ + pFirst->iTable = pColumns->nId; } vector_append_error: - sqlite3ExprDelete(db, pExpr); - sqlite3IdListDelete(db, pColumns); + tdsqlite3ExprUnmapAndDelete(pParse, pExpr); + tdsqlite3IdListDelete(db, pColumns); return pList; } /* ** Set the sort order for the last element on the given ExprList. */ -SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){ +SQLITE_PRIVATE void tdsqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){ + struct ExprList_item *pItem; if( p==0 ) return; - assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 ); assert( p->nExpr>0 ); - if( iSortOrder<0 ){ - assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC ); - return; + + assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 ); + assert( iSortOrder==SQLITE_SO_UNDEFINED + || iSortOrder==SQLITE_SO_ASC + || iSortOrder==SQLITE_SO_DESC + ); + assert( eNulls==SQLITE_SO_UNDEFINED + || eNulls==SQLITE_SO_ASC + || eNulls==SQLITE_SO_DESC + ); + + pItem = &p->a[p->nExpr-1]; + assert( pItem->bNulls==0 ); + if( iSortOrder==SQLITE_SO_UNDEFINED ){ + iSortOrder = SQLITE_SO_ASC; + } + pItem->sortFlags = (u8)iSortOrder; + + if( eNulls!=SQLITE_SO_UNDEFINED ){ + pItem->bNulls = 1; + if( iSortOrder!=eNulls ){ + pItem->sortFlags |= KEYINFO_ORDER_BIGNULL; + } } - p->a[p->nExpr-1].sortOrder = (u8)iSortOrder; } /* -** Set the ExprList.a[].zName element of the most recently added item +** Set the ExprList.a[].zEName element of the most recently added item ** on the expression list. ** ** pList might be NULL following an OOM error. But pName should never be ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag ** is set. */ -SQLITE_PRIVATE void sqlite3ExprListSetName( +SQLITE_PRIVATE void tdsqlite3ExprListSetName( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to add the span. */ Token *pName, /* Name to be added */ @@ -94376,9 +104073,13 @@ SQLITE_PRIVATE void sqlite3ExprListSetName( struct ExprList_item *pItem; assert( pList->nExpr>0 ); pItem = &pList->a[pList->nExpr-1]; - assert( pItem->zName==0 ); - pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); - if( dequote ) sqlite3Dequote(pItem->zName); + assert( pItem->zEName==0 ); + assert( pItem->eEName==ENAME_NAME ); + pItem->zEName = tdsqlite3DbStrNDup(pParse->db, pName->z, pName->n); + if( dequote ) tdsqlite3Dequote(pItem->zEName); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName); + } } } @@ -94390,20 +104091,21 @@ SQLITE_PRIVATE void sqlite3ExprListSetName( ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag ** is set. */ -SQLITE_PRIVATE void sqlite3ExprListSetSpan( +SQLITE_PRIVATE void tdsqlite3ExprListSetSpan( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to add the span. */ - ExprSpan *pSpan /* The span to be added */ + const char *zStart, /* Start of the span */ + const char *zEnd /* End of the span */ ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; assert( pList!=0 || db->mallocFailed!=0 ); if( pList ){ struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; assert( pList->nExpr>0 ); - assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr ); - sqlite3DbFree(db, pItem->zSpan); - pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart, - (int)(pSpan->zEnd - pSpan->zStart)); + if( pItem->zEName==0 ){ + pItem->zEName = tdsqlite3DbSpanDup(db, zStart, zEnd); + pItem->eEName = ENAME_SPAN; + } } } @@ -94411,7 +104113,7 @@ SQLITE_PRIVATE void sqlite3ExprListSetSpan( ** If the expression list pEList contains more than iLimit elements, ** leave an error message in pParse. */ -SQLITE_PRIVATE void sqlite3ExprListCheckLength( +SQLITE_PRIVATE void tdsqlite3ExprListCheckLength( Parse *pParse, ExprList *pEList, const char *zObject @@ -94420,26 +104122,25 @@ SQLITE_PRIVATE void sqlite3ExprListCheckLength( testcase( pEList && pEList->nExpr==mx ); testcase( pEList && pEList->nExpr==mx+1 ); if( pEList && pEList->nExpr>mx ){ - sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); + tdsqlite3ErrorMsg(pParse, "too many columns in %s", zObject); } } /* ** Delete an entire expression list. */ -static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){ - int i; - struct ExprList_item *pItem; - assert( pList->a!=0 || pList->nExpr==0 ); - for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ - sqlite3ExprDelete(db, pItem->pExpr); - sqlite3DbFree(db, pItem->zName); - sqlite3DbFree(db, pItem->zSpan); - } - sqlite3DbFree(db, pList->a); - sqlite3DbFree(db, pList); +static SQLITE_NOINLINE void exprListDeleteNN(tdsqlite3 *db, ExprList *pList){ + int i = pList->nExpr; + struct ExprList_item *pItem = pList->a; + assert( pList->nExpr>0 ); + do{ + tdsqlite3ExprDelete(db, pItem->pExpr); + tdsqlite3DbFree(db, pItem->zEName); + pItem++; + }while( --i>0 ); + tdsqlite3DbFreeNN(db, pList); } -SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ +SQLITE_PRIVATE void tdsqlite3ExprListDelete(tdsqlite3 *db, ExprList *pList){ if( pList ) exprListDeleteNN(db, pList); } @@ -94447,20 +104148,105 @@ SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ ** Return the bitwise-OR of all Expr.flags fields in the given ** ExprList. */ -SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){ +SQLITE_PRIVATE u32 tdsqlite3ExprListFlags(const ExprList *pList){ int i; u32 m = 0; - if( pList ){ - for(i=0; i<pList->nExpr; i++){ - Expr *pExpr = pList->a[i].pExpr; - assert( pExpr!=0 ); - m |= pExpr->flags; - } + assert( pList!=0 ); + for(i=0; i<pList->nExpr; i++){ + Expr *pExpr = pList->a[i].pExpr; + assert( pExpr!=0 ); + m |= pExpr->flags; } return m; } /* +** This is a SELECT-node callback for the expression walker that +** always "fails". By "fail" in this case, we mean set +** pWalker->eCode to zero and abort. +** +** This callback is used by multiple expression walkers. +*/ +SQLITE_PRIVATE int tdsqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){ + UNUSED_PARAMETER(NotUsed); + pWalker->eCode = 0; + return WRC_Abort; +} + +/* +** Check the input string to see if it is "true" or "false" (in any case). +** +** If the string is.... Return +** "true" EP_IsTrue +** "false" EP_IsFalse +** anything else 0 +*/ +SQLITE_PRIVATE u32 tdsqlite3IsTrueOrFalse(const char *zIn){ + if( tdsqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue; + if( tdsqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse; + return 0; +} + + +/* +** If the input expression is an ID with the name "true" or "false" +** then convert it into an TK_TRUEFALSE term. Return non-zero if +** the conversion happened, and zero if the expression is unaltered. +*/ +SQLITE_PRIVATE int tdsqlite3ExprIdToTrueFalse(Expr *pExpr){ + u32 v; + assert( pExpr->op==TK_ID || pExpr->op==TK_STRING ); + if( !ExprHasProperty(pExpr, EP_Quoted) + && (v = tdsqlite3IsTrueOrFalse(pExpr->u.zToken))!=0 + ){ + pExpr->op = TK_TRUEFALSE; + ExprSetProperty(pExpr, v); + return 1; + } + return 0; +} + +/* +** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE +** and 0 if it is FALSE. +*/ +SQLITE_PRIVATE int tdsqlite3ExprTruthValue(const Expr *pExpr){ + pExpr = tdsqlite3ExprSkipCollate((Expr*)pExpr); + assert( pExpr->op==TK_TRUEFALSE ); + assert( tdsqlite3StrICmp(pExpr->u.zToken,"true")==0 + || tdsqlite3StrICmp(pExpr->u.zToken,"false")==0 ); + return pExpr->u.zToken[4]==0; +} + +/* +** If pExpr is an AND or OR expression, try to simplify it by eliminating +** terms that are always true or false. Return the simplified expression. +** Or return the original expression if no simplification is possible. +** +** Examples: +** +** (x<10) AND true => (x<10) +** (x<10) AND false => false +** (x<10) AND (y=22 OR false) => (x<10) AND (y=22) +** (x<10) AND (y=22 OR true) => (x<10) +** (y=22) OR true => true +*/ +SQLITE_PRIVATE Expr *tdsqlite3ExprSimplifiedAndOr(Expr *pExpr){ + assert( pExpr!=0 ); + if( pExpr->op==TK_AND || pExpr->op==TK_OR ){ + Expr *pRight = tdsqlite3ExprSimplifiedAndOr(pExpr->pRight); + Expr *pLeft = tdsqlite3ExprSimplifiedAndOr(pExpr->pLeft); + if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){ + pExpr = pExpr->op==TK_AND ? pRight : pLeft; + }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){ + pExpr = pExpr->op==TK_AND ? pLeft : pRight; + } + } + return pExpr; +} + + +/* ** These routines are Walker callbacks used to check expressions to ** see if they are "constant" for some definition of constant. The ** Walker.eCode value determines the type of "constant" we are looking @@ -94468,18 +104254,19 @@ SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){ ** ** These callback routines are used to implement the following: ** -** sqlite3ExprIsConstant() pWalker->eCode==1 -** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2 -** sqlite3ExprIsTableConstant() pWalker->eCode==3 -** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 +** tdsqlite3ExprIsConstant() pWalker->eCode==1 +** tdsqlite3ExprIsConstantNotJoin() pWalker->eCode==2 +** tdsqlite3ExprIsTableConstant() pWalker->eCode==3 +** tdsqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 ** ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression ** is found to not be a constant. ** -** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions -** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing -** an existing schema and 4 when processing a new statement. A bound -** parameter raises an error for new statements, but is silently converted +** The tdsqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT +** expressions in a CREATE TABLE statement. The Walker.eCode value is 5 +** when parsing an existing schema out of the sqlite_master table and 4 +** when processing a new CREATE TABLE statement. A bound parameter raises +** an error for new statements, but is silently converted ** to NULL for existing schemas. This allows sqlite_master tables that ** contain a bound parameter because they were generated by older versions ** of SQLite to be parsed by newer versions of SQLite without raising a @@ -94500,13 +104287,22 @@ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ ** and either pWalker->eCode==4 or 5 or the function has the ** SQLITE_FUNC_CONST flag. */ case TK_FUNCTION: - if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){ + if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc)) + && !ExprHasProperty(pExpr, EP_WinFunc) + ){ + if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL); return WRC_Continue; }else{ pWalker->eCode = 0; return WRC_Abort; } case TK_ID: + /* Convert "true" or "false" in a DEFAULT clause into the + ** appropriate TK_TRUEFALSE operator */ + if( tdsqlite3ExprIdToTrueFalse(pExpr) ){ + return WRC_Prune; + } + /* Fall thru */ case TK_COLUMN: case TK_AGG_FUNCTION: case TK_AGG_COLUMN: @@ -94514,12 +104310,19 @@ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ testcase( pExpr->op==TK_COLUMN ); testcase( pExpr->op==TK_AGG_FUNCTION ); testcase( pExpr->op==TK_AGG_COLUMN ); + if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){ + return WRC_Continue; + } if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){ return WRC_Continue; - }else{ - pWalker->eCode = 0; - return WRC_Abort; } + /* Fall through */ + case TK_IF_NULL_ROW: + case TK_REGISTER: + testcase( pExpr->op==TK_REGISTER ); + testcase( pExpr->op==TK_IF_NULL_ROW ); + pWalker->eCode = 0; + return WRC_Abort; case TK_VARIABLE: if( pWalker->eCode==5 ){ /* Silently convert bound parameters that appear inside of CREATE @@ -94528,30 +104331,27 @@ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ pExpr->op = TK_NULL; }else if( pWalker->eCode==4 ){ /* A bound parameter in a CREATE statement that originates from - ** sqlite3_prepare() causes an error */ + ** tdsqlite3_prepare() causes an error */ pWalker->eCode = 0; return WRC_Abort; } /* Fall through */ default: - testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */ - testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */ + testcase( pExpr->op==TK_SELECT ); /* tdsqlite3SelectWalkFail() disallows */ + testcase( pExpr->op==TK_EXISTS ); /* tdsqlite3SelectWalkFail() disallows */ return WRC_Continue; } } -static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){ - UNUSED_PARAMETER(NotUsed); - pWalker->eCode = 0; - return WRC_Abort; -} static int exprIsConst(Expr *p, int initFlag, int iCur){ Walker w; - memset(&w, 0, sizeof(w)); w.eCode = initFlag; w.xExprCallback = exprNodeIsConstant; - w.xSelectCallback = selectNodeIsConstant; + w.xSelectCallback = tdsqlite3SelectWalkFail; +#ifdef SQLITE_DEBUG + w.xSelectCallback2 = tdsqlite3SelectWalkAssert2; +#endif w.u.iCur = iCur; - sqlite3WalkExpr(&w, p); + tdsqlite3WalkExpr(&w, p); return w.eCode; } @@ -94563,17 +104363,24 @@ static int exprIsConst(Expr *p, int initFlag, int iCur){ ** is considered a variable but a single-quoted string (ex: 'abc') is ** a constant. */ -SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){ +SQLITE_PRIVATE int tdsqlite3ExprIsConstant(Expr *p){ return exprIsConst(p, 1, 0); } /* -** Walk an expression tree. Return non-zero if the expression is constant -** that does no originate from the ON or USING clauses of a join. -** Return 0 if it involves variables or function calls or terms from -** an ON or USING clause. +** Walk an expression tree. Return non-zero if +** +** (1) the expression is constant, and +** (2) the expression does originate in the ON or USING clause +** of a LEFT JOIN, and +** (3) the expression does not contain any EP_FixedCol TK_COLUMN +** operands created by the constant propagation optimization. +** +** When this routine returns true, it indicates that the expression +** can be added to the pParse->pConstExpr list and evaluated once when +** the prepared statement starts up. See tdsqlite3ExprCodeAtInit(). */ -SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){ +SQLITE_PRIVATE int tdsqlite3ExprIsConstantNotJoin(Expr *p){ return exprIsConst(p, 2, 0); } @@ -94583,20 +104390,91 @@ SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){ ** expression must not refer to any non-deterministic function nor any ** table other than iCur. */ -SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){ +SQLITE_PRIVATE int tdsqlite3ExprIsTableConstant(Expr *p, int iCur){ return exprIsConst(p, 3, iCur); } + /* -** Walk an expression tree. Return non-zero if the expression is constant -** or a function call with constant arguments. Return and 0 if there -** are any variables. +** tdsqlite3WalkExpr() callback used by tdsqlite3ExprIsConstantOrGroupBy(). +*/ +static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){ + ExprList *pGroupBy = pWalker->u.pGroupBy; + int i; + + /* Check if pExpr is identical to any GROUP BY term. If so, consider + ** it constant. */ + for(i=0; i<pGroupBy->nExpr; i++){ + Expr *p = pGroupBy->a[i].pExpr; + if( tdsqlite3ExprCompare(0, pExpr, p, -1)<2 ){ + CollSeq *pColl = tdsqlite3ExprNNCollSeq(pWalker->pParse, p); + if( tdsqlite3IsBinary(pColl) ){ + return WRC_Prune; + } + } + } + + /* Check if pExpr is a sub-select. If so, consider it variable. */ + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + pWalker->eCode = 0; + return WRC_Abort; + } + + return exprNodeIsConstant(pWalker, pExpr); +} + +/* +** Walk the expression tree passed as the first argument. Return non-zero +** if the expression consists entirely of constants or copies of terms +** in pGroupBy that sort with the BINARY collation sequence. +** +** This routine is used to determine if a term of the HAVING clause can +** be promoted into the WHERE clause. In order for such a promotion to work, +** the value of the HAVING clause term must be the same for all members of +** a "group". The requirement that the GROUP BY term must be BINARY +** assumes that no other collating sequence will have a finer-grained +** grouping than binary. In other words (A=B COLLATE binary) implies +** A=B in every other collating sequence. The requirement that the +** GROUP BY be BINARY is stricter than necessary. It would also work +** to promote HAVING clauses that use the same alternative collating +** sequence as the GROUP BY term, but that is much harder to check, +** alternative collating sequences are uncommon, and this is only an +** optimization, so we take the easy way out and simply require the +** GROUP BY to use the BINARY collating sequence. +*/ +SQLITE_PRIVATE int tdsqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){ + Walker w; + w.eCode = 1; + w.xExprCallback = exprNodeIsConstantOrGroupBy; + w.xSelectCallback = 0; + w.u.pGroupBy = pGroupBy; + w.pParse = pParse; + tdsqlite3WalkExpr(&w, p); + return w.eCode; +} + +/* +** Walk an expression tree for the DEFAULT field of a column definition +** in a CREATE TABLE statement. Return non-zero if the expression is +** acceptable for use as a DEFAULT. That is to say, return non-zero if +** the expression is constant or a function call with constant arguments. +** Return and 0 if there are any variables. +** +** isInit is true when parsing from sqlite_master. isInit is false when +** processing a new CREATE TABLE statement. When isInit is true, parameters +** (such as ? or $abc) in the expression are converted into NULL. When +** isInit is false, parameters raise an error. Parameters should not be +** allowed in a CREATE TABLE statement, but some legacy versions of SQLite +** allowed it, so we need to support it when reading sqlite_master for +** backwards compatibility. +** +** If isInit is true, set EP_FromDDL on every TK_FUNCTION node. ** ** For the purposes of this function, a double-quoted string (ex: "abc") ** is considered a variable but a single-quoted string (ex: 'abc') is ** a constant. */ -SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ +SQLITE_PRIVATE int tdsqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ assert( isInit==0 || isInit==1 ); return exprIsConst(p, 4+isInit, 0); } @@ -94606,13 +104484,15 @@ SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ ** Walk an expression tree. Return 1 if the expression contains a ** subquery of some kind. Return 0 if there are no subqueries. */ -SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){ +SQLITE_PRIVATE int tdsqlite3ExprContainsSubquery(Expr *p){ Walker w; - memset(&w, 0, sizeof(w)); w.eCode = 1; - w.xExprCallback = sqlite3ExprWalkNoop; - w.xSelectCallback = selectNodeIsConstant; - sqlite3WalkExpr(&w, p); + w.xExprCallback = tdsqlite3ExprWalkNoop; + w.xSelectCallback = tdsqlite3SelectWalkFail; +#ifdef SQLITE_DEBUG + w.xSelectCallback2 = tdsqlite3SelectWalkAssert2; +#endif + tdsqlite3WalkExpr(&w, p); return w.eCode==0; } #endif @@ -94623,13 +104503,14 @@ SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){ ** in *pValue. If the expression is not an integer or if it is too big ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. */ -SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){ +SQLITE_PRIVATE int tdsqlite3ExprIsInteger(Expr *p, int *pValue){ int rc = 0; + if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */ /* If an expression is an integer literal that fits in a signed 32-bit ** integer, then the EP_IntValue flag will have already been set */ assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 - || sqlite3GetInt32(p->u.zToken, &rc)==0 ); + || tdsqlite3GetInt32(p->u.zToken, &rc)==0 ); if( p->flags & EP_IntValue ){ *pValue = p->u.iValue; @@ -94637,12 +104518,12 @@ SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){ } switch( p->op ){ case TK_UPLUS: { - rc = sqlite3ExprIsInteger(p->pLeft, pValue); + rc = tdsqlite3ExprIsInteger(p->pLeft, pValue); break; } case TK_UMINUS: { int v; - if( sqlite3ExprIsInteger(p->pLeft, &v) ){ + if( tdsqlite3ExprIsInteger(p->pLeft, &v) ){ assert( v!=(-2147483647-1) ); *pValue = -v; rc = 1; @@ -94668,9 +104549,11 @@ SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){ ** will likely result in an incorrect answer. So when in doubt, return ** TRUE. */ -SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){ +SQLITE_PRIVATE int tdsqlite3ExprCanBeNull(const Expr *p){ u8 op; - while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } + while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ + p = p->pLeft; + } op = p->op; if( op==TK_REGISTER ) op = p->op2; switch( op ){ @@ -94680,9 +104563,11 @@ SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){ case TK_BLOB: return 0; case TK_COLUMN: - assert( p->pTab!=0 ); return ExprHasProperty(p, EP_CanBeNull) || - (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0); + p->y.pTab==0 || /* Reference to column of index on expression */ + (p->iColumn>=0 + && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */ + && p->y.pTab->aCol[p->iColumn].notNull==0); default: return 1; } @@ -94698,29 +104583,32 @@ SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){ ** is harmless. A false positive, however, can result in the wrong ** answer. */ -SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ +SQLITE_PRIVATE int tdsqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ u8 op; + int unaryMinus = 0; if( aff==SQLITE_AFF_BLOB ) return 1; - while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } + while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ + if( p->op==TK_UMINUS ) unaryMinus = 1; + p = p->pLeft; + } op = p->op; if( op==TK_REGISTER ) op = p->op2; switch( op ){ case TK_INTEGER: { - return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC; + return aff>=SQLITE_AFF_NUMERIC; } case TK_FLOAT: { - return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC; + return aff>=SQLITE_AFF_NUMERIC; } case TK_STRING: { - return aff==SQLITE_AFF_TEXT; + return !unaryMinus && aff==SQLITE_AFF_TEXT; } case TK_BLOB: { - return 1; + return !unaryMinus; } case TK_COLUMN: { assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ - return p->iColumn<0 - && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC); + return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0; } default: { return 0; @@ -94731,10 +104619,10 @@ SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ /* ** Return TRUE if the given string is a row-id column name. */ -SQLITE_PRIVATE int sqlite3IsRowid(const char *z){ - if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; - if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; - if( sqlite3StrICmp(z, "OID")==0 ) return 1; +SQLITE_PRIVATE int tdsqlite3IsRowid(const char *z){ + if( tdsqlite3StrICmp(z, "_ROWID_")==0 ) return 1; + if( tdsqlite3StrICmp(z, "ROWID")==0 ) return 1; + if( tdsqlite3StrICmp(z, "OID")==0 ) return 1; return 0; } @@ -94763,7 +104651,6 @@ static Select *isCandidateForInOpt(Expr *pX){ } assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ if( p->pLimit ) return 0; /* Has no LIMIT clause */ - assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */ if( p->pWhere ) return 0; /* Has no WHERE clause */ pSrc = p->pSrc; assert( pSrc!=0 ); @@ -94792,14 +104679,14 @@ static Select *isCandidateForInOpt(Expr *pX){ ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull ** to be set to NULL if iCur contains one or more NULL values. */ -static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ +static void tdsqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ int addr1; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); - addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); - sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); + addr1 = tdsqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); + tdsqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); VdbeComment((v, "first_entry_in(%d)", iCur)); - sqlite3VdbeJumpHere(v, addr1); + tdsqlite3VdbeJumpHere(v, addr1); } #endif @@ -94809,13 +104696,13 @@ static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ ** The argument is an IN operator with a list (not a subquery) on the ** right-hand side. Return TRUE if that list is constant. */ -static int sqlite3InRhsIsConstant(Expr *pIn){ +static int tdsqlite3InRhsIsConstant(Expr *pIn){ Expr *pLHS; int res; assert( !ExprHasProperty(pIn, EP_xIsSelect) ); pLHS = pIn->pLeft; pIn->pLeft = 0; - res = sqlite3ExprIsConstant(pIn); + res = tdsqlite3ExprIsConstant(pIn); pIn->pLeft = pLHS; return res; } @@ -94853,16 +104740,15 @@ static int sqlite3InRhsIsConstant(Expr *pIn){ ** pX->iTable made to point to the ephemeral table instead of an ** existing table. ** -** The inFlags parameter must contain exactly one of the bits -** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains -** IN_INDEX_MEMBERSHIP, then the generated table will be used for a -** fast membership test. When the IN_INDEX_LOOP bit is set, the -** IN index will be used to loop over all values of the RHS of the -** IN operator. +** The inFlags parameter must contain, at a minimum, one of the bits +** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains +** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast +** membership test. When the IN_INDEX_LOOP bit is set, the IN index will +** be used to loop over all values of the RHS of the IN operator. ** ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate ** through the set members) then the b-tree must not contain duplicates. -** An epheremal table must be used unless the selected columns are guaranteed +** An epheremal table will be created unless the selected columns are guaranteed ** to be unique - either because it is an INTEGER PRIMARY KEY or due to ** a UNIQUE constraint or index. ** @@ -94903,18 +104789,19 @@ static int sqlite3InRhsIsConstant(Expr *pIn){ ** then aiMap[] is populated with {2, 0, 1}. */ #ifndef SQLITE_OMIT_SUBQUERY -SQLITE_PRIVATE int sqlite3FindInIndex( +SQLITE_PRIVATE int tdsqlite3FindInIndex( Parse *pParse, /* Parsing context */ - Expr *pX, /* The right-hand side (RHS) of the IN operator */ + Expr *pX, /* The IN expression */ u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */ int *prRhsHasNull, /* Register holding NULL status. See notes */ - int *aiMap /* Mapping from Index fields to RHS fields */ + int *aiMap, /* Mapping from Index fields to RHS fields */ + int *piTab /* OUT: index to use */ ){ Select *p; /* SELECT to the right of IN operator */ int eType = 0; /* Type of RHS table. IN_INDEX_* */ int iTab = pParse->nTab++; /* Cursor of the RHS table */ int mustBeUnique; /* True if RHS must be unique */ - Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ + Vdbe *v = tdsqlite3GetVdbe(pParse); /* Virtual machine being coded */ assert( pX->op==TK_IN ); mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0; @@ -94928,7 +104815,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex( int i; ExprList *pEList = pX->x.pSelect->pEList; for(i=0; i<pEList->nExpr; i++){ - if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break; + if( tdsqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break; } if( i==pEList->nExpr ){ prRhsHasNull = 0; @@ -94939,7 +104826,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex( ** satisfy the query. This is preferable to generating a new ** ephemeral table. */ if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){ - sqlite3 *db = pParse->db; /* Database connection */ + tdsqlite3 *db = pParse->db; /* Database connection */ Table *pTab; /* Table <table>. */ i16 iDb; /* Database idx for pTab */ ExprList *pEList = p->pEList; @@ -94951,20 +104838,21 @@ SQLITE_PRIVATE int sqlite3FindInIndex( pTab = p->pSrc->a[0].pTab; /* Code an OP_Transaction and OP_TableLock for <table>. */ - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - sqlite3CodeVerifySchema(pParse, iDb); - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); + tdsqlite3CodeVerifySchema(pParse, iDb); + tdsqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); - assert(v); /* sqlite3GetVdbe() has always been previously called */ + assert(v); /* tdsqlite3GetVdbe() has always been previously called */ if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){ /* The "x IN (SELECT rowid FROM table)" case */ - int iAddr = sqlite3VdbeAddOp0(v, OP_Once); + int iAddr = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); + tdsqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); eType = IN_INDEX_ROWID; - - sqlite3VdbeJumpHere(v, iAddr); + ExplainQueryPlan((pParse, 0, + "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName)); + tdsqlite3VdbeJumpHere(v, iAddr); }else{ Index *pIdx; /* Iterator variable */ int affinity_ok = 1; @@ -94975,24 +104863,24 @@ SQLITE_PRIVATE int sqlite3FindInIndex( ** on the RHS of the IN operator. If it not, it is not possible to ** use any index of the RHS table. */ for(i=0; i<nExpr && affinity_ok; i++){ - Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); + Expr *pLhs = tdsqlite3VectorFieldSubexpr(pX->pLeft, i); int iCol = pEList->a[i].pExpr->iColumn; - char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */ - char cmpaff = sqlite3CompareAffinity(pLhs, idxaff); + char idxaff = tdsqlite3TableColumnAffinity(pTab,iCol); /* RHS table */ + char cmpaff = tdsqlite3CompareAffinity(pLhs, idxaff); testcase( cmpaff==SQLITE_AFF_BLOB ); testcase( cmpaff==SQLITE_AFF_TEXT ); switch( cmpaff ){ case SQLITE_AFF_BLOB: break; case SQLITE_AFF_TEXT: - /* sqlite3CompareAffinity() only returns TEXT if one side or the + /* tdsqlite3CompareAffinity() only returns TEXT if one side or the ** other has no affinity and the other side is TEXT. Hence, ** the only way for cmpaff to be TEXT is for idxaff to be TEXT ** and for the term on the LHS of the IN to have no affinity. */ assert( idxaff==SQLITE_AFF_TEXT ); break; default: - affinity_ok = sqlite3IsNumericAffinity(idxaff); + affinity_ok = tdsqlite3IsNumericAffinity(idxaff); } } @@ -95002,6 +104890,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex( Bitmask colUsed; /* Columns of the index used */ Bitmask mCol; /* Mask for the current column */ if( pIdx->nColumn<nExpr ) continue; + if( pIdx->pPartIdxWhere!=0 ) continue; /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute ** BITMASK(nExpr) without overflowing */ testcase( pIdx->nColumn==BMS-2 ); @@ -95017,16 +104906,16 @@ SQLITE_PRIVATE int sqlite3FindInIndex( colUsed = 0; /* Columns of index used so far */ for(i=0; i<nExpr; i++){ - Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); + Expr *pLhs = tdsqlite3VectorFieldSubexpr(pX->pLeft, i); Expr *pRhs = pEList->a[i].pExpr; - CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); + CollSeq *pReq = tdsqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); int j; assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr ); for(j=0; j<nExpr; j++){ if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue; assert( pIdx->azColl[j] ); - if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){ + if( pReq!=0 && tdsqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){ continue; } break; @@ -95041,14 +104930,11 @@ SQLITE_PRIVATE int sqlite3FindInIndex( assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) ); if( colUsed==(MASKBIT(nExpr)-1) ){ /* If we reach this point, that means the index pIdx is usable */ - int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); -#ifndef SQLITE_OMIT_EXPLAIN - sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0, - sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName), - P4_DYNAMIC); -#endif - sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); + int iAddr = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); + ExplainQueryPlan((pParse, 0, + "USING INDEX %s FOR IN-OPERATOR",pIdx->zName)); + tdsqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); + tdsqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "%s", pIdx->zName)); assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; @@ -95056,15 +104942,15 @@ SQLITE_PRIVATE int sqlite3FindInIndex( if( prRhsHasNull ){ #ifdef SQLITE_ENABLE_COLUMN_USED_MASK i64 mask = (1<<nExpr)-1; - sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, + tdsqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iTab, 0, 0, (u8*)&mask, P4_INT64); #endif *prRhsHasNull = ++pParse->nMem; if( nExpr==1 ){ - sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull); + tdsqlite3SetHasNullFlag(v, iTab, *prRhsHasNull); } } - sqlite3VdbeJumpHere(v, iAddr); + tdsqlite3VdbeJumpHere(v, iAddr); } } /* End loop over indexes */ } /* End if( affinity_ok ) */ @@ -95081,7 +104967,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex( if( eType==0 && (inFlags & IN_INDEX_NOOP_OK) && !ExprHasProperty(pX, EP_xIsSelect) - && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2) + && (!tdsqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2) ){ eType = IN_INDEX_NOOP; } @@ -95095,23 +104981,23 @@ SQLITE_PRIVATE int sqlite3FindInIndex( eType = IN_INDEX_EPH; if( inFlags & IN_INDEX_LOOP ){ pParse->nQueryLoop = 0; - if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){ - eType = IN_INDEX_ROWID; - } }else if( prRhsHasNull ){ *prRhsHasNull = rMayHaveNull = ++pParse->nMem; } - sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID); + assert( pX->op==TK_IN ); + tdsqlite3CodeRhsOfIN(pParse, pX, iTab); + if( rMayHaveNull ){ + tdsqlite3SetHasNullFlag(v, iTab, rMayHaveNull); + } pParse->nQueryLoop = savedNQueryLoop; - }else{ - pX->iTable = iTab; } if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){ int i, n; - n = sqlite3ExprVectorSize(pX->pLeft); + n = tdsqlite3ExprVectorSize(pX->pLeft); for(i=0; i<n; i++) aiMap[i] = i; } + *piTab = iTab; return eType; } #endif @@ -95123,23 +105009,23 @@ SQLITE_PRIVATE int sqlite3FindInIndex( ** the affinities to be used for each column of the comparison. ** ** It is the responsibility of the caller to ensure that the returned -** string is eventually freed using sqlite3DbFree(). +** string is eventually freed using tdsqlite3DbFree(). */ static char *exprINAffinity(Parse *pParse, Expr *pExpr){ Expr *pLeft = pExpr->pLeft; - int nVal = sqlite3ExprVectorSize(pLeft); + int nVal = tdsqlite3ExprVectorSize(pLeft); Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0; char *zRet; assert( pExpr->op==TK_IN ); - zRet = sqlite3DbMallocZero(pParse->db, nVal+1); + zRet = tdsqlite3DbMallocRaw(pParse->db, nVal+1); if( zRet ){ int i; for(i=0; i<nVal; i++){ - Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i); - char a = sqlite3ExprAffinity(pA); + Expr *pA = tdsqlite3VectorFieldSubexpr(pLeft, i); + char a = tdsqlite3ExprAffinity(pA); if( pSelect ){ - zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a); + zRet[i] = tdsqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a); }else{ zRet[i] = a; } @@ -95157,274 +105043,347 @@ static char *exprINAffinity(Parse *pParse, Expr *pExpr){ ** ** "sub-select returns N columns - expected M" */ -SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){ - const char *zFmt = "sub-select returns %d columns - expected %d"; - sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect); +SQLITE_PRIVATE void tdsqlite3SubselectError(Parse *pParse, int nActual, int nExpect){ + if( pParse->nErr==0 ){ + const char *zFmt = "sub-select returns %d columns - expected %d"; + tdsqlite3ErrorMsg(pParse, zFmt, nActual, nExpect); + } } #endif /* -** Generate code for scalar subqueries used as a subquery expression, EXISTS, -** or IN operators. Examples: +** Expression pExpr is a vector that has been used in a context where +** it is not permitted. If pExpr is a sub-select vector, this routine +** loads the Parse object with a message of the form: ** -** (SELECT a FROM b) -- subquery -** EXISTS (SELECT a FROM b) -- EXISTS subquery -** x IN (4,5,11) -- IN operator with list on right-hand side -** x IN (SELECT a FROM b) -- IN operator with subquery on the right +** "sub-select returns N columns - expected 1" ** -** The pExpr parameter describes the expression that contains the IN -** operator or subquery. +** Or, if it is a regular scalar vector: ** -** If parameter isRowid is non-zero, then expression pExpr is guaranteed -** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference -** to some integer key column of a table B-Tree. In this case, use an -** intkey B-Tree to store the set of IN(...) values instead of the usual -** (slower) variable length keys B-Tree. +** "row value misused" +*/ +SQLITE_PRIVATE void tdsqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){ +#ifndef SQLITE_OMIT_SUBQUERY + if( pExpr->flags & EP_xIsSelect ){ + tdsqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1); + }else +#endif + { + tdsqlite3ErrorMsg(pParse, "row value misused"); + } +} + +#ifndef SQLITE_OMIT_SUBQUERY +/* +** Generate code that will construct an ephemeral table containing all terms +** in the RHS of an IN operator. The IN operator can be in either of two +** forms: ** -** If rMayHaveNull is non-zero, that means that the operation is an IN -** (not a SELECT or EXISTS) and that the RHS might contains NULLs. -** All this routine does is initialize the register given by rMayHaveNull -** to NULL. Calling routines will take care of changing this register -** value to non-NULL if the RHS is NULL-free. +** x IN (4,5,11) -- IN operator with list on right-hand side +** x IN (SELECT a FROM b) -- IN operator with subquery on the right ** -** For a SELECT or EXISTS operator, return the register that holds the -** result. For a multi-column SELECT, the result is stored in a contiguous -** array of registers and the return value is the register of the left-most -** result column. Return 0 for IN operators or if an error occurs. -*/ -#ifndef SQLITE_OMIT_SUBQUERY -SQLITE_PRIVATE int sqlite3CodeSubselect( +** The pExpr parameter is the IN operator. The cursor number for the +** constructed ephermeral table is returned. The first time the ephemeral +** table is computed, the cursor number is also stored in pExpr->iTable, +** however the cursor number returned might not be the same, as it might +** have been duplicated using OP_OpenDup. +** +** If the LHS expression ("x" in the examples) is a column value, or +** the SELECT statement returns a column value, then the affinity of that +** column is used to build the index keys. If both 'x' and the +** SELECT... statement are columns, then numeric affinity is used +** if either column has NUMERIC or INTEGER affinity. If neither +** 'x' nor the SELECT... statement are columns, then numeric affinity +** is used. +*/ +SQLITE_PRIVATE void tdsqlite3CodeRhsOfIN( Parse *pParse, /* Parsing context */ - Expr *pExpr, /* The IN, SELECT, or EXISTS operator */ - int rHasNullFlag, /* Register that records whether NULLs exist in RHS */ - int isRowid /* If true, LHS of IN operator is a rowid */ + Expr *pExpr, /* The IN operator */ + int iTab /* Use this cursor number */ ){ - int jmpIfDynamic = -1; /* One-time test address */ - int rReg = 0; /* Register storing resulting */ - Vdbe *v = sqlite3GetVdbe(pParse); - if( NEVER(v==0) ) return 0; - sqlite3ExprCachePush(pParse); + int addrOnce = 0; /* Address of the OP_Once instruction at top */ + int addr; /* Address of OP_OpenEphemeral instruction */ + Expr *pLeft; /* the LHS of the IN operator */ + KeyInfo *pKeyInfo = 0; /* Key information */ + int nVal; /* Size of vector pLeft */ + Vdbe *v; /* The prepared statement under construction */ - /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it + v = pParse->pVdbe; + assert( v!=0 ); + + /* The evaluation of the IN must be repeated every time it ** is encountered if any of the following is true: ** ** * The right-hand side is a correlated subquery ** * The right-hand side is an expression list containing variables ** * We are inside a trigger ** - ** If all of the above are false, then we can run this code just once - ** save the results, and reuse the same result on subsequent invocations. + ** If all of the above are false, then we can compute the RHS just once + ** and reuse it many names. */ - if( !ExprHasProperty(pExpr, EP_VarSelect) ){ - jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - } + if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){ + /* Reuse of the RHS is allowed */ + /* If this routine has already been coded, but the previous code + ** might not have been invoked yet, so invoke it now as a subroutine. + */ + if( ExprHasProperty(pExpr, EP_Subrtn) ){ + addrOnce = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d", + pExpr->x.pSelect->selId)); + } + tdsqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, + pExpr->y.sub.iAddr); + tdsqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable); + tdsqlite3VdbeJumpHere(v, addrOnce); + return; + } -#ifndef SQLITE_OMIT_EXPLAIN - if( pParse->explain==2 ){ - char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d", - jmpIfDynamic>=0?"":"CORRELATED ", - pExpr->op==TK_IN?"LIST":"SCALAR", - pParse->iNextSelectId - ); - sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); - } -#endif + /* Begin coding the subroutine */ + ExprSetProperty(pExpr, EP_Subrtn); + pExpr->y.sub.regReturn = ++pParse->nMem; + pExpr->y.sub.iAddr = + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1; + VdbeComment((v, "return address")); - switch( pExpr->op ){ - case TK_IN: { - int addr; /* Address of OP_OpenEphemeral instruction */ - Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */ - KeyInfo *pKeyInfo = 0; /* Key information */ - int nVal; /* Size of vector pLeft */ - - nVal = sqlite3ExprVectorSize(pLeft); - assert( !isRowid || nVal==1 ); + addrOnce = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); + } - /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)' - ** expression it is handled the same way. An ephemeral table is - ** filled with index keys representing the results from the - ** SELECT or the <exprlist>. - ** - ** If the 'x' expression is a column value, or the SELECT... - ** statement returns a column value, then the affinity of that - ** column is used to build the index keys. If both 'x' and the - ** SELECT... statement are columns, then numeric affinity is used - ** if either column has NUMERIC or INTEGER affinity. If neither - ** 'x' nor the SELECT... statement are columns, then numeric affinity - ** is used. - */ - pExpr->iTable = pParse->nTab++; - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, - pExpr->iTable, (isRowid?0:nVal)); - pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1); + /* Check to see if this is a vector IN operator */ + pLeft = pExpr->pLeft; + nVal = tdsqlite3ExprVectorSize(pLeft); - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - /* Case 1: expr IN (SELECT ...) - ** - ** Generate code to write the results of the select into the temporary - ** table allocated and opened above. - */ - Select *pSelect = pExpr->x.pSelect; - ExprList *pEList = pSelect->pEList; - - assert( !isRowid ); - /* If the LHS and RHS of the IN operator do not match, that - ** error will have been caught long before we reach this point. */ - if( ALWAYS(pEList->nExpr==nVal) ){ - SelectDest dest; - int i; - sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable); - dest.zAffSdst = exprINAffinity(pParse, pExpr); - assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable ); - pSelect->iLimit = 0; - testcase( pSelect->selFlags & SF_Distinct ); - testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ - if( sqlite3Select(pParse, pSelect, &dest) ){ - sqlite3DbFree(pParse->db, dest.zAffSdst); - sqlite3KeyInfoUnref(pKeyInfo); - return 0; - } - sqlite3DbFree(pParse->db, dest.zAffSdst); - assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ - assert( pEList!=0 ); - assert( pEList->nExpr>0 ); - assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); - for(i=0; i<nVal; i++){ - Expr *p = sqlite3VectorFieldSubexpr(pLeft, i); - pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq( - pParse, p, pEList->a[i].pExpr - ); - } - } - }else if( ALWAYS(pExpr->x.pList!=0) ){ - /* Case 2: expr IN (exprlist) - ** - ** For each expression, build an index key from the evaluation and - ** store it in the temporary table. If <expr> is a column, then use - ** that columns affinity when building index keys. If <expr> is not - ** a column, use numeric affinity. - */ - char affinity; /* Affinity of the LHS of the IN */ - int i; - ExprList *pList = pExpr->x.pList; - struct ExprList_item *pItem; - int r1, r2, r3; + /* Construct the ephemeral table that will contain the content of + ** RHS of the IN operator. + */ + pExpr->iTable = iTab; + addr = tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal); +#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId)); + }else{ + VdbeComment((v, "RHS of IN operator")); + } +#endif + pKeyInfo = tdsqlite3KeyInfoAlloc(pParse->db, nVal, 1); - affinity = sqlite3ExprAffinity(pLeft); - if( !affinity ){ - affinity = SQLITE_AFF_BLOB; - } - if( pKeyInfo ){ - assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); - pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); - } - - /* Loop through each expression in <exprlist>. */ - r1 = sqlite3GetTempReg(pParse); - r2 = sqlite3GetTempReg(pParse); - if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2); - for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ - Expr *pE2 = pItem->pExpr; - int iValToIns; - - /* If the expression is not constant then we will need to - ** disable the test that was generated above that makes sure - ** this code only executes once. Because for a non-constant - ** expression we need to rerun this code each time. - */ - if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){ - sqlite3VdbeChangeToNoop(v, jmpIfDynamic); - jmpIfDynamic = -1; - } + if( ExprHasProperty(pExpr, EP_xIsSelect) ){ + /* Case 1: expr IN (SELECT ...) + ** + ** Generate code to write the results of the select into the temporary + ** table allocated and opened above. + */ + Select *pSelect = pExpr->x.pSelect; + ExprList *pEList = pSelect->pEList; - /* Evaluate the expression and insert it into the temp table */ - if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){ - sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns); - }else{ - r3 = sqlite3ExprCodeTarget(pParse, pE2, r1); - if( isRowid ){ - sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, - sqlite3VdbeCurrentAddr(v)+2); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3); - }else{ - sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1); - sqlite3ExprCacheAffinityChange(pParse, r3, 1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2); - } - } - } - sqlite3ReleaseTempReg(pParse, r1); - sqlite3ReleaseTempReg(pParse, r2); + ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d", + addrOnce?"":"CORRELATED ", pSelect->selId + )); + /* If the LHS and RHS of the IN operator do not match, that + ** error will have been caught long before we reach this point. */ + if( ALWAYS(pEList->nExpr==nVal) ){ + SelectDest dest; + int i; + tdsqlite3SelectDestInit(&dest, SRT_Set, iTab); + dest.zAffSdst = exprINAffinity(pParse, pExpr); + pSelect->iLimit = 0; + testcase( pSelect->selFlags & SF_Distinct ); + testcase( pKeyInfo==0 ); /* Caused by OOM in tdsqlite3KeyInfoAlloc() */ + if( tdsqlite3Select(pParse, pSelect, &dest) ){ + tdsqlite3DbFree(pParse->db, dest.zAffSdst); + tdsqlite3KeyInfoUnref(pKeyInfo); + return; } - if( pKeyInfo ){ - sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); + tdsqlite3DbFree(pParse->db, dest.zAffSdst); + assert( pKeyInfo!=0 ); /* OOM will cause exit after tdsqlite3Select() */ + assert( pEList!=0 ); + assert( pEList->nExpr>0 ); + assert( tdsqlite3KeyInfoIsWriteable(pKeyInfo) ); + for(i=0; i<nVal; i++){ + Expr *p = tdsqlite3VectorFieldSubexpr(pLeft, i); + pKeyInfo->aColl[i] = tdsqlite3BinaryCompareCollSeq( + pParse, p, pEList->a[i].pExpr + ); } - break; + } + }else if( ALWAYS(pExpr->x.pList!=0) ){ + /* Case 2: expr IN (exprlist) + ** + ** For each expression, build an index key from the evaluation and + ** store it in the temporary table. If <expr> is a column, then use + ** that columns affinity when building index keys. If <expr> is not + ** a column, use numeric affinity. + */ + char affinity; /* Affinity of the LHS of the IN */ + int i; + ExprList *pList = pExpr->x.pList; + struct ExprList_item *pItem; + int r1, r2; + affinity = tdsqlite3ExprAffinity(pLeft); + if( affinity<=SQLITE_AFF_NONE ){ + affinity = SQLITE_AFF_BLOB; + } + if( pKeyInfo ){ + assert( tdsqlite3KeyInfoIsWriteable(pKeyInfo) ); + pKeyInfo->aColl[0] = tdsqlite3ExprCollSeq(pParse, pExpr->pLeft); } - case TK_EXISTS: - case TK_SELECT: - default: { - /* Case 3: (SELECT ... FROM ...) - ** or: EXISTS(SELECT ... FROM ...) - ** - ** For a SELECT, generate code to put the values for all columns of - ** the first row into an array of registers and return the index of - ** the first register. - ** - ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists) - ** into a register and return that register number. - ** - ** In both cases, the query is augmented with "LIMIT 1". Any - ** preexisting limit is discarded in place of the new LIMIT 1. - */ - Select *pSel; /* SELECT statement to encode */ - SelectDest dest; /* How to deal with SELECT result */ - int nReg; /* Registers to allocate */ - - testcase( pExpr->op==TK_EXISTS ); - testcase( pExpr->op==TK_SELECT ); - assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); - assert( ExprHasProperty(pExpr, EP_xIsSelect) ); + /* Loop through each expression in <exprlist>. */ + r1 = tdsqlite3GetTempReg(pParse); + r2 = tdsqlite3GetTempReg(pParse); + for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ + Expr *pE2 = pItem->pExpr; - pSel = pExpr->x.pSelect; - nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1; - sqlite3SelectDestInit(&dest, 0, pParse->nMem+1); - pParse->nMem += nReg; - if( pExpr->op==TK_SELECT ){ - dest.eDest = SRT_Mem; - dest.iSdst = dest.iSDParm; - dest.nSdst = nReg; - sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1); - VdbeComment((v, "Init subquery result")); - }else{ - dest.eDest = SRT_Exists; - sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); - VdbeComment((v, "Init EXISTS result")); - } - sqlite3ExprDelete(pParse->db, pSel->pLimit); - pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER, - &sqlite3IntTokens[1], 0); - pSel->iLimit = 0; - pSel->selFlags &= ~SF_MultiValue; - if( sqlite3Select(pParse, pSel, &dest) ){ - return 0; + /* If the expression is not constant then we will need to + ** disable the test that was generated above that makes sure + ** this code only executes once. Because for a non-constant + ** expression we need to rerun this code each time. + */ + if( addrOnce && !tdsqlite3ExprIsConstant(pE2) ){ + tdsqlite3VdbeChangeToNoop(v, addrOnce); + ExprClearProperty(pExpr, EP_Subrtn); + addrOnce = 0; } - rReg = dest.iSDParm; - ExprSetVVAProperty(pExpr, EP_NoReduce); - break; + + /* Evaluate the expression and insert it into the temp table */ + tdsqlite3ExprCode(pParse, pE2, r1); + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1); } + tdsqlite3ReleaseTempReg(pParse, r1); + tdsqlite3ReleaseTempReg(pParse, r2); + } + if( pKeyInfo ){ + tdsqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); } + if( addrOnce ){ + tdsqlite3VdbeJumpHere(v, addrOnce); + /* Subroutine return */ + tdsqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn); + tdsqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, tdsqlite3VdbeCurrentAddr(v)-1); + tdsqlite3ClearTempRegCache(pParse); + } +} +#endif /* SQLITE_OMIT_SUBQUERY */ + +/* +** Generate code for scalar subqueries used as a subquery expression +** or EXISTS operator: +** +** (SELECT a FROM b) -- subquery +** EXISTS (SELECT a FROM b) -- EXISTS subquery +** +** The pExpr parameter is the SELECT or EXISTS operator to be coded. +** +** Return the register that holds the result. For a multi-column SELECT, +** the result is stored in a contiguous array of registers and the +** return value is the register of the left-most result column. +** Return 0 if an error occurs. +*/ +#ifndef SQLITE_OMIT_SUBQUERY +SQLITE_PRIVATE int tdsqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ + int addrOnce = 0; /* Address of OP_Once at top of subroutine */ + int rReg = 0; /* Register storing resulting */ + Select *pSel; /* SELECT statement to encode */ + SelectDest dest; /* How to deal with SELECT result */ + int nReg; /* Registers to allocate */ + Expr *pLimit; /* New limit expression */ + + Vdbe *v = pParse->pVdbe; + assert( v!=0 ); + testcase( pExpr->op==TK_EXISTS ); + testcase( pExpr->op==TK_SELECT ); + assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); + assert( ExprHasProperty(pExpr, EP_xIsSelect) ); + pSel = pExpr->x.pSelect; - if( rHasNullFlag ){ - sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag); + /* The evaluation of the EXISTS/SELECT must be repeated every time it + ** is encountered if any of the following is true: + ** + ** * The right-hand side is a correlated subquery + ** * The right-hand side is an expression list containing variables + ** * We are inside a trigger + ** + ** If all of the above are false, then we can run this code just once + ** save the results, and reuse the same result on subsequent invocations. + */ + if( !ExprHasProperty(pExpr, EP_VarSelect) ){ + /* If this routine has already been coded, then invoke it as a + ** subroutine. */ + if( ExprHasProperty(pExpr, EP_Subrtn) ){ + ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId)); + tdsqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, + pExpr->y.sub.iAddr); + return pExpr->iTable; + } + + /* Begin coding the subroutine */ + ExprSetProperty(pExpr, EP_Subrtn); + pExpr->y.sub.regReturn = ++pParse->nMem; + pExpr->y.sub.iAddr = + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1; + VdbeComment((v, "return address")); + + addrOnce = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); + } + + /* For a SELECT, generate code to put the values for all columns of + ** the first row into an array of registers and return the index of + ** the first register. + ** + ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists) + ** into a register and return that register number. + ** + ** In both cases, the query is augmented with "LIMIT 1". Any + ** preexisting limit is discarded in place of the new LIMIT 1. + */ + ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d", + addrOnce?"":"CORRELATED ", pSel->selId)); + nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1; + tdsqlite3SelectDestInit(&dest, 0, pParse->nMem+1); + pParse->nMem += nReg; + if( pExpr->op==TK_SELECT ){ + dest.eDest = SRT_Mem; + dest.iSdst = dest.iSDParm; + dest.nSdst = nReg; + tdsqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1); + VdbeComment((v, "Init subquery result")); + }else{ + dest.eDest = SRT_Exists; + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); + VdbeComment((v, "Init EXISTS result")); + } + if( pSel->pLimit ){ + /* The subquery already has a limit. If the pre-existing limit is X + ** then make the new limit X<>0 so that the new limit is either 1 or 0 */ + tdsqlite3 *db = pParse->db; + pLimit = tdsqlite3Expr(db, TK_INTEGER, "0"); + if( pLimit ){ + pLimit->affExpr = SQLITE_AFF_NUMERIC; + pLimit = tdsqlite3PExpr(pParse, TK_NE, + tdsqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit); + } + tdsqlite3ExprDelete(db, pSel->pLimit->pLeft); + pSel->pLimit->pLeft = pLimit; + }else{ + /* If there is no pre-existing limit add a limit of 1 */ + pLimit = tdsqlite3Expr(pParse->db, TK_INTEGER, "1"); + pSel->pLimit = tdsqlite3PExpr(pParse, TK_LIMIT, pLimit, 0); + } + pSel->iLimit = 0; + if( tdsqlite3Select(pParse, pSel, &dest) ){ + return 0; } + pExpr->iTable = rReg = dest.iSDParm; + ExprSetVVAProperty(pExpr, EP_NoReduce); + if( addrOnce ){ + tdsqlite3VdbeJumpHere(v, addrOnce); - if( jmpIfDynamic>=0 ){ - sqlite3VdbeJumpHere(v, jmpIfDynamic); + /* Subroutine return */ + tdsqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn); + tdsqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, tdsqlite3VdbeCurrentAddr(v)-1); + tdsqlite3ClearTempRegCache(pParse); } - sqlite3ExprCachePop(pParse); return rReg; } @@ -95437,19 +105396,15 @@ SQLITE_PRIVATE int sqlite3CodeSubselect( ** columns as the vector on the LHS. Or, if the RHS of the IN() is not ** a sub-query, that the LHS is a vector of size 1. */ -SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ - int nVector = sqlite3ExprVectorSize(pIn->pLeft); +SQLITE_PRIVATE int tdsqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ + int nVector = tdsqlite3ExprVectorSize(pIn->pLeft); if( (pIn->flags & EP_xIsSelect) ){ if( nVector!=pIn->x.pSelect->pEList->nExpr ){ - sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector); + tdsqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector); return 1; } }else if( nVector!=1 ){ - if( (pIn->pLeft->flags & EP_xIsSelect) ){ - sqlite3SubselectError(pParse, nVector, 1); - }else{ - sqlite3ErrorMsg(pParse, "row value misused"); - } + tdsqlite3VectorErrorMsg(pParse, pIn->pLeft); return 1; } return 0; @@ -95482,7 +105437,7 @@ SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ ** See the separate in-operator.md documentation file in the canonical ** SQLite source tree for additional information. */ -static void sqlite3ExprCodeIN( +static void tdsqlite3ExprCodeIN( Parse *pParse, /* Parsing and code generating context */ Expr *pExpr, /* The IN expression */ int destIfFalse, /* Jump here if LHS is not contained in the RHS */ @@ -95504,26 +105459,28 @@ static void sqlite3ExprCodeIN( int addrTruthOp; /* Address of opcode that determines the IN is true */ int destNotNull; /* Jump here if a comparison is not true in step 6 */ int addrTop; /* Top of the step-6 loop */ + int iTab = 0; /* Index to use */ pLeft = pExpr->pLeft; - if( sqlite3ExprCheckIN(pParse, pExpr) ) return; + if( tdsqlite3ExprCheckIN(pParse, pExpr) ) return; zAff = exprINAffinity(pParse, pExpr); - nVector = sqlite3ExprVectorSize(pExpr->pLeft); - aiMap = (int*)sqlite3DbMallocZero( + nVector = tdsqlite3ExprVectorSize(pExpr->pLeft); + aiMap = (int*)tdsqlite3DbMallocZero( pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1 ); - if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error; + if( pParse->db->mallocFailed ) goto tdsqlite3ExprCodeIN_oom_error; /* Attempt to compute the RHS. After this step, if anything other than - ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable + ** IN_INDEX_NOOP is returned, the table opened with cursor iTab ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned, ** the RHS has not yet been coded. */ v = pParse->pVdbe; assert( v!=0 ); /* OOM detected prior to this routine */ VdbeNoopComment((v, "begin IN expr")); - eType = sqlite3FindInIndex(pParse, pExpr, + eType = tdsqlite3FindInIndex(pParse, pExpr, IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK, - destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap); + destIfFalse==destIfNull ? 0 : &rRhsHasNull, + aiMap, &iTab); assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC @@ -95542,12 +105499,11 @@ static void sqlite3ExprCodeIN( ** vector, then it is stored in an array of nVector registers starting ** at r1. ** - ** sqlite3FindInIndex() might have reordered the fields of the LHS vector + ** tdsqlite3FindInIndex() might have reordered the fields of the LHS vector ** so that the fields are in the same order as an existing index. The ** aiMap[] array contains a mapping from the original LHS field order to ** the field order that matches the RHS index. */ - sqlite3ExprCachePush(pParse); rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy); for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */ if( i==nVector ){ @@ -95555,13 +105511,13 @@ static void sqlite3ExprCodeIN( rLhs = rLhsOrig; }else{ /* Need to reorder the LHS fields according to aiMap */ - rLhs = sqlite3GetTempRange(pParse, nVector); + rLhs = tdsqlite3GetTempRange(pParse, nVector); for(i=0; i<nVector; i++){ - sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0); + tdsqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0); } } - /* If sqlite3FindInIndex() did not find or create an index that is + /* If tdsqlite3FindInIndex() did not find or create an index that is ** suitable for evaluating the IN operator, then evaluate using a ** sequence of comparisons. ** @@ -95569,42 +105525,56 @@ static void sqlite3ExprCodeIN( */ if( eType==IN_INDEX_NOOP ){ ExprList *pList = pExpr->x.pList; - CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); - int labelOk = sqlite3VdbeMakeLabel(v); + CollSeq *pColl = tdsqlite3ExprCollSeq(pParse, pExpr->pLeft); + int labelOk = tdsqlite3VdbeMakeLabel(pParse); int r2, regToFree; int regCkNull = 0; int ii; + int bLhsReal; /* True if the LHS of the IN has REAL affinity */ assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); if( destIfNull!=destIfFalse ){ - regCkNull = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull); + regCkNull = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull); } + bLhsReal = tdsqlite3ExprAffinity(pExpr->pLeft)==SQLITE_AFF_REAL; for(ii=0; ii<pList->nExpr; ii++){ - r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree); - if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){ - sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull); + if( bLhsReal ){ + r2 = regToFree = tdsqlite3GetTempReg(pParse); + tdsqlite3ExprCode(pParse, pList->a[ii].pExpr, r2); + tdsqlite3VdbeAddOp4(v, OP_Affinity, r2, 1, 0, "E", P4_STATIC); + }else{ + r2 = tdsqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree); + } + if( regCkNull && tdsqlite3ExprCanBeNull(pList->a[ii].pExpr) ){ + tdsqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull); } + tdsqlite3ReleaseTempReg(pParse, regToFree); if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){ - sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2, + int op = rLhs!=r2 ? OP_Eq : OP_NotNull; + tdsqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2, (void*)pColl, P4_COLLSEQ); - VdbeCoverageIf(v, ii<pList->nExpr-1); - VdbeCoverageIf(v, ii==pList->nExpr-1); - sqlite3VdbeChangeP5(v, zAff[0]); + VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq); + VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq); + VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull); + VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull); + tdsqlite3VdbeChangeP5(v, zAff[0]); }else{ + int op = rLhs!=r2 ? OP_Ne : OP_IsNull; assert( destIfNull==destIfFalse ); - sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2, - (void*)pColl, P4_COLLSEQ); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); + tdsqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2, + (void*)pColl, P4_COLLSEQ); + VdbeCoverageIf(v, op==OP_Ne); + VdbeCoverageIf(v, op==OP_IsNull); + tdsqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); } - sqlite3ReleaseTempReg(pParse, regToFree); } if( regCkNull ){ - sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v); - sqlite3VdbeGoto(v, destIfFalse); + tdsqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v); + tdsqlite3VdbeGoto(v, destIfFalse); } - sqlite3VdbeResolveLabel(v, labelOk); - sqlite3ReleaseTempReg(pParse, regCkNull); - goto sqlite3ExprCodeIN_finished; + tdsqlite3VdbeResolveLabel(v, labelOk); + tdsqlite3ReleaseTempReg(pParse, regCkNull); + goto tdsqlite3ExprCodeIN_finished; } /* Step 2: Check to see if the LHS contains any NULL columns. If the @@ -95614,12 +105584,13 @@ static void sqlite3ExprCodeIN( if( destIfNull==destIfFalse ){ destStep2 = destIfFalse; }else{ - destStep2 = destStep6 = sqlite3VdbeMakeLabel(v); + destStep2 = destStep6 = tdsqlite3VdbeMakeLabel(pParse); } + if( pParse->nErr ) goto tdsqlite3ExprCodeIN_finished; for(i=0; i<nVector; i++){ - Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i); - if( sqlite3ExprCanBeNull(p) ){ - sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2); + Expr *p = tdsqlite3VectorFieldSubexpr(pExpr->pLeft, i); + if( tdsqlite3ExprCanBeNull(p) ){ + tdsqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2); VdbeCoverage(v); } } @@ -95632,19 +105603,19 @@ static void sqlite3ExprCodeIN( /* In this case, the RHS is the ROWID of table b-tree and so we also ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4 ** into a single opcode. */ - sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs); + tdsqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs); VdbeCoverage(v); - addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ + addrTruthOp = tdsqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ }else{ - sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); + tdsqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); if( destIfFalse==destIfNull ){ /* Combine Step 3 and Step 5 into a single opcode */ - sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, + tdsqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse, rLhs, nVector); VdbeCoverage(v); - goto sqlite3ExprCodeIN_finished; + goto tdsqlite3ExprCodeIN_finished; } /* Ordinary Step 3, for the case where FALSE and NULL are distinct */ - addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, + addrTruthOp = tdsqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0, rLhs, nVector); VdbeCoverage(v); } @@ -95652,14 +105623,14 @@ static void sqlite3ExprCodeIN( ** an match on the search above, then the result must be FALSE. */ if( rRhsHasNull && nVector==1 ){ - sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse); + tdsqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse); VdbeCoverage(v); } /* Step 5. If we do not care about the difference between NULL and ** FALSE, then just return false. */ - if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse); + if( destIfFalse==destIfNull ) tdsqlite3VdbeGoto(v, destIfFalse); /* Step 6: Loop through rows of the RHS. Compare each row to the LHS. ** If any comparison is NULL, then the result is NULL. If all @@ -95668,11 +105639,11 @@ static void sqlite3ExprCodeIN( ** For a scalar LHS, it is sufficient to check just the first row ** of the RHS. */ - if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6); - addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse); + if( destStep6 ) tdsqlite3VdbeResolveLabel(v, destStep6); + addrTop = tdsqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse); VdbeCoverage(v); if( nVector>1 ){ - destNotNull = sqlite3VdbeMakeLabel(v); + destNotNull = tdsqlite3VdbeMakeLabel(pParse); }else{ /* For nVector==1, combine steps 6 and 7 by immediately returning ** FALSE if the first comparison is not NULL */ @@ -95681,36 +105652,35 @@ static void sqlite3ExprCodeIN( for(i=0; i<nVector; i++){ Expr *p; CollSeq *pColl; - int r3 = sqlite3GetTempReg(pParse); - p = sqlite3VectorFieldSubexpr(pLeft, i); - pColl = sqlite3ExprCollSeq(pParse, p); - sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3); - sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, + int r3 = tdsqlite3GetTempReg(pParse); + p = tdsqlite3VectorFieldSubexpr(pLeft, i); + pColl = tdsqlite3ExprCollSeq(pParse, p); + tdsqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3); + tdsqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, (void*)pColl, P4_COLLSEQ); VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, r3); + tdsqlite3ReleaseTempReg(pParse, r3); } - sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); if( nVector>1 ){ - sqlite3VdbeResolveLabel(v, destNotNull); - sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1); + tdsqlite3VdbeResolveLabel(v, destNotNull); + tdsqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1); VdbeCoverage(v); /* Step 7: If we reach this point, we know that the result must ** be false. */ - sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); } /* Jumps here in order to return true. */ - sqlite3VdbeJumpHere(v, addrTruthOp); + tdsqlite3VdbeJumpHere(v, addrTruthOp); -sqlite3ExprCodeIN_finished: - if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs); - sqlite3ExprCachePop(pParse); +tdsqlite3ExprCodeIN_finished: + if( rLhs!=rLhsOrig ) tdsqlite3ReleaseTempReg(pParse, rLhs); VdbeComment((v, "end IN expr")); -sqlite3ExprCodeIN_oom_error: - sqlite3DbFree(pParse->db, aiMap); - sqlite3DbFree(pParse->db, zAff); +tdsqlite3ExprCodeIN_oom_error: + tdsqlite3DbFree(pParse->db, aiMap); + tdsqlite3DbFree(pParse->db, zAff); } #endif /* SQLITE_OMIT_SUBQUERY */ @@ -95726,10 +105696,10 @@ sqlite3ExprCodeIN_oom_error: static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ if( ALWAYS(z!=0) ){ double value; - sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); - assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ + tdsqlite3AtoF(z, &value, tdsqlite3Strlen30(z), SQLITE_UTF8); + assert( !tdsqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ if( negateFlag ) value = -value; - sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL); + tdsqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL); } } #endif @@ -95747,177 +105717,38 @@ static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ int i = pExpr->u.iValue; assert( i>=0 ); if( negFlag ) i = -i; - sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); + tdsqlite3VdbeAddOp2(v, OP_Integer, i, iMem); }else{ int c; i64 value; const char *z = pExpr->u.zToken; assert( z!=0 ); - c = sqlite3DecOrHexToI64(z, &value); - if( c==0 || (c==2 && negFlag) ){ - if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; } - sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64); - }else{ + c = tdsqlite3DecOrHexToI64(z, &value); + if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){ #ifdef SQLITE_OMIT_FLOATING_POINT - sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); + tdsqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); #else #ifndef SQLITE_OMIT_HEX_INTEGER - if( sqlite3_strnicmp(z,"0x",2)==0 ){ - sqlite3ErrorMsg(pParse, "hex literal too big: %s", z); + if( tdsqlite3_strnicmp(z,"0x",2)==0 ){ + tdsqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z); }else #endif { codeReal(v, z, negFlag, iMem); } #endif - } - } -} - -/* -** Erase column-cache entry number i -*/ -static void cacheEntryClear(Parse *pParse, int i){ - if( pParse->aColCache[i].tempReg ){ - if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){ - pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg; - } - } - pParse->nColCache--; - if( i<pParse->nColCache ){ - pParse->aColCache[i] = pParse->aColCache[pParse->nColCache]; - } -} - - -/* -** Record in the column cache that a particular column from a -** particular table is stored in a particular register. -*/ -SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){ - int i; - int minLru; - int idxLru; - struct yColCache *p; - - /* Unless an error has occurred, register numbers are always positive. */ - assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed ); - assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */ - - /* The SQLITE_ColumnCache flag disables the column cache. This is used - ** for testing only - to verify that SQLite always gets the same answer - ** with and without the column cache. - */ - if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return; - - /* First replace any existing entry. - ** - ** Actually, the way the column cache is currently used, we are guaranteed - ** that the object will never already be in cache. Verify this guarantee. - */ -#ifndef NDEBUG - for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ - assert( p->iTable!=iTab || p->iColumn!=iCol ); - } -#endif - - /* If the cache is already full, delete the least recently used entry */ - if( pParse->nColCache>=SQLITE_N_COLCACHE ){ - minLru = 0x7fffffff; - idxLru = -1; - for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ - if( p->lru<minLru ){ - idxLru = i; - minLru = p->lru; - } - } - p = &pParse->aColCache[idxLru]; - }else{ - p = &pParse->aColCache[pParse->nColCache++]; - } - - /* Add the new entry to the end of the cache */ - p->iLevel = pParse->iCacheLevel; - p->iTable = iTab; - p->iColumn = iCol; - p->iReg = iReg; - p->tempReg = 0; - p->lru = pParse->iCacheCnt++; -} - -/* -** Indicate that registers between iReg..iReg+nReg-1 are being overwritten. -** Purge the range of registers from the column cache. -*/ -SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){ - int i = 0; - while( i<pParse->nColCache ){ - struct yColCache *p = &pParse->aColCache[i]; - if( p->iReg >= iReg && p->iReg < iReg+nReg ){ - cacheEntryClear(pParse, i); - }else{ - i++; - } - } -} - -/* -** Remember the current column cache context. Any new entries added -** added to the column cache after this call are removed when the -** corresponding pop occurs. -*/ -SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){ - pParse->iCacheLevel++; -#ifdef SQLITE_DEBUG - if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ - printf("PUSH to %d\n", pParse->iCacheLevel); - } -#endif -} - -/* -** Remove from the column cache any entries that were added since the -** the previous sqlite3ExprCachePush operation. In other words, restore -** the cache to the state it was in prior the most recent Push. -*/ -SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){ - int i = 0; - assert( pParse->iCacheLevel>=1 ); - pParse->iCacheLevel--; -#ifdef SQLITE_DEBUG - if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ - printf("POP to %d\n", pParse->iCacheLevel); - } -#endif - while( i<pParse->nColCache ){ - if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){ - cacheEntryClear(pParse, i); }else{ - i++; + if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; } + tdsqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64); } } } -/* -** When a cached column is reused, make sure that its register is -** no longer available as a temp register. ticket #3879: that same -** register might be in the cache in multiple places, so be sure to -** get them all. -*/ -static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){ - int i; - struct yColCache *p; - for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ - if( p->iReg==iReg ){ - p->tempReg = 0; - } - } -} /* Generate code that will load into register regOut a value that is ** appropriate for the iIdxCol-th column of index pIdx. */ -SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn( +SQLITE_PRIVATE void tdsqlite3ExprCodeLoadIndexColumn( Parse *pParse, /* The parsing context */ Index *pIdx, /* The index whose column is to be loaded */ int iTabCur, /* Cursor pointing to a table row */ @@ -95928,52 +105759,103 @@ SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn( if( iTabCol==XN_EXPR ){ assert( pIdx->aColExpr ); assert( pIdx->aColExpr->nExpr>iIdxCol ); - pParse->iSelfTab = iTabCur; - sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut); + pParse->iSelfTab = iTabCur + 1; + tdsqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut); + pParse->iSelfTab = 0; }else{ - sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur, + tdsqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur, iTabCol, regOut); } } +#ifndef SQLITE_OMIT_GENERATED_COLUMNS +/* +** Generate code that will compute the value of generated column pCol +** and store the result in register regOut +*/ +SQLITE_PRIVATE void tdsqlite3ExprCodeGeneratedColumn( + Parse *pParse, + Column *pCol, + int regOut +){ + int iAddr; + Vdbe *v = pParse->pVdbe; + assert( v!=0 ); + assert( pParse->iSelfTab!=0 ); + if( pParse->iSelfTab>0 ){ + iAddr = tdsqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut); + }else{ + iAddr = 0; + } + tdsqlite3ExprCode(pParse, pCol->pDflt, regOut); + if( pCol->affinity>=SQLITE_AFF_TEXT ){ + tdsqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1); + } + if( iAddr ) tdsqlite3VdbeJumpHere(v, iAddr); +} +#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ + /* ** Generate code to extract the value of the iCol-th column of a table. */ -SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable( - Vdbe *v, /* The VDBE under construction */ +SQLITE_PRIVATE void tdsqlite3ExprCodeGetColumnOfTable( + Vdbe *v, /* Parsing context */ Table *pTab, /* The table containing the value */ int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */ int iCol, /* Index of the column to extract */ int regOut /* Extract the value into this register */ ){ + Column *pCol; + assert( v!=0 ); + if( pTab==0 ){ + tdsqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut); + return; + } if( iCol<0 || iCol==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); + tdsqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); }else{ - int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; - int x = iCol; - if( !HasRowid(pTab) && !IsVirtual(pTab) ){ - x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol); + int op; + int x; + if( IsVirtual(pTab) ){ + op = OP_VColumn; + x = iCol; +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){ + Parse *pParse = tdsqlite3VdbeParser(v); + if( pCol->colFlags & COLFLAG_BUSY ){ + tdsqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName); + }else{ + int savedSelfTab = pParse->iSelfTab; + pCol->colFlags |= COLFLAG_BUSY; + pParse->iSelfTab = iTabCur+1; + tdsqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut); + pParse->iSelfTab = savedSelfTab; + pCol->colFlags &= ~COLFLAG_BUSY; + } + return; +#endif + }else if( !HasRowid(pTab) ){ + testcase( iCol!=tdsqlite3TableColumnToStorage(pTab, iCol) ); + x = tdsqlite3TableColumnToIndex(tdsqlite3PrimaryKeyIndex(pTab), iCol); + op = OP_Column; + }else{ + x = tdsqlite3TableColumnToStorage(pTab,iCol); + testcase( x!=iCol ); + op = OP_Column; } - sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); - } - if( iCol>=0 ){ - sqlite3ColumnDefault(v, pTab, iCol, regOut); + tdsqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); + tdsqlite3ColumnDefault(v, pTab, iCol, regOut); } } /* ** Generate code that will extract the iColumn-th column from -** table pTab and store the column value in a register. -** -** An effort is made to store the column value in register iReg. This -** is not garanteeed for GetColumn() - the result can be stored in -** any register. But the result is guaranteed to land in register iReg -** for GetColumnToReg(). +** table pTab and store the column value in register iReg. ** ** There must be an open cursor to pTab in iTable when this routine ** is called. If iColumn<0 then code is generated that extracts the rowid. */ -SQLITE_PRIVATE int sqlite3ExprCodeGetColumn( +SQLITE_PRIVATE int tdsqlite3ExprCodeGetColumn( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Description of the table we are reading from */ int iColumn, /* Index of the table column */ @@ -95981,103 +105863,30 @@ SQLITE_PRIVATE int sqlite3ExprCodeGetColumn( int iReg, /* Store results here */ u8 p5 /* P5 value for OP_Column + FLAGS */ ){ - Vdbe *v = pParse->pVdbe; - int i; - struct yColCache *p; - - for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ - if( p->iTable==iTable && p->iColumn==iColumn ){ - p->lru = pParse->iCacheCnt++; - sqlite3ExprCachePinRegister(pParse, p->iReg); - return p->iReg; - } - } - assert( v!=0 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg); + assert( pParse->pVdbe!=0 ); + tdsqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg); if( p5 ){ - sqlite3VdbeChangeP5(v, p5); - }else{ - sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg); + VdbeOp *pOp = tdsqlite3VdbeGetOp(pParse->pVdbe,-1); + if( pOp->opcode==OP_Column ) pOp->p5 = p5; } return iReg; } -SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg( - Parse *pParse, /* Parsing and code generating context */ - Table *pTab, /* Description of the table we are reading from */ - int iColumn, /* Index of the table column */ - int iTable, /* The cursor pointing to the table */ - int iReg /* Store results here */ -){ - int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0); - if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg); -} - - -/* -** Clear all column cache entries. -*/ -SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){ - int i; - -#if SQLITE_DEBUG - if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ - printf("CLEAR\n"); - } -#endif - for(i=0; i<pParse->nColCache; i++){ - if( pParse->aColCache[i].tempReg - && pParse->nTempReg<ArraySize(pParse->aTempReg) - ){ - pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg; - } - } - pParse->nColCache = 0; -} - -/* -** Record the fact that an affinity change has occurred on iCount -** registers starting with iStart. -*/ -SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){ - sqlite3ExprCacheRemove(pParse, iStart, iCount); -} /* ** Generate code to move content from registers iFrom...iFrom+nReg-1 -** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ - assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo ); - sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); - sqlite3ExprCacheRemove(pParse, iFrom, nReg); -} - -#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) -/* -** Return true if any register in the range iFrom..iTo (inclusive) -** is used as part of the column cache. -** -** This routine is used within assert() and testcase() macros only -** and does not appear in a normal build. +** over to iTo..iTo+nReg-1. */ -static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){ - int i; - struct yColCache *p; - for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ - int r = p->iReg; - if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/ - } - return 0; +SQLITE_PRIVATE void tdsqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ + tdsqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); } -#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */ - /* ** Convert a scalar expression node to a TK_REGISTER referencing ** register iReg. The caller must ensure that iReg already contains ** the correct value for the expression. */ -static void exprToRegister(Expr *p, int iReg){ +static void exprToRegister(Expr *pExpr, int iReg){ + Expr *p = tdsqlite3ExprSkipCollateAndLikely(pExpr); p->op2 = p->op; p->op = TK_REGISTER; p->iTable = iReg; @@ -96096,25 +105905,132 @@ static void exprToRegister(Expr *p, int iReg){ */ static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){ int iResult; - int nResult = sqlite3ExprVectorSize(p); + int nResult = tdsqlite3ExprVectorSize(p); if( nResult==1 ){ - iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable); + iResult = tdsqlite3ExprCodeTemp(pParse, p, piFreeable); }else{ *piFreeable = 0; if( p->op==TK_SELECT ){ - iResult = sqlite3CodeSubselect(pParse, p, 0, 0); +#if SQLITE_OMIT_SUBQUERY + iResult = 0; +#else + iResult = tdsqlite3CodeSubselect(pParse, p); +#endif }else{ int i; iResult = pParse->nMem+1; pParse->nMem += nResult; for(i=0; i<nResult; i++){ - sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult); + tdsqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult); } } } return iResult; } +/* +** Generate code to implement special SQL functions that are implemented +** in-line rather than by using the usual callbacks. +*/ +static int exprCodeInlineFunction( + Parse *pParse, /* Parsing context */ + ExprList *pFarg, /* List of function arguments */ + int iFuncId, /* Function ID. One of the INTFUNC_... values */ + int target /* Store function result in this register */ +){ + int nFarg; + Vdbe *v = pParse->pVdbe; + assert( v!=0 ); + assert( pFarg!=0 ); + nFarg = pFarg->nExpr; + assert( nFarg>0 ); /* All in-line functions have at least one argument */ + switch( iFuncId ){ + case INLINEFUNC_coalesce: { + /* Attempt a direct implementation of the built-in COALESCE() and + ** IFNULL() functions. This avoids unnecessary evaluation of + ** arguments past the first non-NULL argument. + */ + int endCoalesce = tdsqlite3VdbeMakeLabel(pParse); + int i; + assert( nFarg>=2 ); + tdsqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); + for(i=1; i<nFarg; i++){ + tdsqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce); + VdbeCoverage(v); + tdsqlite3ExprCode(pParse, pFarg->a[i].pExpr, target); + } + if( tdsqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){ + tdsqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergable */ + } + tdsqlite3VdbeResolveLabel(v, endCoalesce); + break; + } + + default: { + /* The UNLIKELY() function is a no-op. The result is the value + ** of the first argument. + */ + assert( nFarg==1 || nFarg==2 ); + target = tdsqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); + break; + } + + /*********************************************************************** + ** Test-only SQL functions that are only usable if enabled + ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS + */ + case INLINEFUNC_expr_compare: { + /* Compare two expressions using tdsqlite3ExprCompare() */ + assert( nFarg==2 ); + tdsqlite3VdbeAddOp2(v, OP_Integer, + tdsqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), + target); + break; + } + + case INLINEFUNC_expr_implies_expr: { + /* Compare two expressions using tdsqlite3ExprImpliesExpr() */ + assert( nFarg==2 ); + tdsqlite3VdbeAddOp2(v, OP_Integer, + tdsqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), + target); + break; + } + + case INLINEFUNC_implies_nonnull_row: { + /* REsult of tdsqlite3ExprImpliesNonNullRow() */ + Expr *pA1; + assert( nFarg==2 ); + pA1 = pFarg->a[1].pExpr; + if( pA1->op==TK_COLUMN ){ + tdsqlite3VdbeAddOp2(v, OP_Integer, + tdsqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable), + target); + }else{ + tdsqlite3VdbeAddOp2(v, OP_Null, 0, target); + } + break; + } + +#ifdef SQLITE_DEBUG + case INLINEFUNC_affinity: { + /* The AFFINITY() function evaluates to a string that describes + ** the type affinity of the argument. This is used for testing of + ** the SQLite type logic. + */ + const char *azAff[] = { "blob", "text", "numeric", "integer", "real" }; + char aff; + assert( nFarg==1 ); + aff = tdsqlite3ExprAffinity(pFarg->a[0].pExpr); + tdsqlite3VdbeLoadString(v, target, + (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]); + break; + } +#endif + } + return target; +} + /* ** Generate code into the current Vdbe to evaluate the given @@ -96127,7 +106043,7 @@ static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){ ** must check the return code and move the results to the desired ** register. */ -SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ +SQLITE_PRIVATE int tdsqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ Vdbe *v = pParse->pVdbe; /* The VM under construction */ int op; /* The opcode being coded */ int inReg = target; /* Results stored in register inReg */ @@ -96143,6 +106059,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) return 0; } +expr_code_doover: if( pExpr==0 ){ op = TK_NULL; }else{ @@ -96156,7 +106073,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) assert( pCol->iMem>0 ); return pCol->iMem; }else if( pAggInfo->useSortingIdx ){ - sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, + tdsqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, pCol->iSorterColumn, target); return target; } @@ -96164,24 +106081,99 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) } case TK_COLUMN: { int iTab = pExpr->iTable; + int iReg; + if( ExprHasProperty(pExpr, EP_FixedCol) ){ + /* This COLUMN expression is really a constant due to WHERE clause + ** constraints, and that constant is coded by the pExpr->pLeft + ** expresssion. However, make sure the constant has the correct + ** datatype by applying the Affinity of the table column to the + ** constant. + */ + int aff; + iReg = tdsqlite3ExprCodeTarget(pParse, pExpr->pLeft,target); + if( pExpr->y.pTab ){ + aff = tdsqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); + }else{ + aff = pExpr->affExpr; + } + if( aff>SQLITE_AFF_BLOB ){ + static const char zAff[] = "B\000C\000D\000E"; + assert( SQLITE_AFF_BLOB=='A' ); + assert( SQLITE_AFF_TEXT=='B' ); + if( iReg!=target ){ + tdsqlite3VdbeAddOp2(v, OP_SCopy, iReg, target); + iReg = target; + } + tdsqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0, + &zAff[(aff-'B')*2], P4_STATIC); + } + return iReg; + } if( iTab<0 ){ - if( pParse->ckBase>0 ){ - /* Generating CHECK constraints or inserting into partial index */ - return pExpr->iColumn + pParse->ckBase; + if( pParse->iSelfTab<0 ){ + /* Other columns in the same row for CHECK constraints or + ** generated columns or for inserting into partial index. + ** The row is unpacked into registers beginning at + ** 0-(pParse->iSelfTab). The rowid (if any) is in a register + ** immediately prior to the first column. + */ + Column *pCol; + Table *pTab = pExpr->y.pTab; + int iSrc; + int iCol = pExpr->iColumn; + assert( pTab!=0 ); + assert( iCol>=XN_ROWID ); + assert( iCol<pTab->nCol ); + if( iCol<0 ){ + return -1-pParse->iSelfTab; + } + pCol = pTab->aCol + iCol; + testcase( iCol!=tdsqlite3TableColumnToStorage(pTab,iCol) ); + iSrc = tdsqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab; +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + if( pCol->colFlags & COLFLAG_GENERATED ){ + if( pCol->colFlags & COLFLAG_BUSY ){ + tdsqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", + pCol->zName); + return 0; + } + pCol->colFlags |= COLFLAG_BUSY; + if( pCol->colFlags & COLFLAG_NOTAVAIL ){ + tdsqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc); + } + pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL); + return iSrc; + }else +#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ + if( pCol->affinity==SQLITE_AFF_REAL ){ + tdsqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target); + tdsqlite3VdbeAddOp1(v, OP_RealAffinity, target); + return target; + }else{ + return iSrc; + } }else{ /* Coding an expression that is part of an index where column names ** in the index refer to the table to which the index belongs */ - iTab = pParse->iSelfTab; + iTab = pParse->iSelfTab - 1; } } - return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab, + iReg = tdsqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab, pExpr->iColumn, iTab, target, pExpr->op2); + if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){ + tdsqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); + } + return iReg; } case TK_INTEGER: { codeInteger(pParse, pExpr, 0, target); return target; } + case TK_TRUEFALSE: { + tdsqlite3VdbeAddOp2(v, OP_Integer, tdsqlite3ExprTruthValue(pExpr), target); + return target; + } #ifndef SQLITE_OMIT_FLOATING_POINT case TK_FLOAT: { assert( !ExprHasProperty(pExpr, EP_IntValue) ); @@ -96191,11 +106183,16 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) #endif case TK_STRING: { assert( !ExprHasProperty(pExpr, EP_IntValue) ); - sqlite3VdbeLoadString(v, target, pExpr->u.zToken); + tdsqlite3VdbeLoadString(v, target, pExpr->u.zToken); return target; } - case TK_NULL: { - sqlite3VdbeAddOp2(v, OP_Null, 0, target); + default: { + /* Make NULL the default case so that if a bug causes an illegal + ** Expr node to be passed into this function, it will be handled + ** sanely and not crash. But keep the assert() to bring the problem + ** to the attention of the developers. */ + assert( op==TK_NULL ); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, target); return target; } #ifndef SQLITE_OMIT_BLOB_LITERAL @@ -96207,10 +106204,10 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); assert( pExpr->u.zToken[1]=='\'' ); z = &pExpr->u.zToken[2]; - n = sqlite3Strlen30(z) - 1; + n = tdsqlite3Strlen30(z) - 1; assert( z[n]=='\'' ); - zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); - sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); + zBlob = tdsqlite3HexToBlob(tdsqlite3VdbeDb(v), z, n); + tdsqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); return target; } #endif @@ -96218,11 +106215,12 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) assert( !ExprHasProperty(pExpr, EP_IntValue) ); assert( pExpr->u.zToken!=0 ); assert( pExpr->u.zToken[0]!=0 ); - sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); + tdsqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); if( pExpr->u.zToken[1]!=0 ){ - assert( pExpr->u.zToken[0]=='?' - || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 ); - sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC); + const char *z = tdsqlite3VListNumToName(pParse->pVList, pExpr->iColumn); + assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) ); + pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */ + tdsqlite3VdbeAppendP4(v, (char*)z, P4_STATIC); } return target; } @@ -96232,15 +106230,13 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) #ifndef SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ - inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + inReg = tdsqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); if( inReg!=target ){ - sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); + tdsqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); inReg = target; } - sqlite3VdbeAddOp2(v, OP_Cast, target, - sqlite3AffinityType(pExpr->u.zToken, 0)); - testcase( usedAsColumnCache(pParse, inReg, inReg) ); - sqlite3ExprCacheAffinityChange(pParse, inReg, 1); + tdsqlite3VdbeAddOp2(v, OP_Cast, target, + tdsqlite3AffinityType(pExpr->u.zToken, 0)); return inReg; } #endif /* SQLITE_OMIT_CAST */ @@ -96256,13 +106252,14 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) case TK_NE: case TK_EQ: { Expr *pLeft = pExpr->pLeft; - if( sqlite3ExprIsVector(pLeft) ){ + if( tdsqlite3ExprIsVector(pLeft) ){ codeVectorCompare(pParse, pExpr, target, op, p5); }else{ - r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + r1 = tdsqlite3ExprCodeTemp(pParse, pLeft, ®Free1); + r2 = tdsqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); codeCompare(pParse, pLeft, pExpr->pRight, op, - r1, r2, inReg, SQLITE_STOREP2 | p5); + r1, r2, inReg, SQLITE_STOREP2 | p5, + ExprHasProperty(pExpr,EP_Commuted)); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); @@ -96297,9 +106294,9 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT ); assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT ); assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); - sqlite3VdbeAddOp3(v, op, r2, r1, target); + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = tdsqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + tdsqlite3VdbeAddOp3(v, op, r2, r1, target); testcase( regFree1==0 ); testcase( regFree2==0 ); break; @@ -96320,9 +106317,9 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) tempX.op = TK_INTEGER; tempX.flags = EP_IntValue|EP_TokenOnly; tempX.u.iValue = 0; - r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); - sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); + r1 = tdsqlite3ExprCodeTemp(pParse, &tempX, ®Free1); + r2 = tdsqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); + tdsqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); testcase( regFree2==0 ); } break; @@ -96331,9 +106328,21 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) case TK_NOT: { assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT ); assert( TK_NOT==OP_Not ); testcase( op==TK_NOT ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); testcase( regFree1==0 ); - sqlite3VdbeAddOp2(v, op, r1, inReg); + tdsqlite3VdbeAddOp2(v, op, r1, inReg); + break; + } + case TK_TRUTH: { + int isTrue; /* IS TRUE or IS NOT TRUE */ + int bNormal; /* IS TRUE or IS FALSE */ + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + testcase( regFree1==0 ); + isTrue = tdsqlite3ExprTruthValue(pExpr->pRight); + bNormal = pExpr->op2==TK_IS; + testcase( isTrue && bNormal); + testcase( !isTrue && bNormal); + tdsqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal); break; } case TK_ISNULL: @@ -96341,21 +106350,21 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) int addr; assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); - sqlite3VdbeAddOp2(v, OP_Integer, 1, target); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, target); + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); testcase( regFree1==0 ); - addr = sqlite3VdbeAddOp1(v, op, r1); + addr = tdsqlite3VdbeAddOp1(v, op, r1); VdbeCoverageIf(v, op==TK_ISNULL); VdbeCoverageIf(v, op==TK_NOTNULL); - sqlite3VdbeAddOp2(v, OP_Integer, 0, target); - sqlite3VdbeJumpHere(v, addr); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, target); + tdsqlite3VdbeJumpHere(v, addr); break; } case TK_AGG_FUNCTION: { AggInfo *pInfo = pExpr->pAggInfo; if( pInfo==0 ){ assert( !ExprHasProperty(pExpr, EP_IntValue) ); - sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); + tdsqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); }else{ return pInfo->aFunc[pExpr->iAgg].iMem; } @@ -96368,10 +106377,21 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) const char *zId; /* The function name */ u32 constMask = 0; /* Mask of function arguments that are constant */ int i; /* Loop counter */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ u8 enc = ENC(db); /* The text encoding used by this database */ CollSeq *pColl = 0; /* A collating sequence */ +#ifndef SQLITE_OMIT_WINDOWFUNC + if( ExprHasProperty(pExpr, EP_WinFunc) ){ + return pExpr->y.pWin->regResult; + } +#endif + + if( ConstFactorOk(pParse) && tdsqlite3ExprIsConstantNotJoin(pExpr) ){ + /* SQL functions can be expensive. So try to move constant functions + ** out of the inner loop, even if that means an extra OP_Copy. */ + return tdsqlite3ExprCodeAtInit(pParse, pExpr, -1); + } assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); if( ExprHasProperty(pExpr, EP_TokenOnly) ){ pFarg = 0; @@ -96381,52 +106401,32 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) nFarg = pFarg ? pFarg->nExpr : 0; assert( !ExprHasProperty(pExpr, EP_IntValue) ); zId = pExpr->u.zToken; - pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0); + pDef = tdsqlite3FindFunction(db, zId, nFarg, enc, 0); #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION if( pDef==0 && pParse->explain ){ - pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0); + pDef = tdsqlite3FindFunction(db, "unknown", nFarg, enc, 0); } #endif if( pDef==0 || pDef->xFinalize!=0 ){ - sqlite3ErrorMsg(pParse, "unknown function: %s()", zId); - break; - } - - /* Attempt a direct implementation of the built-in COALESCE() and - ** IFNULL() functions. This avoids unnecessary evaluation of - ** arguments past the first non-NULL argument. - */ - if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){ - int endCoalesce = sqlite3VdbeMakeLabel(v); - assert( nFarg>=2 ); - sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); - for(i=1; i<nFarg; i++){ - sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce); - VdbeCoverage(v); - sqlite3ExprCacheRemove(pParse, target, 1); - sqlite3ExprCachePush(pParse); - sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target); - sqlite3ExprCachePop(pParse); - } - sqlite3VdbeResolveLabel(v, endCoalesce); + tdsqlite3ErrorMsg(pParse, "unknown function: %s()", zId); break; } - - /* The UNLIKELY() function is a no-op. The result is the value - ** of the first argument. - */ - if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ - assert( nFarg>=1 ); - return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); + if( pDef->funcFlags & SQLITE_FUNC_INLINE ){ + assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 ); + assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 ); + return exprCodeInlineFunction(pParse, pFarg, + SQLITE_PTR_TO_INT(pDef->pUserData), target); + }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){ + tdsqlite3ExprFunctionUsable(pParse, pExpr, pDef); } for(i=0; i<nFarg; i++){ - if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){ + if( i<32 && tdsqlite3ExprIsConstant(pFarg->a[i].pExpr) ){ testcase( i==31 ); constMask |= MASKBIT32(i); } if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ - pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); + pColl = tdsqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); } } if( pFarg ){ @@ -96434,7 +106434,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) r1 = pParse->nMem+1; pParse->nMem += nFarg; }else{ - r1 = sqlite3GetTempRange(pParse, nFarg); + r1 = tdsqlite3GetTempRange(pParse, nFarg); } /* For length() and typeof() functions with a column argument, @@ -96456,10 +106456,8 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) } } - sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */ - sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, + tdsqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR); - sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */ }else{ r1 = 0; } @@ -96476,21 +106474,36 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) ** "glob(B,A). We want to use the A in "A glob B" to test ** for function overloading. But we use the B term in "glob(B,A)". */ - if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){ - pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); + if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){ + pDef = tdsqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); }else if( nFarg>0 ){ - pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); + pDef = tdsqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); } #endif if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ if( !pColl ) pColl = db->pDfltColl; - sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); + tdsqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); } - sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target, - (char*)pDef, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, (u8)nFarg); - if( nFarg && constMask==0 ){ - sqlite3ReleaseTempRange(pParse, r1, nFarg); +#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC + if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){ + Expr *pArg = pFarg->a[0].pExpr; + if( pArg->op==TK_COLUMN ){ + tdsqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target); + }else{ + tdsqlite3VdbeAddOp2(v, OP_Null, 0, target); + } + }else +#endif + { + tdsqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg, + pDef, pExpr->op2); + } + if( nFarg ){ + if( constMask==0 ){ + tdsqlite3ReleaseTempRange(pParse, r1, nFarg); + }else{ + tdsqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1); + } } return target; } @@ -96501,27 +106514,35 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) testcase( op==TK_EXISTS ); testcase( op==TK_SELECT ); if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){ - sqlite3SubselectError(pParse, nCol, 1); + tdsqlite3SubselectError(pParse, nCol, 1); }else{ - return sqlite3CodeSubselect(pParse, pExpr, 0, 0); + return tdsqlite3CodeSubselect(pParse, pExpr); } break; } case TK_SELECT_COLUMN: { + int n; if( pExpr->pLeft->iTable==0 ){ - pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0); + pExpr->pLeft->iTable = tdsqlite3CodeSubselect(pParse, pExpr->pLeft); + } + assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT ); + if( pExpr->iTable!=0 + && pExpr->iTable!=(n = tdsqlite3ExprVectorSize(pExpr->pLeft)) + ){ + tdsqlite3ErrorMsg(pParse, "%d columns assigned %d values", + pExpr->iTable, n); } return pExpr->pLeft->iTable + pExpr->iColumn; } case TK_IN: { - int destIfFalse = sqlite3VdbeMakeLabel(v); - int destIfNull = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp2(v, OP_Null, 0, target); - sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); - sqlite3VdbeAddOp2(v, OP_Integer, 1, target); - sqlite3VdbeResolveLabel(v, destIfFalse); - sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); - sqlite3VdbeResolveLabel(v, destIfNull); + int destIfFalse = tdsqlite3VdbeMakeLabel(pParse); + int destIfNull = tdsqlite3VdbeMakeLabel(pParse); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, target); + tdsqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, target); + tdsqlite3VdbeResolveLabel(v, destIfFalse); + tdsqlite3VdbeAddOp2(v, OP_AddImm, target, 0); + tdsqlite3VdbeResolveLabel(v, destIfNull); return target; } #endif /* SQLITE_OMIT_SUBQUERY */ @@ -96545,7 +106566,8 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) case TK_SPAN: case TK_COLLATE: case TK_UPLUS: { - return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + pExpr = pExpr->pLeft; + goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */ } case TK_TRIGGER: { @@ -96574,19 +106596,20 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) ** p1==1 -> old.a p1==4 -> new.a ** p1==2 -> old.b p1==5 -> new.b */ - Table *pTab = pExpr->pTab; - int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn; + Table *pTab = pExpr->y.pTab; + int iCol = pExpr->iColumn; + int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + + tdsqlite3TableColumnToStorage(pTab, iCol); assert( pExpr->iTable==0 || pExpr->iTable==1 ); - assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol ); - assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey ); + assert( iCol>=-1 && iCol<pTab->nCol ); + assert( pTab->iPKey<0 || iCol!=pTab->iPKey ); assert( p1>=0 && p1<(pTab->nCol*2+2) ); - sqlite3VdbeAddOp2(v, OP_Param, p1, target); - VdbeComment((v, "%s.%s -> $%d", + tdsqlite3VdbeAddOp2(v, OP_Param, p1, target); + VdbeComment((v, "r[%d]=%s.%s", target, (pExpr->iTable ? "new" : "old"), - (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName), - target + (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName) )); #ifndef SQLITE_OMIT_FLOATING_POINT @@ -96595,17 +106618,37 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) ** ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to ** floating point when extracting it from the record. */ - if( pExpr->iColumn>=0 - && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL - ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, target); + if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){ + tdsqlite3VdbeAddOp1(v, OP_RealAffinity, target); } #endif break; } case TK_VECTOR: { - sqlite3ErrorMsg(pParse, "row value misused"); + tdsqlite3ErrorMsg(pParse, "row value misused"); + break; + } + + /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions + ** that derive from the right-hand table of a LEFT JOIN. The + ** Expr.iTable value is the table number for the right-hand table. + ** The expression is only evaluated if that table is not currently + ** on a LEFT JOIN NULL row. + */ + case TK_IF_NULL_ROW: { + int addrINR; + u8 okConstFactor = pParse->okConstFactor; + addrINR = tdsqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable); + /* Temporarily disable factoring of constant expressions, since + ** even though expressions may appear to be constant, they are not + ** really constant because they originate from the right-hand side + ** of a LEFT JOIN. */ + pParse->okConstFactor = 0; + inReg = tdsqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + pParse->okConstFactor = okConstFactor; + tdsqlite3VdbeJumpHere(v, addrINR); + tdsqlite3VdbeChangeP3(v, addrINR, inReg); break; } @@ -96630,7 +106673,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) ** or if there is no matching Ei, the ELSE term Y, or if there is ** no ELSE term, NULL. */ - default: assert( op==TK_CASE ); { + case TK_CASE: { int endLabel; /* GOTO label for end of CASE stmt */ int nextCase; /* GOTO label for next WHEN clause */ int nExpr; /* 2x number of WHEN terms */ @@ -96640,22 +106683,27 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) Expr opCompare; /* The X==Ei expression */ Expr *pX; /* The X expression */ Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ - VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; ) + Expr *pDel = 0; + tdsqlite3 *db = pParse->db; assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList ); assert(pExpr->x.pList->nExpr > 0); pEList = pExpr->x.pList; aListelem = pEList->a; nExpr = pEList->nExpr; - endLabel = sqlite3VdbeMakeLabel(v); + endLabel = tdsqlite3VdbeMakeLabel(pParse); if( (pX = pExpr->pLeft)!=0 ){ - tempX = *pX; + pDel = tdsqlite3ExprDup(db, pX, 0); + if( db->mallocFailed ){ + tdsqlite3ExprDelete(db, pDel); + break; + } testcase( pX->op==TK_COLUMN ); - exprToRegister(&tempX, exprCodeVector(pParse, &tempX, ®Free1)); + exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); testcase( regFree1==0 ); memset(&opCompare, 0, sizeof(opCompare)); opCompare.op = TK_EQ; - opCompare.pLeft = &tempX; + opCompare.pLeft = pDel; pTest = &opCompare; /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: ** The value in regFree1 might get SCopy-ed into the file result. @@ -96664,88 +106712,99 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) regFree1 = 0; } for(i=0; i<nExpr-1; i=i+2){ - sqlite3ExprCachePush(pParse); if( pX ){ assert( pTest!=0 ); opCompare.pRight = aListelem[i].pExpr; }else{ pTest = aListelem[i].pExpr; } - nextCase = sqlite3VdbeMakeLabel(v); + nextCase = tdsqlite3VdbeMakeLabel(pParse); testcase( pTest->op==TK_COLUMN ); - sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); + tdsqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); - sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); - sqlite3VdbeGoto(v, endLabel); - sqlite3ExprCachePop(pParse); - sqlite3VdbeResolveLabel(v, nextCase); + tdsqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); + tdsqlite3VdbeGoto(v, endLabel); + tdsqlite3VdbeResolveLabel(v, nextCase); } if( (nExpr&1)!=0 ){ - sqlite3ExprCachePush(pParse); - sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); - sqlite3ExprCachePop(pParse); + tdsqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, target); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, target); } - assert( pParse->db->mallocFailed || pParse->nErr>0 - || pParse->iCacheLevel==iCacheLevel ); - sqlite3VdbeResolveLabel(v, endLabel); + tdsqlite3ExprDelete(db, pDel); + tdsqlite3VdbeResolveLabel(v, endLabel); break; } #ifndef SQLITE_OMIT_TRIGGER case TK_RAISE: { - assert( pExpr->affinity==OE_Rollback - || pExpr->affinity==OE_Abort - || pExpr->affinity==OE_Fail - || pExpr->affinity==OE_Ignore + assert( pExpr->affExpr==OE_Rollback + || pExpr->affExpr==OE_Abort + || pExpr->affExpr==OE_Fail + || pExpr->affExpr==OE_Ignore ); if( !pParse->pTriggerTab ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "RAISE() may only be used within a trigger-program"); return 0; } - if( pExpr->affinity==OE_Abort ){ - sqlite3MayAbort(pParse); + if( pExpr->affExpr==OE_Abort ){ + tdsqlite3MayAbort(pParse); } assert( !ExprHasProperty(pExpr, EP_IntValue) ); - if( pExpr->affinity==OE_Ignore ){ - sqlite3VdbeAddOp4( + if( pExpr->affExpr==OE_Ignore ){ + tdsqlite3VdbeAddOp4( v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); VdbeCoverage(v); }else{ - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER, - pExpr->affinity, pExpr->u.zToken, 0, 0); + tdsqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER, + pExpr->affExpr, pExpr->u.zToken, 0, 0); } break; } #endif } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); + tdsqlite3ReleaseTempReg(pParse, regFree1); + tdsqlite3ReleaseTempReg(pParse, regFree2); return inReg; } /* ** Factor out the code of the given expression to initialization time. +** +** If regDest>=0 then the result is always stored in that register and the +** result is not reusable. If regDest<0 then this routine is free to +** store the value whereever it wants. The register where the expression +** is stored is returned. When regDest<0, two identical expressions will +** code to the same register. */ -SQLITE_PRIVATE void sqlite3ExprCodeAtInit( +SQLITE_PRIVATE int tdsqlite3ExprCodeAtInit( Parse *pParse, /* Parsing context */ Expr *pExpr, /* The expression to code when the VDBE initializes */ - int regDest, /* Store the value in this register */ - u8 reusable /* True if this expression is reusable */ + int regDest /* Store the value in this register */ ){ ExprList *p; assert( ConstFactorOk(pParse) ); p = pParse->pConstExpr; - pExpr = sqlite3ExprDup(pParse->db, pExpr, 0); - p = sqlite3ExprListAppend(pParse, p, pExpr); + if( regDest<0 && p ){ + struct ExprList_item *pItem; + int i; + for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){ + if( pItem->reusable && tdsqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){ + return pItem->u.iConstExprReg; + } + } + } + pExpr = tdsqlite3ExprDup(pParse->db, pExpr, 0); + p = tdsqlite3ExprListAppend(pParse, p, pExpr); if( p ){ struct ExprList_item *pItem = &p->a[p->nExpr-1]; + pItem->reusable = regDest<0; + if( regDest<0 ) regDest = ++pParse->nMem; pItem->u.iConstExprReg = regDest; - pItem->reusable = reusable; } pParse->pConstExpr = p; + return regDest; } /* @@ -96761,33 +106820,22 @@ SQLITE_PRIVATE void sqlite3ExprCodeAtInit( ** code to fill the register in the initialization section of the ** VDBE program, in order to factor it out of the evaluation loop. */ -SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ +SQLITE_PRIVATE int tdsqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ int r2; - pExpr = sqlite3ExprSkipCollate(pExpr); + pExpr = tdsqlite3ExprSkipCollateAndLikely(pExpr); if( ConstFactorOk(pParse) && pExpr->op!=TK_REGISTER - && sqlite3ExprIsConstantNotJoin(pExpr) + && tdsqlite3ExprIsConstantNotJoin(pExpr) ){ - ExprList *p = pParse->pConstExpr; - int i; *pReg = 0; - if( p ){ - struct ExprList_item *pItem; - for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){ - if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){ - return pItem->u.iConstExprReg; - } - } - } - r2 = ++pParse->nMem; - sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1); + r2 = tdsqlite3ExprCodeAtInit(pParse, pExpr, -1); }else{ - int r1 = sqlite3GetTempReg(pParse); - r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); + int r1 = tdsqlite3GetTempReg(pParse); + r2 = tdsqlite3ExprCodeTarget(pParse, pExpr, r1); if( r2==r1 ){ *pReg = r1; }else{ - sqlite3ReleaseTempReg(pParse, r1); + tdsqlite3ReleaseTempReg(pParse, r1); *pReg = 0; } } @@ -96799,31 +106847,33 @@ SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ ** results in register target. The results are guaranteed to appear ** in register target. */ -SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ +SQLITE_PRIVATE void tdsqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ int inReg; assert( target>0 && target<=pParse->nMem ); - if( pExpr && pExpr->op==TK_REGISTER ){ - sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target); - }else{ - inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); - assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); - if( inReg!=target && pParse->pVdbe ){ - sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target); + inReg = tdsqlite3ExprCodeTarget(pParse, pExpr, target); + assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); + if( inReg!=target && pParse->pVdbe ){ + u8 op; + if( ExprHasProperty(pExpr,EP_Subquery) ){ + op = OP_Copy; + }else{ + op = OP_SCopy; } + tdsqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target); } } /* ** Make a transient copy of expression pExpr and then code it using -** sqlite3ExprCode(). This routine works just like sqlite3ExprCode() +** tdsqlite3ExprCode(). This routine works just like tdsqlite3ExprCode() ** except that the input expression is guaranteed to be unchanged. */ -SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ - sqlite3 *db = pParse->db; - pExpr = sqlite3ExprDup(db, pExpr, 0); - if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target); - sqlite3ExprDelete(db, pExpr); +SQLITE_PRIVATE void tdsqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ + tdsqlite3 *db = pParse->db; + pExpr = tdsqlite3ExprDup(db, pExpr, 0); + if( !db->mallocFailed ) tdsqlite3ExprCode(pParse, pExpr, target); + tdsqlite3ExprDelete(db, pExpr); } /* @@ -96832,43 +106882,21 @@ SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ ** in register target. If the expression is constant, then this routine ** might choose to code the expression at initialization time. */ -SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){ - if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){ - sqlite3ExprCodeAtInit(pParse, pExpr, target, 0); +SQLITE_PRIVATE void tdsqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){ + if( pParse->okConstFactor && tdsqlite3ExprIsConstantNotJoin(pExpr) ){ + tdsqlite3ExprCodeAtInit(pParse, pExpr, target); }else{ - sqlite3ExprCode(pParse, pExpr, target); + tdsqlite3ExprCode(pParse, pExpr, target); } } /* -** Generate code that evaluates the given expression and puts the result -** in register target. -** -** Also make a copy of the expression results into another "cache" register -** and modify the expression so that the next time it is evaluated, -** the result is a copy of the cache register. -** -** This routine is used for expressions that are used multiple -** times. They are evaluated once and the results of the expression -** are reused. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ - Vdbe *v = pParse->pVdbe; - int iMem; - - assert( target>0 ); - assert( pExpr->op!=TK_REGISTER ); - sqlite3ExprCode(pParse, pExpr, target); - iMem = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Copy, target, iMem); - exprToRegister(pExpr, iMem); -} - -/* ** Generate code that pushes the value of every element of the given ** expression list into a sequence of registers beginning at target. ** -** Return the number of elements evaluated. +** Return the number of elements evaluated. The number returned will +** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF +** is defined. ** ** The SQLITE_ECEL_DUP flag prevents the arguments from being ** filled using OP_SCopy. OP_Copy must be used instead. @@ -96879,8 +106907,10 @@ SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int targ ** The SQLITE_ECEL_REF flag means that expressions in the list with ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored ** in registers at srcReg, and so the value can be copied from there. +** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0 +** are simply omitted rather than being copied from srcReg. */ -SQLITE_PRIVATE int sqlite3ExprCodeExprList( +SQLITE_PRIVATE int tdsqlite3ExprCodeExprList( Parse *pParse, /* Parsing context */ ExprList *pList, /* The expression list to be coded */ int target, /* Where to write results */ @@ -96898,22 +106928,36 @@ SQLITE_PRIVATE int sqlite3ExprCodeExprList( if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR; for(pItem=pList->a, i=0; i<n; i++, pItem++){ Expr *pExpr = pItem->pExpr; - if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){ - sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i); - }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){ - sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0); +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + if( pItem->bSorterRef ){ + i--; + n--; + }else +#endif + if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){ + if( flags & SQLITE_ECEL_OMITREF ){ + i--; + n--; + }else{ + tdsqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i); + } + }else if( (flags & SQLITE_ECEL_FACTOR)!=0 + && tdsqlite3ExprIsConstantNotJoin(pExpr) + ){ + tdsqlite3ExprCodeAtInit(pParse, pExpr, target+i); }else{ - int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); + int inReg = tdsqlite3ExprCodeTarget(pParse, pExpr, target+i); if( inReg!=target+i ){ VdbeOp *pOp; if( copyOp==OP_Copy - && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy + && (pOp=tdsqlite3VdbeGetOp(v, -1))->opcode==OP_Copy && pOp->p1+pOp->p3+1==inReg && pOp->p2+pOp->p3+1==target+i + && pOp->p5==0 /* The do-not-merge flag must be clear */ ){ pOp->p3++; }else{ - sqlite3VdbeAddOp2(v, copyOp, inReg, target+i); + tdsqlite3VdbeAddOp2(v, copyOp, inReg, target+i); } } } @@ -96936,8 +106980,8 @@ SQLITE_PRIVATE int sqlite3ExprCodeExprList( ** The xJumpIf parameter determines details: ** ** NULL: Store the boolean result in reg[dest] -** sqlite3ExprIfTrue: Jump to dest if true -** sqlite3ExprIfFalse: Jump to dest if false +** tdsqlite3ExprIfTrue: Jump to dest if true +** tdsqlite3ExprIfFalse: Jump to dest if false ** ** The jumpIfNull parameter is ignored if xJumpIf is NULL. */ @@ -96948,46 +106992,54 @@ static void exprCodeBetween( void (*xJump)(Parse*,Expr*,int,int), /* Action to take */ int jumpIfNull /* Take the jump if the BETWEEN is NULL */ ){ - Expr exprAnd; /* The AND operator in x>=y AND x<=z */ + Expr exprAnd; /* The AND operator in x>=y AND x<=z */ Expr compLeft; /* The x>=y term */ Expr compRight; /* The x<=z term */ - Expr exprX; /* The x subexpression */ int regFree1 = 0; /* Temporary use register */ - + Expr *pDel = 0; + tdsqlite3 *db = pParse->db; memset(&compLeft, 0, sizeof(Expr)); memset(&compRight, 0, sizeof(Expr)); memset(&exprAnd, 0, sizeof(Expr)); assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - exprX = *pExpr->pLeft; - exprAnd.op = TK_AND; - exprAnd.pLeft = &compLeft; - exprAnd.pRight = &compRight; - compLeft.op = TK_GE; - compLeft.pLeft = &exprX; - compLeft.pRight = pExpr->x.pList->a[0].pExpr; - compRight.op = TK_LE; - compRight.pLeft = &exprX; - compRight.pRight = pExpr->x.pList->a[1].pExpr; - exprToRegister(&exprX, exprCodeVector(pParse, &exprX, ®Free1)); - if( xJump ){ - xJump(pParse, &exprAnd, dest, jumpIfNull); - }else{ - exprX.flags |= EP_FromJoin; - sqlite3ExprCodeTarget(pParse, &exprAnd, dest); - } - sqlite3ReleaseTempReg(pParse, regFree1); + pDel = tdsqlite3ExprDup(db, pExpr->pLeft, 0); + if( db->mallocFailed==0 ){ + exprAnd.op = TK_AND; + exprAnd.pLeft = &compLeft; + exprAnd.pRight = &compRight; + compLeft.op = TK_GE; + compLeft.pLeft = pDel; + compLeft.pRight = pExpr->x.pList->a[0].pExpr; + compRight.op = TK_LE; + compRight.pLeft = pDel; + compRight.pRight = pExpr->x.pList->a[1].pExpr; + exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); + if( xJump ){ + xJump(pParse, &exprAnd, dest, jumpIfNull); + }else{ + /* Mark the expression is being from the ON or USING clause of a join + ** so that the tdsqlite3ExprCodeTarget() routine will not attempt to move + ** it into the Parse.pConstExpr list. We should use a new bit for this, + ** for clarity, but we are out of bits in the Expr.flags field so we + ** have to reuse the EP_FromJoin bit. Bummer. */ + pDel->flags |= EP_FromJoin; + tdsqlite3ExprCodeTarget(pParse, &exprAnd, dest); + } + tdsqlite3ReleaseTempReg(pParse, regFree1); + } + tdsqlite3ExprDelete(db, pDel); /* Ensure adequate test coverage */ - testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 ); - testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 ); - testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 ); - testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 ); - testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 ); - testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 ); - testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 ); - testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 ); + testcase( xJump==tdsqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 ); + testcase( xJump==tdsqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 ); + testcase( xJump==tdsqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 ); + testcase( xJump==tdsqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 ); + testcase( xJump==tdsqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 ); + testcase( xJump==tdsqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 ); + testcase( xJump==tdsqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 ); + testcase( xJump==tdsqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 ); testcase( xJump==0 ); } @@ -97005,7 +107057,7 @@ static void exprCodeBetween( ** the make process cause these values to align. Assert()s in the code ** below verify that the numbers are aligned correctly. */ -SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ +SQLITE_PRIVATE void tdsqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; int regFree1 = 0; @@ -97017,27 +107069,45 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int if( NEVER(pExpr==0) ) return; /* No way this can happen */ op = pExpr->op; switch( op ){ - case TK_AND: { - int d2 = sqlite3VdbeMakeLabel(v); - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL); - sqlite3ExprCachePush(pParse); - sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3VdbeResolveLabel(v, d2); - sqlite3ExprCachePop(pParse); + case TK_AND: + case TK_OR: { + Expr *pAlt = tdsqlite3ExprSimplifiedAndOr(pExpr); + if( pAlt!=pExpr ){ + tdsqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull); + }else if( op==TK_AND ){ + int d2 = tdsqlite3VdbeMakeLabel(pParse); + testcase( jumpIfNull==0 ); + tdsqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, + jumpIfNull^SQLITE_JUMPIFNULL); + tdsqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); + tdsqlite3VdbeResolveLabel(v, d2); + }else{ + testcase( jumpIfNull==0 ); + tdsqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); + tdsqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); + } break; } - case TK_OR: { + case TK_NOT: { testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); - sqlite3ExprCachePush(pParse); - sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3ExprCachePop(pParse); + tdsqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); break; } - case TK_NOT: { + case TK_TRUTH: { + int isNot; /* IS NOT TRUE or IS NOT FALSE */ + int isTrue; /* IS TRUE or IS NOT TRUE */ testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); + isNot = pExpr->op2==TK_ISNOT; + isTrue = tdsqlite3ExprTruthValue(pExpr->pRight); + testcase( isTrue && isNot ); + testcase( !isTrue && isNot ); + if( isTrue ^ isNot ){ + tdsqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, + isNot ? SQLITE_JUMPIFNULL : 0); + }else{ + tdsqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, + isNot ? SQLITE_JUMPIFNULL : 0); + } break; } case TK_IS: @@ -97053,12 +107123,12 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int case TK_GE: case TK_NE: case TK_EQ: { - if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; + if( tdsqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; testcase( jumpIfNull==0 ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = tdsqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, - r1, r2, dest, jumpIfNull); + r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted)); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); @@ -97077,8 +107147,8 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int case TK_NOTNULL: { assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - sqlite3VdbeAddOp2(v, op, r1, dest); + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + tdsqlite3VdbeAddOp2(v, op, r1, dest); VdbeCoverageIf(v, op==TK_ISNULL); VdbeCoverageIf(v, op==TK_NOTNULL); testcase( regFree1==0 ); @@ -97086,28 +107156,28 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int } case TK_BETWEEN: { testcase( jumpIfNull==0 ); - exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull); + exprCodeBetween(pParse, pExpr, dest, tdsqlite3ExprIfTrue, jumpIfNull); break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_IN: { - int destIfFalse = sqlite3VdbeMakeLabel(v); + int destIfFalse = tdsqlite3VdbeMakeLabel(pParse); int destIfNull = jumpIfNull ? dest : destIfFalse; - sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); - sqlite3VdbeGoto(v, dest); - sqlite3VdbeResolveLabel(v, destIfFalse); + tdsqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); + tdsqlite3VdbeGoto(v, dest); + tdsqlite3VdbeResolveLabel(v, destIfFalse); break; } #endif default: { default_expr: - if( exprAlwaysTrue(pExpr) ){ - sqlite3VdbeGoto(v, dest); - }else if( exprAlwaysFalse(pExpr) ){ + if( ExprAlwaysTrue(pExpr) ){ + tdsqlite3VdbeGoto(v, dest); + }else if( ExprAlwaysFalse(pExpr) ){ /* No-op */ }else{ - r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); - sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr, ®Free1); + tdsqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); VdbeCoverage(v); testcase( regFree1==0 ); testcase( jumpIfNull==0 ); @@ -97115,8 +107185,8 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int break; } } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); + tdsqlite3ReleaseTempReg(pParse, regFree1); + tdsqlite3ReleaseTempReg(pParse, regFree2); } /* @@ -97128,7 +107198,7 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull ** is 0. */ -SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ +SQLITE_PRIVATE void tdsqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; int regFree1 = 0; @@ -97171,27 +107241,48 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int assert( pExpr->op!=TK_GE || op==OP_Lt ); switch( pExpr->op ){ - case TK_AND: { - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); - sqlite3ExprCachePush(pParse); - sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3ExprCachePop(pParse); + case TK_AND: + case TK_OR: { + Expr *pAlt = tdsqlite3ExprSimplifiedAndOr(pExpr); + if( pAlt!=pExpr ){ + tdsqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull); + }else if( pExpr->op==TK_AND ){ + testcase( jumpIfNull==0 ); + tdsqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); + tdsqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); + }else{ + int d2 = tdsqlite3VdbeMakeLabel(pParse); + testcase( jumpIfNull==0 ); + tdsqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, + jumpIfNull^SQLITE_JUMPIFNULL); + tdsqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); + tdsqlite3VdbeResolveLabel(v, d2); + } break; } - case TK_OR: { - int d2 = sqlite3VdbeMakeLabel(v); + case TK_NOT: { testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL); - sqlite3ExprCachePush(pParse); - sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3VdbeResolveLabel(v, d2); - sqlite3ExprCachePop(pParse); + tdsqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); break; } - case TK_NOT: { + case TK_TRUTH: { + int isNot; /* IS NOT TRUE or IS NOT FALSE */ + int isTrue; /* IS TRUE or IS NOT TRUE */ testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); + isNot = pExpr->op2==TK_ISNOT; + isTrue = tdsqlite3ExprTruthValue(pExpr->pRight); + testcase( isTrue && isNot ); + testcase( !isTrue && isNot ); + if( isTrue ^ isNot ){ + /* IS TRUE and IS NOT FALSE */ + tdsqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, + isNot ? 0 : SQLITE_JUMPIFNULL); + + }else{ + /* IS FALSE and IS NOT TRUE */ + tdsqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, + isNot ? 0 : SQLITE_JUMPIFNULL); + } break; } case TK_IS: @@ -97207,12 +107298,12 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int case TK_GE: case TK_NE: case TK_EQ: { - if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; + if( tdsqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; testcase( jumpIfNull==0 ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = tdsqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, - r1, r2, dest, jumpIfNull); + r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted)); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); @@ -97229,8 +107320,8 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int } case TK_ISNULL: case TK_NOTNULL: { - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - sqlite3VdbeAddOp2(v, op, r1, dest); + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + tdsqlite3VdbeAddOp2(v, op, r1, dest); testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL); testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL); testcase( regFree1==0 ); @@ -97238,30 +107329,30 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int } case TK_BETWEEN: { testcase( jumpIfNull==0 ); - exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull); + exprCodeBetween(pParse, pExpr, dest, tdsqlite3ExprIfFalse, jumpIfNull); break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_IN: { if( jumpIfNull ){ - sqlite3ExprCodeIN(pParse, pExpr, dest, dest); + tdsqlite3ExprCodeIN(pParse, pExpr, dest, dest); }else{ - int destIfNull = sqlite3VdbeMakeLabel(v); - sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); - sqlite3VdbeResolveLabel(v, destIfNull); + int destIfNull = tdsqlite3VdbeMakeLabel(pParse); + tdsqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); + tdsqlite3VdbeResolveLabel(v, destIfNull); } break; } #endif default: { default_expr: - if( exprAlwaysFalse(pExpr) ){ - sqlite3VdbeGoto(v, dest); - }else if( exprAlwaysTrue(pExpr) ){ + if( ExprAlwaysFalse(pExpr) ){ + tdsqlite3VdbeGoto(v, dest); + }else if( ExprAlwaysTrue(pExpr) ){ /* no-op */ }else{ - r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); - sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); + r1 = tdsqlite3ExprCodeTemp(pParse, pExpr, ®Free1); + tdsqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); VdbeCoverage(v); testcase( regFree1==0 ); testcase( jumpIfNull==0 ); @@ -97269,24 +107360,59 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int break; } } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); + tdsqlite3ReleaseTempReg(pParse, regFree1); + tdsqlite3ReleaseTempReg(pParse, regFree2); } /* -** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before +** Like tdsqlite3ExprIfFalse() except that a copy is made of pExpr before ** code generation, and that copy is deleted after code generation. This ** ensures that the original pExpr is unchanged. */ -SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){ - sqlite3 *db = pParse->db; - Expr *pCopy = sqlite3ExprDup(db, pExpr, 0); +SQLITE_PRIVATE void tdsqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){ + tdsqlite3 *db = pParse->db; + Expr *pCopy = tdsqlite3ExprDup(db, pExpr, 0); if( db->mallocFailed==0 ){ - sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull); + tdsqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull); } - sqlite3ExprDelete(db, pCopy); + tdsqlite3ExprDelete(db, pCopy); } +/* +** Expression pVar is guaranteed to be an SQL variable. pExpr may be any +** type of expression. +** +** If pExpr is a simple SQL value - an integer, real, string, blob +** or NULL value - then the VDBE currently being prepared is configured +** to re-prepare each time a new value is bound to variable pVar. +** +** Additionally, if pExpr is a simple SQL value and the value is the +** same as that currently bound to variable pVar, non-zero is returned. +** Otherwise, if the values are not the same or if pExpr is not a simple +** SQL value, zero is returned. +*/ +static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){ + int res = 0; + int iVar; + tdsqlite3_value *pL, *pR = 0; + + tdsqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR); + if( pR ){ + iVar = pVar->iColumn; + tdsqlite3VdbeSetVarmask(pParse->pVdbe, iVar); + pL = tdsqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB); + if( pL ){ + if( tdsqlite3_value_type(pL)==SQLITE_TEXT ){ + tdsqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */ + } + res = 0==tdsqlite3MemCompare(pL, pR, 0); + } + tdsqlite3ValueFree(pR); + tdsqlite3ValueFree(pL); + } + + return res; +} /* ** Do a deep comparison of two expression trees. Return 0 if the two @@ -97309,12 +107435,22 @@ SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,i ** this routine is used, it does not hurt to get an extra 2 - that ** just might result in some slightly slower code. But returning ** an incorrect 0 or 1 could lead to a malfunction. +** +** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in +** pParse->pReprepare can be matched against literals in pB. The +** pParse->pVdbe->expmask bitmask is updated for each variable referenced. +** If pParse is NULL (the normal case) then any TK_VARIABLE term in +** Argument pParse should normally be NULL. If it is not NULL and pA or +** pB causes a return value of 2. */ -SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){ +SQLITE_PRIVATE int tdsqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){ u32 combinedFlags; if( pA==0 || pB==0 ){ return pB==pA ? 0 : 2; } + if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){ + return 0; + } combinedFlags = pA->flags | pB->flags; if( combinedFlags & EP_IntValue ){ if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){ @@ -97322,40 +107458,77 @@ SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){ } return 2; } - if( pA->op!=pB->op ){ - if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){ + if( pA->op!=pB->op || pA->op==TK_RAISE ){ + if( pA->op==TK_COLLATE && tdsqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){ return 1; } - if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){ + if( pB->op==TK_COLLATE && tdsqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){ return 1; } return 2; } if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){ - if( pA->op==TK_FUNCTION ){ - if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; - }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ - return pA->op==TK_COLLATE ? 1 : 2; + if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){ + if( tdsqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; +#ifndef SQLITE_OMIT_WINDOWFUNC + assert( pA->op==pB->op ); + if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){ + return 2; + } + if( ExprHasProperty(pA,EP_WinFunc) ){ + if( tdsqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){ + return 2; + } + } +#endif + }else if( pA->op==TK_NULL ){ + return 0; + }else if( pA->op==TK_COLLATE ){ + if( tdsqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; + }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ + return 2; } } - if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2; - if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){ + if( (pA->flags & (EP_Distinct|EP_Commuted)) + != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2; + if( (combinedFlags & EP_TokenOnly)==0 ){ if( combinedFlags & EP_xIsSelect ) return 2; - if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2; - if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2; - if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; - if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){ + if( (combinedFlags & EP_FixedCol)==0 + && tdsqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2; + if( tdsqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2; + if( tdsqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; + if( pA->op!=TK_STRING + && pA->op!=TK_TRUEFALSE + && (combinedFlags & EP_Reduced)==0 + ){ if( pA->iColumn!=pB->iColumn ) return 2; - if( pA->iTable!=pB->iTable - && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2; + if( pA->op2!=pB->op2 ){ + if( pA->op==TK_TRUTH ) return 2; + if( pA->op==TK_FUNCTION && iTab<0 ){ + /* Ex: CREATE TABLE t1(a CHECK( a<julianday('now') )); + ** INSERT INTO t1(a) VALUES(julianday('now')+10); + ** Without this test, tdsqlite3ExprCodeAtInit() will run on the + ** the julianday() of INSERT first, and remember that expression. + ** Then tdsqlite3ExprCodeInit() will see the julianday() in the CHECK + ** constraint as redundant, reusing the one from the INSERT, even + ** though the julianday() in INSERT lacks the critical NC_IsCheck + ** flag. See ticket [830277d9db6c3ba1] (2019-10-30) + */ + return 2; + } + } + if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){ + return 2; + } } } return 0; } /* -** Compare two ExprList objects. Return 0 if they are identical and -** non-zero if they differ in any way. +** Compare two ExprList objects. Return 0 if they are identical, 1 +** if they are certainly different, or 2 if it is not possible to +** determine if they are identical or not. ** ** If any subelement of pB has Expr.iTable==(-1) then it is allowed ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. @@ -97368,16 +107541,105 @@ SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){ ** Two NULL pointers are considered to be the same. But a NULL pointer ** always differs from a non-NULL pointer. */ -SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ +SQLITE_PRIVATE int tdsqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ int i; if( pA==0 && pB==0 ) return 0; if( pA==0 || pB==0 ) return 1; if( pA->nExpr!=pB->nExpr ) return 1; for(i=0; i<pA->nExpr; i++){ + int res; Expr *pExprA = pA->a[i].pExpr; Expr *pExprB = pB->a[i].pExpr; - if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1; - if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1; + if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1; + if( (res = tdsqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res; + } + return 0; +} + +/* +** Like tdsqlite3ExprCompare() except COLLATE operators at the top-level +** are ignored. +*/ +SQLITE_PRIVATE int tdsqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){ + return tdsqlite3ExprCompare(0, + tdsqlite3ExprSkipCollateAndLikely(pA), + tdsqlite3ExprSkipCollateAndLikely(pB), + iTab); +} + +/* +** Return non-zero if Expr p can only be true if pNN is not NULL. +** +** Or if seenNot is true, return non-zero if Expr p can only be +** non-NULL if pNN is not NULL +*/ +static int exprImpliesNotNull( + Parse *pParse, /* Parsing context */ + Expr *p, /* The expression to be checked */ + Expr *pNN, /* The expression that is NOT NULL */ + int iTab, /* Table being evaluated */ + int seenNot /* Return true only if p can be any non-NULL value */ +){ + assert( p ); + assert( pNN ); + if( tdsqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){ + return pNN->op!=TK_NULL; + } + switch( p->op ){ + case TK_IN: { + if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0; + assert( ExprHasProperty(p,EP_xIsSelect) + || (p->x.pList!=0 && p->x.pList->nExpr>0) ); + return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); + } + case TK_BETWEEN: { + ExprList *pList = p->x.pList; + assert( pList!=0 ); + assert( pList->nExpr==2 ); + if( seenNot ) return 0; + if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1) + || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1) + ){ + return 1; + } + return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); + } + case TK_EQ: + case TK_NE: + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + case TK_PLUS: + case TK_MINUS: + case TK_BITOR: + case TK_LSHIFT: + case TK_RSHIFT: + case TK_CONCAT: + seenNot = 1; + /* Fall thru */ + case TK_STAR: + case TK_REM: + case TK_BITAND: + case TK_SLASH: { + if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1; + /* Fall thru into the next case */ + } + case TK_SPAN: + case TK_COLLATE: + case TK_UPLUS: + case TK_UMINUS: { + return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot); + } + case TK_TRUTH: { + if( seenNot ) return 0; + if( p->op2!=TK_IS ) return 0; + return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); + } + case TK_BITNOT: + case TK_NOT: { + return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); + } } return 0; } @@ -97398,23 +107660,27 @@ SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has ** Expr.iTable<0 then assume a table number given by iTab. ** +** If pParse is not NULL, then the values of bound variables in pE1 are +** compared against literal values in pE2 and pParse->pVdbe->expmask is +** modified to record which bound variables are referenced. If pParse +** is NULL, then false will be returned if pE1 contains any bound variables. +** ** When in doubt, return false. Returning true might give a performance ** improvement. Returning false might cause a performance reduction, but ** it will always give the correct answer and is hence always safe. */ -SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){ - if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){ +SQLITE_PRIVATE int tdsqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){ + if( tdsqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){ return 1; } if( pE2->op==TK_OR - && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab) - || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) ) + && (tdsqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab) + || tdsqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) ) ){ return 1; } if( pE2->op==TK_NOTNULL - && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0 - && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS) + && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0) ){ return 1; } @@ -97422,6 +107688,134 @@ SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){ } /* +** This is the Expr node callback for tdsqlite3ExprImpliesNonNullRow(). +** If the expression node requires that the table at pWalker->iCur +** have one or more non-NULL column, then set pWalker->eCode to 1 and abort. +** +** This routine controls an optimization. False positives (setting +** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives +** (never setting pWalker->eCode) is a harmless missed optimization. +*/ +static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){ + testcase( pExpr->op==TK_AGG_COLUMN ); + testcase( pExpr->op==TK_AGG_FUNCTION ); + if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune; + switch( pExpr->op ){ + case TK_ISNOT: + case TK_ISNULL: + case TK_NOTNULL: + case TK_IS: + case TK_OR: + case TK_VECTOR: + case TK_CASE: + case TK_IN: + case TK_FUNCTION: + case TK_TRUTH: + testcase( pExpr->op==TK_ISNOT ); + testcase( pExpr->op==TK_ISNULL ); + testcase( pExpr->op==TK_NOTNULL ); + testcase( pExpr->op==TK_IS ); + testcase( pExpr->op==TK_OR ); + testcase( pExpr->op==TK_VECTOR ); + testcase( pExpr->op==TK_CASE ); + testcase( pExpr->op==TK_IN ); + testcase( pExpr->op==TK_FUNCTION ); + testcase( pExpr->op==TK_TRUTH ); + return WRC_Prune; + case TK_COLUMN: + if( pWalker->u.iCur==pExpr->iTable ){ + pWalker->eCode = 1; + return WRC_Abort; + } + return WRC_Prune; + + case TK_AND: + if( pWalker->eCode==0 ){ + tdsqlite3WalkExpr(pWalker, pExpr->pLeft); + if( pWalker->eCode ){ + pWalker->eCode = 0; + tdsqlite3WalkExpr(pWalker, pExpr->pRight); + } + } + return WRC_Prune; + + case TK_BETWEEN: + if( tdsqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){ + assert( pWalker->eCode ); + return WRC_Abort; + } + return WRC_Prune; + + /* Virtual tables are allowed to use constraints like x=NULL. So + ** a term of the form x=y does not prove that y is not null if x + ** is the column of a virtual table */ + case TK_EQ: + case TK_NE: + case TK_LT: + case TK_LE: + case TK_GT: + case TK_GE: + testcase( pExpr->op==TK_EQ ); + testcase( pExpr->op==TK_NE ); + testcase( pExpr->op==TK_LT ); + testcase( pExpr->op==TK_LE ); + testcase( pExpr->op==TK_GT ); + testcase( pExpr->op==TK_GE ); + if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab)) + || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab)) + ){ + return WRC_Prune; + } + + default: + return WRC_Continue; + } +} + +/* +** Return true (non-zero) if expression p can only be true if at least +** one column of table iTab is non-null. In other words, return true +** if expression p will always be NULL or false if every column of iTab +** is NULL. +** +** False negatives are acceptable. In other words, it is ok to return +** zero even if expression p will never be true of every column of iTab +** is NULL. A false negative is merely a missed optimization opportunity. +** +** False positives are not allowed, however. A false positive may result +** in an incorrect answer. +** +** Terms of p that are marked with EP_FromJoin (and hence that come from +** the ON or USING clauses of LEFT JOINS) are excluded from the analysis. +** +** This routine is used to check if a LEFT JOIN can be converted into +** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE +** clause requires that some column of the right table of the LEFT JOIN +** be non-NULL, then the LEFT JOIN can be safely converted into an +** ordinary join. +*/ +SQLITE_PRIVATE int tdsqlite3ExprImpliesNonNullRow(Expr *p, int iTab){ + Walker w; + p = tdsqlite3ExprSkipCollateAndLikely(p); + if( p==0 ) return 0; + if( p->op==TK_NOTNULL ){ + p = p->pLeft; + }else{ + while( p->op==TK_AND ){ + if( tdsqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1; + p = p->pRight; + } + } + w.xExprCallback = impliesNotNullRow; + w.xSelectCallback = 0; + w.xSelectCallback2 = 0; + w.eCode = 0; + w.u.iCur = iTab; + tdsqlite3WalkExpr(&w, p); + return w.eCode; +} + +/* ** An instance of the following structure is used by the tree walker ** to determine if an expression can be evaluated by reference to the ** index only, without having to do a search for the corresponding @@ -97441,7 +107835,7 @@ struct IdxCover { static int exprIdxCover(Walker *pWalker, Expr *pExpr){ if( pExpr->op==TK_COLUMN && pExpr->iTable==pWalker->u.pIdxCover->iCur - && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0 + && tdsqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0 ){ pWalker->eCode = 1; return WRC_Abort; @@ -97459,7 +107853,7 @@ static int exprIdxCover(Walker *pWalker, Expr *pExpr){ ** evaluated using only the index and without having to lookup the ** corresponding table entry. */ -SQLITE_PRIVATE int sqlite3ExprCoveredByIndex( +SQLITE_PRIVATE int tdsqlite3ExprCoveredByIndex( Expr *pExpr, /* The index to be tested */ int iCur, /* The cursor number for the corresponding table */ Index *pIdx /* The index that might be used for coverage */ @@ -97471,7 +107865,7 @@ SQLITE_PRIVATE int sqlite3ExprCoveredByIndex( xcov.pIdx = pIdx; w.xExprCallback = exprIdxCover; w.u.pIdxCover = &xcov; - sqlite3WalkExpr(&w, pExpr); + tdsqlite3WalkExpr(&w, pExpr); return !w.eCode; } @@ -97480,7 +107874,7 @@ SQLITE_PRIVATE int sqlite3ExprCoveredByIndex( ** An instance of the following structure is used by the tree walker ** to count references to table columns in the arguments of an ** aggregate function, in order to implement the -** sqlite3FunctionThisSrc() routine. +** tdsqlite3FunctionThisSrc() routine. */ struct SrcCount { SrcList *pSrc; /* One particular FROM clause in a nested query */ @@ -97492,12 +107886,13 @@ struct SrcCount { ** Count the number of references to columns. */ static int exprSrcCount(Walker *pWalker, Expr *pExpr){ - /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc() - ** is always called before sqlite3ExprAnalyzeAggregates() and so the - ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If - ** sqlite3FunctionUsesThisSrc() is used differently in the future, the - ** NEVER() will need to be removed. */ - if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){ + /* There was once a NEVER() on the second term on the grounds that + ** tdsqlite3FunctionUsesThisSrc() was always called before + ** tdsqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet + ** been converted into TK_AGG_COLUMN. But this is no longer true due + ** to window functions - tdsqlite3WindowRewrite() may now indirectly call + ** FunctionUsesThisSrc() when creating a new sub-select. */ + if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){ int i; struct SrcCount *p = pWalker->u.pSrcCount; SrcList *pSrc = p->pSrc; @@ -97507,7 +107902,10 @@ static int exprSrcCount(Walker *pWalker, Expr *pExpr){ } if( i<nSrc ){ p->nThis++; - }else{ + }else if( nSrc==0 || pExpr->iTable<pSrc->a[0].iCursor ){ + /* In a well-formed parse tree (no name resolution errors), + ** TK_COLUMN nodes with smaller Expr.iTable values are in an + ** outer context. Those are the only ones to count as "other" */ p->nOther++; } } @@ -97520,17 +107918,23 @@ static int exprSrcCount(Walker *pWalker, Expr *pExpr){ ** has no arguments or has only constant arguments. Return false if pExpr ** references columns but not columns of tables found in pSrcList. */ -SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ +SQLITE_PRIVATE int tdsqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ Walker w; struct SrcCount cnt; assert( pExpr->op==TK_AGG_FUNCTION ); memset(&w, 0, sizeof(w)); w.xExprCallback = exprSrcCount; + w.xSelectCallback = tdsqlite3SelectWalkNoop; w.u.pSrcCount = &cnt; cnt.pSrc = pSrcList; cnt.nThis = 0; cnt.nOther = 0; - sqlite3WalkExprList(&w, pExpr->x.pList); + tdsqlite3WalkExprList(&w, pExpr->x.pList); +#ifndef SQLITE_OMIT_WINDOWFUNC + if( ExprHasProperty(pExpr, EP_WinFunc) ){ + tdsqlite3WalkExpr(&w, pExpr->y.pWin->pFilter); + } +#endif return cnt.nThis>0 || cnt.nOther==0; } @@ -97538,9 +107942,9 @@ SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ ** Add a new element to the pAggInfo->aCol[] array. Return the index of ** the new element. Return a negative number if malloc fails. */ -static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ +static int addAggInfoColumn(tdsqlite3 *db, AggInfo *pInfo){ int i; - pInfo->aCol = sqlite3ArrayAllocate( + pInfo->aCol = tdsqlite3ArrayAllocate( db, pInfo->aCol, sizeof(pInfo->aCol[0]), @@ -97554,9 +107958,9 @@ static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ ** Add a new element to the pAggInfo->aFunc[] array. Return the index of ** the new element. Return a negative number if malloc fails. */ -static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ +static int addAggInfoFunc(tdsqlite3 *db, AggInfo *pInfo){ int i; - pInfo->aFunc = sqlite3ArrayAllocate( + pInfo->aFunc = tdsqlite3ArrayAllocate( db, pInfo->aFunc, sizeof(pInfo->aFunc[0]), @@ -97568,7 +107972,7 @@ static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ /* ** This is the xExprCallback for a tree walker. It is used to -** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates +** implement tdsqlite3ExprAnalyzeAggregates(). See tdsqlite3ExprAnalyzeAggregates ** for additional information. */ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ @@ -97576,8 +107980,9 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ NameContext *pNC = pWalker->u.pNC; Parse *pParse = pNC->pParse; SrcList *pSrcList = pNC->pSrcList; - AggInfo *pAggInfo = pNC->pAggInfo; + AggInfo *pAggInfo = pNC->uNC.pAggInfo; + assert( pNC->ncFlags & NC_UAggInfo ); switch( pExpr->op ){ case TK_AGG_COLUMN: case TK_COLUMN: { @@ -97609,7 +108014,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 ){ pCol = &pAggInfo->aCol[k]; - pCol->pTab = pExpr->pTab; + pCol->pTab = pExpr->y.pTab; pCol->iTable = pExpr->iTable; pCol->iColumn = pExpr->iColumn; pCol->iMem = ++pParse->nMem; @@ -97657,7 +108062,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ */ struct AggInfo_func *pItem = pAggInfo->aFunc; for(i=0; i<pAggInfo->nFunc; i++, pItem++){ - if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){ + if( tdsqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){ break; } } @@ -97672,7 +108077,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ pItem->pExpr = pExpr; pItem->iMem = ++pParse->nMem; assert( !ExprHasProperty(pExpr, EP_IntValue) ); - pItem->pFunc = sqlite3FindFunction(pParse->db, + pItem->pFunc = tdsqlite3FindFunction(pParse->db, pExpr->u.zToken, pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0); if( pExpr->flags & EP_Distinct ){ @@ -97697,10 +108102,14 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ return WRC_Continue; } static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){ - UNUSED_PARAMETER(pWalker); UNUSED_PARAMETER(pSelect); + pWalker->walkerDepth++; return WRC_Continue; } +static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){ + UNUSED_PARAMETER(pSelect); + pWalker->walkerDepth--; +} /* ** Analyze the pExpr expression looking for aggregate functions and @@ -97709,30 +108118,32 @@ static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){ ** necessary. ** ** This routine should only be called after the expression has been -** analyzed by sqlite3ResolveExprNames(). +** analyzed by tdsqlite3ResolveExprNames(). */ -SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ +SQLITE_PRIVATE void tdsqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ Walker w; - memset(&w, 0, sizeof(w)); w.xExprCallback = analyzeAggregate; w.xSelectCallback = analyzeAggregatesInSelect; + w.xSelectCallback2 = analyzeAggregatesInSelectEnd; + w.walkerDepth = 0; w.u.pNC = pNC; + w.pParse = 0; assert( pNC->pSrcList!=0 ); - sqlite3WalkExpr(&w, pExpr); + tdsqlite3WalkExpr(&w, pExpr); } /* -** Call sqlite3ExprAnalyzeAggregates() for every expression in an +** Call tdsqlite3ExprAnalyzeAggregates() for every expression in an ** expression list. Return the number of errors. ** ** If an error is found, the analysis is cut short. */ -SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ +SQLITE_PRIVATE void tdsqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ struct ExprList_item *pItem; int i; if( pList ){ for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ - sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); + tdsqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); } } } @@ -97740,7 +108151,7 @@ SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList) /* ** Allocate a single new register for use to hold some intermediate result. */ -SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){ +SQLITE_PRIVATE int tdsqlite3GetTempReg(Parse *pParse){ if( pParse->nTempReg==0 ){ return ++pParse->nMem; } @@ -97750,35 +108161,25 @@ SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){ /* ** Deallocate a register, making available for reuse for some other ** purpose. -** -** If a register is currently being used by the column cache, then -** the deallocation is deferred until the column cache line that uses -** the register becomes stale. */ -SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ - if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){ - int i; - struct yColCache *p; - for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){ - if( p->iReg==iReg ){ - p->tempReg = 1; - return; - } +SQLITE_PRIVATE void tdsqlite3ReleaseTempReg(Parse *pParse, int iReg){ + if( iReg ){ + tdsqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0); + if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){ + pParse->aTempReg[pParse->nTempReg++] = iReg; } - pParse->aTempReg[pParse->nTempReg++] = iReg; } } /* ** Allocate or deallocate a block of nReg consecutive registers. */ -SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){ +SQLITE_PRIVATE int tdsqlite3GetTempRange(Parse *pParse, int nReg){ int i, n; - if( nReg==1 ) return sqlite3GetTempReg(pParse); + if( nReg==1 ) return tdsqlite3GetTempReg(pParse); i = pParse->iRangeReg; n = pParse->nRangeReg; if( nReg<=n ){ - assert( !usedAsColumnCache(pParse, i, i+n-1) ); pParse->iRangeReg += nReg; pParse->nRangeReg -= nReg; }else{ @@ -97787,12 +108188,12 @@ SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){ } return i; } -SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ +SQLITE_PRIVATE void tdsqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ if( nReg==1 ){ - sqlite3ReleaseTempReg(pParse, iReg); + tdsqlite3ReleaseTempReg(pParse, iReg); return; } - sqlite3ExprCacheRemove(pParse, iReg, nReg); + tdsqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0); if( nReg>pParse->nRangeReg ){ pParse->nRangeReg = nReg; pParse->iRangeReg = iReg; @@ -97801,8 +108202,13 @@ SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ /* ** Mark all temporary registers as being unavailable for reuse. +** +** Always invoke this procedure after coding a subroutine or co-routine +** that might be invoked from other parts of the code, to ensure that +** the sub/co-routine does not use registers in common with the code that +** invokes the sub/co-routine. */ -SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){ +SQLITE_PRIVATE void tdsqlite3ClearTempRegCache(Parse *pParse){ pParse->nTempReg = 0; pParse->nRangeReg = 0; } @@ -97813,11 +108219,11 @@ SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){ ** statements. */ #ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ +SQLITE_PRIVATE int tdsqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ int i; if( pParse->nRangeReg>0 - && pParse->iRangeReg+pParse->nRangeReg<iLast - && pParse->iRangeReg>=iFirst + && pParse->iRangeReg+pParse->nRangeReg > iFirst + && pParse->iRangeReg <= iLast ){ return 0; } @@ -97854,373 +108260,76 @@ SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ */ #ifndef SQLITE_OMIT_ALTERTABLE - -/* -** This function is used by SQL generated to implement the -** ALTER TABLE command. The first argument is the text of a CREATE TABLE or -** CREATE INDEX command. The second is a table name. The table name in -** the CREATE TABLE or CREATE INDEX statement is replaced with the third -** argument and the result returned. Examples: -** -** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def') -** -> 'CREATE TABLE def(a, b, c)' -** -** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def') -** -> 'CREATE INDEX i ON def(a, b, c)' -*/ -static void renameTableFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - unsigned char const *zSql = sqlite3_value_text(argv[0]); - unsigned char const *zTableName = sqlite3_value_text(argv[1]); - - int token; - Token tname; - unsigned char const *zCsr = zSql; - int len = 0; - char *zRet; - - sqlite3 *db = sqlite3_context_db_handle(context); - - UNUSED_PARAMETER(NotUsed); - - /* The principle used to locate the table name in the CREATE TABLE - ** statement is that the table name is the first non-space token that - ** is immediately followed by a TK_LP or TK_USING token. - */ - if( zSql ){ - do { - if( !*zCsr ){ - /* Ran out of input before finding an opening bracket. Return NULL. */ - return; - } - - /* Store the token that zCsr points to in tname. */ - tname.z = (char*)zCsr; - tname.n = len; - - /* Advance zCsr to the next token. Store that token type in 'token', - ** and its length in 'len' (to be used next iteration of this loop). - */ - do { - zCsr += len; - len = sqlite3GetToken(zCsr, &token); - } while( token==TK_SPACE ); - assert( len>0 ); - } while( token!=TK_LP && token!=TK_USING ); - - zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql), - zSql, zTableName, tname.z+tname.n); - sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); - } -} - /* -** This C function implements an SQL user function that is used by SQL code -** generated by the ALTER TABLE ... RENAME command to modify the definition -** of any foreign key constraints that use the table being renamed as the -** parent table. It is passed three arguments: -** -** 1) The complete text of the CREATE TABLE statement being modified, -** 2) The old name of the table being renamed, and -** 3) The new name of the table being renamed. -** -** It returns the new CREATE TABLE statement. For example: +** Parameter zName is the name of a table that is about to be altered +** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). +** If the table is a system table, this function leaves an error message +** in pParse->zErr (system tables may not be altered) and returns non-zero. ** -** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3') -** -> 'CREATE TABLE t1(a REFERENCES t3)' -*/ -#ifndef SQLITE_OMIT_FOREIGN_KEY -static void renameParentFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - sqlite3 *db = sqlite3_context_db_handle(context); - char *zOutput = 0; - char *zResult; - unsigned char const *zInput = sqlite3_value_text(argv[0]); - unsigned char const *zOld = sqlite3_value_text(argv[1]); - unsigned char const *zNew = sqlite3_value_text(argv[2]); - - unsigned const char *z; /* Pointer to token */ - int n; /* Length of token z */ - int token; /* Type of token */ - - UNUSED_PARAMETER(NotUsed); - if( zInput==0 || zOld==0 ) return; - for(z=zInput; *z; z=z+n){ - n = sqlite3GetToken(z, &token); - if( token==TK_REFERENCES ){ - char *zParent; - do { - z += n; - n = sqlite3GetToken(z, &token); - }while( token==TK_SPACE ); - - if( token==TK_ILLEGAL ) break; - zParent = sqlite3DbStrNDup(db, (const char *)z, n); - if( zParent==0 ) break; - sqlite3Dequote(zParent); - if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){ - char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", - (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew - ); - sqlite3DbFree(db, zOutput); - zOutput = zOut; - zInput = &z[n]; - } - sqlite3DbFree(db, zParent); - } - } - - zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), - sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC); - sqlite3DbFree(db, zOutput); -} -#endif - -#ifndef SQLITE_OMIT_TRIGGER -/* This function is used by SQL generated to implement the -** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER -** statement. The second is a table name. The table name in the CREATE -** TRIGGER statement is replaced with the third argument and the result -** returned. This is analagous to renameTableFunc() above, except for CREATE -** TRIGGER, not CREATE INDEX and CREATE TABLE. -*/ -static void renameTriggerFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - unsigned char const *zSql = sqlite3_value_text(argv[0]); - unsigned char const *zTableName = sqlite3_value_text(argv[1]); - - int token; - Token tname; - int dist = 3; - unsigned char const *zCsr = zSql; - int len = 0; - char *zRet; - sqlite3 *db = sqlite3_context_db_handle(context); - - UNUSED_PARAMETER(NotUsed); - - /* The principle used to locate the table name in the CREATE TRIGGER - ** statement is that the table name is the first token that is immediately - ** preceded by either TK_ON or TK_DOT and immediately followed by one - ** of TK_WHEN, TK_BEGIN or TK_FOR. - */ - if( zSql ){ - do { - - if( !*zCsr ){ - /* Ran out of input before finding the table name. Return NULL. */ - return; - } - - /* Store the token that zCsr points to in tname. */ - tname.z = (char*)zCsr; - tname.n = len; - - /* Advance zCsr to the next token. Store that token type in 'token', - ** and its length in 'len' (to be used next iteration of this loop). - */ - do { - zCsr += len; - len = sqlite3GetToken(zCsr, &token); - }while( token==TK_SPACE ); - assert( len>0 ); - - /* Variable 'dist' stores the number of tokens read since the most - ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN - ** token is read and 'dist' equals 2, the condition stated above - ** to be met. - ** - ** Note that ON cannot be a database, table or column name, so - ** there is no need to worry about syntax like - ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. - */ - dist++; - if( token==TK_DOT || token==TK_ON ){ - dist = 0; - } - } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) ); - - /* Variable tname now contains the token that is the old table-name - ** in the CREATE TRIGGER statement. - */ - zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql), - zSql, zTableName, tname.z+tname.n); - sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); - } -} -#endif /* !SQLITE_OMIT_TRIGGER */ - -/* -** Register built-in functions used to help implement ALTER TABLE +** Or, if zName is not a system table, zero is returned. */ -SQLITE_PRIVATE void sqlite3AlterFunctions(void){ - static FuncDef aAlterTableFuncs[] = { - FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc), -#ifndef SQLITE_OMIT_TRIGGER - FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc), -#endif -#ifndef SQLITE_OMIT_FOREIGN_KEY - FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc), +static int isAlterableTable(Parse *pParse, Table *pTab){ + if( 0==tdsqlite3StrNICmp(pTab->zName, "sqlite_", 7) +#ifndef SQLITE_OMIT_VIRTUALTABLE + || ( (pTab->tabFlags & TF_Shadow)!=0 + && tdsqlite3ReadOnlyShadowTables(pParse->db) + ) #endif - }; - sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs)); -} - -/* -** This function is used to create the text of expressions of the form: -** -** name=<constant1> OR name=<constant2> OR ... -** -** If argument zWhere is NULL, then a pointer string containing the text -** "name=<constant>" is returned, where <constant> is the quoted version -** of the string passed as argument zConstant. The returned buffer is -** allocated using sqlite3DbMalloc(). It is the responsibility of the -** caller to ensure that it is eventually freed. -** -** If argument zWhere is not NULL, then the string returned is -** "<where> OR name=<constant>", where <where> is the contents of zWhere. -** In this case zWhere is passed to sqlite3DbFree() before returning. -** -*/ -static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){ - char *zNew; - if( !zWhere ){ - zNew = sqlite3MPrintf(db, "name=%Q", zConstant); - }else{ - zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant); - sqlite3DbFree(db, zWhere); - } - return zNew; -} - -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) -/* -** Generate the text of a WHERE expression which can be used to select all -** tables that have foreign key constraints that refer to table pTab (i.e. -** constraints for which pTab is the parent table) from the sqlite_master -** table. -*/ -static char *whereForeignKeys(Parse *pParse, Table *pTab){ - FKey *p; - char *zWhere = 0; - for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ - zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName); + ){ + tdsqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName); + return 1; } - return zWhere; + return 0; } -#endif /* -** Generate the text of a WHERE expression which can be used to select all -** temporary triggers on table pTab from the sqlite_temp_master table. If -** table pTab has no temporary triggers, or is itself stored in the -** temporary database, NULL is returned. +** Generate code to verify that the schemas of database zDb and, if +** bTemp is not true, database "temp", can still be parsed. This is +** called at the end of the generation of an ALTER TABLE ... RENAME ... +** statement to ensure that the operation has not rendered any schema +** objects unusable. */ -static char *whereTempTriggers(Parse *pParse, Table *pTab){ - Trigger *pTrig; - char *zWhere = 0; - const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */ +static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){ + tdsqlite3NestedParse(pParse, + "SELECT 1 " + "FROM \"%w\".%s " + "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" + " AND sql NOT LIKE 'create virtual%%'" + " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ", + zDb, MASTER_NAME, + zDb, bTemp + ); - /* If the table is not located in the temp-db (in which case NULL is - ** returned, loop through the tables list of triggers. For each trigger - ** that is not part of the temp-db schema, add a clause to the WHERE - ** expression being built up in zWhere. - */ - if( pTab->pSchema!=pTempSchema ){ - sqlite3 *db = pParse->db; - for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ - if( pTrig->pSchema==pTempSchema ){ - zWhere = whereOrName(db, zWhere, pTrig->zName); - } - } - } - if( zWhere ){ - char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere); - sqlite3DbFree(pParse->db, zWhere); - zWhere = zNew; + if( bTemp==0 ){ + tdsqlite3NestedParse(pParse, + "SELECT 1 " + "FROM temp.%s " + "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" + " AND sql NOT LIKE 'create virtual%%'" + " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ", + MASTER_NAME, zDb + ); } - return zWhere; } /* -** Generate code to drop and reload the internal representation of table -** pTab from the database, including triggers and temporary triggers. -** Argument zName is the name of the table in the database schema at -** the time the generated code is executed. This can be different from -** pTab->zName if this function is being called to code part of an -** "ALTER TABLE RENAME TO" statement. +** Generate code to reload the schema for database iDb. And, if iDb!=1, for +** the temp database as well. */ -static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){ - Vdbe *v; - char *zWhere; - int iDb; /* Index of database containing pTab */ -#ifndef SQLITE_OMIT_TRIGGER - Trigger *pTrig; -#endif - - v = sqlite3GetVdbe(pParse); - if( NEVER(v==0) ) return; - assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - assert( iDb>=0 ); - -#ifndef SQLITE_OMIT_TRIGGER - /* Drop any table triggers from the internal schema. */ - for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ - int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); - assert( iTrigDb==iDb || iTrigDb==1 ); - sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0); - } -#endif - - /* Drop the table and index from the internal schema. */ - sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); - - /* Reload the table, index and permanent trigger schemas. */ - zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName); - if( !zWhere ) return; - sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); - -#ifndef SQLITE_OMIT_TRIGGER - /* Now, if the table is not stored in the temp database, reload any temp - ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. - */ - if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ - sqlite3VdbeAddParseSchemaOp(v, 1, zWhere); - } -#endif -} - -/* -** Parameter zName is the name of a table that is about to be altered -** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). -** If the table is a system table, this function leaves an error message -** in pParse->zErr (system tables may not be altered) and returns non-zero. -** -** Or, if zName is not a system table, zero is returned. -*/ -static int isSystemTable(Parse *pParse, const char *zName){ - if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ - sqlite3ErrorMsg(pParse, "table %s may not be altered", zName); - return 1; +static void renameReloadSchema(Parse *pParse, int iDb){ + Vdbe *v = pParse->pVdbe; + if( v ){ + tdsqlite3ChangeCookie(pParse, iDb); + tdsqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0); + if( iDb!=1 ) tdsqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0); } - return 0; } /* ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" ** command. */ -SQLITE_PRIVATE void sqlite3AlterRenameTable( +SQLITE_PRIVATE void tdsqlite3AlterRenameTable( Parse *pParse, /* Parser context. */ SrcList *pSrc, /* The table to rename. */ Token *pName /* The new table name. */ @@ -98229,36 +108338,33 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable( char *zDb; /* Name of database iDb */ Table *pTab; /* Table being renamed */ char *zName = 0; /* NULL-terminated version of pName */ - sqlite3 *db = pParse->db; /* Database connection */ + tdsqlite3 *db = pParse->db; /* Database connection */ int nTabName; /* Number of UTF-8 characters in zTabName */ const char *zTabName; /* Original name of the table */ Vdbe *v; -#ifndef SQLITE_OMIT_TRIGGER - char *zWhere = 0; /* Where clause to locate temp triggers */ -#endif VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */ - int savedDbFlags; /* Saved value of db->flags */ + u32 savedDbFlags; /* Saved value of db->mDbFlags */ - savedDbFlags = db->flags; + savedDbFlags = db->mDbFlags; if( NEVER(db->mallocFailed) ) goto exit_rename_table; assert( pSrc->nSrc==1 ); - assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); + assert( tdsqlite3BtreeHoldsAllMutexes(pParse->db) ); - pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); + pTab = tdsqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); if( !pTab ) goto exit_rename_table; - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(pParse->db, pTab->pSchema); zDb = db->aDb[iDb].zDbSName; - db->flags |= SQLITE_PreferBuiltin; + db->mDbFlags |= DBFLAG_PreferBuiltin; /* Get a NULL terminated version of the new table name. */ - zName = sqlite3NameFromToken(db, pName); + zName = tdsqlite3NameFromToken(db, pName); if( !zName ) goto exit_rename_table; /* Check that a table or index named 'zName' does not already exist ** in database iDb. If so, this is an error. */ - if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){ - sqlite3ErrorMsg(pParse, + if( tdsqlite3FindTable(db, zName, zDb) || tdsqlite3FindIndex(db, zName, zDb) ){ + tdsqlite3ErrorMsg(pParse, "there is already another table or index with this name: %s", zName); goto exit_rename_table; } @@ -98266,154 +108372,127 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable( /* Make sure it is not a system table being altered, or a reserved name ** that the table is being renamed to. */ - if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ + if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){ goto exit_rename_table; } - if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto - exit_rename_table; + if( SQLITE_OK!=tdsqlite3CheckObjectName(pParse,zName,"table",zName) ){ + goto exit_rename_table; } #ifndef SQLITE_OMIT_VIEW if( pTab->pSelect ){ - sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); + tdsqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); goto exit_rename_table; } #endif #ifndef SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ - if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ + if( tdsqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ goto exit_rename_table; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE - if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + if( tdsqlite3ViewGetColumnNames(pParse, pTab) ){ goto exit_rename_table; } if( IsVirtual(pTab) ){ - pVTab = sqlite3GetVTable(db, pTab); + pVTab = tdsqlite3GetVTable(db, pTab); if( pVTab->pVtab->pModule->xRename==0 ){ pVTab = 0; } } #endif - /* Begin a transaction for database iDb. - ** Then modify the schema cookie (since the ALTER TABLE modifies the - ** schema). Open a statement transaction if the table is a virtual - ** table. - */ - v = sqlite3GetVdbe(pParse); + /* Begin a transaction for database iDb. Then modify the schema cookie + ** (since the ALTER TABLE modifies the schema). Call tdsqlite3MayAbort(), + ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the + ** nested SQL may raise an exception. */ + v = tdsqlite3GetVdbe(pParse); if( v==0 ){ goto exit_rename_table; } - sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb); - sqlite3ChangeCookie(pParse, iDb); - - /* If this is a virtual table, invoke the xRename() function if - ** one is defined. The xRename() callback will modify the names - ** of any resources used by the v-table implementation (including other - ** SQLite tables) that are identified by the name of the virtual table. - */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( pVTab ){ - int i = ++pParse->nMem; - sqlite3VdbeLoadString(v, i, zName); - sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB); - sqlite3MayAbort(pParse); - } -#endif + tdsqlite3MayAbort(pParse); /* figure out how many UTF-8 characters are in zName */ zTabName = pTab->zName; - nTabName = sqlite3Utf8CharLen(zTabName, -1); - -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - if( db->flags&SQLITE_ForeignKeys ){ - /* If foreign-key support is enabled, rewrite the CREATE TABLE - ** statements corresponding to all child tables of foreign key constraints - ** for which the renamed table is the parent table. */ - if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){ - sqlite3NestedParse(pParse, - "UPDATE \"%w\".%s SET " - "sql = sqlite_rename_parent(sql, %Q, %Q) " - "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere); - sqlite3DbFree(db, zWhere); - } - } -#endif + nTabName = tdsqlite3Utf8CharLen(zTabName, -1); + + /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in + ** the schema to use the new table name. */ + tdsqlite3NestedParse(pParse, + "UPDATE \"%w\".%s SET " + "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) " + "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)" + "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" + , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName + ); - /* Modify the sqlite_master table to use the new table name. */ - sqlite3NestedParse(pParse, + /* Update the tbl_name and name columns of the sqlite_master table + ** as required. */ + tdsqlite3NestedParse(pParse, "UPDATE %Q.%s SET " -#ifdef SQLITE_OMIT_TRIGGER - "sql = sqlite_rename_table(sql, %Q), " -#else - "sql = CASE " - "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" - "ELSE sqlite_rename_table(sql, %Q) END, " -#endif "tbl_name = %Q, " "name = CASE " "WHEN type='table' THEN %Q " - "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " + "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' " + " AND type='index' THEN " "'sqlite_autoindex_' || %Q || substr(name,%d+18) " "ELSE name END " "WHERE tbl_name=%Q COLLATE nocase AND " "(type='table' OR type='index' OR type='trigger');", - zDb, SCHEMA_TABLE(iDb), zName, zName, zName, -#ifndef SQLITE_OMIT_TRIGGER - zName, -#endif - zName, nTabName, zTabName + zDb, MASTER_NAME, + zName, zName, zName, + nTabName, zTabName ); #ifndef SQLITE_OMIT_AUTOINCREMENT /* If the sqlite_sequence table exists in this database, then update ** it with the new table name. */ - if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ - sqlite3NestedParse(pParse, + if( tdsqlite3FindTable(db, "sqlite_sequence", zDb) ){ + tdsqlite3NestedParse(pParse, "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", zDb, zName, pTab->zName); } #endif -#ifndef SQLITE_OMIT_TRIGGER - /* If there are TEMP triggers on this table, modify the sqlite_temp_master - ** table. Don't do this if the table being ALTERed is itself located in - ** the temp database. - */ - if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ - sqlite3NestedParse(pParse, + /* If the table being renamed is not itself part of the temp database, + ** edit view and trigger definitions within the temp database + ** as required. */ + if( iDb!=1 ){ + tdsqlite3NestedParse(pParse, "UPDATE sqlite_temp_master SET " - "sql = sqlite_rename_trigger(sql, %Q), " - "tbl_name = %Q " - "WHERE %s;", zName, zName, zWhere); - sqlite3DbFree(db, zWhere); + "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), " + "tbl_name = " + "CASE WHEN tbl_name=%Q COLLATE nocase AND " + " sqlite_rename_test(%Q, sql, type, name, 1) " + "THEN %Q ELSE tbl_name END " + "WHERE type IN ('view', 'trigger')" + , zDb, zTabName, zName, zTabName, zDb, zName); } -#endif -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - if( db->flags&SQLITE_ForeignKeys ){ - FKey *p; - for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ - Table *pFrom = p->pFrom; - if( pFrom!=pTab ){ - reloadTableSchema(pParse, p->pFrom, pFrom->zName); - } - } + /* If this is a virtual table, invoke the xRename() function if + ** one is defined. The xRename() callback will modify the names + ** of any resources used by the v-table implementation (including other + ** SQLite tables) that are identified by the name of the virtual table. + */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( pVTab ){ + int i = ++pParse->nMem; + tdsqlite3VdbeLoadString(v, i, zName); + tdsqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB); } #endif - /* Drop and reload the internal table schema. */ - reloadTableSchema(pParse, pTab, zName); + renameReloadSchema(pParse, iDb); + renameTestSchema(pParse, zDb, iDb==1); exit_rename_table: - sqlite3SrcListDelete(db, pSrc); - sqlite3DbFree(db, zName); - db->flags = savedDbFlags; + tdsqlite3SrcListDelete(db, pSrc); + tdsqlite3DbFree(db, zName); + db->mDbFlags = savedDbFlags; } /* @@ -98424,7 +108503,7 @@ exit_rename_table: ** The Table structure pParse->pNewTable was extended to include ** the new column during parsing. */ -SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ +SQLITE_PRIVATE void tdsqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ Table *pNew; /* Copy of pParse->pNewTable */ Table *pTab; /* Table being altered */ int iDb; /* Database number */ @@ -98433,118 +108512,126 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ char *zCol; /* Null-terminated column definition */ Column *pCol; /* The new column */ Expr *pDflt; /* Default value for the new column */ - sqlite3 *db; /* The database connection; */ - Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ + tdsqlite3 *db; /* The database connection; */ + Vdbe *v; /* The prepared statement under construction */ int r1; /* Temporary registers */ db = pParse->db; if( pParse->nErr || db->mallocFailed ) return; - assert( v!=0 ); pNew = pParse->pNewTable; assert( pNew ); - assert( sqlite3BtreeHoldsAllMutexes(db) ); - iDb = sqlite3SchemaToIndex(db, pNew->pSchema); + assert( tdsqlite3BtreeHoldsAllMutexes(db) ); + iDb = tdsqlite3SchemaToIndex(db, pNew->pSchema); zDb = db->aDb[iDb].zDbSName; zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ pCol = &pNew->aCol[pNew->nCol-1]; pDflt = pCol->pDflt; - pTab = sqlite3FindTable(db, zTab, zDb); + pTab = tdsqlite3FindTable(db, zTab, zDb); assert( pTab ); #ifndef SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ - if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ + if( tdsqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ return; } #endif - /* If the default value for the new column was specified with a - ** literal NULL, then set pDflt to 0. This simplifies checking - ** for an SQL NULL default below. - */ - assert( pDflt==0 || pDflt->op==TK_SPAN ); - if( pDflt && pDflt->pLeft->op==TK_NULL ){ - pDflt = 0; - } /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. ** If there is a NOT NULL constraint, then the default value for the ** column must not be NULL. */ if( pCol->colFlags & COLFLAG_PRIMKEY ){ - sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); + tdsqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); return; } if( pNew->pIndex ){ - sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column"); + tdsqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column"); return; } - if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){ - sqlite3ErrorMsg(pParse, - "Cannot add a REFERENCES column with non-NULL default value"); - return; - } - if( pCol->notNull && !pDflt ){ - sqlite3ErrorMsg(pParse, - "Cannot add a NOT NULL column with default value NULL"); - return; - } - - /* Ensure the default expression is something that sqlite3ValueFromExpr() - ** can handle (i.e. not CURRENT_TIME etc.) - */ - if( pDflt ){ - sqlite3_value *pVal = 0; - int rc; - rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal); - assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); - if( rc!=SQLITE_OK ){ - assert( db->mallocFailed == 1 ); + if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){ + /* If the default value for the new column was specified with a + ** literal NULL, then set pDflt to 0. This simplifies checking + ** for an SQL NULL default below. + */ + assert( pDflt==0 || pDflt->op==TK_SPAN ); + if( pDflt && pDflt->pLeft->op==TK_NULL ){ + pDflt = 0; + } + if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){ + tdsqlite3ErrorMsg(pParse, + "Cannot add a REFERENCES column with non-NULL default value"); return; } - if( !pVal ){ - sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default"); + if( pCol->notNull && !pDflt ){ + tdsqlite3ErrorMsg(pParse, + "Cannot add a NOT NULL column with default value NULL"); return; } - sqlite3ValueFree(pVal); + + /* Ensure the default expression is something that tdsqlite3ValueFromExpr() + ** can handle (i.e. not CURRENT_TIME etc.) + */ + if( pDflt ){ + tdsqlite3_value *pVal = 0; + int rc; + rc = tdsqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal); + assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); + if( rc!=SQLITE_OK ){ + assert( db->mallocFailed == 1 ); + return; + } + if( !pVal ){ + tdsqlite3ErrorMsg(pParse,"Cannot add a column with non-constant default"); + return; + } + tdsqlite3ValueFree(pVal); + } + }else if( pCol->colFlags & COLFLAG_STORED ){ + tdsqlite3ErrorMsg(pParse, "cannot add a STORED column"); + return; } + /* Modify the CREATE TABLE statement. */ - zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n); + zCol = tdsqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n); if( zCol ){ char *zEnd = &zCol[pColDef->n-1]; - int savedDbFlags = db->flags; - while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ + u32 savedDbFlags = db->mDbFlags; + while( zEnd>zCol && (*zEnd==';' || tdsqlite3Isspace(*zEnd)) ){ *zEnd-- = '\0'; } - db->flags |= SQLITE_PreferBuiltin; - sqlite3NestedParse(pParse, + db->mDbFlags |= DBFLAG_PreferBuiltin; + tdsqlite3NestedParse(pParse, "UPDATE \"%w\".%s SET " "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " "WHERE type = 'table' AND name = %Q", - zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1, + zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1, zTab ); - sqlite3DbFree(db, zCol); - db->flags = savedDbFlags; + tdsqlite3DbFree(db, zCol); + db->mDbFlags = savedDbFlags; } /* Make sure the schema version is at least 3. But do not upgrade ** from less than 3 to 4, as that will corrupt any preexisting DESC ** index. */ - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); - sqlite3VdbeUsesBtree(v, iDb); - sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2); - sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3); - sqlite3ReleaseTempReg(pParse, r1); + v = tdsqlite3GetVdbe(pParse); + if( v ){ + r1 = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); + tdsqlite3VdbeUsesBtree(v, iDb); + tdsqlite3VdbeAddOp2(v, OP_AddImm, r1, -2); + tdsqlite3VdbeAddOp2(v, OP_IfPos, r1, tdsqlite3VdbeCurrentAddr(v)+2); + VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3); + tdsqlite3ReleaseTempReg(pParse, r1); + } - /* Reload the schema of the modified table. */ - reloadTableSchema(pParse, pTab, pTab->zName); + /* Reload the table definition */ + renameReloadSchema(pParse, iDb); } /* @@ -98555,65 +108642,65 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ ** This routine makes a (partial) copy of the Table structure ** for the table being altered and sets Parse.pNewTable to point ** to it. Routines called by the parser as the column definition -** is parsed (i.e. sqlite3AddColumn()) add the new Column data to +** is parsed (i.e. tdsqlite3AddColumn()) add the new Column data to ** the copy. The copy of the Table structure is deleted by tokenize.c ** after parsing is finished. ** -** Routine sqlite3AlterFinishAddColumn() will be called to complete +** Routine tdsqlite3AlterFinishAddColumn() will be called to complete ** coding the "ALTER TABLE ... ADD" statement. */ -SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ +SQLITE_PRIVATE void tdsqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ Table *pNew; Table *pTab; - Vdbe *v; int iDb; int i; int nAlloc; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; /* Look up the table being altered. */ assert( pParse->pNewTable==0 ); - assert( sqlite3BtreeHoldsAllMutexes(db) ); + assert( tdsqlite3BtreeHoldsAllMutexes(db) ); if( db->mallocFailed ) goto exit_begin_add_column; - pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); + pTab = tdsqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); if( !pTab ) goto exit_begin_add_column; #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ - sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); + tdsqlite3ErrorMsg(pParse, "virtual tables may not be altered"); goto exit_begin_add_column; } #endif /* Make sure this is not an attempt to ALTER a view. */ if( pTab->pSelect ){ - sqlite3ErrorMsg(pParse, "Cannot add a column to a view"); + tdsqlite3ErrorMsg(pParse, "Cannot add a column to a view"); goto exit_begin_add_column; } - if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ + if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){ goto exit_begin_add_column; } + tdsqlite3MayAbort(pParse); assert( pTab->addColOffset>0 ); - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); /* Put a copy of the Table struct in Parse.pNewTable for the - ** sqlite3AddColumn() function and friends to modify. But modify + ** tdsqlite3AddColumn() function and friends to modify. But modify ** the name by adding an "sqlite_altertab_" prefix. By adding this ** prefix, we insure that the name will not collide with an existing ** table because user table are not allowed to have the "sqlite_" ** prefix on their name. */ - pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table)); + pNew = (Table*)tdsqlite3DbMallocZero(db, sizeof(Table)); if( !pNew ) goto exit_begin_add_column; pParse->pNewTable = pNew; - pNew->nRef = 1; + pNew->nTabRef = 1; pNew->nCol = pTab->nCol; assert( pNew->nCol>0 ); nAlloc = (((pNew->nCol-1)/8)*8)+8; assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); - pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc); - pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); + pNew->aCol = (Column*)tdsqlite3DbMallocZero(db, sizeof(Column)*nAlloc); + pNew->zName = tdsqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); if( !pNew->aCol || !pNew->zName ){ assert( db->mallocFailed ); goto exit_begin_add_column; @@ -98621,24 +108708,1239 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); for(i=0; i<pNew->nCol; i++){ Column *pCol = &pNew->aCol[i]; - pCol->zName = sqlite3DbStrDup(db, pCol->zName); + pCol->zName = tdsqlite3DbStrDup(db, pCol->zName); pCol->zColl = 0; pCol->pDflt = 0; } pNew->pSchema = db->aDb[iDb].pSchema; pNew->addColOffset = pTab->addColOffset; - pNew->nRef = 1; - - /* Begin a transaction and increment the schema cookie. */ - sqlite3BeginWriteOperation(pParse, 0, iDb); - v = sqlite3GetVdbe(pParse); - if( !v ) goto exit_begin_add_column; - sqlite3ChangeCookie(pParse, iDb); + pNew->nTabRef = 1; exit_begin_add_column: - sqlite3SrcListDelete(db, pSrc); + tdsqlite3SrcListDelete(db, pSrc); + return; +} + +/* +** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN +** command. This function checks if the table is a view or virtual +** table (columns of views or virtual tables may not be renamed). If so, +** it loads an error message into pParse and returns non-zero. +** +** Or, if pTab is not a view or virtual table, zero is returned. +*/ +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) +static int isRealTable(Parse *pParse, Table *pTab){ + const char *zType = 0; +#ifndef SQLITE_OMIT_VIEW + if( pTab->pSelect ){ + zType = "view"; + } +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) ){ + zType = "virtual table"; + } +#endif + if( zType ){ + tdsqlite3ErrorMsg( + pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName + ); + return 1; + } + return 0; +} +#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ +# define isRealTable(x,y) (0) +#endif + +/* +** Handles the following parser reduction: +** +** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew +*/ +SQLITE_PRIVATE void tdsqlite3AlterRenameColumn( + Parse *pParse, /* Parsing context */ + SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */ + Token *pOld, /* Name of column being changed */ + Token *pNew /* New column name */ +){ + tdsqlite3 *db = pParse->db; /* Database connection */ + Table *pTab; /* Table being updated */ + int iCol; /* Index of column being renamed */ + char *zOld = 0; /* Old column name */ + char *zNew = 0; /* New column name */ + const char *zDb; /* Name of schema containing the table */ + int iSchema; /* Index of the schema */ + int bQuote; /* True to quote the new name */ + + /* Locate the table to be altered */ + pTab = tdsqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); + if( !pTab ) goto exit_rename_column; + + /* Cannot alter a system table */ + if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column; + if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column; + + /* Which schema holds the table to be altered */ + iSchema = tdsqlite3SchemaToIndex(db, pTab->pSchema); + assert( iSchema>=0 ); + zDb = db->aDb[iSchema].zDbSName; + +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Invoke the authorization callback. */ + if( tdsqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ + goto exit_rename_column; + } +#endif + + /* Make sure the old name really is a column name in the table to be + ** altered. Set iCol to be the index of the column being renamed */ + zOld = tdsqlite3NameFromToken(db, pOld); + if( !zOld ) goto exit_rename_column; + for(iCol=0; iCol<pTab->nCol; iCol++){ + if( 0==tdsqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break; + } + if( iCol==pTab->nCol ){ + tdsqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld); + goto exit_rename_column; + } + + /* Do the rename operation using a recursive UPDATE statement that + ** uses the sqlite_rename_column() SQL function to compute the new + ** CREATE statement text for the sqlite_master table. + */ + tdsqlite3MayAbort(pParse); + zNew = tdsqlite3NameFromToken(db, pNew); + if( !zNew ) goto exit_rename_column; + assert( pNew->n>0 ); + bQuote = tdsqlite3Isquote(pNew->z[0]); + tdsqlite3NestedParse(pParse, + "UPDATE \"%w\".%s SET " + "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) " + "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' " + " AND (type != 'index' OR tbl_name = %Q)" + " AND sql NOT LIKE 'create virtual%%'", + zDb, MASTER_NAME, + zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1, + pTab->zName + ); + + tdsqlite3NestedParse(pParse, + "UPDATE temp.%s SET " + "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) " + "WHERE type IN ('trigger', 'view')", + MASTER_NAME, + zDb, pTab->zName, iCol, zNew, bQuote + ); + + /* Drop and reload the database schema. */ + renameReloadSchema(pParse, iSchema); + renameTestSchema(pParse, zDb, iSchema==1); + + exit_rename_column: + tdsqlite3SrcListDelete(db, pSrc); + tdsqlite3DbFree(db, zOld); + tdsqlite3DbFree(db, zNew); + return; +} + +/* +** Each RenameToken object maps an element of the parse tree into +** the token that generated that element. The parse tree element +** might be one of: +** +** * A pointer to an Expr that represents an ID +** * The name of a table column in Column.zName +** +** A list of RenameToken objects can be constructed during parsing. +** Each new object is created by tdsqlite3RenameTokenMap(). +** As the parse tree is transformed, the tdsqlite3RenameTokenRemap() +** routine is used to keep the mapping current. +** +** After the parse finishes, renameTokenFind() routine can be used +** to look up the actual token value that created some element in +** the parse tree. +*/ +struct RenameToken { + void *p; /* Parse tree element created by token t */ + Token t; /* The token that created parse tree element p */ + RenameToken *pNext; /* Next is a list of all RenameToken objects */ +}; + +/* +** The context of an ALTER TABLE RENAME COLUMN operation that gets passed +** down into the Walker. +*/ +typedef struct RenameCtx RenameCtx; +struct RenameCtx { + RenameToken *pList; /* List of tokens to overwrite */ + int nList; /* Number of tokens in pList */ + int iCol; /* Index of column being renamed */ + Table *pTab; /* Table being ALTERed */ + const char *zOld; /* Old column name */ +}; + +#ifdef SQLITE_DEBUG +/* +** This function is only for debugging. It performs two tasks: +** +** 1. Checks that pointer pPtr does not already appear in the +** rename-token list. +** +** 2. Dereferences each pointer in the rename-token list. +** +** The second is most effective when debugging under valgrind or +** address-sanitizer or similar. If any of these pointers no longer +** point to valid objects, an exception is raised by the memory-checking +** tool. +** +** The point of this is to prevent comparisons of invalid pointer values. +** Even though this always seems to work, it is undefined according to the +** C standard. Example of undefined comparison: +** +** tdsqlite3_free(x); +** if( x==y ) ... +** +** Technically, as x no longer points into a valid object or to the byte +** following a valid object, it may not be used in comparison operations. +*/ +static void renameTokenCheckAll(Parse *pParse, void *pPtr){ + if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){ + RenameToken *p; + u8 i = 0; + for(p=pParse->pRename; p; p=p->pNext){ + if( p->p ){ + assert( p->p!=pPtr ); + i += *(u8*)(p->p); + } + } + } +} +#else +# define renameTokenCheckAll(x,y) +#endif + +/* +** Remember that the parser tree element pPtr was created using +** the token pToken. +** +** In other words, construct a new RenameToken object and add it +** to the list of RenameToken objects currently being built up +** in pParse->pRename. +** +** The pPtr argument is returned so that this routine can be used +** with tail recursion in tokenExpr() routine, for a small performance +** improvement. +*/ +SQLITE_PRIVATE void *tdsqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){ + RenameToken *pNew; + assert( pPtr || pParse->db->mallocFailed ); + renameTokenCheckAll(pParse, pPtr); + if( pParse->eParseMode!=PARSE_MODE_UNMAP ){ + pNew = tdsqlite3DbMallocZero(pParse->db, sizeof(RenameToken)); + if( pNew ){ + pNew->p = pPtr; + pNew->t = *pToken; + pNew->pNext = pParse->pRename; + pParse->pRename = pNew; + } + } + + return pPtr; +} + +/* +** It is assumed that there is already a RenameToken object associated +** with parse tree element pFrom. This function remaps the associated token +** to parse tree element pTo. +*/ +SQLITE_PRIVATE void tdsqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){ + RenameToken *p; + renameTokenCheckAll(pParse, pTo); + for(p=pParse->pRename; p; p=p->pNext){ + if( p->p==pFrom ){ + p->p = pTo; + break; + } + } +} + +/* +** Walker callback used by tdsqlite3RenameExprUnmap(). +*/ +static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){ + Parse *pParse = pWalker->pParse; + tdsqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); + return WRC_Continue; +} + +/* +** Iterate through the Select objects that are part of WITH clauses attached +** to select statement pSelect. +*/ +static void renameWalkWith(Walker *pWalker, Select *pSelect){ + With *pWith = pSelect->pWith; + if( pWith ){ + int i; + for(i=0; i<pWith->nCte; i++){ + Select *p = pWith->a[i].pSelect; + NameContext sNC; + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pWalker->pParse; + tdsqlite3SelectPrep(sNC.pParse, p, &sNC); + tdsqlite3WalkSelect(pWalker, p); + tdsqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols); + } + } +} + +/* +** Walker callback used by tdsqlite3RenameExprUnmap(). +*/ +static int renameUnmapSelectCb(Walker *pWalker, Select *p){ + Parse *pParse = pWalker->pParse; + int i; + if( pParse->nErr ) return WRC_Abort; + if( NEVER(p->selFlags & SF_View) ) return WRC_Prune; + if( ALWAYS(p->pEList) ){ + ExprList *pList = p->pEList; + for(i=0; i<pList->nExpr; i++){ + if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){ + tdsqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName); + } + } + } + if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */ + SrcList *pSrc = p->pSrc; + for(i=0; i<pSrc->nSrc; i++){ + tdsqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName); + if( tdsqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort; + } + } + + renameWalkWith(pWalker, p); + return WRC_Continue; +} + +/* +** Remove all nodes that are part of expression pExpr from the rename list. +*/ +SQLITE_PRIVATE void tdsqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){ + u8 eMode = pParse->eParseMode; + Walker sWalker; + memset(&sWalker, 0, sizeof(Walker)); + sWalker.pParse = pParse; + sWalker.xExprCallback = renameUnmapExprCb; + sWalker.xSelectCallback = renameUnmapSelectCb; + pParse->eParseMode = PARSE_MODE_UNMAP; + tdsqlite3WalkExpr(&sWalker, pExpr); + pParse->eParseMode = eMode; +} + +/* +** Remove all nodes that are part of expression-list pEList from the +** rename list. +*/ +SQLITE_PRIVATE void tdsqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){ + if( pEList ){ + int i; + Walker sWalker; + memset(&sWalker, 0, sizeof(Walker)); + sWalker.pParse = pParse; + sWalker.xExprCallback = renameUnmapExprCb; + tdsqlite3WalkExprList(&sWalker, pEList); + for(i=0; i<pEList->nExpr; i++){ + if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){ + tdsqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName); + } + } + } +} + +/* +** Free the list of RenameToken objects given in the second argument +*/ +static void renameTokenFree(tdsqlite3 *db, RenameToken *pToken){ + RenameToken *pNext; + RenameToken *p; + for(p=pToken; p; p=pNext){ + pNext = p->pNext; + tdsqlite3DbFree(db, p); + } +} + +/* +** Search the Parse object passed as the first argument for a RenameToken +** object associated with parse tree element pPtr. If found, remove it +** from the Parse object and add it to the list maintained by the +** RenameCtx object passed as the second argument. +*/ +static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){ + RenameToken **pp; + assert( pPtr!=0 ); + for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){ + if( (*pp)->p==pPtr ){ + RenameToken *pToken = *pp; + *pp = pToken->pNext; + pToken->pNext = pCtx->pList; + pCtx->pList = pToken; + pCtx->nList++; + break; + } + } +} + +/* +** This is a Walker select callback. It does nothing. It is only required +** because without a dummy callback, tdsqlite3WalkExpr() and similar do not +** descend into sub-select statements. +*/ +static int renameColumnSelectCb(Walker *pWalker, Select *p){ + if( p->selFlags & SF_View ) return WRC_Prune; + renameWalkWith(pWalker, p); + return WRC_Continue; +} + +/* +** This is a Walker expression callback. +** +** For every TK_COLUMN node in the expression tree, search to see +** if the column being references is the column being renamed by an +** ALTER TABLE statement. If it is, then attach its associated +** RenameToken object to the list of RenameToken objects being +** constructed in RenameCtx object at pWalker->u.pRename. +*/ +static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){ + RenameCtx *p = pWalker->u.pRename; + if( pExpr->op==TK_TRIGGER + && pExpr->iColumn==p->iCol + && pWalker->pParse->pTriggerTab==p->pTab + ){ + renameTokenFind(pWalker->pParse, p, (void*)pExpr); + }else if( pExpr->op==TK_COLUMN + && pExpr->iColumn==p->iCol + && p->pTab==pExpr->y.pTab + ){ + renameTokenFind(pWalker->pParse, p, (void*)pExpr); + } + return WRC_Continue; +} + +/* +** The RenameCtx contains a list of tokens that reference a column that +** is being renamed by an ALTER TABLE statement. Return the "last" +** RenameToken in the RenameCtx and remove that RenameToken from the +** RenameContext. "Last" means the last RenameToken encountered when +** the input SQL is parsed from left to right. Repeated calls to this routine +** return all column name tokens in the order that they are encountered +** in the SQL statement. +*/ +static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){ + RenameToken *pBest = pCtx->pList; + RenameToken *pToken; + RenameToken **pp; + + for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){ + if( pToken->t.z>pBest->t.z ) pBest = pToken; + } + for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext); + *pp = pBest->pNext; + + return pBest; +} + +/* +** An error occured while parsing or otherwise processing a database +** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an +** ALTER TABLE RENAME COLUMN program. The error message emitted by the +** sub-routine is currently stored in pParse->zErrMsg. This function +** adds context to the error message and then stores it in pCtx. +*/ +static void renameColumnParseError( + tdsqlite3_context *pCtx, + int bPost, + tdsqlite3_value *pType, + tdsqlite3_value *pObject, + Parse *pParse +){ + const char *zT = (const char*)tdsqlite3_value_text(pType); + const char *zN = (const char*)tdsqlite3_value_text(pObject); + char *zErr; + + zErr = tdsqlite3_mprintf("error in %s %s%s: %s", + zT, zN, (bPost ? " after rename" : ""), + pParse->zErrMsg + ); + tdsqlite3_result_error(pCtx, zErr, -1); + tdsqlite3_free(zErr); +} + +/* +** For each name in the the expression-list pEList (i.e. each +** pEList->a[i].zName) that matches the string in zOld, extract the +** corresponding rename-token from Parse object pParse and add it +** to the RenameCtx pCtx. +*/ +static void renameColumnElistNames( + Parse *pParse, + RenameCtx *pCtx, + ExprList *pEList, + const char *zOld +){ + if( pEList ){ + int i; + for(i=0; i<pEList->nExpr; i++){ + char *zName = pEList->a[i].zEName; + if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) + && ALWAYS(zName!=0) + && 0==tdsqlite3_stricmp(zName, zOld) + ){ + renameTokenFind(pParse, pCtx, (void*)zName); + } + } + } +} + +/* +** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName) +** that matches the string in zOld, extract the corresponding rename-token +** from Parse object pParse and add it to the RenameCtx pCtx. +*/ +static void renameColumnIdlistNames( + Parse *pParse, + RenameCtx *pCtx, + IdList *pIdList, + const char *zOld +){ + if( pIdList ){ + int i; + for(i=0; i<pIdList->nId; i++){ + char *zName = pIdList->a[i].zName; + if( 0==tdsqlite3_stricmp(zName, zOld) ){ + renameTokenFind(pParse, pCtx, (void*)zName); + } + } + } +} + +/* +** Parse the SQL statement zSql using Parse object (*p). The Parse object +** is initialized by this function before it is used. +*/ +static int renameParseSql( + Parse *p, /* Memory to use for Parse object */ + const char *zDb, /* Name of schema SQL belongs to */ + tdsqlite3 *db, /* Database handle */ + const char *zSql, /* SQL to parse */ + int bTemp /* True if SQL is from temp schema */ +){ + int rc; + char *zErr = 0; + + db->init.iDb = bTemp ? 1 : tdsqlite3FindDbName(db, zDb); + + /* Parse the SQL statement passed as the first argument. If no error + ** occurs and the parse does not result in a new table, index or + ** trigger object, the database must be corrupt. */ + memset(p, 0, sizeof(Parse)); + p->eParseMode = PARSE_MODE_RENAME; + p->db = db; + p->nQueryLoop = 1; + rc = tdsqlite3RunParser(p, zSql, &zErr); + assert( p->zErrMsg==0 ); + assert( rc!=SQLITE_OK || zErr==0 ); + p->zErrMsg = zErr; + if( db->mallocFailed ) rc = SQLITE_NOMEM; + if( rc==SQLITE_OK + && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0 + ){ + rc = SQLITE_CORRUPT_BKPT; + } + +#ifdef SQLITE_DEBUG + /* Ensure that all mappings in the Parse.pRename list really do map to + ** a part of the input string. */ + if( rc==SQLITE_OK ){ + int nSql = tdsqlite3Strlen30(zSql); + RenameToken *pToken; + for(pToken=p->pRename; pToken; pToken=pToken->pNext){ + assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] ); + } + } +#endif + + db->init.iDb = 0; + return rc; +} + +/* +** This function edits SQL statement zSql, replacing each token identified +** by the linked list pRename with the text of zNew. If argument bQuote is +** true, then zNew is always quoted first. If no error occurs, the result +** is loaded into context object pCtx as the result. +** +** Or, if an error occurs (i.e. an OOM condition), an error is left in +** pCtx and an SQLite error code returned. +*/ +static int renameEditSql( + tdsqlite3_context *pCtx, /* Return result here */ + RenameCtx *pRename, /* Rename context */ + const char *zSql, /* SQL statement to edit */ + const char *zNew, /* New token text */ + int bQuote /* True to always quote token */ +){ + int nNew = tdsqlite3Strlen30(zNew); + int nSql = tdsqlite3Strlen30(zSql); + tdsqlite3 *db = tdsqlite3_context_db_handle(pCtx); + int rc = SQLITE_OK; + char *zQuot; + char *zOut; + int nQuot; + + /* Set zQuot to point to a buffer containing a quoted copy of the + ** identifier zNew. If the corresponding identifier in the original + ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to + ** point to zQuot so that all substitutions are made using the + ** quoted version of the new column name. */ + zQuot = tdsqlite3MPrintf(db, "\"%w\"", zNew); + if( zQuot==0 ){ + return SQLITE_NOMEM; + }else{ + nQuot = tdsqlite3Strlen30(zQuot); + } + if( bQuote ){ + zNew = zQuot; + nNew = nQuot; + } + + /* At this point pRename->pList contains a list of RenameToken objects + ** corresponding to all tokens in the input SQL that must be replaced + ** with the new column name. All that remains is to construct and + ** return the edited SQL string. */ + assert( nQuot>=nNew ); + zOut = tdsqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1); + if( zOut ){ + int nOut = nSql; + memcpy(zOut, zSql, nSql); + while( pRename->pList ){ + int iOff; /* Offset of token to replace in zOut */ + RenameToken *pBest = renameColumnTokenNext(pRename); + + u32 nReplace; + const char *zReplace; + if( tdsqlite3IsIdChar(*pBest->t.z) ){ + nReplace = nNew; + zReplace = zNew; + }else{ + nReplace = nQuot; + zReplace = zQuot; + } + + iOff = pBest->t.z - zSql; + if( pBest->t.n!=nReplace ){ + memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n], + nOut - (iOff + pBest->t.n) + ); + nOut += nReplace - pBest->t.n; + zOut[nOut] = '\0'; + } + memcpy(&zOut[iOff], zReplace, nReplace); + tdsqlite3DbFree(db, pBest); + } + + tdsqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT); + tdsqlite3DbFree(db, zOut); + }else{ + rc = SQLITE_NOMEM; + } + + tdsqlite3_free(zQuot); + return rc; +} + +/* +** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming +** it was read from the schema of database zDb. Return SQLITE_OK if +** successful. Otherwise, return an SQLite error code and leave an error +** message in the Parse object. +*/ +static int renameResolveTrigger(Parse *pParse, const char *zDb){ + tdsqlite3 *db = pParse->db; + Trigger *pNew = pParse->pNewTrigger; + TriggerStep *pStep; + NameContext sNC; + int rc = SQLITE_OK; + + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + assert( pNew->pTabSchema ); + pParse->pTriggerTab = tdsqlite3FindTable(db, pNew->table, + db->aDb[tdsqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName + ); + pParse->eTriggerOp = pNew->op; + /* ALWAYS() because if the table of the trigger does not exist, the + ** error would have been hit before this point */ + if( ALWAYS(pParse->pTriggerTab) ){ + rc = tdsqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab); + } + + /* Resolve symbols in WHEN clause */ + if( rc==SQLITE_OK && pNew->pWhen ){ + rc = tdsqlite3ResolveExprNames(&sNC, pNew->pWhen); + } + + for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){ + if( pStep->pSelect ){ + tdsqlite3SelectPrep(pParse, pStep->pSelect, &sNC); + if( pParse->nErr ) rc = pParse->rc; + } + if( rc==SQLITE_OK && pStep->zTarget ){ + Table *pTarget = tdsqlite3LocateTable(pParse, 0, pStep->zTarget, zDb); + if( pTarget==0 ){ + rc = SQLITE_ERROR; + }else if( SQLITE_OK==(rc = tdsqlite3ViewGetColumnNames(pParse, pTarget)) ){ + SrcList sSrc; + memset(&sSrc, 0, sizeof(sSrc)); + sSrc.nSrc = 1; + sSrc.a[0].zName = pStep->zTarget; + sSrc.a[0].pTab = pTarget; + sNC.pSrcList = &sSrc; + if( pStep->pWhere ){ + rc = tdsqlite3ResolveExprNames(&sNC, pStep->pWhere); + } + if( rc==SQLITE_OK ){ + rc = tdsqlite3ResolveExprListNames(&sNC, pStep->pExprList); + } + assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) ); + if( pStep->pUpsert ){ + Upsert *pUpsert = pStep->pUpsert; + assert( rc==SQLITE_OK ); + pUpsert->pUpsertSrc = &sSrc; + sNC.uNC.pUpsert = pUpsert; + sNC.ncFlags = NC_UUpsert; + rc = tdsqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget); + if( rc==SQLITE_OK ){ + ExprList *pUpsertSet = pUpsert->pUpsertSet; + rc = tdsqlite3ResolveExprListNames(&sNC, pUpsertSet); + } + if( rc==SQLITE_OK ){ + rc = tdsqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere); + } + if( rc==SQLITE_OK ){ + rc = tdsqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere); + } + sNC.ncFlags = 0; + } + sNC.pSrcList = 0; + } + } + } + return rc; +} + +/* +** Invoke tdsqlite3WalkExpr() or tdsqlite3WalkSelect() on all Select or Expr +** objects that are part of the trigger passed as the second argument. +*/ +static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){ + TriggerStep *pStep; + + /* Find tokens to edit in WHEN clause */ + tdsqlite3WalkExpr(pWalker, pTrigger->pWhen); + + /* Find tokens to edit in trigger steps */ + for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ + tdsqlite3WalkSelect(pWalker, pStep->pSelect); + tdsqlite3WalkExpr(pWalker, pStep->pWhere); + tdsqlite3WalkExprList(pWalker, pStep->pExprList); + if( pStep->pUpsert ){ + Upsert *pUpsert = pStep->pUpsert; + tdsqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget); + tdsqlite3WalkExprList(pWalker, pUpsert->pUpsertSet); + tdsqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere); + tdsqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere); + } + } +} + +/* +** Free the contents of Parse object (*pParse). Do not free the memory +** occupied by the Parse object itself. +*/ +static void renameParseCleanup(Parse *pParse){ + tdsqlite3 *db = pParse->db; + Index *pIdx; + if( pParse->pVdbe ){ + tdsqlite3VdbeFinalize(pParse->pVdbe); + } + tdsqlite3DeleteTable(db, pParse->pNewTable); + while( (pIdx = pParse->pNewIndex)!=0 ){ + pParse->pNewIndex = pIdx->pNext; + tdsqlite3FreeIndex(db, pIdx); + } + tdsqlite3DeleteTrigger(db, pParse->pNewTrigger); + tdsqlite3DbFree(db, pParse->zErrMsg); + renameTokenFree(db, pParse->pRename); + tdsqlite3ParserReset(pParse); +} + +/* +** SQL function: +** +** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld) +** +** 0. zSql: SQL statement to rewrite +** 1. type: Type of object ("table", "view" etc.) +** 2. object: Name of object +** 3. Database: Database name (e.g. "main") +** 4. Table: Table name +** 5. iCol: Index of column to rename +** 6. zNew: New column name +** 7. bQuote: Non-zero if the new column name should be quoted. +** 8. bTemp: True if zSql comes from temp schema +** +** Do a column rename operation on the CREATE statement given in zSql. +** The iCol-th column (left-most is 0) of table zTable is renamed from zCol +** into zNew. The name should be quoted if bQuote is true. +** +** This function is used internally by the ALTER TABLE RENAME COLUMN command. +** It is only accessible to SQL created using tdsqlite3NestedParse(). It is +** not reachable from ordinary SQL passed into tdsqlite3_prepare(). +*/ +static void renameColumnFunc( + tdsqlite3_context *context, + int NotUsed, + tdsqlite3_value **argv +){ + tdsqlite3 *db = tdsqlite3_context_db_handle(context); + RenameCtx sCtx; + const char *zSql = (const char*)tdsqlite3_value_text(argv[0]); + const char *zDb = (const char*)tdsqlite3_value_text(argv[3]); + const char *zTable = (const char*)tdsqlite3_value_text(argv[4]); + int iCol = tdsqlite3_value_int(argv[5]); + const char *zNew = (const char*)tdsqlite3_value_text(argv[6]); + int bQuote = tdsqlite3_value_int(argv[7]); + int bTemp = tdsqlite3_value_int(argv[8]); + const char *zOld; + int rc; + Parse sParse; + Walker sWalker; + Index *pIdx; + int i; + Table *pTab; +#ifndef SQLITE_OMIT_AUTHORIZATION + tdsqlite3_xauth xAuth = db->xAuth; +#endif + + UNUSED_PARAMETER(NotUsed); + if( zSql==0 ) return; + if( zTable==0 ) return; + if( zNew==0 ) return; + if( iCol<0 ) return; + tdsqlite3BtreeEnterAll(db); + pTab = tdsqlite3FindTable(db, zTable, zDb); + if( pTab==0 || iCol>=pTab->nCol ){ + tdsqlite3BtreeLeaveAll(db); + return; + } + zOld = pTab->aCol[iCol].zName; + memset(&sCtx, 0, sizeof(sCtx)); + sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol); + +#ifndef SQLITE_OMIT_AUTHORIZATION + db->xAuth = 0; +#endif + rc = renameParseSql(&sParse, zDb, db, zSql, bTemp); + + /* Find tokens that need to be replaced. */ + memset(&sWalker, 0, sizeof(Walker)); + sWalker.pParse = &sParse; + sWalker.xExprCallback = renameColumnExprCb; + sWalker.xSelectCallback = renameColumnSelectCb; + sWalker.u.pRename = &sCtx; + + sCtx.pTab = pTab; + if( rc!=SQLITE_OK ) goto renameColumnFunc_done; + if( sParse.pNewTable ){ + Select *pSelect = sParse.pNewTable->pSelect; + if( pSelect ){ + pSelect->selFlags &= ~SF_View; + sParse.rc = SQLITE_OK; + tdsqlite3SelectPrep(&sParse, pSelect, 0); + rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc); + if( rc==SQLITE_OK ){ + tdsqlite3WalkSelect(&sWalker, pSelect); + } + if( rc!=SQLITE_OK ) goto renameColumnFunc_done; + }else{ + /* A regular table */ + int bFKOnly = tdsqlite3_stricmp(zTable, sParse.pNewTable->zName); + FKey *pFKey; + assert( sParse.pNewTable->pSelect==0 ); + sCtx.pTab = sParse.pNewTable; + if( bFKOnly==0 ){ + renameTokenFind( + &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName + ); + if( sCtx.iCol<0 ){ + renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey); + } + tdsqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck); + for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){ + tdsqlite3WalkExprList(&sWalker, pIdx->aColExpr); + } + for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){ + tdsqlite3WalkExprList(&sWalker, pIdx->aColExpr); + } + } +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + for(i=0; i<sParse.pNewTable->nCol; i++){ + tdsqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt); + } +#endif + + for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){ + for(i=0; i<pFKey->nCol; i++){ + if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){ + renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]); + } + if( 0==tdsqlite3_stricmp(pFKey->zTo, zTable) + && 0==tdsqlite3_stricmp(pFKey->aCol[i].zCol, zOld) + ){ + renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol); + } + } + } + } + }else if( sParse.pNewIndex ){ + tdsqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr); + tdsqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); + }else{ + /* A trigger */ + TriggerStep *pStep; + rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb)); + if( rc!=SQLITE_OK ) goto renameColumnFunc_done; + + for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){ + if( pStep->zTarget ){ + Table *pTarget = tdsqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb); + if( pTarget==pTab ){ + if( pStep->pUpsert ){ + ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet; + renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld); + } + renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld); + renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld); + } + } + } + + + /* Find tokens to edit in UPDATE OF clause */ + if( sParse.pTriggerTab==pTab ){ + renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld); + } + + /* Find tokens to edit in various expressions and selects */ + renameWalkTrigger(&sWalker, sParse.pNewTrigger); + } + + assert( rc==SQLITE_OK ); + rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote); + +renameColumnFunc_done: + if( rc!=SQLITE_OK ){ + if( sParse.zErrMsg ){ + renameColumnParseError(context, 0, argv[1], argv[2], &sParse); + }else{ + tdsqlite3_result_error_code(context, rc); + } + } + + renameParseCleanup(&sParse); + renameTokenFree(db, sCtx.pList); +#ifndef SQLITE_OMIT_AUTHORIZATION + db->xAuth = xAuth; +#endif + tdsqlite3BtreeLeaveAll(db); +} + +/* +** Walker expression callback used by "RENAME TABLE". +*/ +static int renameTableExprCb(Walker *pWalker, Expr *pExpr){ + RenameCtx *p = pWalker->u.pRename; + if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){ + renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab); + } + return WRC_Continue; +} + +/* +** Walker select callback used by "RENAME TABLE". +*/ +static int renameTableSelectCb(Walker *pWalker, Select *pSelect){ + int i; + RenameCtx *p = pWalker->u.pRename; + SrcList *pSrc = pSelect->pSrc; + if( pSelect->selFlags & SF_View ) return WRC_Prune; + if( pSrc==0 ){ + assert( pWalker->pParse->db->mallocFailed ); + return WRC_Abort; + } + for(i=0; i<pSrc->nSrc; i++){ + struct SrcList_item *pItem = &pSrc->a[i]; + if( pItem->pTab==p->pTab ){ + renameTokenFind(pWalker->pParse, p, pItem->zName); + } + } + renameWalkWith(pWalker, pSelect); + + return WRC_Continue; +} + + +/* +** This C function implements an SQL user function that is used by SQL code +** generated by the ALTER TABLE ... RENAME command to modify the definition +** of any foreign key constraints that use the table being renamed as the +** parent table. It is passed three arguments: +** +** 0: The database containing the table being renamed. +** 1. type: Type of object ("table", "view" etc.) +** 2. object: Name of object +** 3: The complete text of the schema statement being modified, +** 4: The old name of the table being renamed, and +** 5: The new name of the table being renamed. +** 6: True if the schema statement comes from the temp db. +** +** It returns the new schema statement. For example: +** +** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0) +** -> 'CREATE TABLE t1(a REFERENCES t3)' +*/ +static void renameTableFunc( + tdsqlite3_context *context, + int NotUsed, + tdsqlite3_value **argv +){ + tdsqlite3 *db = tdsqlite3_context_db_handle(context); + const char *zDb = (const char*)tdsqlite3_value_text(argv[0]); + const char *zInput = (const char*)tdsqlite3_value_text(argv[3]); + const char *zOld = (const char*)tdsqlite3_value_text(argv[4]); + const char *zNew = (const char*)tdsqlite3_value_text(argv[5]); + int bTemp = tdsqlite3_value_int(argv[6]); + UNUSED_PARAMETER(NotUsed); + + if( zInput && zOld && zNew ){ + Parse sParse; + int rc; + int bQuote = 1; + RenameCtx sCtx; + Walker sWalker; + +#ifndef SQLITE_OMIT_AUTHORIZATION + tdsqlite3_xauth xAuth = db->xAuth; + db->xAuth = 0; +#endif + + tdsqlite3BtreeEnterAll(db); + + memset(&sCtx, 0, sizeof(RenameCtx)); + sCtx.pTab = tdsqlite3FindTable(db, zOld, zDb); + memset(&sWalker, 0, sizeof(Walker)); + sWalker.pParse = &sParse; + sWalker.xExprCallback = renameTableExprCb; + sWalker.xSelectCallback = renameTableSelectCb; + sWalker.u.pRename = &sCtx; + + rc = renameParseSql(&sParse, zDb, db, zInput, bTemp); + + if( rc==SQLITE_OK ){ + int isLegacy = (db->flags & SQLITE_LegacyAlter); + if( sParse.pNewTable ){ + Table *pTab = sParse.pNewTable; + + if( pTab->pSelect ){ + if( isLegacy==0 ){ + Select *pSelect = pTab->pSelect; + NameContext sNC; + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = &sParse; + + assert( pSelect->selFlags & SF_View ); + pSelect->selFlags &= ~SF_View; + tdsqlite3SelectPrep(&sParse, pTab->pSelect, &sNC); + if( sParse.nErr ){ + rc = sParse.rc; + }else{ + tdsqlite3WalkSelect(&sWalker, pTab->pSelect); + } + } + }else{ + /* Modify any FK definitions to point to the new table. */ +#ifndef SQLITE_OMIT_FOREIGN_KEY + if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){ + FKey *pFKey; + for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ + if( tdsqlite3_stricmp(pFKey->zTo, zOld)==0 ){ + renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo); + } + } + } +#endif + + /* If this is the table being altered, fix any table refs in CHECK + ** expressions. Also update the name that appears right after the + ** "CREATE [VIRTUAL] TABLE" bit. */ + if( tdsqlite3_stricmp(zOld, pTab->zName)==0 ){ + sCtx.pTab = pTab; + if( isLegacy==0 ){ + tdsqlite3WalkExprList(&sWalker, pTab->pCheck); + } + renameTokenFind(&sParse, &sCtx, pTab->zName); + } + } + } + + else if( sParse.pNewIndex ){ + renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName); + if( isLegacy==0 ){ + tdsqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); + } + } + +#ifndef SQLITE_OMIT_TRIGGER + else{ + Trigger *pTrigger = sParse.pNewTrigger; + TriggerStep *pStep; + if( 0==tdsqlite3_stricmp(sParse.pNewTrigger->table, zOld) + && sCtx.pTab->pSchema==pTrigger->pTabSchema + ){ + renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table); + } + + if( isLegacy==0 ){ + rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb); + if( rc==SQLITE_OK ){ + renameWalkTrigger(&sWalker, pTrigger); + for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ + if( pStep->zTarget && 0==tdsqlite3_stricmp(pStep->zTarget, zOld) ){ + renameTokenFind(&sParse, &sCtx, pStep->zTarget); + } + } + } + } + } +#endif + } + + if( rc==SQLITE_OK ){ + rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote); + } + if( rc!=SQLITE_OK ){ + if( sParse.zErrMsg ){ + renameColumnParseError(context, 0, argv[1], argv[2], &sParse); + }else{ + tdsqlite3_result_error_code(context, rc); + } + } + + renameParseCleanup(&sParse); + renameTokenFree(db, sCtx.pList); + tdsqlite3BtreeLeaveAll(db); +#ifndef SQLITE_OMIT_AUTHORIZATION + db->xAuth = xAuth; +#endif + } + return; } + +/* +** An SQL user function that checks that there are no parse or symbol +** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement. +** After an ALTER TABLE .. RENAME operation is performed and the schema +** reloaded, this function is called on each SQL statement in the schema +** to ensure that it is still usable. +** +** 0: Database name ("main", "temp" etc.). +** 1: SQL statement. +** 2: Object type ("view", "table", "trigger" or "index"). +** 3: Object name. +** 4: True if object is from temp schema. +** +** Unless it finds an error, this function normally returns NULL. However, it +** returns integer value 1 if: +** +** * the SQL argument creates a trigger, and +** * the table that the trigger is attached to is in database zDb. +*/ +static void renameTableTest( + tdsqlite3_context *context, + int NotUsed, + tdsqlite3_value **argv +){ + tdsqlite3 *db = tdsqlite3_context_db_handle(context); + char const *zDb = (const char*)tdsqlite3_value_text(argv[0]); + char const *zInput = (const char*)tdsqlite3_value_text(argv[1]); + int bTemp = tdsqlite3_value_int(argv[4]); + int isLegacy = (db->flags & SQLITE_LegacyAlter); + +#ifndef SQLITE_OMIT_AUTHORIZATION + tdsqlite3_xauth xAuth = db->xAuth; + db->xAuth = 0; +#endif + + UNUSED_PARAMETER(NotUsed); + if( zDb && zInput ){ + int rc; + Parse sParse; + rc = renameParseSql(&sParse, zDb, db, zInput, bTemp); + if( rc==SQLITE_OK ){ + if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){ + NameContext sNC; + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = &sParse; + tdsqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC); + if( sParse.nErr ) rc = sParse.rc; + } + + else if( sParse.pNewTrigger ){ + if( isLegacy==0 ){ + rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb); + } + if( rc==SQLITE_OK ){ + int i1 = tdsqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema); + int i2 = tdsqlite3FindDbName(db, zDb); + if( i1==i2 ) tdsqlite3_result_int(context, 1); + } + } + } + + if( rc!=SQLITE_OK ){ + renameColumnParseError(context, 1, argv[2], argv[3], &sParse); + } + renameParseCleanup(&sParse); + } + +#ifndef SQLITE_OMIT_AUTHORIZATION + db->xAuth = xAuth; +#endif +} + +/* +** Register built-in functions used to help implement ALTER TABLE +*/ +SQLITE_PRIVATE void tdsqlite3AlterFunctions(void){ + static FuncDef aAlterTableFuncs[] = { + INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc), + INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc), + INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest), + }; + tdsqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs)); +} #endif /* SQLITE_ALTER_TABLE */ /************** End of alter.c ***********************************************/ @@ -98672,13 +109974,13 @@ exit_begin_add_column: ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only -** created and used by SQLite versions 3.7.9 and later and with +** created and used by SQLite versions 3.7.9 through 3.29.0 when ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3 -** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced -** version of sqlite_stat3 and is only available when compiled with -** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is -** not possible to enable both STAT3 and STAT4 at the same time. If they -** are both enabled, then STAT4 takes precedence. +** is a superset of sqlite_stat2 and is also now deprecated. The +** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only +** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite +** versions 3.8.1 and later. STAT4 is the only variant that is still +** supported. ** ** For most applications, sqlite_stat1 provides all the statistics required ** for the query planner to make good choices. @@ -98789,17 +110091,11 @@ exit_begin_add_column: #if defined(SQLITE_ENABLE_STAT4) # define IsStat4 1 -# define IsStat3 0 -#elif defined(SQLITE_ENABLE_STAT3) -# define IsStat4 0 -# define IsStat3 1 #else # define IsStat4 0 -# define IsStat3 0 # undef SQLITE_STAT4_SAMPLES # define SQLITE_STAT4_SAMPLES 1 #endif -#define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */ /* ** This routine generates code that opens the sqlite_statN tables. @@ -98828,25 +110124,21 @@ static void openStatTable( { "sqlite_stat1", "tbl,idx,stat" }, #if defined(SQLITE_ENABLE_STAT4) { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" }, - { "sqlite_stat3", 0 }, -#elif defined(SQLITE_ENABLE_STAT3) - { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" }, - { "sqlite_stat4", 0 }, #else - { "sqlite_stat3", 0 }, { "sqlite_stat4", 0 }, #endif + { "sqlite_stat3", 0 }, }; int i; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Db *pDb; - Vdbe *v = sqlite3GetVdbe(pParse); + Vdbe *v = tdsqlite3GetVdbe(pParse); int aRoot[ArraySize(aTable)]; u8 aCreateTbl[ArraySize(aTable)]; if( v==0 ) return; - assert( sqlite3BtreeHoldsAllMutexes(db) ); - assert( sqlite3VdbeDb(v)==db ); + assert( tdsqlite3BtreeHoldsAllMutexes(db) ); + assert( tdsqlite3VdbeDb(v)==db ); pDb = &db->aDb[iDb]; /* Create new statistic tables if they do not exist, or clear them @@ -98855,13 +110147,13 @@ static void openStatTable( for(i=0; i<ArraySize(aTable); i++){ const char *zTab = aTable[i].zName; Table *pStat; - if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){ + if( (pStat = tdsqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){ if( aTable[i].zCols ){ /* The sqlite_statN table does not exist. Create it. Note that a ** side-effect of the CREATE TABLE statement is to leave the rootpage ** of the new table in register pParse->regRoot. This is important ** because the OpenWrite opcode below will be needing it. */ - sqlite3NestedParse(pParse, + tdsqlite3NestedParse(pParse, "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols ); aRoot[i] = pParse->regRoot; @@ -98873,15 +110165,19 @@ static void openStatTable( ** entire contents of the table. */ aRoot[i] = pStat->tnum; aCreateTbl[i] = 0; - sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab); + tdsqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab); if( zWhere ){ - sqlite3NestedParse(pParse, + tdsqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zDbSName, zTab, zWhereType, zWhere ); +#ifdef SQLITE_ENABLE_PREUPDATE_HOOK + }else if( db->xPreUpdateCallback ){ + tdsqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab); +#endif }else{ /* The sqlite_stat[134] table already exists. Delete all rows. */ - sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb); + tdsqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb); } } } @@ -98889,8 +110185,8 @@ static void openStatTable( /* Open the sqlite_stat[134] tables for writing. */ for(i=0; aTable[i].zCols; i++){ assert( i<ArraySize(aTable) ); - sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3); - sqlite3VdbeChangeP5(v, aCreateTbl[i]); + tdsqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3); + tdsqlite3VdbeChangeP5(v, aCreateTbl[i]); VdbeComment((v, aTable[i].zName)); } } @@ -98912,7 +110208,7 @@ typedef struct Stat4Sample Stat4Sample; struct Stat4Sample { tRowcnt *anEq; /* sqlite_stat4.nEq */ tRowcnt *anDLt; /* sqlite_stat4.nDLt */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 tRowcnt *anLt; /* sqlite_stat4.nLt */ union { i64 iRowid; /* Rowid in main table of the key */ @@ -98935,18 +110231,19 @@ struct Stat4Accum { Stat4Sample *aBest; /* Array of nCol best samples */ int iMin; /* Index in a[] of entry with minimum score */ int nSample; /* Current number of samples */ + int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */ int iGet; /* Index of current sample accessed by stat_get() */ Stat4Sample *a; /* Array of mxSample Stat4Sample objects */ - sqlite3 *db; /* Database connection, for malloc() */ + tdsqlite3 *db; /* Database connection, for malloc() */ }; /* Reclaim memory used by a Stat4Sample */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 -static void sampleClear(sqlite3 *db, Stat4Sample *p){ +#ifdef SQLITE_ENABLE_STAT4 +static void sampleClear(tdsqlite3 *db, Stat4Sample *p){ assert( db!=0 ); if( p->nRowid ){ - sqlite3DbFree(db, p->u.aRowid); + tdsqlite3DbFree(db, p->u.aRowid); p->nRowid = 0; } } @@ -98954,11 +110251,11 @@ static void sampleClear(sqlite3 *db, Stat4Sample *p){ /* Initialize the BLOB value of a ROWID */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 -static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){ +#ifdef SQLITE_ENABLE_STAT4 +static void sampleSetRowid(tdsqlite3 *db, Stat4Sample *p, int n, const u8 *pData){ assert( db!=0 ); - if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); - p->u.aRowid = sqlite3DbMallocRawNN(db, n); + if( p->nRowid ) tdsqlite3DbFree(db, p->u.aRowid); + p->u.aRowid = tdsqlite3DbMallocRawNN(db, n); if( p->u.aRowid ){ p->nRowid = n; memcpy(p->u.aRowid, pData, n); @@ -98970,10 +110267,10 @@ static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){ /* Initialize the INTEGER value of a ROWID. */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 -static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){ +#ifdef SQLITE_ENABLE_STAT4 +static void sampleSetRowidInt64(tdsqlite3 *db, Stat4Sample *p, i64 iRowid){ assert( db!=0 ); - if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); + if( p->nRowid ) tdsqlite3DbFree(db, p->u.aRowid); p->nRowid = 0; p->u.iRowid = iRowid; } @@ -98983,7 +110280,7 @@ static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){ /* ** Copy the contents of object (*pFrom) into (*pTo). */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){ pTo->isPSample = pFrom->isPSample; pTo->iCol = pFrom->iCol; @@ -99004,13 +110301,13 @@ static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){ */ static void stat4Destructor(void *pOld){ Stat4Accum *p = (Stat4Accum*)pOld; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 int i; for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i); for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i); sampleClear(p->db, &p->current); #endif - sqlite3DbFree(p->db, p); + tdsqlite3DbFree(p->db, p); } /* @@ -99024,7 +110321,7 @@ static void stat4Destructor(void *pOld){ ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the ** total number of columns in the table. ** -** Note 2: C is only used for STAT3 and STAT4. +** Note 2: C is only used for STAT4. ** ** For indexes on ordinary rowid tables, N==K+1. But for indexes on ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the @@ -99037,26 +110334,26 @@ static void stat4Destructor(void *pOld){ ** object. */ static void statInit( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ Stat4Accum *p; int nCol; /* Number of columns in index being sampled */ int nKeyCol; /* Number of key columns */ int nColUp; /* nCol rounded up for alignment */ int n; /* Bytes of space to allocate */ - sqlite3 *db; /* Database connection */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + tdsqlite3 *db; /* Database connection */ +#ifdef SQLITE_ENABLE_STAT4 int mxSample = SQLITE_STAT4_SAMPLES; #endif /* Decode the three function arguments */ UNUSED_PARAMETER(argc); - nCol = sqlite3_value_int(argv[0]); + nCol = tdsqlite3_value_int(argv[0]); assert( nCol>0 ); nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol; - nKeyCol = sqlite3_value_int(argv[1]); + nKeyCol = tdsqlite3_value_int(argv[1]); assert( nKeyCol<=nCol ); assert( nKeyCol>0 ); @@ -99064,16 +110361,16 @@ static void statInit( n = sizeof(*p) + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */ + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */ + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */ + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample) #endif ; - db = sqlite3_context_db_handle(context); - p = sqlite3DbMallocZero(db, n); + db = tdsqlite3_context_db_handle(context); + p = tdsqlite3DbMallocZero(db, n); if( p==0 ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); return; } @@ -99084,16 +110381,16 @@ static void statInit( p->current.anDLt = (tRowcnt*)&p[1]; p->current.anEq = &p->current.anDLt[nColUp]; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 { u8 *pSpace; /* Allocated space not yet assigned */ int i; /* Used to iterate through p->aSample[] */ p->iGet = -1; p->mxSample = mxSample; - p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1); + p->nPSample = (tRowcnt)(tdsqlite3_value_int64(argv[2])/(mxSample/3+1) + 1); p->current.anLt = &p->current.anEq[nColUp]; - p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]); + p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)tdsqlite3_value_int(argv[2]); /* Set up the Stat4Accum.a[] and aBest[] arrays */ p->a = (struct Stat4Sample*)&p->current.anLt[nColUp]; @@ -99116,15 +110413,16 @@ static void statInit( ** only the pointer (the 2nd parameter) matters. The size of the object ** (given by the 3rd parameter) is never used and can be any positive ** value. */ - sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor); + tdsqlite3_result_blob(context, p, sizeof(*p), stat4Destructor); } static const FuncDef statInitFuncdef = { - 2+IsStat34, /* nArg */ + 2+IsStat4, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ statInit, /* xSFunc */ 0, /* xFinalize */ + 0, 0, /* xValue, xInverse */ "stat_init", /* zName */ {0} }; @@ -99158,7 +110456,7 @@ static int sampleIsBetterPost( } #endif -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 /* ** Return true if pNew is to be preferred over pOld. ** @@ -99177,15 +110475,11 @@ static int sampleIsBetter( assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) ); if( (nEqNew>nEqOld) ) return 1; -#ifdef SQLITE_ENABLE_STAT4 if( nEqNew==nEqOld ){ if( pNew->iCol<pOld->iCol ) return 1; return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld)); } return 0; -#else - return (nEqNew==nEqOld && pNew->iHash>pOld->iHash); -#endif } /* @@ -99198,7 +110492,13 @@ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ assert( IsStat4 || nEqZero==0 ); -#ifdef SQLITE_ENABLE_STAT4 + /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0 + ** values in the anEq[] array of any sample in Stat4Accum.a[]. In + ** other words, if nMaxEqZero is n, then it is guaranteed that there + ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */ + if( nEqZero>p->nMaxEqZero ){ + p->nMaxEqZero = nEqZero; + } if( pNew->isPSample==0 ){ Stat4Sample *pUpgrade = 0; assert( pNew->anEq[pNew->iCol]>0 ); @@ -99225,7 +110525,6 @@ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ goto find_new_min; } } -#endif /* If necessary, remove sample iMin to make room for the new sample. */ if( p->nSample>=p->mxSample ){ @@ -99246,10 +110545,8 @@ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ /* The "rows less-than" for the rowid column must be greater than that ** for the last sample in the p->a[] array. Otherwise, the samples would ** be out of order. */ -#ifdef SQLITE_ENABLE_STAT4 assert( p->nSample==0 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] ); -#endif /* Insert the new sample */ pSample = &p->a[p->nSample]; @@ -99259,9 +110556,7 @@ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ /* Zero the first nEqZero entries in the anEq[] array. */ memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero); -#ifdef SQLITE_ENABLE_STAT4 - find_new_min: -#endif +find_new_min: if( p->nSample>=p->mxSample ){ int iMin = -1; for(i=0; i<p->mxSample; i++){ @@ -99274,7 +110569,7 @@ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ p->iMin = iMin; } } -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ /* ** Field iChng of the index being scanned has changed. So at this point @@ -99296,37 +110591,26 @@ static void samplePushPrevious(Stat4Accum *p, int iChng){ } } - /* Update the anEq[] fields of any samples already collected. */ + /* Check that no sample contains an anEq[] entry with an index of + ** p->nMaxEqZero or greater set to zero. */ for(i=p->nSample-1; i>=0; i--){ int j; - for(j=iChng; j<p->nCol; j++){ - if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j]; - } + for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 ); } -#endif - -#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4) - if( iChng==0 ){ - tRowcnt nLt = p->current.anLt[0]; - tRowcnt nEq = p->current.anEq[0]; - - /* Check if this is to be a periodic sample. If so, add it. */ - if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){ - p->current.isPSample = 1; - sampleInsert(p, &p->current, 0); - p->current.isPSample = 0; - }else - /* Or if it is a non-periodic sample. Add it in this case too. */ - if( p->nSample<p->mxSample - || sampleIsBetter(p, &p->current, &p->a[p->iMin]) - ){ - sampleInsert(p, &p->current, 0); + /* Update the anEq[] fields of any samples already collected. */ + if( iChng<p->nMaxEqZero ){ + for(i=p->nSample-1; i>=0; i--){ + int j; + for(j=iChng; j<p->nCol; j++){ + if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j]; + } } + p->nMaxEqZero = iChng; } #endif -#ifndef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifndef SQLITE_ENABLE_STAT4 UNUSED_PARAMETER( p ); UNUSED_PARAMETER( iChng ); #endif @@ -99346,18 +110630,18 @@ static void samplePushPrevious(Stat4Accum *p, int iChng){ ** index being analyzed. The stat_get() SQL function will later be used to ** extract relevant information for constructing the sqlite_statN tables. ** -** The R parameter is only used for STAT3 and STAT4 +** The R parameter is only used for STAT4 */ static void statPush( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ int i; /* The three function arguments */ - Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); - int iChng = sqlite3_value_int(argv[1]); + Stat4Accum *p = (Stat4Accum*)tdsqlite3_value_blob(argv[0]); + int iChng = tdsqlite3_value_int(argv[1]); UNUSED_PARAMETER( argc ); UNUSED_PARAMETER( context ); @@ -99378,19 +110662,19 @@ static void statPush( } for(i=iChng; i<p->nCol; i++){ p->current.anDLt[i]++; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 p->current.anLt[i] += p->current.anEq[i]; #endif p->current.anEq[i] = 1; } } p->nRow++; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){ - sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2])); +#ifdef SQLITE_ENABLE_STAT4 + if( tdsqlite3_value_type(argv[2])==SQLITE_INTEGER ){ + sampleSetRowidInt64(p->db, &p->current, tdsqlite3_value_int64(argv[2])); }else{ - sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]), - sqlite3_value_blob(argv[2])); + sampleSetRowid(p->db, &p->current, tdsqlite3_value_bytes(argv[2]), + tdsqlite3_value_blob(argv[2])); } p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345; #endif @@ -99418,12 +110702,13 @@ static void statPush( #endif } static const FuncDef statPushFuncdef = { - 2+IsStat34, /* nArg */ + 2+IsStat4, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ statPush, /* xSFunc */ 0, /* xFinalize */ + 0, 0, /* xValue, xInverse */ "stat_push", /* zName */ {0} }; @@ -99442,20 +110727,26 @@ static const FuncDef statPushFuncdef = { ** The content to returned is determined by the parameter J ** which is one of the STAT_GET_xxxx values defined above. ** -** If neither STAT3 nor STAT4 are enabled, then J is always +** The stat_get(P,J) function is not available to generic SQL. It is +** inserted as part of a manually constructed bytecode program. (See +** the callStatGet() routine below.) It is guaranteed that the P +** parameter will always be a poiner to a Stat4Accum object, never a +** NULL. +** +** If STAT4 is not enabled, then J is always ** STAT_GET_STAT1 and is hence omitted and this routine becomes ** a one-parameter function, stat_get(P), that always returns the ** stat1 table entry information. */ static void statGet( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ - Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - /* STAT3 and STAT4 have a parameter on this routine. */ - int eCall = sqlite3_value_int(argv[1]); + Stat4Accum *p = (Stat4Accum*)tdsqlite3_value_blob(argv[0]); +#ifdef SQLITE_ENABLE_STAT4 + /* STAT4 has a parameter on this routine. */ + int eCall = tdsqlite3_value_int(argv[1]); assert( argc==2 ); assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT @@ -99490,26 +110781,26 @@ static void statGet( char *z; int i; - char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 ); + char *zRet = tdsqlite3MallocZero( (p->nKeyCol+1)*25 ); if( zRet==0 ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); return; } - sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow); - z = zRet + sqlite3Strlen30(zRet); + tdsqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow); + z = zRet + tdsqlite3Strlen30(zRet); for(i=0; i<p->nKeyCol; i++){ u64 nDistinct = p->current.anDLt[i] + 1; u64 iVal = (p->nRow + nDistinct - 1) / nDistinct; - sqlite3_snprintf(24, z, " %llu", iVal); - z += sqlite3Strlen30(z); + tdsqlite3_snprintf(24, z, " %llu", iVal); + z += tdsqlite3Strlen30(z); assert( p->current.anEq[i] ); } assert( z[0]=='\0' && z>zRet ); - sqlite3_result_text(context, zRet, -1, sqlite3_free); + tdsqlite3_result_text(context, zRet, -1, tdsqlite3_free); } -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 else if( eCall==STAT_GET_ROWID ){ if( p->iGet<0 ){ samplePushPrevious(p, 0); @@ -99518,9 +110809,9 @@ static void statGet( if( p->iGet<p->nSample ){ Stat4Sample *pS = p->a + p->iGet; if( pS->nRowid==0 ){ - sqlite3_result_int64(context, pS->u.iRowid); + tdsqlite3_result_int64(context, pS->u.iRowid); }else{ - sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid, + tdsqlite3_result_blob(context, pS->u.aRowid, pS->nRowid, SQLITE_TRANSIENT); } } @@ -99538,53 +110829,51 @@ static void statGet( } } - if( IsStat3 ){ - sqlite3_result_int64(context, (i64)aCnt[0]); - }else{ - char *zRet = sqlite3MallocZero(p->nCol * 25); + { + char *zRet = tdsqlite3MallocZero(p->nCol * 25); if( zRet==0 ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); }else{ int i; char *z = zRet; for(i=0; i<p->nCol; i++){ - sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]); - z += sqlite3Strlen30(z); + tdsqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]); + z += tdsqlite3Strlen30(z); } assert( z[0]=='\0' && z>zRet ); z[-1] = '\0'; - sqlite3_result_text(context, zRet, -1, sqlite3_free); + tdsqlite3_result_text(context, zRet, -1, tdsqlite3_free); } } } -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ #ifndef SQLITE_DEBUG UNUSED_PARAMETER( argc ); #endif } static const FuncDef statGetFuncdef = { - 1+IsStat34, /* nArg */ + 1+IsStat4, /* nArg */ SQLITE_UTF8, /* funcFlags */ 0, /* pUserData */ 0, /* pNext */ statGet, /* xSFunc */ 0, /* xFinalize */ + 0, 0, /* xValue, xInverse */ "stat_get", /* zName */ {0} }; -static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){ - assert( regOut!=regStat4 && regOut!=regStat4+1 ); -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1); +static void callStatGet(Parse *pParse, int regStat4, int iParam, int regOut){ +#ifdef SQLITE_ENABLE_STAT4 + tdsqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat4+1); #elif SQLITE_DEBUG assert( iParam==STAT_GET_STAT1 ); #else UNUSED_PARAMETER( iParam ); #endif - sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut, - (char*)&statGetFuncdef, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, 1 + IsStat34); + assert( regOut!=regStat4 && regOut!=regStat4+1 ); + tdsqlite3VdbeAddFunctionCall(pParse, 0, regStat4, regOut, 1+IsStat4, + &statGetFuncdef, 0); } /* @@ -99599,7 +110888,7 @@ static void analyzeOneTable( int iMem, /* Available memory locations begin here */ int iTab /* Next available cursor */ ){ - sqlite3 *db = pParse->db; /* Database handle */ + tdsqlite3 *db = pParse->db; /* Database handle */ Index *pIdx; /* An index to being analyzed */ int iIdxCur; /* Cursor open on index being analyzed */ int iTabCur; /* Table cursor */ @@ -99611,7 +110900,7 @@ static void analyzeOneTable( int regNewRowid = iMem++; /* Rowid for the inserted record */ int regStat4 = iMem++; /* Register to hold Stat4Accum object */ int regChng = iMem++; /* Index of changed index field */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 int regRowid = iMem++; /* Rowid argument passed to stat_push() */ #endif int regTemp = iMem++; /* Temporary use register */ @@ -99619,9 +110908,12 @@ static void analyzeOneTable( int regIdxname = iMem++; /* Register containing index name */ int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */ int regPrev = iMem; /* MUST BE LAST (see below) */ +#ifdef SQLITE_ENABLE_PREUPDATE_HOOK + Table *pStat1 = 0; +#endif pParse->nMem = MAX(pParse->nMem, iMem); - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( v==0 || NEVER(pTab==0) ){ return; } @@ -99629,31 +110921,43 @@ static void analyzeOneTable( /* Do not gather statistics on views or virtual tables */ return; } - if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){ + if( tdsqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){ /* Do not gather statistics on system tables */ return; } - assert( sqlite3BtreeHoldsAllMutexes(db) ); - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( tdsqlite3BtreeHoldsAllMutexes(db) ); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb>=0 ); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); #ifndef SQLITE_OMIT_AUTHORIZATION - if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0, + if( tdsqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0, db->aDb[iDb].zDbSName ) ){ return; } #endif +#ifdef SQLITE_ENABLE_PREUPDATE_HOOK + if( db->xPreUpdateCallback ){ + pStat1 = (Table*)tdsqlite3DbMallocZero(db, sizeof(Table) + 13); + if( pStat1==0 ) return; + pStat1->zName = (char*)&pStat1[1]; + memcpy(pStat1->zName, "sqlite_stat1", 13); + pStat1->nCol = 3; + pStat1->iPKey = -1; + tdsqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB); + } +#endif + /* Establish a read-lock on the table at the shared-cache level. ** Open a read-only cursor on the table. Also allocate a cursor number ** to use for scanning indexes (iIdxCur). No index cursor is opened at ** this time though. */ - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + tdsqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); iTabCur = iTab++; iIdxCur = iTab++; pParse->nTab = MAX(pParse->nTab, iTab); - sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); - sqlite3VdbeLoadString(v, regTabname, pTab->zName); + tdsqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); + tdsqlite3VdbeLoadString(v, regTabname, pTab->zName); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int nCol; /* Number of columns in pIdx. "N" */ @@ -99675,7 +110979,7 @@ static void analyzeOneTable( } /* Populate the register containing the index name. */ - sqlite3VdbeLoadString(v, regIdxname, zIdxName); + tdsqlite3VdbeLoadString(v, regIdxname, zIdxName); VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName)); /* @@ -99717,9 +111021,9 @@ static void analyzeOneTable( pParse->nMem = MAX(pParse->nMem, regPrev+nColTest); /* Open a read-only cursor on the index being analyzed. */ - assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) ); - sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); + assert( iDb==tdsqlite3SchemaToIndex(db, pIdx->pSchema) ); + tdsqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb); + tdsqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "%s", pIdx->zName)); /* Invoke the stat_init() function. The arguments are: @@ -99730,16 +111034,15 @@ static void analyzeOneTable( ** (3) the number of rows in the index, ** ** - ** The third argument is only used for STAT3 and STAT4 + ** The third argument is only used for STAT4 */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3); +#ifdef SQLITE_ENABLE_STAT4 + tdsqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3); #endif - sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1); - sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2); - sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4, - (char*)&statInitFuncdef, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, 2+IsStat34); + tdsqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1); + tdsqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2); + tdsqlite3VdbeAddFunctionCall(pParse, 0, regStat4+1, regStat4, 2+IsStat4, + &statInitFuncdef, 0); /* Implementation of the following: ** @@ -99749,15 +111052,15 @@ static void analyzeOneTable( ** goto next_push_0; ** */ - addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur); + addrRewind = tdsqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng); - addrNextRow = sqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regChng); + addrNextRow = tdsqlite3VdbeCurrentAddr(v); if( nColTest>0 ){ - int endDistinctTest = sqlite3VdbeMakeLabel(v); + int endDistinctTest = tdsqlite3VdbeMakeLabel(pParse); int *aGotoChng; /* Array of jump instruction addresses */ - aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest); + aGotoChng = tdsqlite3DbMallocRawNN(db, sizeof(int)*nColTest); if( aGotoChng==0 ) continue; /* @@ -99770,26 +111073,26 @@ static void analyzeOneTable( ** regChng = N ** goto endDistinctTest */ - sqlite3VdbeAddOp0(v, OP_Goto); - addrNextRow = sqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp0(v, OP_Goto); + addrNextRow = tdsqlite3VdbeCurrentAddr(v); if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){ /* For a single-column UNIQUE index, once we have found a non-NULL ** row, we know that all the rest will be distinct, so skip ** subsequent distinctness tests. */ - sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest); + tdsqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest); VdbeCoverage(v); } for(i=0; i<nColTest; i++){ - char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]); - sqlite3VdbeAddOp2(v, OP_Integer, i, regChng); - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp); + char *pColl = (char*)tdsqlite3LocateCollSeq(pParse, pIdx->azColl[i]); + tdsqlite3VdbeAddOp2(v, OP_Integer, i, regChng); + tdsqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp); aGotoChng[i] = - sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ); - sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); + tdsqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ); + tdsqlite3VdbeChangeP5(v, SQLITE_NULLEQ); VdbeCoverage(v); } - sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng); - sqlite3VdbeGoto(v, endDistinctTest); + tdsqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng); + tdsqlite3VdbeGoto(v, endDistinctTest); /* @@ -99799,56 +111102,58 @@ static void analyzeOneTable( ** regPrev(1) = idx(1) ** ... */ - sqlite3VdbeJumpHere(v, addrNextRow-1); + tdsqlite3VdbeJumpHere(v, addrNextRow-1); for(i=0; i<nColTest; i++){ - sqlite3VdbeJumpHere(v, aGotoChng[i]); - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i); + tdsqlite3VdbeJumpHere(v, aGotoChng[i]); + tdsqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i); } - sqlite3VdbeResolveLabel(v, endDistinctTest); - sqlite3DbFree(db, aGotoChng); + tdsqlite3VdbeResolveLabel(v, endDistinctTest); + tdsqlite3DbFree(db, aGotoChng); } /* ** chng_addr_N: - ** regRowid = idx(rowid) // STAT34 only - ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only + ** regRowid = idx(rowid) // STAT4 only + ** stat_push(P, regChng, regRowid) // 3rd parameter STAT4 only ** Next csr ** if !eof(csr) goto next_row; */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 assert( regRowid==(regStat4+2) ); if( HasRowid(pTab) ){ - sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid); + tdsqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid); }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); + Index *pPk = tdsqlite3PrimaryKeyIndex(pIdx->pTable); int j, k, regKey; - regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol); + regKey = tdsqlite3GetTempRange(pParse, pPk->nKeyCol); for(j=0; j<pPk->nKeyCol; j++){ - k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); - assert( k>=0 && k<pTab->nCol ); - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j); + k = tdsqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]); + assert( k>=0 && k<pIdx->nColumn ); + tdsqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j); VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName)); } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid); - sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid); + tdsqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol); } #endif assert( regChng==(regStat4+1) ); - sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp, - (char*)&statPushFuncdef, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, 2+IsStat34); - sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v); + tdsqlite3VdbeAddFunctionCall(pParse, 1, regStat4, regTemp, 2+IsStat4, + &statPushFuncdef, 0); + tdsqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v); /* Add the entry to the stat1 table. */ - callStatGet(v, regStat4, STAT_GET_STAT1, regStat1); + callStatGet(pParse, regStat4, STAT_GET_STAT1, regStat1); assert( "BBB"[0]==SQLITE_AFF_TEXT ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); - sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); - sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); + tdsqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); + tdsqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); +#ifdef SQLITE_ENABLE_PREUPDATE_HOOK + tdsqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE); +#endif + tdsqlite3VdbeChangeP5(v, OPFLAG_APPEND); - /* Add the entries to the stat3 or stat4 table. */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 + /* Add the entries to the stat4 table. */ +#ifdef SQLITE_ENABLE_STAT4 { int regEq = regStat1; int regLt = regStat1+1; @@ -99862,36 +111167,29 @@ static void analyzeOneTable( pParse->nMem = MAX(pParse->nMem, regCol+nCol); - addrNext = sqlite3VdbeCurrentAddr(v); - callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid); - addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid); + addrNext = tdsqlite3VdbeCurrentAddr(v); + callStatGet(pParse, regStat4, STAT_GET_ROWID, regSampleRowid); + addrIsNull = tdsqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid); + VdbeCoverage(v); + callStatGet(pParse, regStat4, STAT_GET_NEQ, regEq); + callStatGet(pParse, regStat4, STAT_GET_NLT, regLt); + callStatGet(pParse, regStat4, STAT_GET_NDLT, regDLt); + tdsqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0); VdbeCoverage(v); - callStatGet(v, regStat4, STAT_GET_NEQ, regEq); - callStatGet(v, regStat4, STAT_GET_NLT, regLt); - callStatGet(v, regStat4, STAT_GET_NDLT, regDLt); - sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0); - /* We know that the regSampleRowid row exists because it was read by - ** the previous loop. Thus the not-found jump of seekOp will never - ** be taken */ - VdbeCoverageNeverTaken(v); -#ifdef SQLITE_ENABLE_STAT3 - sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample); -#else for(i=0; i<nCol; i++){ - sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i); + tdsqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i); } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample); -#endif - sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp); - sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid); - sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid); - sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */ - sqlite3VdbeJumpHere(v, addrIsNull); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp); + tdsqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid); + tdsqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid); + tdsqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */ + tdsqlite3VdbeJumpHere(v, addrIsNull); } -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ /* End of analysis */ - sqlite3VdbeJumpHere(v, addrRewind); + tdsqlite3VdbeJumpHere(v, addrRewind); } @@ -99900,15 +111198,18 @@ static void analyzeOneTable( */ if( pOnlyIdx==0 && needTableCnt ){ VdbeComment((v, "%s", pTab->zName)); - sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1); - jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname); + tdsqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1); + jZeroRows = tdsqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname); assert( "BBB"[0]==SQLITE_AFF_TEXT ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); - sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); - sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3VdbeJumpHere(v, jZeroRows); + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); + tdsqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); + tdsqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); + tdsqlite3VdbeChangeP5(v, OPFLAG_APPEND); +#ifdef SQLITE_ENABLE_PREUPDATE_HOOK + tdsqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE); +#endif + tdsqlite3VdbeJumpHere(v, jZeroRows); } } @@ -99918,9 +111219,9 @@ static void analyzeOneTable( ** be loaded into internal hash tables where is can be used. */ static void loadAnalysis(Parse *pParse, int iDb){ - Vdbe *v = sqlite3GetVdbe(pParse); + Vdbe *v = tdsqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb); + tdsqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb); } } @@ -99928,20 +111229,20 @@ static void loadAnalysis(Parse *pParse, int iDb){ ** Generate code that will do an analysis of an entire database */ static void analyzeDatabase(Parse *pParse, int iDb){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */ HashElem *k; int iStatCur; int iMem; int iTab; - sqlite3BeginWriteOperation(pParse, 0, iDb); + tdsqlite3BeginWriteOperation(pParse, 0, iDb); iStatCur = pParse->nTab; pParse->nTab += 3; openStatTable(pParse, iDb, iStatCur, 0, 0); iMem = pParse->nMem+1; iTab = pParse->nTab; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ Table *pTab = (Table*)sqliteHashData(k); analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab); @@ -99959,9 +111260,9 @@ static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){ int iStatCur; assert( pTab!=0 ); - assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - sqlite3BeginWriteOperation(pParse, 0, iDb); + assert( tdsqlite3BtreeHoldsAllMutexes(pParse->db) ); + iDb = tdsqlite3SchemaToIndex(pParse->db, pTab->pSchema); + tdsqlite3BeginWriteOperation(pParse, 0, iDb); iStatCur = pParse->nTab; pParse->nTab += 3; if( pOnlyIdx ){ @@ -99985,8 +111286,8 @@ static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){ ** Form 2 analyzes all indices the single database named. ** Form 3 analyzes all indices associated with the named table. */ -SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ - sqlite3 *db = pParse->db; +SQLITE_PRIVATE void tdsqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ + tdsqlite3 *db = pParse->db; int iDb; int i; char *z, *zDb; @@ -99997,8 +111298,8 @@ SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ - assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + assert( tdsqlite3BtreeHoldsAllMutexes(pParse->db) ); + if( SQLITE_OK!=tdsqlite3ReadSchema(pParse) ){ return; } @@ -100009,40 +111310,28 @@ SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ if( i==1 ) continue; /* Do not analyze the TEMP database */ analyzeDatabase(pParse, i); } - }else if( pName2->n==0 ){ - /* Form 2: Analyze the database or table named */ - iDb = sqlite3FindDb(db, pName1); - if( iDb>=0 ){ - analyzeDatabase(pParse, iDb); - }else{ - z = sqlite3NameFromToken(db, pName1); - if( z ){ - if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){ - analyzeTable(pParse, pIdx->pTable, pIdx); - }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){ - analyzeTable(pParse, pTab, 0); - } - sqlite3DbFree(db, z); - } - } + }else if( pName2->n==0 && (iDb = tdsqlite3FindDb(db, pName1))>=0 ){ + /* Analyze the schema named as the argument */ + analyzeDatabase(pParse, iDb); }else{ - /* Form 3: Analyze the fully qualified table name */ - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName); + /* Form 3: Analyze the table or index named as an argument */ + iDb = tdsqlite3TwoPartName(pParse, pName1, pName2, &pTableName); if( iDb>=0 ){ - zDb = db->aDb[iDb].zDbSName; - z = sqlite3NameFromToken(db, pTableName); + zDb = pName2->n ? db->aDb[iDb].zDbSName : 0; + z = tdsqlite3NameFromToken(db, pTableName); if( z ){ - if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){ + if( (pIdx = tdsqlite3FindIndex(db, z, zDb))!=0 ){ analyzeTable(pParse, pIdx->pTable, pIdx); - }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){ + }else if( (pTab = tdsqlite3LocateTable(pParse, 0, z, zDb))!=0 ){ analyzeTable(pParse, pTab, 0); } - sqlite3DbFree(db, z); + tdsqlite3DbFree(db, z); } - } + } + } + if( db->nSqlExec==0 && (v = tdsqlite3GetVdbe(pParse))!=0 ){ + tdsqlite3VdbeAddOp0(v, OP_Expire); } - v = sqlite3GetVdbe(pParse); - if( v ) sqlite3VdbeAddOp0(v, OP_Expire); } /* @@ -100051,7 +111340,7 @@ SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ */ typedef struct analysisInfo analysisInfo; struct analysisInfo { - sqlite3 *db; + tdsqlite3 *db; const char *zDatabase; }; @@ -100072,7 +111361,7 @@ static void decodeIntArray( int i; tRowcnt v; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 if( z==0 ) z = ""; #else assert( z!=0 ); @@ -100083,18 +111372,18 @@ static void decodeIntArray( v = v*10 + c - '0'; z++; } -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 if( aOut ) aOut[i] = v; - if( aLog ) aLog[i] = sqlite3LogEst(v); + if( aLog ) aLog[i] = tdsqlite3LogEst(v); #else assert( aOut==0 ); UNUSED_PARAMETER(aOut); assert( aLog!=0 ); - aLog[i] = sqlite3LogEst(v); + aLog[i] = tdsqlite3LogEst(v); #endif if( *z==' ' ) z++; } -#ifndef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifndef SQLITE_ENABLE_STAT4 assert( pIndex!=0 ); { #else if( pIndex ){ @@ -100102,16 +111391,18 @@ static void decodeIntArray( pIndex->bUnordered = 0; pIndex->noSkipScan = 0; while( z[0] ){ - if( sqlite3_strglob("unordered*", z)==0 ){ + if( tdsqlite3_strglob("unordered*", z)==0 ){ pIndex->bUnordered = 1; - }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){ - pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3)); - }else if( sqlite3_strglob("noskipscan*", z)==0 ){ + }else if( tdsqlite3_strglob("sz=[0-9]*", z)==0 ){ + int sz = tdsqlite3Atoi(z+3); + if( sz<2 ) sz = 2; + pIndex->szIdxRow = tdsqlite3LogEst(sz); + }else if( tdsqlite3_strglob("noskipscan*", z)==0 ){ pIndex->noSkipScan = 1; } #ifdef SQLITE_ENABLE_COSTMULT - else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){ - pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9)); + else if( tdsqlite3_strglob("costmult=[0-9]*",z)==0 ){ + pIndex->pTable->costMult = tdsqlite3LogEst(tdsqlite3Atoi(z+9)); } #endif while( z[0]!=0 && z[0]!=' ' ) z++; @@ -100143,35 +111434,39 @@ static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){ if( argv==0 || argv[0]==0 || argv[2]==0 ){ return 0; } - pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase); + pTable = tdsqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase); if( pTable==0 ){ return 0; } if( argv[1]==0 ){ pIndex = 0; - }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){ - pIndex = sqlite3PrimaryKeyIndex(pTable); + }else if( tdsqlite3_stricmp(argv[0],argv[1])==0 ){ + pIndex = tdsqlite3PrimaryKeyIndex(pTable); }else{ - pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase); + pIndex = tdsqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase); } z = argv[2]; if( pIndex ){ tRowcnt *aiRowEst = 0; int nCol = pIndex->nKeyCol+1; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 /* Index.aiRowEst may already be set here if there are duplicate ** sqlite_stat1 entries for this index. In that case just clobber ** the old data with the new instead of allocating a new array. */ if( pIndex->aiRowEst==0 ){ - pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol); - if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db); + pIndex->aiRowEst = (tRowcnt*)tdsqlite3MallocZero(sizeof(tRowcnt) * nCol); + if( pIndex->aiRowEst==0 ) tdsqlite3OomFault(pInfo->db); } aiRowEst = pIndex->aiRowEst; #endif pIndex->bUnordered = 0; decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex); - if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0]; + pIndex->hasStat1 = 1; + if( pIndex->pPartIdxWhere==0 ){ + pTable->nRowLogEst = pIndex->aiRowLogEst[0]; + pTable->tabFlags |= TF_HasStat1; + } }else{ Index fakeIdx; fakeIdx.szIdxRow = pTable->szTabRow; @@ -100180,6 +111475,7 @@ static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){ #endif decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx); pTable->szTabRow = fakeIdx.szIdxRow; + pTable->tabFlags |= TF_HasStat1; } return 0; @@ -100189,15 +111485,15 @@ static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){ ** If the Index.aSample variable is not NULL, delete the aSample[] array ** and its contents. */ -SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +SQLITE_PRIVATE void tdsqlite3DeleteIndexSamples(tdsqlite3 *db, Index *pIdx){ +#ifdef SQLITE_ENABLE_STAT4 if( pIdx->aSample ){ int j; for(j=0; j<pIdx->nSample; j++){ IndexSample *p = &pIdx->aSample[j]; - sqlite3DbFree(db, p->p); + tdsqlite3DbFree(db, p->p); } - sqlite3DbFree(db, pIdx->aSample); + tdsqlite3DbFree(db, pIdx->aSample); } if( db && db->pnBytesFreed==0 ){ pIdx->nSample = 0; @@ -100206,10 +111502,10 @@ SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){ #else UNUSED_PARAMETER(db); UNUSED_PARAMETER(pIdx); -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ } -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 /* ** Populate the pIdx->aAvgEq[] array based on the samples currently ** stored in pIdx->aSample[]. @@ -100260,7 +111556,7 @@ static void initAvgEq(Index *pIdx){ } } - if( nDist100>nSum100 ){ + if( nDist100>nSum100 && sumEq<nRow ){ avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100); } if( avgEq==0 ) avgEq = 1; @@ -100274,25 +111570,24 @@ static void initAvgEq(Index *pIdx){ ** is supplied instead, find the PRIMARY KEY index for that table. */ static Index *findIndexOrPrimaryKey( - sqlite3 *db, + tdsqlite3 *db, const char *zName, const char *zDb ){ - Index *pIdx = sqlite3FindIndex(db, zName, zDb); + Index *pIdx = tdsqlite3FindIndex(db, zName, zDb); if( pIdx==0 ){ - Table *pTab = sqlite3FindTable(db, zName, zDb); - if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab); + Table *pTab = tdsqlite3FindTable(db, zName, zDb); + if( pTab && !HasRowid(pTab) ) pIdx = tdsqlite3PrimaryKeyIndex(pTab); } return pIdx; } /* -** Load the content from either the sqlite_stat4 or sqlite_stat3 table +** Load the content from either the sqlite_stat4 ** into the relevant Index.aSample[] arrays. ** ** Arguments zSql1 and zSql2 must point to SQL statements that return -** data equivalent to the following (statements are different for stat3, -** see the caller of this function for details): +** data equivalent to the following: ** ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4 @@ -100300,28 +111595,27 @@ static Index *findIndexOrPrimaryKey( ** where %Q is replaced with the database name before the SQL is executed. */ static int loadStatTbl( - sqlite3 *db, /* Database handle */ - int bStat3, /* Assume single column records only */ + tdsqlite3 *db, /* Database handle */ const char *zSql1, /* SQL statement 1 (see above) */ const char *zSql2, /* SQL statement 2 (see above) */ const char *zDb /* Database name (e.g. "main") */ ){ int rc; /* Result codes from subroutines */ - sqlite3_stmt *pStmt = 0; /* An SQL statement being run */ + tdsqlite3_stmt *pStmt = 0; /* An SQL statement being run */ char *zSql; /* Text of the SQL statement */ Index *pPrevIdx = 0; /* Previous index in the loop */ IndexSample *pSample; /* A slot in pIdx->aSample[] */ assert( db->lookaside.bDisable ); - zSql = sqlite3MPrintf(db, zSql1, zDb); + zSql = tdsqlite3MPrintf(db, zSql1, zDb); if( !zSql ){ return SQLITE_NOMEM_BKPT; } - rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); - sqlite3DbFree(db, zSql); + rc = tdsqlite3_prepare(db, zSql, -1, &pStmt, 0); + tdsqlite3DbFree(db, zSql); if( rc ) return rc; - while( sqlite3_step(pStmt)==SQLITE_ROW ){ + while( tdsqlite3_step(pStmt)==SQLITE_ROW ){ int nIdxCol = 1; /* Number of columns in stat4 records */ char *zIndex; /* Index name */ @@ -100331,30 +111625,26 @@ static int loadStatTbl( int i; /* Bytes of space required */ tRowcnt *pSpace; - zIndex = (char *)sqlite3_column_text(pStmt, 0); + zIndex = (char *)tdsqlite3_column_text(pStmt, 0); if( zIndex==0 ) continue; - nSample = sqlite3_column_int(pStmt, 1); + nSample = tdsqlite3_column_int(pStmt, 1); pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); - assert( pIdx==0 || bStat3 || pIdx->nSample==0 ); - /* Index.nSample is non-zero at this point if data has already been - ** loaded from the stat4 table. In this case ignore stat3 data. */ - if( pIdx==0 || pIdx->nSample ) continue; - if( bStat3==0 ){ - assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 ); - if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){ - nIdxCol = pIdx->nKeyCol; - }else{ - nIdxCol = pIdx->nColumn; - } + assert( pIdx==0 || pIdx->nSample==0 ); + if( pIdx==0 ) continue; + assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 ); + if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){ + nIdxCol = pIdx->nKeyCol; + }else{ + nIdxCol = pIdx->nColumn; } pIdx->nSampleCol = nIdxCol; nByte = sizeof(IndexSample) * nSample; nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample; nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */ - pIdx->aSample = sqlite3DbMallocZero(db, nByte); + pIdx->aSample = tdsqlite3DbMallocZero(db, nByte); if( pIdx->aSample==0 ){ - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); return SQLITE_NOMEM_BKPT; } pSpace = (tRowcnt*)&pIdx->aSample[nSample]; @@ -100366,99 +111656,91 @@ static int loadStatTbl( } assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) ); } - rc = sqlite3_finalize(pStmt); + rc = tdsqlite3_finalize(pStmt); if( rc ) return rc; - zSql = sqlite3MPrintf(db, zSql2, zDb); + zSql = tdsqlite3MPrintf(db, zSql2, zDb); if( !zSql ){ return SQLITE_NOMEM_BKPT; } - rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); - sqlite3DbFree(db, zSql); + rc = tdsqlite3_prepare(db, zSql, -1, &pStmt, 0); + tdsqlite3DbFree(db, zSql); if( rc ) return rc; - while( sqlite3_step(pStmt)==SQLITE_ROW ){ + while( tdsqlite3_step(pStmt)==SQLITE_ROW ){ char *zIndex; /* Index name */ Index *pIdx; /* Pointer to the index object */ int nCol = 1; /* Number of columns in index */ - zIndex = (char *)sqlite3_column_text(pStmt, 0); + zIndex = (char *)tdsqlite3_column_text(pStmt, 0); if( zIndex==0 ) continue; pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); if( pIdx==0 ) continue; /* This next condition is true if data has already been loaded from - ** the sqlite_stat4 table. In this case ignore stat3 data. */ + ** the sqlite_stat4 table. */ nCol = pIdx->nSampleCol; - if( bStat3 && nCol>1 ) continue; if( pIdx!=pPrevIdx ){ initAvgEq(pPrevIdx); pPrevIdx = pIdx; } pSample = &pIdx->aSample[pIdx->nSample]; - decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0); - decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0); - decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0); + decodeIntArray((char*)tdsqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0); + decodeIntArray((char*)tdsqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0); + decodeIntArray((char*)tdsqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0); /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer. ** This is in case the sample record is corrupted. In that case, the - ** sqlite3VdbeRecordCompare() may read up to two varints past the + ** tdsqlite3VdbeRecordCompare() may read up to two varints past the ** end of the allocated buffer before it realizes it is dealing with ** a corrupt record. Adding the two 0x00 bytes prevents this from causing ** a buffer overread. */ - pSample->n = sqlite3_column_bytes(pStmt, 4); - pSample->p = sqlite3DbMallocZero(db, pSample->n + 2); + pSample->n = tdsqlite3_column_bytes(pStmt, 4); + pSample->p = tdsqlite3DbMallocZero(db, pSample->n + 2); if( pSample->p==0 ){ - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); return SQLITE_NOMEM_BKPT; } - memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n); + if( pSample->n ){ + memcpy(pSample->p, tdsqlite3_column_blob(pStmt, 4), pSample->n); + } pIdx->nSample++; } - rc = sqlite3_finalize(pStmt); + rc = tdsqlite3_finalize(pStmt); if( rc==SQLITE_OK ) initAvgEq(pPrevIdx); return rc; } /* -** Load content from the sqlite_stat4 and sqlite_stat3 tables into +** Load content from the sqlite_stat4 table into ** the Index.aSample[] arrays of all indices. */ -static int loadStat4(sqlite3 *db, const char *zDb){ +static int loadStat4(tdsqlite3 *db, const char *zDb){ int rc = SQLITE_OK; /* Result codes from subroutines */ assert( db->lookaside.bDisable ); - if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){ - rc = loadStatTbl(db, 0, + if( tdsqlite3FindTable(db, "sqlite_stat4", zDb) ){ + rc = loadStatTbl(db, "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4", zDb ); } - - if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){ - rc = loadStatTbl(db, 1, - "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", - "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3", - zDb - ); - } - return rc; } -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ /* -** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The +** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] -** arrays. The contents of sqlite_stat3/4 are used to populate the +** arrays. The contents of sqlite_stat4 are used to populate the ** Index.aSample[] arrays. ** ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR -** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined -** during compilation and the sqlite_stat3/4 table is present, no data is +** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined +** during compilation and the sqlite_stat4 table is present, no data is ** read from it. ** -** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the +** If SQLITE_ENABLE_STAT4 was defined during compilation and the ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is ** returned. However, in this case, data is read from the sqlite_stat1 ** table (if it is present) before returning. @@ -100467,22 +111749,27 @@ static int loadStat4(sqlite3 *db, const char *zDb){ ** This means if the caller does not care about other errors, the return ** code may be ignored. */ -SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){ +SQLITE_PRIVATE int tdsqlite3AnalysisLoad(tdsqlite3 *db, int iDb){ analysisInfo sInfo; HashElem *i; char *zSql; int rc = SQLITE_OK; + Schema *pSchema = db->aDb[iDb].pSchema; assert( iDb>=0 && iDb<db->nDb ); assert( db->aDb[iDb].pBt!=0 ); /* Clear any prior statistics */ - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); + for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){ + Table *pTab = sqliteHashData(i); + pTab->tabFlags &= ~TF_HasStat1; + } + for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){ Index *pIdx = sqliteHashData(i); - pIdx->aiRowLogEst[0] = 0; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - sqlite3DeleteIndexSamples(db, pIdx); + pIdx->hasStat1 = 0; +#ifdef SQLITE_ENABLE_STAT4 + tdsqlite3DeleteIndexSamples(db, pIdx); pIdx->aSample = 0; #endif } @@ -100490,40 +111777,40 @@ SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){ /* Load new statistics out of the sqlite_stat1 table */ sInfo.db = db; sInfo.zDatabase = db->aDb[iDb].zDbSName; - if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){ - zSql = sqlite3MPrintf(db, + if( tdsqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){ + zSql = tdsqlite3MPrintf(db, "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase); if( zSql==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ - rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0); - sqlite3DbFree(db, zSql); + rc = tdsqlite3_exec(db, zSql, analysisLoader, &sInfo, 0); + tdsqlite3DbFree(db, zSql); } } /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */ - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); + for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){ Index *pIdx = sqliteHashData(i); - if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx); + if( !pIdx->hasStat1 ) tdsqlite3DefaultRowEst(pIdx); } /* Load the statistics from the sqlite_stat4 table. */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){ - db->lookaside.bDisable++; +#ifdef SQLITE_ENABLE_STAT4 + if( rc==SQLITE_OK ){ + DisableLookaside; rc = loadStat4(db, sInfo.zDatabase); - db->lookaside.bDisable--; + EnableLookaside; } - for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){ + for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){ Index *pIdx = sqliteHashData(i); - sqlite3_free(pIdx->aiRowEst); + tdsqlite3_free(pIdx->aiRowEst); pIdx->aiRowEst = 0; } #endif if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); } return rc; } @@ -100572,7 +111859,7 @@ static int resolveAttachExpr(NameContext *pName, Expr *pExpr) int rc = SQLITE_OK; if( pExpr ){ if( pExpr->op!=TK_ID ){ - rc = sqlite3ResolveExprNames(pName, pExpr); + rc = tdsqlite3ResolveExprNames(pName, pExpr); }else{ pExpr->op = TK_STRING; } @@ -100590,186 +111877,218 @@ static int resolveAttachExpr(NameContext *pName, Expr *pExpr) ** ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the ** third argument. +** +** If the db->init.reopenMemdb flags is set, then instead of attaching a +** new database, close the database on db->init.iDb and reopen it as an +** empty MemDB. */ static void attachFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **argv + tdsqlite3_value **argv ){ int i; int rc = 0; - sqlite3 *db = sqlite3_context_db_handle(context); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); const char *zName; const char *zFile; char *zPath = 0; char *zErr = 0; unsigned int flags; - Db *aNew; + Db *aNew; /* New array of Db pointers */ + Db *pNew; /* Db object for the newly attached database */ char *zErrDyn = 0; - sqlite3_vfs *pVfs; + tdsqlite3_vfs *pVfs; UNUSED_PARAMETER(NotUsed); - - zFile = (const char *)sqlite3_value_text(argv[0]); - zName = (const char *)sqlite3_value_text(argv[1]); + zFile = (const char *)tdsqlite3_value_text(argv[0]); + zName = (const char *)tdsqlite3_value_text(argv[1]); if( zFile==0 ) zFile = ""; if( zName==0 ) zName = ""; - /* Check for the following errors: - ** - ** * Too many attached databases, - ** * Transaction currently open - ** * Specified database name already being used. - */ - if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){ - zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", - db->aLimit[SQLITE_LIMIT_ATTACHED] - ); - goto attach_error; - } - if( !db->autoCommit ){ - zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction"); - goto attach_error; - } - for(i=0; i<db->nDb; i++){ - char *z = db->aDb[i].zDbSName; - assert( z && zName ); - if( sqlite3StrICmp(z, zName)==0 ){ - zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName); +#ifdef SQLITE_ENABLE_DESERIALIZE +# define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb) +#else +# define REOPEN_AS_MEMDB(db) (0) +#endif + + if( REOPEN_AS_MEMDB(db) ){ + /* This is not a real ATTACH. Instead, this routine is being called + ** from tdsqlite3_deserialize() to close database db->init.iDb and + ** reopen it as a MemDB */ + pVfs = tdsqlite3_vfs_find("memdb"); + if( pVfs==0 ) return; + pNew = &db->aDb[db->init.iDb]; + if( pNew->pBt ) tdsqlite3BtreeClose(pNew->pBt); + pNew->pBt = 0; + pNew->pSchema = 0; + rc = tdsqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB); + }else{ + /* This is a real ATTACH + ** + ** Check for the following errors: + ** + ** * Too many attached databases, + ** * Transaction currently open + ** * Specified database name already being used. + */ + if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){ + zErrDyn = tdsqlite3MPrintf(db, "too many attached databases - max %d", + db->aLimit[SQLITE_LIMIT_ATTACHED] + ); goto attach_error; } + for(i=0; i<db->nDb; i++){ + char *z = db->aDb[i].zDbSName; + assert( z && zName ); + if( tdsqlite3StrICmp(z, zName)==0 ){ + zErrDyn = tdsqlite3MPrintf(db, "database %s is already in use", zName); + goto attach_error; + } + } + + /* Allocate the new entry in the db->aDb[] array and initialize the schema + ** hash tables. + */ + if( db->aDb==db->aDbStatic ){ + aNew = tdsqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 ); + if( aNew==0 ) return; + memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); + }else{ + aNew = tdsqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); + if( aNew==0 ) return; + } + db->aDb = aNew; + pNew = &db->aDb[db->nDb]; + memset(pNew, 0, sizeof(*pNew)); + + /* Open the database file. If the btree is successfully opened, use + ** it to obtain the database schema. At this point the schema may + ** or may not be initialized. + */ + flags = db->openFlags; + rc = tdsqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM ) tdsqlite3OomFault(db); + tdsqlite3_result_error(context, zErr, -1); + tdsqlite3_free(zErr); + return; + } + assert( pVfs ); + flags |= SQLITE_OPEN_MAIN_DB; + rc = tdsqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags); + db->nDb++; + pNew->zDbSName = tdsqlite3DbStrDup(db, zName); } - - /* Allocate the new entry in the db->aDb[] array and initialize the schema - ** hash tables. - */ - if( db->aDb==db->aDbStatic ){ - aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 ); - if( aNew==0 ) return; - memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); - }else{ - aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); - if( aNew==0 ) return; - } - db->aDb = aNew; - aNew = &db->aDb[db->nDb]; - memset(aNew, 0, sizeof(*aNew)); - - /* Open the database file. If the btree is successfully opened, use - ** it to obtain the database schema. At this point the schema may - ** or may not be initialized. - */ - flags = db->openFlags; - rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); - sqlite3_result_error(context, zErr, -1); - sqlite3_free(zErr); - return; - } - assert( pVfs ); - flags |= SQLITE_OPEN_MAIN_DB; - rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags); - sqlite3_free( zPath ); - db->nDb++; + db->noSharedCache = 0; if( rc==SQLITE_CONSTRAINT ){ rc = SQLITE_ERROR; - zErrDyn = sqlite3MPrintf(db, "database is already attached"); + zErrDyn = tdsqlite3MPrintf(db, "database is already attached"); }else if( rc==SQLITE_OK ){ Pager *pPager; - aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt); - if( !aNew->pSchema ){ + pNew->pSchema = tdsqlite3SchemaGet(db, pNew->pBt); + if( !pNew->pSchema ){ rc = SQLITE_NOMEM_BKPT; - }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){ - zErrDyn = sqlite3MPrintf(db, + }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){ + zErrDyn = tdsqlite3MPrintf(db, "attached databases must use the same text encoding as main database"); rc = SQLITE_ERROR; } - sqlite3BtreeEnter(aNew->pBt); - pPager = sqlite3BtreePager(aNew->pBt); - sqlite3PagerLockingMode(pPager, db->dfltLockMode); - sqlite3BtreeSecureDelete(aNew->pBt, - sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) ); + tdsqlite3BtreeEnter(pNew->pBt); + pPager = tdsqlite3BtreePager(pNew->pBt); + tdsqlite3PagerLockingMode(pPager, db->dfltLockMode); + tdsqlite3BtreeSecureDelete(pNew->pBt, + tdsqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) ); #ifndef SQLITE_OMIT_PAGER_PRAGMAS - sqlite3BtreeSetPagerFlags(aNew->pBt, + tdsqlite3BtreeSetPagerFlags(pNew->pBt, PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK)); #endif - sqlite3BtreeLeave(aNew->pBt); + tdsqlite3BtreeLeave(pNew->pBt); } - aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; - aNew->zDbSName = sqlite3DbStrDup(db, zName); - if( rc==SQLITE_OK && aNew->zDbSName==0 ){ + pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; + if( rc==SQLITE_OK && pNew->zDbSName==0 ){ rc = SQLITE_NOMEM_BKPT; } #ifdef SQLITE_HAS_CODEC if( rc==SQLITE_OK ){ - extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); - extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); + extern int tdsqlite3CodecAttach(tdsqlite3*, int, const void*, int); + extern void tdsqlite3CodecGetKey(tdsqlite3*, int, void**, int*); int nKey; char *zKey; - int t = sqlite3_value_type(argv[2]); + int t = tdsqlite3_value_type(argv[2]); switch( t ){ case SQLITE_INTEGER: case SQLITE_FLOAT: - zErrDyn = sqlite3DbStrDup(db, "Invalid key value"); + zErrDyn = tdsqlite3DbStrDup(db, "Invalid key value"); rc = SQLITE_ERROR; break; case SQLITE_TEXT: case SQLITE_BLOB: - nKey = sqlite3_value_bytes(argv[2]); - zKey = (char *)sqlite3_value_blob(argv[2]); - rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); + nKey = tdsqlite3_value_bytes(argv[2]); + zKey = (char *)tdsqlite3_value_blob(argv[2]); + rc = tdsqlite3CodecAttach(db, db->nDb-1, zKey, nKey); break; case SQLITE_NULL: - /* No key specified. Use the key from the main database */ - sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); - if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){ - rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); + /* No key specified. Use the key from URI filename, or if none, + ** use the key from the main database. */ + if( tdsqlite3CodecQueryParameters(db, zName, zPath)==0 ){ + tdsqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); + if( nKey || tdsqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){ + rc = tdsqlite3CodecAttach(db, db->nDb-1, zKey, nKey); + } } break; } } #endif + tdsqlite3_free( zPath ); /* If the file was opened successfully, read the schema for the new database. ** If this fails, or if opening the file failed, then close the file and - ** remove the entry from the db->aDb[] array. i.e. put everything back the way - ** we found it. + ** remove the entry from the db->aDb[] array. i.e. put everything back the + ** way we found it. */ if( rc==SQLITE_OK ){ - sqlite3BtreeEnterAll(db); - rc = sqlite3Init(db, &zErrDyn); - sqlite3BtreeLeaveAll(db); + tdsqlite3BtreeEnterAll(db); + db->init.iDb = 0; + db->mDbFlags &= ~(DBFLAG_SchemaKnownOk); + if( !REOPEN_AS_MEMDB(db) ){ + rc = tdsqlite3Init(db, &zErrDyn); + } + tdsqlite3BtreeLeaveAll(db); + assert( zErrDyn==0 || rc!=SQLITE_OK ); } #ifdef SQLITE_USER_AUTHENTICATION - if( rc==SQLITE_OK ){ + if( rc==SQLITE_OK && !REOPEN_AS_MEMDB(db) ){ u8 newAuth = 0; - rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth); + rc = tdsqlite3UserAuthCheckLogin(db, zName, &newAuth); if( newAuth<db->auth.authLevel ){ rc = SQLITE_AUTH_USER; } } #endif if( rc ){ - int iDb = db->nDb - 1; - assert( iDb>=2 ); - if( db->aDb[iDb].pBt ){ - sqlite3BtreeClose(db->aDb[iDb].pBt); - db->aDb[iDb].pBt = 0; - db->aDb[iDb].pSchema = 0; - } - sqlite3ResetAllSchemasOfConnection(db); - db->nDb = iDb; - if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ - sqlite3OomFault(db); - sqlite3DbFree(db, zErrDyn); - zErrDyn = sqlite3MPrintf(db, "out of memory"); - }else if( zErrDyn==0 ){ - zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile); + if( !REOPEN_AS_MEMDB(db) ){ + int iDb = db->nDb - 1; + assert( iDb>=2 ); + if( db->aDb[iDb].pBt ){ + tdsqlite3BtreeClose(db->aDb[iDb].pBt); + db->aDb[iDb].pBt = 0; + db->aDb[iDb].pSchema = 0; + } + tdsqlite3ResetAllSchemasOfConnection(db); + db->nDb = iDb; + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ + tdsqlite3OomFault(db); + tdsqlite3DbFree(db, zErrDyn); + zErrDyn = tdsqlite3MPrintf(db, "out of memory"); + }else if( zErrDyn==0 ){ + zErrDyn = tdsqlite3MPrintf(db, "unable to open database: %s", zFile); + } } goto attach_error; } @@ -100779,10 +112098,10 @@ static void attachFunc( attach_error: /* Return an error if we get here */ if( zErrDyn ){ - sqlite3_result_error(context, zErrDyn, -1); - sqlite3DbFree(db, zErrDyn); + tdsqlite3_result_error(context, zErrDyn, -1); + tdsqlite3DbFree(db, zErrDyn); } - if( rc ) sqlite3_result_error_code(context, rc); + if( rc ) tdsqlite3_result_error_code(context, rc); } /* @@ -100794,14 +112113,15 @@ attach_error: ** SELECT sqlite_detach(x) */ static void detachFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **argv + tdsqlite3_value **argv ){ - const char *zName = (const char *)sqlite3_value_text(argv[0]); - sqlite3 *db = sqlite3_context_db_handle(context); + const char *zName = (const char *)tdsqlite3_value_text(argv[0]); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); int i; Db *pDb = 0; + HashElem *pEntry; char zErr[128]; UNUSED_PARAMETER(NotUsed); @@ -100810,35 +112130,42 @@ static void detachFunc( for(i=0; i<db->nDb; i++){ pDb = &db->aDb[i]; if( pDb->pBt==0 ) continue; - if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break; + if( tdsqlite3StrICmp(pDb->zDbSName, zName)==0 ) break; } if( i>=db->nDb ){ - sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName); + tdsqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName); goto detach_error; } if( i<2 ){ - sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName); + tdsqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName); goto detach_error; } - if( !db->autoCommit ){ - sqlite3_snprintf(sizeof(zErr), zErr, - "cannot DETACH database within transaction"); + if( tdsqlite3BtreeIsInReadTrans(pDb->pBt) || tdsqlite3BtreeIsInBackup(pDb->pBt) ){ + tdsqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName); goto detach_error; } - if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){ - sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName); - goto detach_error; + + /* If any TEMP triggers reference the schema being detached, move those + ** triggers to reference the TEMP schema itself. */ + assert( db->aDb[1].pSchema ); + pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash); + while( pEntry ){ + Trigger *pTrig = (Trigger*)sqliteHashData(pEntry); + if( pTrig->pTabSchema==pDb->pSchema ){ + pTrig->pTabSchema = pTrig->pSchema; + } + pEntry = sqliteHashNext(pEntry); } - sqlite3BtreeClose(pDb->pBt); + tdsqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; pDb->pSchema = 0; - sqlite3CollapseDatabaseArray(db); + tdsqlite3CollapseDatabaseArray(db); return; detach_error: - sqlite3_result_error(context, zErr, -1); + tdsqlite3_result_error(context, zErr, -1); } /* @@ -100857,7 +112184,7 @@ static void codeAttach( int rc; NameContext sName; Vdbe *v; - sqlite3* db = pParse->db; + tdsqlite3* db = pParse->db; int regArgs; if( pParse->nErr ) goto attach_end; @@ -100880,7 +112207,7 @@ static void codeAttach( }else{ zAuthArg = 0; } - rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); + rc = tdsqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); if(rc!=SQLITE_OK ){ goto attach_end; } @@ -100888,30 +112215,27 @@ static void codeAttach( #endif /* SQLITE_OMIT_AUTHORIZATION */ - v = sqlite3GetVdbe(pParse); - regArgs = sqlite3GetTempRange(pParse, 4); - sqlite3ExprCode(pParse, pFilename, regArgs); - sqlite3ExprCode(pParse, pDbname, regArgs+1); - sqlite3ExprCode(pParse, pKey, regArgs+2); + v = tdsqlite3GetVdbe(pParse); + regArgs = tdsqlite3GetTempRange(pParse, 4); + tdsqlite3ExprCode(pParse, pFilename, regArgs); + tdsqlite3ExprCode(pParse, pDbname, regArgs+1); + tdsqlite3ExprCode(pParse, pKey, regArgs+2); assert( v || db->mallocFailed ); if( v ){ - sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3, - (char *)pFunc, P4_FUNCDEF); - assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg ); - sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg)); - + tdsqlite3VdbeAddFunctionCall(pParse, 0, regArgs+3-pFunc->nArg, regArgs+3, + pFunc->nArg, pFunc, 0); /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this ** statement only). For DETACH, set it to false (expire all existing ** statements). */ - sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH)); + tdsqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH)); } attach_end: - sqlite3ExprDelete(db, pFilename); - sqlite3ExprDelete(db, pDbname); - sqlite3ExprDelete(db, pKey); + tdsqlite3ExprDelete(db, pFilename); + tdsqlite3ExprDelete(db, pDbname); + tdsqlite3ExprDelete(db, pKey); } /* @@ -100919,7 +112243,7 @@ attach_end: ** ** DETACH pDbname */ -SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){ +SQLITE_PRIVATE void tdsqlite3Detach(Parse *pParse, Expr *pDbname){ static const FuncDef detach_func = { 1, /* nArg */ SQLITE_UTF8, /* funcFlags */ @@ -100927,6 +112251,7 @@ SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){ 0, /* pNext */ detachFunc, /* xSFunc */ 0, /* xFinalize */ + 0, 0, /* xValue, xInverse */ "sqlite_detach", /* zName */ {0} }; @@ -100938,7 +112263,7 @@ SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){ ** ** ATTACH p AS pDbname KEY pKey */ -SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){ +SQLITE_PRIVATE void tdsqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){ static const FuncDef attach_func = { 3, /* nArg */ SQLITE_UTF8, /* funcFlags */ @@ -100946,6 +112271,7 @@ SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *p 0, /* pNext */ attachFunc, /* xSFunc */ 0, /* xFinalize */ + 0, 0, /* xValue, xInverse */ "sqlite_attach", /* zName */ {0} }; @@ -100957,14 +112283,14 @@ SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *p ** Initialize a DbFixer structure. This routine must be called prior ** to passing the structure to one of the sqliteFixAAAA() routines below. */ -SQLITE_PRIVATE void sqlite3FixInit( +SQLITE_PRIVATE void tdsqlite3FixInit( DbFixer *pFix, /* The fixer to be initialized */ Parse *pParse, /* Error messages will be written here */ int iDb, /* This is the database that must be used */ const char *zType, /* "view", "trigger", or "index" */ const Token *pName /* Name of the view, trigger, or index */ ){ - sqlite3 *db; + tdsqlite3 *db; db = pParse->db; assert( db->nDb>iDb ); @@ -100973,14 +112299,14 @@ SQLITE_PRIVATE void sqlite3FixInit( pFix->pSchema = db->aDb[iDb].pSchema; pFix->zType = zType; pFix->pName = pName; - pFix->bVarOnly = (iDb==1); + pFix->bTemp = (iDb==1); } /* ** The following set of routines walk through the parse tree and assign ** a specific database to all table references where the database name ** was left unspecified in the original SQL statement. The pFix structure -** must have been initialized by a prior call to sqlite3FixInit(). +** must have been initialized by a prior call to tdsqlite3FixInit(). ** ** These routines are used to make sure that an index, trigger, or ** view in one database does not refer to objects in a different database. @@ -100990,7 +112316,7 @@ SQLITE_PRIVATE void sqlite3FixInit( ** pParse->zErrMsg and these routines return non-zero. If everything ** checks out, these routines return 0. */ -SQLITE_PRIVATE int sqlite3FixSrcList( +SQLITE_PRIVATE int tdsqlite3FixSrcList( DbFixer *pFix, /* Context of the fixation */ SrcList *pList /* The Source list to check and modify */ ){ @@ -101001,85 +112327,95 @@ SQLITE_PRIVATE int sqlite3FixSrcList( if( NEVER(pList==0) ) return 0; zDb = pFix->zDb; for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ - if( pFix->bVarOnly==0 ){ - if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){ - sqlite3ErrorMsg(pFix->pParse, + if( pFix->bTemp==0 ){ + if( pItem->zDatabase && tdsqlite3StrICmp(pItem->zDatabase, zDb) ){ + tdsqlite3ErrorMsg(pFix->pParse, "%s %T cannot reference objects in database %s", pFix->zType, pFix->pName, pItem->zDatabase); return 1; } - sqlite3DbFree(pFix->pParse->db, pItem->zDatabase); + tdsqlite3DbFree(pFix->pParse->db, pItem->zDatabase); pItem->zDatabase = 0; pItem->pSchema = pFix->pSchema; + pItem->fg.fromDDL = 1; } #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) - if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1; - if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1; + if( tdsqlite3FixSelect(pFix, pItem->pSelect) ) return 1; + if( tdsqlite3FixExpr(pFix, pItem->pOn) ) return 1; #endif + if( pItem->fg.isTabFunc && tdsqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){ + return 1; + } } return 0; } #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) -SQLITE_PRIVATE int sqlite3FixSelect( +SQLITE_PRIVATE int tdsqlite3FixSelect( DbFixer *pFix, /* Context of the fixation */ Select *pSelect /* The SELECT statement to be fixed to one database */ ){ while( pSelect ){ - if( sqlite3FixExprList(pFix, pSelect->pEList) ){ + if( tdsqlite3FixExprList(pFix, pSelect->pEList) ){ return 1; } - if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){ + if( tdsqlite3FixSrcList(pFix, pSelect->pSrc) ){ return 1; } - if( sqlite3FixExpr(pFix, pSelect->pWhere) ){ + if( tdsqlite3FixExpr(pFix, pSelect->pWhere) ){ return 1; } - if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){ + if( tdsqlite3FixExprList(pFix, pSelect->pGroupBy) ){ return 1; } - if( sqlite3FixExpr(pFix, pSelect->pHaving) ){ + if( tdsqlite3FixExpr(pFix, pSelect->pHaving) ){ return 1; } - if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){ + if( tdsqlite3FixExprList(pFix, pSelect->pOrderBy) ){ return 1; } - if( sqlite3FixExpr(pFix, pSelect->pLimit) ){ + if( tdsqlite3FixExpr(pFix, pSelect->pLimit) ){ return 1; } - if( sqlite3FixExpr(pFix, pSelect->pOffset) ){ - return 1; + if( pSelect->pWith ){ + int i; + for(i=0; i<pSelect->pWith->nCte; i++){ + if( tdsqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){ + return 1; + } + } } pSelect = pSelect->pPrior; } return 0; } -SQLITE_PRIVATE int sqlite3FixExpr( +SQLITE_PRIVATE int tdsqlite3FixExpr( DbFixer *pFix, /* Context of the fixation */ Expr *pExpr /* The expression to be fixed to one database */ ){ while( pExpr ){ + if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL); if( pExpr->op==TK_VARIABLE ){ if( pFix->pParse->db->init.busy ){ pExpr->op = TK_NULL; }else{ - sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType); + tdsqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType); return 1; } } if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1; + if( tdsqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1; }else{ - if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1; + if( tdsqlite3FixExprList(pFix, pExpr->x.pList) ) return 1; } - if( sqlite3FixExpr(pFix, pExpr->pRight) ){ + if( tdsqlite3FixExpr(pFix, pExpr->pRight) ){ return 1; } pExpr = pExpr->pLeft; } return 0; } -SQLITE_PRIVATE int sqlite3FixExprList( +SQLITE_PRIVATE int tdsqlite3FixExprList( DbFixer *pFix, /* Context of the fixation */ ExprList *pList /* The expression to be fixed to one database */ ){ @@ -101087,7 +112423,7 @@ SQLITE_PRIVATE int sqlite3FixExprList( struct ExprList_item *pItem; if( pList==0 ) return 0; for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){ - if( sqlite3FixExpr(pFix, pItem->pExpr) ){ + if( tdsqlite3FixExpr(pFix, pItem->pExpr) ){ return 1; } } @@ -101096,20 +112432,32 @@ SQLITE_PRIVATE int sqlite3FixExprList( #endif #ifndef SQLITE_OMIT_TRIGGER -SQLITE_PRIVATE int sqlite3FixTriggerStep( +SQLITE_PRIVATE int tdsqlite3FixTriggerStep( DbFixer *pFix, /* Context of the fixation */ TriggerStep *pStep /* The trigger step be fixed to one database */ ){ while( pStep ){ - if( sqlite3FixSelect(pFix, pStep->pSelect) ){ + if( tdsqlite3FixSelect(pFix, pStep->pSelect) ){ return 1; } - if( sqlite3FixExpr(pFix, pStep->pWhere) ){ + if( tdsqlite3FixExpr(pFix, pStep->pWhere) ){ return 1; } - if( sqlite3FixExprList(pFix, pStep->pExprList) ){ + if( tdsqlite3FixExprList(pFix, pStep->pExprList) ){ return 1; } +#ifndef SQLITE_OMIT_UPSERT + if( pStep->pUpsert ){ + Upsert *pUp = pStep->pUpsert; + if( tdsqlite3FixExprList(pFix, pUp->pUpsertTarget) + || tdsqlite3FixExpr(pFix, pUp->pUpsertTargetWhere) + || tdsqlite3FixExprList(pFix, pUp->pUpsertSet) + || tdsqlite3FixExpr(pFix, pUp->pUpsertWhere) + ){ + return 1; + } + } +#endif pStep = pStep->pNext; } return 0; @@ -101129,7 +112477,7 @@ SQLITE_PRIVATE int sqlite3FixTriggerStep( ** May you share freely, never taking more than you give. ** ************************************************************************* -** This file contains code used to implement the sqlite3_set_authorizer() +** This file contains code used to implement the tdsqlite3_set_authorizer() ** API. This facility is an optional feature of the library. Embedded ** systems that do not need this facility may omit it by recompiling ** the library with -DSQLITE_OMIT_AUTHORIZATION=1 @@ -101179,7 +112527,7 @@ SQLITE_PRIVATE int sqlite3FixTriggerStep( ** the table and the column that are being accessed. The auth function ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY -** means that the SQL statement will never-run - the sqlite3_exec() call +** means that the SQL statement will never-run - the tdsqlite3_exec() call ** will return with an error. SQLITE_IGNORE means that the SQL statement ** should run but attempts to read the specified column will return NULL ** and attempts to write the column will be ignored. @@ -101187,19 +112535,19 @@ SQLITE_PRIVATE int sqlite3FixTriggerStep( ** Setting the auth function to NULL disables this hook. The default ** setting of the auth function is NULL. */ -SQLITE_API int sqlite3_set_authorizer( - sqlite3 *db, +SQLITE_API int tdsqlite3_set_authorizer( + tdsqlite3 *db, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); - db->xAuth = (sqlite3_xauth)xAuth; + tdsqlite3_mutex_enter(db->mutex); + db->xAuth = (tdsqlite3_xauth)xAuth; db->pAuthArg = pArg; - sqlite3ExpirePreparedStatements(db); - sqlite3_mutex_leave(db->mutex); + if( db->xAuth ) tdsqlite3ExpirePreparedStatements(db, 1); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_OK; } @@ -101208,7 +112556,7 @@ SQLITE_API int sqlite3_set_authorizer( ** user-supplied authorization function returned an illegal value. */ static void sqliteAuthBadReturnCode(Parse *pParse){ - sqlite3ErrorMsg(pParse, "authorizer malfunction"); + tdsqlite3ErrorMsg(pParse, "authorizer malfunction"); pParse->rc = SQLITE_ERROR; } @@ -101221,13 +112569,13 @@ static void sqliteAuthBadReturnCode(Parse *pParse){ ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE ** is treated as SQLITE_DENY. In this case an error is left in pParse. */ -SQLITE_PRIVATE int sqlite3AuthReadCol( +SQLITE_PRIVATE int tdsqlite3AuthReadCol( Parse *pParse, /* The parser context */ const char *zTab, /* Table name */ const char *zCol, /* Column name */ int iDb /* Index of containing database. */ ){ - sqlite3 *db = pParse->db; /* Database handle */ + tdsqlite3 *db = pParse->db; /* Database handle */ char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */ int rc; /* Auth callback return code */ @@ -101238,11 +112586,9 @@ SQLITE_PRIVATE int sqlite3AuthReadCol( #endif ); if( rc==SQLITE_DENY ){ - if( db->nDb>2 || iDb!=0 ){ - sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol); - }else{ - sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol); - } + char *z = tdsqlite3_mprintf("%s.%s", zTab, zCol); + if( db->nDb>2 || iDb!=0 ) z = tdsqlite3_mprintf("%s.%z", zDb, z); + tdsqlite3ErrorMsg(pParse, "access to %z is prohibited", z); pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){ sqliteAuthBadReturnCode(pParse); @@ -101259,28 +112605,29 @@ SQLITE_PRIVATE int sqlite3AuthReadCol( ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, ** then generate an error. */ -SQLITE_PRIVATE void sqlite3AuthRead( +SQLITE_PRIVATE void tdsqlite3AuthRead( Parse *pParse, /* The parser context */ Expr *pExpr, /* The expression to check authorization on */ Schema *pSchema, /* The schema of the expression */ SrcList *pTabList /* All table that pExpr might refer to */ ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Table *pTab = 0; /* The table being read */ const char *zCol; /* Name of the column of the table */ int iSrc; /* Index in pTabList->a[] of table being read */ int iDb; /* The index of the database the expression refers to */ int iCol; /* Index of column in table */ + assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); + assert( !IN_RENAME_OBJECT || db->xAuth==0 ); if( db->xAuth==0 ) return; - iDb = sqlite3SchemaToIndex(pParse->db, pSchema); + iDb = tdsqlite3SchemaToIndex(pParse->db, pSchema); if( iDb<0 ){ /* An attempt to read a column out of a subquery or other ** temporary table. */ return; } - assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); if( pExpr->op==TK_TRIGGER ){ pTab = pParse->pTriggerTab; }else{ @@ -101305,7 +112652,7 @@ SQLITE_PRIVATE void sqlite3AuthRead( zCol = "ROWID"; } assert( iDb>=0 && iDb<db->nDb ); - if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ + if( SQLITE_IGNORE==tdsqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ pExpr->op = TK_NULL; } } @@ -101316,33 +112663,46 @@ SQLITE_PRIVATE void sqlite3AuthRead( ** is returned, then the error count and error message in pParse are ** modified appropriately. */ -SQLITE_PRIVATE int sqlite3AuthCheck( +SQLITE_PRIVATE int tdsqlite3AuthCheck( Parse *pParse, int code, const char *zArg1, const char *zArg2, const char *zArg3 ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; int rc; /* Don't do any authorization checks if the database is initialising - ** or if the parser is being invoked from within sqlite3_declare_vtab. + ** or if the parser is being invoked from within tdsqlite3_declare_vtab. */ - if( db->init.busy || IN_DECLARE_VTAB ){ + assert( !IN_RENAME_OBJECT || db->xAuth==0 ); + if( db->init.busy || IN_SPECIAL_PARSE ){ return SQLITE_OK; } if( db->xAuth==0 ){ return SQLITE_OK; } + + /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the + ** callback are either NULL pointers or zero-terminated strings that + ** contain additional details about the action to be authorized. + ** + ** The following testcase() macros show that any of the 3rd through 6th + ** parameters can be either NULL or a string. */ + testcase( zArg1==0 ); + testcase( zArg2==0 ); + testcase( zArg3==0 ); + testcase( pParse->zAuthContext==0 ); + rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext #ifdef SQLITE_USER_AUTHENTICATION ,db->auth.zAuthUser #endif ); if( rc==SQLITE_DENY ){ - sqlite3ErrorMsg(pParse, "not authorized"); + tdsqlite3ErrorMsg(pParse, "not authorized"); pParse->rc = SQLITE_AUTH; }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ rc = SQLITE_DENY; @@ -101356,7 +112716,7 @@ SQLITE_PRIVATE int sqlite3AuthCheck( ** zArg3 argument to authorization callbacks will be zContext until ** popped. Or if pParse==0, this routine is a no-op. */ -SQLITE_PRIVATE void sqlite3AuthContextPush( +SQLITE_PRIVATE void tdsqlite3AuthContextPush( Parse *pParse, AuthContext *pContext, const char *zContext @@ -101369,9 +112729,9 @@ SQLITE_PRIVATE void sqlite3AuthContextPush( /* ** Pop an authorization context that was previously pushed -** by sqlite3AuthContextPush +** by tdsqlite3AuthContextPush */ -SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){ +SQLITE_PRIVATE void tdsqlite3AuthContextPop(AuthContext *pContext){ if( pContext->pParse ){ pContext->pParse->zAuthContext = pContext->zAuthContext; pContext->pParse = 0; @@ -101410,14 +112770,14 @@ SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){ #ifndef SQLITE_OMIT_SHARED_CACHE /* -** The TableLock structure is only used by the sqlite3TableLock() and +** The TableLock structure is only used by the tdsqlite3TableLock() and ** codeTableLocks() functions. */ struct TableLock { - int iDb; /* The database containing the table to be locked */ - int iTab; /* The root page of the table to be locked */ - u8 isWriteLock; /* True for write lock. False for a read lock */ - const char *zName; /* Name of the table */ + int iDb; /* The database containing the table to be locked */ + int iTab; /* The root page of the table to be locked */ + u8 isWriteLock; /* True for write lock. False for a read lock */ + const char *zLockName; /* Name of the table */ }; /* @@ -101428,21 +112788,23 @@ struct TableLock { ** ** This routine just records the fact that the lock is desired. The ** code to make the lock occur is generated by a later call to -** codeTableLocks() which occurs during sqlite3FinishCoding(). +** codeTableLocks() which occurs during tdsqlite3FinishCoding(). */ -SQLITE_PRIVATE void sqlite3TableLock( +SQLITE_PRIVATE void tdsqlite3TableLock( Parse *pParse, /* Parsing context */ int iDb, /* Index of the database containing the table to lock */ int iTab, /* Root page number of the table to be locked */ u8 isWriteLock, /* True for a write lock */ const char *zName /* Name of the table to be locked */ ){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); + Parse *pToplevel = tdsqlite3ParseToplevel(pParse); int i; int nBytes; TableLock *p; assert( iDb>=0 ); + if( iDb==1 ) return; + if( !tdsqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return; for(i=0; i<pToplevel->nTableLock; i++){ p = &pToplevel->aTableLock[i]; if( p->iDb==iDb && p->iTab==iTab ){ @@ -101453,35 +112815,35 @@ SQLITE_PRIVATE void sqlite3TableLock( nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); pToplevel->aTableLock = - sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); + tdsqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); if( pToplevel->aTableLock ){ p = &pToplevel->aTableLock[pToplevel->nTableLock++]; p->iDb = iDb; p->iTab = iTab; p->isWriteLock = isWriteLock; - p->zName = zName; + p->zLockName = zName; }else{ pToplevel->nTableLock = 0; - sqlite3OomFault(pToplevel->db); + tdsqlite3OomFault(pToplevel->db); } } /* ** Code an OP_TableLock instruction for each table locked by the -** statement (configured by calls to sqlite3TableLock()). +** statement (configured by calls to tdsqlite3TableLock()). */ static void codeTableLocks(Parse *pParse){ int i; Vdbe *pVdbe; - pVdbe = sqlite3GetVdbe(pParse); - assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ + pVdbe = tdsqlite3GetVdbe(pParse); + assert( pVdbe!=0 ); /* tdsqlite3GetVdbe cannot fail: VDBE already allocated */ for(i=0; i<pParse->nTableLock; i++){ TableLock *p = &pParse->aTableLock[i]; int p1 = p->iDb; - sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, - p->zName, P4_STATIC); + tdsqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, + p->zLockName, P4_STATIC); } } #else @@ -101494,7 +112856,7 @@ static void codeTableLocks(Parse *pParse){ ** macros when SQLITE_MAX_ATTACHED is greater than 30. */ #if SQLITE_MAX_ATTACHED>30 -SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){ +SQLITE_PRIVATE int tdsqlite3DbMaskAllZero(yDbMask m){ int i; for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0; return 1; @@ -101511,8 +112873,8 @@ SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){ ** Note that if an error occurred, it might be the case that ** no VDBE code was generated. */ -SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ - sqlite3 *db; +SQLITE_PRIVATE void tdsqlite3FinishCoding(Parse *pParse){ + tdsqlite3 *db; Vdbe *v; assert( pParse->pToplevel==0 ); @@ -101526,17 +112888,17 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ /* Begin by generating some termination code at the end of the ** vdbe program */ - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); assert( !pParse->isMultiWrite - || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); + || tdsqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); if( v ){ - sqlite3VdbeAddOp0(v, OP_Halt); + tdsqlite3VdbeAddOp0(v, OP_Halt); #if SQLITE_USER_AUTHENTICATION if( pParse->nTableLock>0 && db->init.busy==0 ){ - sqlite3UserAuthInit(db); + tdsqlite3UserAuthInit(db); if( db->auth.authLevel<UAUTH_User ){ - sqlite3ErrorMsg(pParse, "user not authenticated"); + tdsqlite3ErrorMsg(pParse, "user not authenticated"); pParse->rc = SQLITE_AUTH_USER; return; } @@ -101553,28 +112915,28 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr) ){ int iDb, i; - assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); - sqlite3VdbeJumpHere(v, 0); + assert( tdsqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); + tdsqlite3VdbeJumpHere(v, 0); for(iDb=0; iDb<db->nDb; iDb++){ Schema *pSchema; if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue; - sqlite3VdbeUsesBtree(v, iDb); + tdsqlite3VdbeUsesBtree(v, iDb); pSchema = db->aDb[iDb].pSchema; - sqlite3VdbeAddOp4Int(v, + tdsqlite3VdbeAddOp4Int(v, OP_Transaction, /* Opcode */ iDb, /* P1 */ DbMaskTest(pParse->writeMask,iDb), /* P2 */ pSchema->schema_cookie, /* P3 */ pSchema->iGeneration /* P4 */ ); - if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1); + if( db->init.busy==0 ) tdsqlite3VdbeChangeP5(v, 1); VdbeComment((v, "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite)); } #ifndef SQLITE_OMIT_VIRTUALTABLE for(i=0; i<pParse->nVtabLock; i++){ - char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); - sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); + char *vtab = (char *)tdsqlite3GetVTable(db, pParse->apVtabLock[i]); + tdsqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); } pParse->nVtabLock = 0; #endif @@ -101587,19 +112949,19 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ /* Initialize any AUTOINCREMENT data structures required. */ - sqlite3AutoincrementBegin(pParse); + tdsqlite3AutoincrementBegin(pParse); /* Code constant expressions that where factored out of inner loops */ if( pParse->pConstExpr ){ ExprList *pEL = pParse->pConstExpr; pParse->okConstFactor = 0; for(i=0; i<pEL->nExpr; i++){ - sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg); + tdsqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg); } } /* Finally, jump back to the beginning of the executable code. */ - sqlite3VdbeGoto(v, 1); + tdsqlite3VdbeGoto(v, 1); } } @@ -101607,11 +112969,10 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ /* Get the VDBE program ready for execution */ if( v && pParse->nErr==0 && !db->mallocFailed ){ - assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ /* A minimum of one cursor is required if autoincrement is used * See ticket [a696379c1f08866] */ - if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; - sqlite3VdbeMakeReady(v, pParse); + assert( pParse->pAinc==0 || pParse->nTab>0 ); + tdsqlite3VdbeMakeReady(v, pParse); pParse->rc = SQLITE_DONE; }else{ pParse->rc = SQLITE_ERROR; @@ -101630,27 +112991,32 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use ** care if you decide to try to use this routine for some other purposes. */ -SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ +SQLITE_PRIVATE void tdsqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ va_list ap; char *zSql; char *zErrMsg = 0; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; char saveBuf[PARSE_TAIL_SZ]; if( pParse->nErr ) return; assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ va_start(ap, zFormat); - zSql = sqlite3VMPrintf(db, zFormat, ap); + zSql = tdsqlite3VMPrintf(db, zFormat, ap); va_end(ap); if( zSql==0 ){ - return; /* A malloc must have failed */ + /* This can result either from an OOM or because the formatted string + ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set + ** an error */ + if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG; + pParse->nErr++; + return; } pParse->nested++; memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ); memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ); - sqlite3RunParser(pParse, zSql, &zErrMsg); - sqlite3DbFree(db, zErrMsg); - sqlite3DbFree(db, zSql); + tdsqlite3RunParser(pParse, zSql, &zErrMsg); + tdsqlite3DbFree(db, zErrMsg); + tdsqlite3DbFree(db, zSql); memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ); pParse->nested--; } @@ -101660,8 +113026,8 @@ SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ ** Return TRUE if zTable is the name of the system table that stores the ** list of users and their access credentials. */ -SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){ - return sqlite3_stricmp(zTable, "sqlite_user")==0; +SQLITE_PRIVATE int tdsqlite3UserAuthTable(const char *zTable){ + return tdsqlite3_stricmp(zTable, "sqlite_user")==0; } #endif @@ -101675,30 +113041,37 @@ SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){ ** names is done.) The search order is TEMP first, then MAIN, then any ** auxiliary databases added using the ATTACH command. ** -** See also sqlite3LocateTable(). +** See also tdsqlite3LocateTable(). */ -SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ +SQLITE_PRIVATE Table *tdsqlite3FindTable(tdsqlite3 *db, const char *zName, const char *zDatabase){ Table *p = 0; int i; /* All mutexes are required for schema access. Make sure we hold them. */ - assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); + assert( zDatabase!=0 || tdsqlite3BtreeHoldsAllMutexes(db) ); #if SQLITE_USER_AUTHENTICATION /* Only the admin user is allowed to know that the sqlite_user table ** exists */ - if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){ + if( db->auth.authLevel<UAUTH_Admin && tdsqlite3UserAuthTable(zName)!=0 ){ return 0; } #endif - for(i=OMIT_TEMPDB; i<db->nDb; i++){ - int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ - if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){ - assert( sqlite3SchemaMutexHeld(db, j, 0) ); - p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName); - if( p ) break; + while(1){ + for(i=OMIT_TEMPDB; i<db->nDb; i++){ + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ + if( zDatabase==0 || tdsqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){ + assert( tdsqlite3SchemaMutexHeld(db, j, 0) ); + p = tdsqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName); + if( p ) return p; + } } + /* Not found. If the name we were looking for was temp.sqlite_master + ** then change the name to sqlite_temp_master and try again. */ + if( tdsqlite3StrICmp(zName, MASTER_NAME)!=0 ) break; + if( tdsqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break; + zName = TEMP_MASTER_NAME; } - return p; + return 0; } /* @@ -101707,45 +113080,55 @@ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const cha ** database containing the table. Return NULL if not found. Also leave an ** error message in pParse->zErrMsg. ** -** The difference between this routine and sqlite3FindTable() is that this +** The difference between this routine and tdsqlite3FindTable() is that this ** routine leaves an error message in pParse->zErrMsg where -** sqlite3FindTable() does not. +** tdsqlite3FindTable() does not. */ -SQLITE_PRIVATE Table *sqlite3LocateTable( +SQLITE_PRIVATE Table *tdsqlite3LocateTable( Parse *pParse, /* context in which to report errors */ u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */ const char *zName, /* Name of the table we are looking for */ const char *zDbase /* Name of the database. Might be NULL */ ){ Table *p; + tdsqlite3 *db = pParse->db; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 + && SQLITE_OK!=tdsqlite3ReadSchema(pParse) + ){ return 0; } - p = sqlite3FindTable(pParse->db, zName, zDbase); + p = tdsqlite3FindTable(db, zName, zDbase); if( p==0 ){ - const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table"; #ifndef SQLITE_OMIT_VIRTUALTABLE - if( sqlite3FindDbName(pParse->db, zDbase)<1 ){ - /* If zName is the not the name of a table in the schema created using - ** CREATE, then check to see if it is the name of an virtual table that - ** can be an eponymous virtual table. */ - Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName); - if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ + /* If zName is the not the name of a table in the schema created using + ** CREATE, then check to see if it is the name of an virtual table that + ** can be an eponymous virtual table. */ + if( pParse->disableVtab==0 ){ + Module *pMod = (Module*)tdsqlite3HashFind(&db->aModule, zName); + if( pMod==0 && tdsqlite3_strnicmp(zName, "pragma_", 7)==0 ){ + pMod = tdsqlite3PragmaVtabRegister(db, zName); + } + if( pMod && tdsqlite3VtabEponymousTableInit(pParse, pMod) ){ return pMod->pEpoTab; } } #endif - if( (flags & LOCATE_NOERR)==0 ){ - if( zDbase ){ - sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); - }else{ - sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); - } - pParse->checkSchema = 1; + if( flags & LOCATE_NOERR ) return 0; + pParse->checkSchema = 1; + }else if( IsVirtual(p) && pParse->disableVtab ){ + p = 0; + } + + if( p==0 ){ + const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table"; + if( zDbase ){ + tdsqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); + }else{ + tdsqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); } } @@ -101755,13 +113138,13 @@ SQLITE_PRIVATE Table *sqlite3LocateTable( /* ** Locate the table identified by *p. ** -** This is a wrapper around sqlite3LocateTable(). The difference between -** sqlite3LocateTable() and this function is that this function restricts +** This is a wrapper around tdsqlite3LocateTable(). The difference between +** tdsqlite3LocateTable() and this function is that this function restricts ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be ** non-NULL if it is part of a view or trigger program definition. See -** sqlite3FixSrcList() for details. +** tdsqlite3FixSrcList() for details. */ -SQLITE_PRIVATE Table *sqlite3LocateTableItem( +SQLITE_PRIVATE Table *tdsqlite3LocateTableItem( Parse *pParse, u32 flags, struct SrcList_item *p @@ -101769,12 +113152,12 @@ SQLITE_PRIVATE Table *sqlite3LocateTableItem( const char *zDb; assert( p->pSchema==0 || p->zDatabase==0 ); if( p->pSchema ){ - int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); + int iDb = tdsqlite3SchemaToIndex(pParse->db, p->pSchema); zDb = pParse->db->aDb[iDb].zDbSName; }else{ zDb = p->zDatabase; } - return sqlite3LocateTable(pParse, flags, p->zName, zDb); + return tdsqlite3LocateTable(pParse, flags, p->zName, zDb); } /* @@ -101789,18 +113172,18 @@ SQLITE_PRIVATE Table *sqlite3LocateTableItem( ** TEMP first, then MAIN, then any auxiliary databases added ** using the ATTACH command. */ -SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ +SQLITE_PRIVATE Index *tdsqlite3FindIndex(tdsqlite3 *db, const char *zName, const char *zDb){ Index *p = 0; int i; /* All mutexes are required for schema access. Make sure we hold them. */ - assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); + assert( zDb!=0 || tdsqlite3BtreeHoldsAllMutexes(db) ); for(i=OMIT_TEMPDB; i<db->nDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ Schema *pSchema = db->aDb[j].pSchema; assert( pSchema ); - if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue; - assert( sqlite3SchemaMutexHeld(db, j, 0) ); - p = sqlite3HashFind(&pSchema->idxHash, zName); + if( zDb && tdsqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue; + assert( tdsqlite3SchemaMutexHeld(db, j, 0) ); + p = tdsqlite3HashFind(&pSchema->idxHash, zName); if( p ) break; } return p; @@ -101809,18 +113192,18 @@ SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const cha /* ** Reclaim the memory used by an index */ -static void freeIndex(sqlite3 *db, Index *p){ +SQLITE_PRIVATE void tdsqlite3FreeIndex(tdsqlite3 *db, Index *p){ #ifndef SQLITE_OMIT_ANALYZE - sqlite3DeleteIndexSamples(db, p); + tdsqlite3DeleteIndexSamples(db, p); #endif - sqlite3ExprDelete(db, p->pPartIdxWhere); - sqlite3ExprListDelete(db, p->aColExpr); - sqlite3DbFree(db, p->zColAff); - if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl); -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - sqlite3_free(p->aiRowEst); + tdsqlite3ExprDelete(db, p->pPartIdxWhere); + tdsqlite3ExprListDelete(db, p->aColExpr); + tdsqlite3DbFree(db, p->zColAff); + if( p->isResized ) tdsqlite3DbFree(db, (void *)p->azColl); +#ifdef SQLITE_ENABLE_STAT4 + tdsqlite3_free(p->aiRowEst); #endif - sqlite3DbFree(db, p); + tdsqlite3DbFree(db, p); } /* @@ -101829,13 +113212,13 @@ static void freeIndex(sqlite3 *db, Index *p){ ** the index hash table and free all memory structures associated ** with the index. */ -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ +SQLITE_PRIVATE void tdsqlite3UnlinkAndDeleteIndex(tdsqlite3 *db, int iDb, const char *zIdxName){ Index *pIndex; Hash *pHash; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); pHash = &db->aDb[iDb].pSchema->idxHash; - pIndex = sqlite3HashInsert(pHash, zIdxName, 0); + pIndex = tdsqlite3HashInsert(pHash, zIdxName, 0); if( ALWAYS(pIndex) ){ if( pIndex->pTable->pIndex==pIndex ){ pIndex->pTable->pIndex = pIndex->pNext; @@ -101849,9 +113232,9 @@ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char p->pNext = pIndex->pNext; } } - freeIndex(db, pIndex); + tdsqlite3FreeIndex(db, pIndex); } - db->flags |= SQLITE_InternChanges; + db->mDbFlags |= DBFLAG_SchemaChange; } /* @@ -101862,12 +113245,12 @@ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char ** Entry 0 (the "main" database) and entry 1 (the "temp" database) ** are never candidates for being collapsed. */ -SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3CollapseDatabaseArray(tdsqlite3 *db){ int i, j; for(i=j=2; i<db->nDb; i++){ struct Db *pDb = &db->aDb[i]; if( pDb->pBt==0 ){ - sqlite3DbFree(db, pDb->zDbSName); + tdsqlite3DbFree(db, pDb->zDbSName); pDb->zDbSName = 0; continue; } @@ -101879,78 +113262,83 @@ SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){ db->nDb = j; if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); - sqlite3DbFree(db, db->aDb); + tdsqlite3DbFree(db, db->aDb); db->aDb = db->aDbStatic; } } /* ** Reset the schema for the database at index iDb. Also reset the -** TEMP schema. +** TEMP schema. The reset is deferred if db->nSchemaLock is not zero. +** Deferred resets may be run by calling with iDb<0. */ -SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ - Db *pDb; +SQLITE_PRIVATE void tdsqlite3ResetOneSchema(tdsqlite3 *db, int iDb){ + int i; assert( iDb<db->nDb ); - /* Case 1: Reset the single schema identified by iDb */ - pDb = &db->aDb[iDb]; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - assert( pDb->pSchema!=0 ); - sqlite3SchemaClear(pDb->pSchema); + if( iDb>=0 ){ + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); + DbSetProperty(db, iDb, DB_ResetWanted); + DbSetProperty(db, 1, DB_ResetWanted); + db->mDbFlags &= ~DBFLAG_SchemaKnownOk; + } - /* If any database other than TEMP is reset, then also reset TEMP - ** since TEMP might be holding triggers that reference tables in the - ** other database. - */ - if( iDb!=1 ){ - pDb = &db->aDb[1]; - assert( pDb->pSchema!=0 ); - sqlite3SchemaClear(pDb->pSchema); + if( db->nSchemaLock==0 ){ + for(i=0; i<db->nDb; i++){ + if( DbHasProperty(db, i, DB_ResetWanted) ){ + tdsqlite3SchemaClear(db->aDb[i].pSchema); + } + } } - return; } /* ** Erase all schema information from all attached databases (including ** "main" and "temp") for a single database connection. */ -SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3ResetAllSchemasOfConnection(tdsqlite3 *db){ int i; - sqlite3BtreeEnterAll(db); + tdsqlite3BtreeEnterAll(db); for(i=0; i<db->nDb; i++){ Db *pDb = &db->aDb[i]; if( pDb->pSchema ){ - sqlite3SchemaClear(pDb->pSchema); + if( db->nSchemaLock==0 ){ + tdsqlite3SchemaClear(pDb->pSchema); + }else{ + DbSetProperty(db, i, DB_ResetWanted); + } } } - db->flags &= ~SQLITE_InternChanges; - sqlite3VtabUnlockList(db); - sqlite3BtreeLeaveAll(db); - sqlite3CollapseDatabaseArray(db); + db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk); + tdsqlite3VtabUnlockList(db); + tdsqlite3BtreeLeaveAll(db); + if( db->nSchemaLock==0 ){ + tdsqlite3CollapseDatabaseArray(db); + } } /* ** This routine is called when a commit occurs. */ -SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){ - db->flags &= ~SQLITE_InternChanges; +SQLITE_PRIVATE void tdsqlite3CommitInternalChanges(tdsqlite3 *db){ + db->mDbFlags &= ~DBFLAG_SchemaChange; } /* ** Delete memory allocated for the column names of a table or view (the ** Table.aCol[] array). */ -SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ +SQLITE_PRIVATE void tdsqlite3DeleteColumnNames(tdsqlite3 *db, Table *pTable){ int i; Column *pCol; assert( pTable!=0 ); if( (pCol = pTable->aCol)!=0 ){ for(i=0; i<pTable->nCol; i++, pCol++){ - sqlite3DbFree(db, pCol->zName); - sqlite3ExprDelete(db, pCol->pDflt); - sqlite3DbFree(db, pCol->zColl); + tdsqlite3DbFree(db, pCol->zName); + tdsqlite3ExprDelete(db, pCol->pDflt); + tdsqlite3DbFree(db, pCol->zColl); } - sqlite3DbFree(db, pTable->aCol); + tdsqlite3DbFree(db, pTable->aCol); } } @@ -101969,15 +113357,22 @@ SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ ** db parameter can be used with db->pnBytesFreed to measure the memory ** used by the Table object. */ -static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){ +static void SQLITE_NOINLINE deleteTable(tdsqlite3 *db, Table *pTable){ Index *pIndex, *pNext; - TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */ +#ifdef SQLITE_DEBUG /* Record the number of outstanding lookaside allocations in schema Tables - ** prior to doing any free() operations. Since schema Tables do not use - ** lookaside, this number should not change. */ - TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ? - db->lookaside.nOut : 0 ); + ** prior to doing any free() operations. Since schema Tables do not use + ** lookaside, this number should not change. + ** + ** If malloc has already failed, it may be that it failed while allocating + ** a Table object that was going to be marked ephemeral. So do not check + ** that no lookaside memory is used in this case either. */ + int nLookaside = 0; + if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){ + nLookaside = tdsqlite3LookasideUsed(db, 0); + } +#endif /* Delete all indices associated with this table. */ for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ @@ -101986,37 +113381,37 @@ static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){ || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) ); if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){ char *zName = pIndex->zName; - TESTONLY ( Index *pOld = ) sqlite3HashInsert( + TESTONLY ( Index *pOld = ) tdsqlite3HashInsert( &pIndex->pSchema->idxHash, zName, 0 ); - assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); + assert( db==0 || tdsqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); assert( pOld==pIndex || pOld==0 ); } - freeIndex(db, pIndex); + tdsqlite3FreeIndex(db, pIndex); } /* Delete any foreign keys attached to this table. */ - sqlite3FkDelete(db, pTable); + tdsqlite3FkDelete(db, pTable); /* Delete the Table structure itself. */ - sqlite3DeleteColumnNames(db, pTable); - sqlite3DbFree(db, pTable->zName); - sqlite3DbFree(db, pTable->zColAff); - sqlite3SelectDelete(db, pTable->pSelect); - sqlite3ExprListDelete(db, pTable->pCheck); + tdsqlite3DeleteColumnNames(db, pTable); + tdsqlite3DbFree(db, pTable->zName); + tdsqlite3DbFree(db, pTable->zColAff); + tdsqlite3SelectDelete(db, pTable->pSelect); + tdsqlite3ExprListDelete(db, pTable->pCheck); #ifndef SQLITE_OMIT_VIRTUALTABLE - sqlite3VtabClear(db, pTable); + tdsqlite3VtabClear(db, pTable); #endif - sqlite3DbFree(db, pTable); + tdsqlite3DbFree(db, pTable); /* Verify that no lookaside memory was used by schema tables */ - assert( nLookaside==0 || nLookaside==db->lookaside.nOut ); + assert( nLookaside==0 || nLookaside==tdsqlite3LookasideUsed(db,0) ); } -SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ +SQLITE_PRIVATE void tdsqlite3DeleteTable(tdsqlite3 *db, Table *pTable){ /* Do not delete the table until the reference count reaches zero. */ if( !pTable ) return; - if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return; + if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return; deleteTable(db, pTable); } @@ -102025,19 +113420,19 @@ SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ ** Unlink the given table from the hash tables and the delete the ** table structure with all its indices and foreign keys. */ -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ +SQLITE_PRIVATE void tdsqlite3UnlinkAndDeleteTable(tdsqlite3 *db, int iDb, const char *zTabName){ Table *p; Db *pDb; assert( db!=0 ); assert( iDb>=0 && iDb<db->nDb ); assert( zTabName ); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ pDb = &db->aDb[iDb]; - p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); - sqlite3DeleteTable(db, p); - db->flags |= SQLITE_InternChanges; + p = tdsqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); + tdsqlite3DeleteTable(db, p); + db->mDbFlags |= DBFLAG_SchemaChange; } /* @@ -102053,11 +113448,11 @@ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char ** are not \000 terminated and are not persistent. The returned string ** is \000 terminated and is persistent. */ -SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ +SQLITE_PRIVATE char *tdsqlite3NameFromToken(tdsqlite3 *db, Token *pName){ char *zName; if( pName ){ - zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); - sqlite3Dequote(zName); + zName = tdsqlite3DbStrNDup(db, (char*)pName->z, pName->n); + tdsqlite3Dequote(zName); }else{ zName = 0; } @@ -102068,10 +113463,10 @@ SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ ** Open the sqlite_master table stored in database number iDb for ** writing. The table is opened using cursor 0. */ -SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){ - Vdbe *v = sqlite3GetVdbe(p); - sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); - sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5); +SQLITE_PRIVATE void tdsqlite3OpenMasterTable(Parse *p, int iDb){ + Vdbe *v = tdsqlite3GetVdbe(p); + tdsqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME); + tdsqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5); if( p->nTab==0 ){ p->nTab = 1; } @@ -102083,12 +113478,15 @@ SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){ ** function returns the index of the named database in db->aDb[], or ** -1 if the named db cannot be found. */ -SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){ +SQLITE_PRIVATE int tdsqlite3FindDbName(tdsqlite3 *db, const char *zName){ int i = -1; /* Database number */ if( zName ){ Db *pDb; for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ - if( 0==sqlite3StrICmp(pDb->zDbSName, zName) ) break; + if( 0==tdsqlite3_stricmp(pDb->zDbSName, zName) ) break; + /* "main" is always an acceptable alias for the primary database + ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */ + if( i==0 && 0==tdsqlite3_stricmp("main", zName) ) break; } } return i; @@ -102100,12 +113498,12 @@ SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){ ** index of the named database in db->aDb[], or -1 if the named db ** does not exist. */ -SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){ +SQLITE_PRIVATE int tdsqlite3FindDb(tdsqlite3 *db, Token *pName){ int i; /* Database number */ char *zName; /* Name we are searching for */ - zName = sqlite3NameFromToken(db, pName); - i = sqlite3FindDbName(db, zName); - sqlite3DbFree(db, zName); + zName = tdsqlite3NameFromToken(db, pName); + i = tdsqlite3FindDbName(db, zName); + tdsqlite3DbFree(db, zName); return i; } @@ -102125,29 +113523,30 @@ SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){ ** pName2) that stores the unqualified table name. The index of the ** database "xxx" is returned. */ -SQLITE_PRIVATE int sqlite3TwoPartName( +SQLITE_PRIVATE int tdsqlite3TwoPartName( Parse *pParse, /* Parsing and code generating context */ Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ Token *pName2, /* The "yyy" in the name "xxx.yyy" */ Token **pUnqual /* Write the unqualified object name here */ ){ int iDb; /* Database holding the object */ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; assert( pName2!=0 ); if( pName2->n>0 ){ if( db->init.busy ) { - sqlite3ErrorMsg(pParse, "corrupt database"); + tdsqlite3ErrorMsg(pParse, "corrupt database"); return -1; } *pUnqual = pName2; - iDb = sqlite3FindDb(db, pName1); + iDb = tdsqlite3FindDb(db, pName1); if( iDb<0 ){ - sqlite3ErrorMsg(pParse, "unknown database %T", pName1); + tdsqlite3ErrorMsg(pParse, "unknown database %T", pName1); return -1; } }else{ - assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0); + assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT + || (db->mDbFlags & DBFLAG_Vacuum)!=0); iDb = db->init.iDb; *pUnqual = pName1; } @@ -102155,18 +113554,60 @@ SQLITE_PRIVATE int sqlite3TwoPartName( } /* +** True if PRAGMA writable_schema is ON +*/ +SQLITE_PRIVATE int tdsqlite3WritableSchema(tdsqlite3 *db){ + testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 ); + testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== + SQLITE_WriteSchema ); + testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== + SQLITE_Defensive ); + testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== + (SQLITE_WriteSchema|SQLITE_Defensive) ); + return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema; +} + +/* ** This routine is used to check if the UTF-8 string zName is a legal ** unqualified name for a new schema object (table, index, view or ** trigger). All names are legal except those that begin with the string ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace ** is reserved for internal use. +** +** When parsing the sqlite_master table, this routine also checks to +** make sure the "type", "name", and "tbl_name" columns are consistent +** with the SQL. */ -SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){ - if( !pParse->db->init.busy && pParse->nested==0 - && (pParse->db->flags & SQLITE_WriteSchema)==0 - && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ - sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); - return SQLITE_ERROR; +SQLITE_PRIVATE int tdsqlite3CheckObjectName( + Parse *pParse, /* Parsing context */ + const char *zName, /* Name of the object to check */ + const char *zType, /* Type of this object */ + const char *zTblName /* Parent table name for triggers and indexes */ +){ + tdsqlite3 *db = pParse->db; + if( tdsqlite3WritableSchema(db) || db->init.imposterTable ){ + /* Skip these error checks for writable_schema=ON */ + return SQLITE_OK; + } + if( db->init.busy ){ + if( tdsqlite3_stricmp(zType, db->init.azInit[0]) + || tdsqlite3_stricmp(zName, db->init.azInit[1]) + || tdsqlite3_stricmp(zTblName, db->init.azInit[2]) + ){ + if( tdsqlite3Config.bExtraSchemaChecks ){ + tdsqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */ + return SQLITE_ERROR; + } + } + }else{ + if( (pParse->nested==0 && 0==tdsqlite3StrNICmp(zName, "sqlite_", 7)) + || (tdsqlite3ReadOnlyShadowTables(db) && tdsqlite3ShadowTableName(db, zName)) + ){ + tdsqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", + zName); + return SQLITE_ERROR; + } + } return SQLITE_OK; } @@ -102174,17 +113615,19 @@ SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){ /* ** Return the PRIMARY KEY index of a table */ -SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){ +SQLITE_PRIVATE Index *tdsqlite3PrimaryKeyIndex(Table *pTab){ Index *p; for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){} return p; } /* -** Return the column of index pIdx that corresponds to table -** column iCol. Return -1 if not found. +** Convert an table column number into a index column number. That is, +** for the column iCol in the table (as defined by the CREATE TABLE statement) +** find the (first) offset of that column in index pIdx. Or return -1 +** if column iCol is not used in index pIdx. */ -SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ +SQLITE_PRIVATE i16 tdsqlite3TableColumnToIndex(Index *pIdx, i16 iCol){ int i; for(i=0; i<pIdx->nColumn; i++){ if( iCol==pIdx->aiColumn[i] ) return i; @@ -102192,6 +113635,84 @@ SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ return -1; } +#ifndef SQLITE_OMIT_GENERATED_COLUMNS +/* Convert a storage column number into a table column number. +** +** The storage column number (0,1,2,....) is the index of the value +** as it appears in the record on disk. The true column number +** is the index (0,1,2,...) of the column in the CREATE TABLE statement. +** +** The storage column number is less than the table column number if +** and only there are VIRTUAL columns to the left. +** +** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro. +*/ +SQLITE_PRIVATE i16 tdsqlite3StorageColumnToTable(Table *pTab, i16 iCol){ + if( pTab->tabFlags & TF_HasVirtual ){ + int i; + for(i=0; i<=iCol; i++){ + if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++; + } + } + return iCol; +} +#endif + +#ifndef SQLITE_OMIT_GENERATED_COLUMNS +/* Convert a table column number into a storage column number. +** +** The storage column number (0,1,2,....) is the index of the value +** as it appears in the record on disk. Or, if the input column is +** the N-th virtual column (zero-based) then the storage number is +** the number of non-virtual columns in the table plus N. +** +** The true column number is the index (0,1,2,...) of the column in +** the CREATE TABLE statement. +** +** If the input column is a VIRTUAL column, then it should not appear +** in storage. But the value sometimes is cached in registers that +** follow the range of registers used to construct storage. This +** avoids computing the same VIRTUAL column multiple times, and provides +** values for use by OP_Param opcodes in triggers. Hence, if the +** input column is a VIRTUAL table, put it after all the other columns. +** +** In the following, N means "normal column", S means STORED, and +** V means VIRTUAL. Suppose the CREATE TABLE has columns like this: +** +** CREATE TABLE ex(N,S,V,N,S,V,N,S,V); +** -- 0 1 2 3 4 5 6 7 8 +** +** Then the mapping from this function is as follows: +** +** INPUTS: 0 1 2 3 4 5 6 7 8 +** OUTPUTS: 0 1 6 2 3 7 4 5 8 +** +** So, in other words, this routine shifts all the virtual columns to +** the end. +** +** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and +** this routine is a no-op macro. If the pTab does not have any virtual +** columns, then this routine is no-op that always return iCol. If iCol +** is negative (indicating the ROWID column) then this routine return iCol. +*/ +SQLITE_PRIVATE i16 tdsqlite3TableColumnToStorage(Table *pTab, i16 iCol){ + int i; + i16 n; + assert( iCol<pTab->nCol ); + if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol; + for(i=0, n=0; i<iCol; i++){ + if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++; + } + if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){ + /* iCol is a virtual column itself */ + return pTab->nNVCol + i - n; + }else{ + /* iCol is a normal or stored column */ + return n; + } +} +#endif + /* ** Begin constructing a new table representation in memory. This is ** the first of several action routines that get called in response @@ -102205,10 +113726,10 @@ SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ ** The new table record is initialized and put in pParse->pNewTable. ** As more of the CREATE TABLE statement is parsed, additional action ** routines will be called to add more information to this record. -** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine +** At the end of the CREATE TABLE statement, the tdsqlite3EndTable() routine ** is called to complete the construction of the new table record. */ -SQLITE_PRIVATE void sqlite3StartTable( +SQLITE_PRIVATE void tdsqlite3StartTable( Parse *pParse, /* Parser context */ Token *pName1, /* First part of the name of the table or view */ Token *pName2, /* Second part of the name of the table or view */ @@ -102219,7 +113740,7 @@ SQLITE_PRIVATE void sqlite3StartTable( ){ Table *pTable; char *zName = 0; /* The name of the new table */ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Vdbe *v; int iDb; /* Database number to create the table in */ Token *pName; /* Unqualified name of the table to create */ @@ -102227,24 +113748,27 @@ SQLITE_PRIVATE void sqlite3StartTable( if( db->init.busy && db->init.newTnum==1 ){ /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */ iDb = db->init.iDb; - zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb)); + zName = tdsqlite3DbStrDup(db, SCHEMA_TABLE(iDb)); pName = pName1; }else{ /* The common case */ - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); + iDb = tdsqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ) return; if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ /* If creating a temp table, the name may not be qualified. Unless ** the database name is "temp" anyway. */ - sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); + tdsqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); return; } if( !OMIT_TEMPDB && isTemp ) iDb = 1; - zName = sqlite3NameFromToken(db, pName); + zName = tdsqlite3NameFromToken(db, pName); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenMap(pParse, (void*)zName, pName); + } } pParse->sNameToken = *pName; if( zName==0 ) return; - if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ + if( tdsqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){ goto begin_table_error; } if( db->init.iDb==1 ) isTemp = 1; @@ -102259,10 +113783,10 @@ SQLITE_PRIVATE void sqlite3StartTable( SQLITE_CREATE_TEMP_VIEW }; char *zDb = db->aDb[iDb].zDbSName; - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ + if( tdsqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ goto begin_table_error; } - if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView], + if( !isVirtual && tdsqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView], zName, 0, zDb) ){ goto begin_table_error; } @@ -102272,32 +113796,32 @@ SQLITE_PRIVATE void sqlite3StartTable( /* Make sure the new table name does not collide with an existing ** index or table name in the same database. Issue an error message if ** it does. The exception is if the statement being parsed was passed - ** to an sqlite3_declare_vtab() call. In that case only the column names + ** to an tdsqlite3_declare_vtab() call. In that case only the column names ** and types will be used, so there is no need to test for namespace ** collisions. */ - if( !IN_DECLARE_VTAB ){ + if( !IN_SPECIAL_PARSE ){ char *zDb = db->aDb[iDb].zDbSName; - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + if( SQLITE_OK!=tdsqlite3ReadSchema(pParse) ){ goto begin_table_error; } - pTable = sqlite3FindTable(db, zName, zDb); + pTable = tdsqlite3FindTable(db, zName, zDb); if( pTable ){ if( !noErr ){ - sqlite3ErrorMsg(pParse, "table %T already exists", pName); + tdsqlite3ErrorMsg(pParse, "table %T already exists", pName); }else{ assert( !db->init.busy || CORRUPT_DB ); - sqlite3CodeVerifySchema(pParse, iDb); + tdsqlite3CodeVerifySchema(pParse, iDb); } goto begin_table_error; } - if( sqlite3FindIndex(db, zName, zDb)!=0 ){ - sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); + if( tdsqlite3FindIndex(db, zName, zDb)!=0 ){ + tdsqlite3ErrorMsg(pParse, "there is already an index named %s", zName); goto begin_table_error; } } - pTable = sqlite3DbMallocZero(db, sizeof(Table)); + pTable = tdsqlite3DbMallocZero(db, sizeof(Table)); if( pTable==0 ){ assert( db->mallocFailed ); pParse->rc = SQLITE_NOMEM_BKPT; @@ -102307,8 +113831,12 @@ SQLITE_PRIVATE void sqlite3StartTable( pTable->zName = zName; pTable->iPKey = -1; pTable->pSchema = db->aDb[iDb].pSchema; - pTable->nRef = 1; - pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); + pTable->nTabRef = 1; +#ifdef SQLITE_DEFAULT_ROWEST + pTable->nRowLogEst = tdsqlite3LogEst(SQLITE_DEFAULT_ROWEST); +#else + pTable->nRowLogEst = 200; assert( 200==tdsqlite3LogEst(1048576) ); +#endif assert( pParse->pNewTable==0 ); pParse->pNewTable = pTable; @@ -102318,7 +113846,7 @@ SQLITE_PRIVATE void sqlite3StartTable( */ #ifndef SQLITE_OMIT_AUTOINCREMENT if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); pTable->pSchema->pSeqTab = pTable; } #endif @@ -102331,17 +113859,17 @@ SQLITE_PRIVATE void sqlite3StartTable( ** indices. Hence, the record number for the table must be allocated ** now. */ - if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ + if( !db->init.busy && (v = tdsqlite3GetVdbe(pParse))!=0 ){ int addr1; int fileFormat; int reg1, reg2, reg3; /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */ static const char nullRow[] = { 6, 0, 0, 0, 0, 0 }; - sqlite3BeginWriteOperation(pParse, 1, iDb); + tdsqlite3BeginWriteOperation(pParse, 1, iDb); #ifndef SQLITE_OMIT_VIRTUALTABLE if( isVirtual ){ - sqlite3VdbeAddOp0(v, OP_VBegin); + tdsqlite3VdbeAddOp0(v, OP_VBegin); } #endif @@ -102351,38 +113879,39 @@ SQLITE_PRIVATE void sqlite3StartTable( reg1 = pParse->regRowid = ++pParse->nMem; reg2 = pParse->regRoot = ++pParse->nMem; reg3 = ++pParse->nMem; - sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); - sqlite3VdbeUsesBtree(v, iDb); - addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); + tdsqlite3VdbeUsesBtree(v, iDb); + addr1 = tdsqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 1 : SQLITE_MAX_FILE_FORMAT; - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db)); - sqlite3VdbeJumpHere(v, addr1); + tdsqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat); + tdsqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db)); + tdsqlite3VdbeJumpHere(v, addr1); /* This just creates a place-holder record in the sqlite_master table. ** The record created does not contain anything yet. It will be replaced - ** by the real entry in code generated at sqlite3EndTable(). + ** by the real entry in code generated at tdsqlite3EndTable(). ** ** The rowid for the new entry is left in register pParse->regRowid. ** The root page number of the new table is left in reg pParse->regRoot. ** The rowid and root page number values are needed by the code that - ** sqlite3EndTable will generate. + ** tdsqlite3EndTable will generate. */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) if( isView || isVirtual ){ - sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); }else #endif { - pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); + pParse->addrCrTab = + tdsqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY); } - sqlite3OpenMasterTable(pParse, iDb); - sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); - sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC); - sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3VdbeAddOp0(v, OP_Close); + tdsqlite3OpenMasterTable(pParse, iDb); + tdsqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); + tdsqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC); + tdsqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); + tdsqlite3VdbeChangeP5(v, OPFLAG_APPEND); + tdsqlite3VdbeAddOp0(v, OP_Close); } /* Normal (non-error) return. */ @@ -102390,7 +113919,7 @@ SQLITE_PRIVATE void sqlite3StartTable( /* If an error occurs, we jump here */ begin_table_error: - sqlite3DbFree(db, zName); + tdsqlite3DbFree(db, zName); return; } @@ -102398,8 +113927,8 @@ begin_table_error: ** name of the column. */ #if SQLITE_ENABLE_HIDDEN_COLUMNS -SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ - if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){ +SQLITE_PRIVATE void tdsqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ + if( tdsqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){ pCol->colFlags |= COLFLAG_HIDDEN; }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){ pTab->tabFlags |= TF_OOOHidden; @@ -102412,41 +113941,40 @@ SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ ** Add a new column to the table currently being constructed. ** ** The parser calls this routine once for each column declaration -** in a CREATE TABLE statement. sqlite3StartTable() gets called +** in a CREATE TABLE statement. tdsqlite3StartTable() gets called ** first to get things going. Then this routine is called for each ** column. */ -SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ +SQLITE_PRIVATE void tdsqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ Table *p; int i; char *z; char *zType; Column *pCol; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; if( (p = pParse->pNewTable)==0 ) return; -#if SQLITE_MAX_COLUMN if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); + tdsqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); return; } -#endif - z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2); + z = tdsqlite3DbMallocRaw(db, pName->n + pType->n + 2); if( z==0 ) return; + if( IN_RENAME_OBJECT ) tdsqlite3RenameTokenMap(pParse, (void*)z, pName); memcpy(z, pName->z, pName->n); z[pName->n] = 0; - sqlite3Dequote(z); + tdsqlite3Dequote(z); for(i=0; i<p->nCol; i++){ - if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){ - sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); - sqlite3DbFree(db, z); + if( tdsqlite3_stricmp(z, p->aCol[i].zName)==0 ){ + tdsqlite3ErrorMsg(pParse, "duplicate column name: %s", z); + tdsqlite3DbFree(db, z); return; } } if( (p->nCol & 0x7)==0 ){ Column *aNew; - aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); + aNew = tdsqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); if( aNew==0 ){ - sqlite3DbFree(db, z); + tdsqlite3DbFree(db, z); return; } p->aCol = aNew; @@ -102454,22 +113982,28 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ pCol = &p->aCol[p->nCol]; memset(pCol, 0, sizeof(p->aCol[0])); pCol->zName = z; - sqlite3ColumnPropertiesFromName(p, pCol); + tdsqlite3ColumnPropertiesFromName(p, pCol); if( pType->n==0 ){ /* If there is no type specified, columns have the default affinity - ** 'BLOB'. */ + ** 'BLOB' with a default size of 4 bytes. */ pCol->affinity = SQLITE_AFF_BLOB; pCol->szEst = 1; +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + if( 4>=tdsqlite3GlobalConfig.szSorterRef ){ + pCol->colFlags |= COLFLAG_SORTERREF; + } +#endif }else{ - zType = z + sqlite3Strlen30(z) + 1; + zType = z + tdsqlite3Strlen30(z) + 1; memcpy(zType, pType->z, pType->n); zType[pType->n] = 0; - sqlite3Dequote(zType); - pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst); + tdsqlite3Dequote(zType); + pCol->affinity = tdsqlite3AffinityType(zType, pCol); pCol->colFlags |= COLFLAG_HASTYPE; } p->nCol++; + p->nNVCol++; pParse->constraintName.n = 0; } @@ -102479,11 +114013,26 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ ** been seen on a column. This routine sets the notNull flag on ** the column currently under construction. */ -SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){ +SQLITE_PRIVATE void tdsqlite3AddNotNull(Parse *pParse, int onError){ Table *p; + Column *pCol; p = pParse->pNewTable; if( p==0 || NEVER(p->nCol<1) ) return; - p->aCol[p->nCol-1].notNull = (u8)onError; + pCol = &p->aCol[p->nCol-1]; + pCol->notNull = (u8)onError; + p->tabFlags |= TF_HasNotNull; + + /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created + ** on this column. */ + if( pCol->colFlags & COLFLAG_UNIQUE ){ + Index *pIdx; + for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ + assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None ); + if( pIdx->aiColumn[0]==p->nCol-1 ){ + pIdx->uniqNotNull = 1; + } + } + } } /* @@ -102511,14 +114060,14 @@ SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){ ** If none of the substrings in the above table are found, ** SQLITE_AFF_NUMERIC is returned. */ -SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){ +SQLITE_PRIVATE char tdsqlite3AffinityType(const char *zIn, Column *pCol){ u32 h = 0; char aff = SQLITE_AFF_NUMERIC; const char *zChar = 0; assert( zIn!=0 ); while( zIn[0] ){ - h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; + h = (h<<8) + tdsqlite3UpperToLower[(*zIn)&0xff]; zIn++; if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ aff = SQLITE_AFF_TEXT; @@ -102548,27 +114097,32 @@ SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){ } } - /* If pszEst is not NULL, store an estimate of the field size. The + /* If pCol is not NULL, store an estimate of the field size. The ** estimate is scaled so that the size of an integer is 1. */ - if( pszEst ){ - *pszEst = 1; /* default size is approx 4 bytes */ + if( pCol ){ + int v = 0; /* default size is approx 4 bytes */ if( aff<SQLITE_AFF_NUMERIC ){ if( zChar ){ while( zChar[0] ){ - if( sqlite3Isdigit(zChar[0]) ){ - int v = 0; - sqlite3GetInt32(zChar, &v); - v = v/4 + 1; - if( v>255 ) v = 255; - *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ + if( tdsqlite3Isdigit(zChar[0]) ){ + /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ + tdsqlite3GetInt32(zChar, &v); break; } zChar++; } }else{ - *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ + v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ } } +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + if( v>=tdsqlite3GlobalConfig.szSorterRef ){ + pCol->colFlags |= COLFLAG_SORTERREF; + } +#endif + v = v/4 + 1; + if( v>255 ) v = 255; + pCol->szEst = v; } return aff; } @@ -102583,34 +114137,47 @@ SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){ ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. */ -SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ +SQLITE_PRIVATE void tdsqlite3AddDefaultValue( + Parse *pParse, /* Parsing context */ + Expr *pExpr, /* The parsed expression of the default value */ + const char *zStart, /* Start of the default value text */ + const char *zEnd /* First character past end of defaut value text */ +){ Table *p; Column *pCol; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; p = pParse->pNewTable; if( p!=0 ){ + int isInit = db->init.busy && db->init.iDb!=1; pCol = &(p->aCol[p->nCol-1]); - if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){ - sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", + if( !tdsqlite3ExprIsConstantOrFunction(pExpr, isInit) ){ + tdsqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", pCol->zName); +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + }else if( pCol->colFlags & COLFLAG_GENERATED ){ + testcase( pCol->colFlags & COLFLAG_VIRTUAL ); + testcase( pCol->colFlags & COLFLAG_STORED ); + tdsqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column"); +#endif }else{ /* A copy of pExpr is used instead of the original, as pExpr contains - ** tokens that point to volatile memory. The 'span' of the expression - ** is required by pragma table_info. + ** tokens that point to volatile memory. */ Expr x; - sqlite3ExprDelete(db, pCol->pDflt); + tdsqlite3ExprDelete(db, pCol->pDflt); memset(&x, 0, sizeof(x)); x.op = TK_SPAN; - x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart, - (int)(pSpan->zEnd - pSpan->zStart)); - x.pLeft = pSpan->pExpr; + x.u.zToken = tdsqlite3DbSpanDup(db, zStart, zEnd); + x.pLeft = pExpr; x.flags = EP_Skip; - pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE); - sqlite3DbFree(db, x.u.zToken); + pCol->pDflt = tdsqlite3ExprDup(db, &x, EXPRDUP_REDUCE); + tdsqlite3DbFree(db, x.u.zToken); } } - sqlite3ExprDelete(db, pSpan->pExpr); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameExprUnmap(pParse, pExpr); + } + tdsqlite3ExprDelete(db, pExpr); } /* @@ -102626,10 +114193,10 @@ SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){ ** accept it. This routine does the necessary conversion. It converts ** the expression given in its argument from a TK_STRING into a TK_ID ** if the expression is just a TK_STRING with an optional COLLATE clause. -** If the epxression is anything other than TK_STRING, the expression is +** If the expression is anything other than TK_STRING, the expression is ** unchanged. */ -static void sqlite3StringToId(Expr *p){ +static void tdsqlite3StringToId(Expr *p){ if( p->op==TK_STRING ){ p->op = TK_ID; }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){ @@ -102638,6 +114205,21 @@ static void sqlite3StringToId(Expr *p){ } /* +** Tag the given column as being part of the PRIMARY KEY +*/ +static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){ + pCol->colFlags |= COLFLAG_PRIMKEY; +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + if( pCol->colFlags & COLFLAG_GENERATED ){ + testcase( pCol->colFlags & COLFLAG_VIRTUAL ); + testcase( pCol->colFlags & COLFLAG_STORED ); + tdsqlite3ErrorMsg(pParse, + "generated columns cannot be part of the PRIMARY KEY"); + } +#endif +} + +/* ** Designate the PRIMARY KEY for the table. pList is a list of names ** of columns that form the primary key. If pList is NULL, then the ** most recently added column of the table is the primary key. @@ -102655,7 +114237,7 @@ static void sqlite3StringToId(Expr *p){ ** If the key is not an INTEGER PRIMARY KEY, then create a unique ** index for the key. No index is created for INTEGER PRIMARY KEYs. */ -SQLITE_PRIVATE void sqlite3AddPrimaryKey( +SQLITE_PRIVATE void tdsqlite3AddPrimaryKey( Parse *pParse, /* Parsing context */ ExprList *pList, /* List of field names to be indexed */ int onError, /* What to do with a uniqueness conflict */ @@ -102668,7 +114250,7 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey( int nTerm; if( pTab==0 ) goto primary_key_exit; if( pTab->tabFlags & TF_HasPrimaryKey ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "table \"%s\" has more than one primary key", pTab->zName); goto primary_key_exit; } @@ -102676,20 +114258,20 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey( if( pList==0 ){ iCol = pTab->nCol - 1; pCol = &pTab->aCol[iCol]; - pCol->colFlags |= COLFLAG_PRIMKEY; + makeColumnPartOfPrimaryKey(pParse, pCol); nTerm = 1; }else{ nTerm = pList->nExpr; for(i=0; i<nTerm; i++){ - Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr); + Expr *pCExpr = tdsqlite3ExprSkipCollate(pList->a[i].pExpr); assert( pCExpr!=0 ); - sqlite3StringToId(pCExpr); + tdsqlite3StringToId(pCExpr); if( pCExpr->op==TK_ID ){ const char *zCName = pCExpr->u.zToken; for(iCol=0; iCol<pTab->nCol; iCol++){ - if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ + if( tdsqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ pCol = &pTab->aCol[iCol]; - pCol->colFlags |= COLFLAG_PRIMKEY; + makeColumnPartOfPrimaryKey(pParse, pCol); break; } } @@ -102698,51 +114280,56 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey( } if( nTerm==1 && pCol - && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0 + && tdsqlite3StrICmp(tdsqlite3ColumnType(pCol,""), "INTEGER")==0 && sortOrder!=SQLITE_SO_DESC ){ + if( IN_RENAME_OBJECT && pList ){ + Expr *pCExpr = tdsqlite3ExprSkipCollate(pList->a[0].pExpr); + tdsqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr); + } pTab->iPKey = iCol; pTab->keyConf = (u8)onError; assert( autoInc==0 || autoInc==1 ); pTab->tabFlags |= autoInc*TF_Autoincrement; - if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder; + if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags; + (void)tdsqlite3HasExplicitNulls(pParse, pList); }else if( autoInc ){ #ifndef SQLITE_OMIT_AUTOINCREMENT - sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " + tdsqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " "INTEGER PRIMARY KEY"); #endif }else{ - sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, + tdsqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY); pList = 0; } primary_key_exit: - sqlite3ExprListDelete(pParse->db, pList); + tdsqlite3ExprListDelete(pParse->db, pList); return; } /* ** Add a new CHECK constraint to the table currently under construction. */ -SQLITE_PRIVATE void sqlite3AddCheckConstraint( +SQLITE_PRIVATE void tdsqlite3AddCheckConstraint( Parse *pParse, /* Parsing context */ Expr *pCheckExpr /* The check expression */ ){ #ifndef SQLITE_OMIT_CHECK Table *pTab = pParse->pNewTable; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; if( pTab && !IN_DECLARE_VTAB - && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) + && !tdsqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) ){ - pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); + pTab->pCheck = tdsqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); if( pParse->constraintName.n ){ - sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); + tdsqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); } }else #endif { - sqlite3ExprDelete(pParse->db, pCheckExpr); + tdsqlite3ExprDelete(pParse->db, pCheckExpr); } } @@ -102750,21 +114337,21 @@ SQLITE_PRIVATE void sqlite3AddCheckConstraint( ** Set the collation function of the most recently parsed table column ** to the CollSeq given. */ -SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){ +SQLITE_PRIVATE void tdsqlite3AddCollateType(Parse *pParse, Token *pToken){ Table *p; int i; char *zColl; /* Dequoted name of collation sequence */ - sqlite3 *db; + tdsqlite3 *db; if( (p = pParse->pNewTable)==0 ) return; i = p->nCol-1; db = pParse->db; - zColl = sqlite3NameFromToken(db, pToken); + zColl = tdsqlite3NameFromToken(db, pToken); if( !zColl ) return; - if( sqlite3LocateCollSeq(pParse, zColl) ){ + if( tdsqlite3LocateCollSeq(pParse, zColl) ){ Index *pIdx; - sqlite3DbFree(db, p->aCol[i].zColl); + tdsqlite3DbFree(db, p->aCol[i].zColl); p->aCol[i].zColl = zColl; /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", @@ -102778,45 +114365,62 @@ SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){ } } }else{ - sqlite3DbFree(db, zColl); + tdsqlite3DbFree(db, zColl); } } -/* -** This function returns the collation sequence for database native text -** encoding identified by the string zName, length nName. -** -** If the requested collation sequence is not available, or not available -** in the database native encoding, the collation factory is invoked to -** request it. If the collation factory does not supply such a sequence, -** and the sequence is available in another text encoding, then that is -** returned instead. -** -** If no versions of the requested collations sequence are available, or -** another error occurs, NULL is returned and an error message written into -** pParse. -** -** This routine is a wrapper around sqlite3FindCollSeq(). This routine -** invokes the collation factory if the named collation cannot be found -** and generates an error message. -** -** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() +/* Change the most recently parsed column to be a GENERATED ALWAYS AS +** column. */ -SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ - sqlite3 *db = pParse->db; - u8 enc = ENC(db); - u8 initbusy = db->init.busy; - CollSeq *pColl; - - pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); - if( !initbusy && (!pColl || !pColl->xCmp) ){ - pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); +SQLITE_PRIVATE void tdsqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){ +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + u8 eType = COLFLAG_VIRTUAL; + Table *pTab = pParse->pNewTable; + Column *pCol; + if( pTab==0 ){ + /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */ + goto generated_done; + } + pCol = &(pTab->aCol[pTab->nCol-1]); + if( IN_DECLARE_VTAB ){ + tdsqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns"); + goto generated_done; + } + if( pCol->pDflt ) goto generated_error; + if( pType ){ + if( pType->n==7 && tdsqlite3StrNICmp("virtual",pType->z,7)==0 ){ + /* no-op */ + }else if( pType->n==6 && tdsqlite3StrNICmp("stored",pType->z,6)==0 ){ + eType = COLFLAG_STORED; + }else{ + goto generated_error; + } + } + if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--; + pCol->colFlags |= eType; + assert( TF_HasVirtual==COLFLAG_VIRTUAL ); + assert( TF_HasStored==COLFLAG_STORED ); + pTab->tabFlags |= eType; + if( pCol->colFlags & COLFLAG_PRIMKEY ){ + makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */ } + pCol->pDflt = pExpr; + pExpr = 0; + goto generated_done; - return pColl; +generated_error: + tdsqlite3ErrorMsg(pParse, "error in generated column \"%s\"", + pCol->zName); +generated_done: + tdsqlite3ExprDelete(pParse->db, pExpr); +#else + /* Throw and error for the GENERATED ALWAYS AS clause if the + ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */ + tdsqlite3ErrorMsg(pParse, "generated columns not supported"); + tdsqlite3ExprDelete(pParse->db, pExpr); +#endif } - /* ** Generate code that will increment the schema cookie. ** @@ -102836,12 +114440,12 @@ SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments ** the schema-version whenever the schema changes. */ -SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){ - sqlite3 *db = pParse->db; +SQLITE_PRIVATE void tdsqlite3ChangeCookie(Parse *pParse, int iDb){ + tdsqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, - db->aDb[iDb].pSchema->schema_cookie+1); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); + tdsqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, + (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie)); } /* @@ -102879,10 +114483,10 @@ static void identPut(char *z, int *pIdx, char *zSignedIdent){ i = *pIdx; for(j=0; zIdent[j]; j++){ - if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; + if( !tdsqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; } - needQuote = sqlite3Isdigit(zIdent[0]) - || sqlite3KeywordCode(zIdent, j)!=TK_ID + needQuote = tdsqlite3Isdigit(zIdent[0]) + || tdsqlite3KeywordCode(zIdent, j)!=TK_ID || zIdent[j]!=0 || j==0; @@ -102901,7 +114505,7 @@ static void identPut(char *z, int *pIdx, char *zSignedIdent){ ** table. Memory to hold the text of the statement is obtained ** from sqliteMalloc() and must be freed by the calling function. */ -static char *createTableStmt(sqlite3 *db, Table *p){ +static char *createTableStmt(tdsqlite3 *db, Table *p){ int i, k, n; char *zStmt; char *zSep, *zSep2, *zEnd; @@ -102921,13 +114525,13 @@ static char *createTableStmt(sqlite3 *db, Table *p){ zEnd = "\n)"; } n += 35 + 6*p->nCol; - zStmt = sqlite3DbMallocRaw(0, n); + zStmt = tdsqlite3DbMallocRaw(0, n); if( zStmt==0 ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); return 0; } - sqlite3_snprintf(n, zStmt, "CREATE TABLE "); - k = sqlite3Strlen30(zStmt); + tdsqlite3_snprintf(n, zStmt, "CREATE TABLE "); + k = tdsqlite3Strlen30(zStmt); identPut(zStmt, &k, p->zName); zStmt[k++] = '('; for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ @@ -102941,8 +114545,8 @@ static char *createTableStmt(sqlite3 *db, Table *p){ int len; const char *zType; - sqlite3_snprintf(n-k, &zStmt[k], zSep); - k += sqlite3Strlen30(&zStmt[k]); + tdsqlite3_snprintf(n-k, &zStmt[k], zSep); + k += tdsqlite3Strlen30(&zStmt[k]); zSep = zSep2; identPut(zStmt, &k, pCol->zName); assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); @@ -102954,14 +114558,14 @@ static char *createTableStmt(sqlite3 *db, Table *p){ testcase( pCol->affinity==SQLITE_AFF_REAL ); zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; - len = sqlite3Strlen30(zType); + len = tdsqlite3Strlen30(zType); assert( pCol->affinity==SQLITE_AFF_BLOB - || pCol->affinity==sqlite3AffinityType(zType, 0) ); + || pCol->affinity==tdsqlite3AffinityType(zType, 0) ); memcpy(&zStmt[k], zType, len); k += len; assert( k<=n ); } - sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); + tdsqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); return zStmt; } @@ -102969,13 +114573,13 @@ static char *createTableStmt(sqlite3 *db, Table *p){ ** Resize an Index object to hold N columns total. Return SQLITE_OK ** on success and SQLITE_NOMEM on an OOM error. */ -static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ +static int resizeIndexObject(tdsqlite3 *db, Index *pIdx, int N){ char *zExtra; int nByte; if( pIdx->nColumn>=N ) return SQLITE_OK; assert( pIdx->isResized==0 ); nByte = (sizeof(char*) + sizeof(i16) + 1)*N; - zExtra = sqlite3DbMallocZero(db, nByte); + zExtra = tdsqlite3DbMallocZero(db, nByte); if( zExtra==0 ) return SQLITE_NOMEM_BKPT; memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); pIdx->azColl = (const char**)zExtra; @@ -103001,7 +114605,7 @@ static void estimateTableWidth(Table *pTab){ wTable += pTabCol->szEst; } if( pTab->iPKey<0 ) wTable++; - pTab->szTabRow = sqlite3LogEst(wTable*4); + pTab->szTabRow = tdsqlite3LogEst(wTable*4); } /* @@ -103016,16 +114620,91 @@ static void estimateIndexWidth(Index *pIdx){ assert( x<pIdx->pTable->nCol ); wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; } - pIdx->szIdxRow = sqlite3LogEst(wIndex*4); + pIdx->szIdxRow = tdsqlite3LogEst(wIndex*4); } -/* Return true if value x is found any of the first nCol entries of aiCol[] +/* Return true if column number x is any of the first nCol entries of aiCol[]. +** This is used to determine if the column number x appears in any of the +** first nCol entries of an index. */ static int hasColumn(const i16 *aiCol, int nCol, int x){ - while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1; + while( nCol-- > 0 ){ + assert( aiCol[0]>=0 ); + if( x==*(aiCol++) ){ + return 1; + } + } + return 0; +} + +/* +** Return true if any of the first nKey entries of index pIdx exactly +** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID +** PRIMARY KEY index. pIdx is an index on the same table. pIdx may +** or may not be the same index as pPk. +** +** The first nKey entries of pIdx are guaranteed to be ordinary columns, +** not a rowid or expression. +** +** This routine differs from hasColumn() in that both the column and the +** collating sequence must match for this routine, but for hasColumn() only +** the column name must match. +*/ +static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){ + int i, j; + assert( nKey<=pIdx->nColumn ); + assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) ); + assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY ); + assert( pPk->pTable->tabFlags & TF_WithoutRowid ); + assert( pPk->pTable==pIdx->pTable ); + testcase( pPk==pIdx ); + j = pPk->aiColumn[iCol]; + assert( j!=XN_ROWID && j!=XN_EXPR ); + for(i=0; i<nKey; i++){ + assert( pIdx->aiColumn[i]>=0 || j>=0 ); + if( pIdx->aiColumn[i]==j + && tdsqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0 + ){ + return 1; + } + } return 0; } +/* Recompute the colNotIdxed field of the Index. +** +** colNotIdxed is a bitmask that has a 0 bit representing each indexed +** columns that are within the first 63 columns of the table. The +** high-order bit of colNotIdxed is always 1. All unindexed columns +** of the table have a 1. +** +** 2019-10-24: For the purpose of this computation, virtual columns are +** not considered to be covered by the index, even if they are in the +** index, because we do not trust the logic in whereIndexExprTrans() to be +** able to find all instances of a reference to the indexed table column +** and convert them into references to the index. Hence we always want +** the actual table at hand in order to recompute the virtual column, if +** necessary. +** +** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask +** to determine if the index is covering index. +*/ +static void recomputeColumnsNotIndexed(Index *pIdx){ + Bitmask m = 0; + int j; + Table *pTab = pIdx->pTable; + for(j=pIdx->nColumn-1; j>=0; j--){ + int x = pIdx->aiColumn[j]; + if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){ + testcase( x==BMS-1 ); + testcase( x==BMS-2 ); + if( x<BMS-1 ) m |= MASKBIT(x); + } + } + pIdx->colNotIdxed = ~m; + assert( (pIdx->colNotIdxed>>63)==1 ); +} + /* ** This routine runs at the end of parsing a CREATE TABLE statement that ** has a WITHOUT ROWID clause. The job of this routine is to convert both @@ -103034,9 +114713,8 @@ static int hasColumn(const i16 *aiCol, int nCol, int x){ ** Changes include: ** ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL. -** (2) Convert the OP_CreateTable into an OP_CreateIndex. There is -** no rowid btree for a WITHOUT ROWID. Instead, the canonical -** data storage is a covering index btree. +** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY +** into BTREE_BLOBKEY. ** (3) Bypass the creation of the sqlite_master table entry ** for the PRIMARY KEY as the primary key index is now ** identified by the sqlite_master table entry of the table itself. @@ -103044,7 +114722,7 @@ static int hasColumn(const i16 *aiCol, int nCol, int x){ ** schema to the rootpage from the main table. ** (5) Add all table columns to the PRIMARY KEY Index object ** so that the PRIMARY KEY is a covering index. The surplus -** columns are part of KeyInfo.nXField and are not used for +** columns are part of KeyInfo.nAllField and are not used for ** sorting or lookup or uniqueness checks. ** (6) Replace the rowid tail on all automatically generated UNIQUE ** indices with the PRIMARY KEY columns. @@ -103055,8 +114733,9 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ Index *pIdx; Index *pPk; int nPk; + int nExtra; int i, j; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables) @@ -103067,19 +114746,15 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ pTab->aCol[i].notNull = OE_Abort; } } + pTab->tabFlags |= TF_HasNotNull; } - /* The remaining transformations only apply to b-tree tables, not to - ** virtual tables */ - if( IN_DECLARE_VTAB ) return; - - /* Convert the OP_CreateTable opcode that would normally create the - ** root-page for the table into an OP_CreateIndex opcode. The index - ** created will become the PRIMARY KEY index. + /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY + ** into BTREE_BLOBKEY. */ if( pParse->addrCrTab ){ assert( v ); - sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex); + tdsqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY); } /* Locate the PRIMARY KEY index. Or, if this table was originally @@ -103088,28 +114763,24 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ if( pTab->iPKey>=0 ){ ExprList *pList; Token ipkToken; - sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName); - pList = sqlite3ExprListAppend(pParse, 0, - sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); + tdsqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName); + pList = tdsqlite3ExprListAppend(pParse, 0, + tdsqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); if( pList==0 ) return; - pList->a[0].sortOrder = pParse->iPkSortOrder; + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey); + } + pList->a[0].sortFlags = pParse->iPkSortOrder; assert( pParse->pNewTable==pTab ); - sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, - SQLITE_IDXTYPE_PRIMARYKEY); - if( db->mallocFailed ) return; - pPk = sqlite3PrimaryKeyIndex(pTab); pTab->iPKey = -1; + tdsqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, + SQLITE_IDXTYPE_PRIMARYKEY); + if( db->mallocFailed || pParse->nErr ) return; + pPk = tdsqlite3PrimaryKeyIndex(pTab); + assert( pPk->nKeyCol==1 ); }else{ - pPk = sqlite3PrimaryKeyIndex(pTab); - - /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master - ** table entry. This is only required if currently generating VDBE - ** code for a CREATE TABLE (not when parsing one as part of reading - ** a database schema). */ - if( v ){ - assert( db->init.busy==0 ); - sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto); - } + pPk = tdsqlite3PrimaryKeyIndex(pTab); + assert( pPk!=0 ); /* ** Remove all redundant columns from the PRIMARY KEY. For example, change @@ -103117,9 +114788,12 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ ** code assumes the PRIMARY KEY contains no repeated columns. */ for(i=j=1; i<pPk->nKeyCol; i++){ - if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){ + if( isDupColumn(pPk, j, pPk, i) ){ pPk->nColumn--; }else{ + testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ); + pPk->azColl[j] = pPk->azColl[i]; + pPk->aSortOrder[j] = pPk->aSortOrder[i]; pPk->aiColumn[j++] = pPk->aiColumn[i]; } } @@ -103128,7 +114802,16 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ assert( pPk!=0 ); pPk->isCovering = 1; if( !db->init.imposterTable ) pPk->uniqNotNull = 1; - nPk = pPk->nKeyCol; + nPk = pPk->nColumn = pPk->nKeyCol; + + /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master + ** table entry. This is only required if currently generating VDBE + ** code for a CREATE TABLE (not when parsing one as part of reading + ** a database schema). */ + if( v && pPk->tnum>0 ){ + assert( db->init.busy==0 ); + tdsqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto); + } /* The root page of the PRIMARY KEY is the table root page */ pPk->tnum = pTab->tnum; @@ -103140,7 +114823,10 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ int n; if( IsPrimaryKeyIndex(pIdx) ) continue; for(i=n=0; i<nPk; i++){ - if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++; + if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){ + testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); + n++; + } } if( n==0 ){ /* This index is a superset of the primary key */ @@ -103149,9 +114835,14 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ } if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ - if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){ + if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){ + testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); pIdx->aiColumn[j] = pPk->aiColumn[i]; pIdx->azColl[j] = pPk->azColl[i]; + if( pPk->aSortOrder[i] ){ + /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */ + pIdx->bAscKeyBug = 1; + } j++; } } @@ -103161,22 +114852,54 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ /* Add all table columns to the PRIMARY KEY index */ - if( nPk<pTab->nCol ){ - if( resizeIndexObject(db, pPk, pTab->nCol) ) return; - for(i=0, j=nPk; i<pTab->nCol; i++){ - if( !hasColumn(pPk->aiColumn, j, i) ){ - assert( j<pPk->nColumn ); - pPk->aiColumn[j] = i; - pPk->azColl[j] = sqlite3StrBINARY; - j++; - } + nExtra = 0; + for(i=0; i<pTab->nCol; i++){ + if( !hasColumn(pPk->aiColumn, nPk, i) + && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++; + } + if( resizeIndexObject(db, pPk, nPk+nExtra) ) return; + for(i=0, j=nPk; i<pTab->nCol; i++){ + if( !hasColumn(pPk->aiColumn, j, i) + && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 + ){ + assert( j<pPk->nColumn ); + pPk->aiColumn[j] = i; + pPk->azColl[j] = tdsqlite3StrBINARY; + j++; } - assert( pPk->nColumn==j ); - assert( pTab->nCol==j ); - }else{ - pPk->nColumn = pTab->nCol; } + assert( pPk->nColumn==j ); + assert( pTab->nNVCol<=j ); + recomputeColumnsNotIndexed(pPk); +} + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/* +** Return true if zName is a shadow table name in the current database +** connection. +** +** zName is temporarily modified while this routine is running, but is +** restored to its original value prior to this routine returning. +*/ +SQLITE_PRIVATE int tdsqlite3ShadowTableName(tdsqlite3 *db, const char *zName){ + char *zTail; /* Pointer to the last "_" in zName */ + Table *pTab; /* Table that zName is a shadow of */ + Module *pMod; /* Module for the virtual table */ + + zTail = strrchr(zName, '_'); + if( zTail==0 ) return 0; + *zTail = 0; + pTab = tdsqlite3FindTable(db, zName, 0); + *zTail = '_'; + if( pTab==0 ) return 0; + if( !IsVirtual(pTab) ) return 0; + pMod = (Module*)tdsqlite3HashFind(&db->aModule, pTab->azModuleArg[0]); + if( pMod==0 ) return 0; + if( pMod->pModule->iVersion<3 ) return 0; + if( pMod->pModule->xShadowName==0 ) return 0; + return pMod->pModule->xShadowName(zTail+1); } +#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ /* ** This routine is called to report the final ")" that terminates @@ -103198,7 +114921,7 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ ** "CREATE TABLE ... AS SELECT ..." statement. The column names of ** the new table will match the result set of the SELECT. */ -SQLITE_PRIVATE void sqlite3EndTable( +SQLITE_PRIVATE void tdsqlite3EndTable( Parse *pParse, /* Parse context */ Token *pCons, /* The ',' token after the last column defn. */ Token *pEnd, /* The ')' before options in the CREATE TABLE */ @@ -103206,7 +114929,7 @@ SQLITE_PRIVATE void sqlite3EndTable( Select *pSelect /* Select from a "CREATE ... AS SELECT" */ ){ Table *p; /* The new table */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ int iDb; /* Database in which the table lives */ Index *pIdx; /* An implied index of the table */ @@ -103217,7 +114940,9 @@ SQLITE_PRIVATE void sqlite3EndTable( p = pParse->pNewTable; if( p==0 ) return; - assert( !db->init.busy || !pSelect ); + if( pSelect==0 && tdsqlite3ShadowTableName(db, p->zName) ){ + p->tabFlags |= TF_Shadow; + } /* If the db->init.busy is 1 it means we are reading the SQL off the ** "sqlite_master" or "sqlite_temp_master" table on the disk. @@ -103229,34 +114954,79 @@ SQLITE_PRIVATE void sqlite3EndTable( ** table itself. So mark it read-only. */ if( db->init.busy ){ + if( pSelect ){ + tdsqlite3ErrorMsg(pParse, ""); + return; + } p->tnum = db->init.newTnum; if( p->tnum==1 ) p->tabFlags |= TF_Readonly; } + assert( (p->tabFlags & TF_HasPrimaryKey)==0 + || p->iPKey>=0 || tdsqlite3PrimaryKeyIndex(p)!=0 ); + assert( (p->tabFlags & TF_HasPrimaryKey)!=0 + || (p->iPKey<0 && tdsqlite3PrimaryKeyIndex(p)==0) ); + /* Special processing for WITHOUT ROWID Tables */ if( tabOpts & TF_WithoutRowid ){ if( (p->tabFlags & TF_Autoincrement) ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); return; } if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ - sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); - }else{ - p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; - convertToWithoutRowidTable(pParse, p); + tdsqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); + return; } + p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; + convertToWithoutRowidTable(pParse, p); } - - iDb = sqlite3SchemaToIndex(db, p->pSchema); + iDb = tdsqlite3SchemaToIndex(db, p->pSchema); #ifndef SQLITE_OMIT_CHECK /* Resolve names in all CHECK constraint expressions. */ if( p->pCheck ){ - sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); + tdsqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); + if( pParse->nErr ){ + /* If errors are seen, delete the CHECK constraints now, else they might + ** actually be used if PRAGMA writable_schema=ON is set. */ + tdsqlite3ExprListDelete(db, p->pCheck); + p->pCheck = 0; + } } #endif /* !defined(SQLITE_OMIT_CHECK) */ +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + if( p->tabFlags & TF_HasGenerated ){ + int ii, nNG = 0; + testcase( p->tabFlags & TF_HasVirtual ); + testcase( p->tabFlags & TF_HasStored ); + for(ii=0; ii<p->nCol; ii++){ + u32 colFlags = p->aCol[ii].colFlags; + if( (colFlags & COLFLAG_GENERATED)!=0 ){ + Expr *pX = p->aCol[ii].pDflt; + testcase( colFlags & COLFLAG_VIRTUAL ); + testcase( colFlags & COLFLAG_STORED ); + if( tdsqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){ + /* If there are errors in resolving the expression, change the + ** expression to a NULL. This prevents code generators that operate + ** on the expression from inserting extra parts into the expression + ** tree that have been allocated from lookaside memory, which is + ** illegal in a schema and will lead to errors or heap corruption + ** when the database connection closes. */ + tdsqlite3ExprDelete(db, pX); + p->aCol[ii].pDflt = tdsqlite3ExprAlloc(db, TK_NULL, 0, 0); + } + }else{ + nNG++; + } + } + if( nNG==0 ){ + tdsqlite3ErrorMsg(pParse, "must have at least one non-generated column"); + return; + } + } +#endif /* Estimate the average row size for the table and for all implied indices */ estimateTableWidth(p); @@ -103277,10 +115047,10 @@ SQLITE_PRIVATE void sqlite3EndTable( char *zType2; /* "VIEW" or "TABLE" */ char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( NEVER(v==0) ) return; - sqlite3VdbeAddOp1(v, OP_Close, 0); + tdsqlite3VdbeAddOp1(v, OP_Close, 0); /* ** Initialize zType for the new view or table. @@ -103301,7 +115071,7 @@ SQLITE_PRIVATE void sqlite3EndTable( ** statement to populate the new table. The root-page number for the ** new table is in register pParse->regRoot. ** - ** Once the SELECT has been coded by sqlite3Select(), it is in a + ** Once the SELECT has been coded by tdsqlite3Select(), it is in a ** suitable state to query for the column names and types to be used ** by the new table. ** @@ -103323,34 +115093,35 @@ SQLITE_PRIVATE void sqlite3EndTable( regRec = ++pParse->nMem; regRowid = ++pParse->nMem; assert(pParse->nTab==1); - sqlite3MayAbort(pParse); - sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); - sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); + tdsqlite3MayAbort(pParse); + tdsqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); + tdsqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); pParse->nTab = 2; - addrTop = sqlite3VdbeCurrentAddr(v) + 1; - sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); - sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); - sqlite3Select(pParse, pSelect, &dest); - sqlite3VdbeEndCoroutine(v, regYield); - sqlite3VdbeJumpHere(v, addrTop - 1); + addrTop = tdsqlite3VdbeCurrentAddr(v) + 1; + tdsqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); if( pParse->nErr ) return; - pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); + pSelTab = tdsqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB); if( pSelTab==0 ) return; assert( p->aCol==0 ); - p->nCol = pSelTab->nCol; + p->nCol = p->nNVCol = pSelTab->nCol; p->aCol = pSelTab->aCol; pSelTab->nCol = 0; pSelTab->aCol = 0; - sqlite3DeleteTable(db, pSelTab); - addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); + tdsqlite3DeleteTable(db, pSelTab); + tdsqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); + tdsqlite3Select(pParse, pSelect, &dest); + if( pParse->nErr ) return; + tdsqlite3VdbeEndCoroutine(v, regYield); + tdsqlite3VdbeJumpHere(v, addrTop - 1); + addrInsLoop = tdsqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); - sqlite3TableAffinity(v, p, 0); - sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); - sqlite3VdbeGoto(v, addrInsLoop); - sqlite3VdbeJumpHere(v, addrInsLoop); - sqlite3VdbeAddOp1(v, OP_Close, 1); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); + tdsqlite3TableAffinity(v, p, 0); + tdsqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); + tdsqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); + tdsqlite3VdbeGoto(v, addrInsLoop); + tdsqlite3VdbeJumpHere(v, addrInsLoop); + tdsqlite3VdbeAddOp1(v, OP_Close, 1); } /* Compute the complete text of the CREATE statement */ @@ -103360,7 +115131,7 @@ SQLITE_PRIVATE void sqlite3EndTable( Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; n = (int)(pEnd2->z - pParse->sNameToken.z); if( pEnd2->z[0]!=';' ) n += pEnd2->n; - zStmt = sqlite3MPrintf(db, + zStmt = tdsqlite3MPrintf(db, "CREATE %s %.*s", zType2, n, pParse->sNameToken.z ); } @@ -103369,11 +115140,11 @@ SQLITE_PRIVATE void sqlite3EndTable( ** SQLITE_MASTER table. We just need to update that slot with all ** the information we've collected. */ - sqlite3NestedParse(pParse, + tdsqlite3NestedParse(pParse, "UPDATE %Q.%s " "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " "WHERE rowid=#%d", - db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), + db->aDb[iDb].zDbSName, MASTER_NAME, zType, p->zName, p->zName, @@ -103381,8 +115152,8 @@ SQLITE_PRIVATE void sqlite3EndTable( zStmt, pParse->regRowid ); - sqlite3DbFree(db, zStmt); - sqlite3ChangeCookie(pParse, iDb); + tdsqlite3DbFree(db, zStmt); + tdsqlite3ChangeCookie(pParse, iDb); #ifndef SQLITE_OMIT_AUTOINCREMENT /* Check to see if we need to create an sqlite_sequence table for @@ -103390,9 +115161,9 @@ SQLITE_PRIVATE void sqlite3EndTable( */ if( (p->tabFlags & TF_Autoincrement)!=0 ){ Db *pDb = &db->aDb[iDb]; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); if( pDb->pSchema->pSeqTab==0 ){ - sqlite3NestedParse(pParse, + tdsqlite3NestedParse(pParse, "CREATE TABLE %Q.sqlite_sequence(name,seq)", pDb->zDbSName ); @@ -103401,25 +115172,24 @@ SQLITE_PRIVATE void sqlite3EndTable( #endif /* Reparse everything to update our internal data structures */ - sqlite3VdbeAddParseSchemaOp(v, iDb, - sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName)); + tdsqlite3VdbeAddParseSchemaOp(v, iDb, + tdsqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName)); } - /* Add the table to the in-memory representation of the database. */ if( db->init.busy ){ Table *pOld; Schema *pSchema = p->pSchema; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); + pOld = tdsqlite3HashInsert(&pSchema->tblHash, p->zName, p); if( pOld ){ assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ - sqlite3OomFault(db); + tdsqlite3OomFault(db); return; } pParse->pNewTable = 0; - db->flags |= SQLITE_InternChanges; + db->mDbFlags |= DBFLAG_SchemaChange; #ifndef SQLITE_OMIT_ALTERTABLE if( !p->pSelect ){ @@ -103430,7 +115200,7 @@ SQLITE_PRIVATE void sqlite3EndTable( pCons = pEnd; } nName = (int)((const char *)pCons->z - zName); - p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); + p->addColOffset = 13 + tdsqlite3Utf8CharLen(zName, nName); } #endif } @@ -103440,7 +115210,7 @@ SQLITE_PRIVATE void sqlite3EndTable( /* ** The parser calls this routine in order to create a new VIEW */ -SQLITE_PRIVATE void sqlite3CreateView( +SQLITE_PRIVATE void tdsqlite3CreateView( Parse *pParse, /* The parsing context */ Token *pBegin, /* The CREATE token that begins the statement */ Token *pName1, /* The token that holds the name of the view */ @@ -103457,34 +115227,40 @@ SQLITE_PRIVATE void sqlite3CreateView( DbFixer sFix; Token *pName = 0; int iDb; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; if( pParse->nVar>0 ){ - sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); + tdsqlite3ErrorMsg(pParse, "parameters are not allowed in views"); goto create_view_fail; } - sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); + tdsqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); p = pParse->pNewTable; if( p==0 || pParse->nErr ) goto create_view_fail; - sqlite3TwoPartName(pParse, pName1, pName2, &pName); - iDb = sqlite3SchemaToIndex(db, p->pSchema); - sqlite3FixInit(&sFix, pParse, iDb, "view", pName); - if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; + tdsqlite3TwoPartName(pParse, pName1, pName2, &pName); + iDb = tdsqlite3SchemaToIndex(db, p->pSchema); + tdsqlite3FixInit(&sFix, pParse, iDb, "view", pName); + if( tdsqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; /* Make a copy of the entire SELECT statement that defines the view. ** This will force all the Expr.token.z values to be dynamically ** allocated rather than point to the input string - which means that - ** they will persist after the current sqlite3_exec() call returns. + ** they will persist after the current tdsqlite3_exec() call returns. */ - p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); - p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); + pSelect->selFlags |= SF_View; + if( IN_RENAME_OBJECT ){ + p->pSelect = pSelect; + pSelect = 0; + }else{ + p->pSelect = tdsqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + } + p->pCheck = tdsqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); if( db->mallocFailed ) goto create_view_fail; /* Locate the end of the CREATE VIEW statement. Make sEnd point to ** the end. */ sEnd = pParse->sLastToken; - assert( sEnd.z[0]!=0 ); + assert( sEnd.z[0]!=0 || sEnd.n==0 ); if( sEnd.z[0]!=';' ){ sEnd.z += sEnd.n; } @@ -103492,16 +115268,19 @@ SQLITE_PRIVATE void sqlite3CreateView( n = (int)(sEnd.z - pBegin->z); assert( n>0 ); z = pBegin->z; - while( sqlite3Isspace(z[n-1]) ){ n--; } + while( tdsqlite3Isspace(z[n-1]) ){ n--; } sEnd.z = &z[n-1]; sEnd.n = 1; - /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */ - sqlite3EndTable(pParse, 0, &sEnd, 0, 0); + /* Use tdsqlite3EndTable() to add the view to the SQLITE_MASTER table */ + tdsqlite3EndTable(pParse, 0, &sEnd, 0, 0); create_view_fail: - sqlite3SelectDelete(db, pSelect); - sqlite3ExprListDelete(db, pCNames); + tdsqlite3SelectDelete(db, pSelect); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameExprlistUnmap(pParse, pCNames); + } + tdsqlite3ExprListDelete(db, pCNames); return; } #endif /* SQLITE_OMIT_VIEW */ @@ -103512,21 +115291,27 @@ create_view_fail: ** the columns of the view in the pTable structure. Return the number ** of errors. If an error is seen leave an error message in pParse->zErrMsg. */ -SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ +SQLITE_PRIVATE int tdsqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ Table *pSelTab; /* A fake table from which we get the result set */ Select *pSel; /* Copy of the SELECT that implements the view */ int nErr = 0; /* Number of errors encountered */ int n; /* Temporarily holds the number of cursors assigned */ - sqlite3 *db = pParse->db; /* Database connection for malloc errors */ + tdsqlite3 *db = pParse->db; /* Database connection for malloc errors */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + int rc; +#endif #ifndef SQLITE_OMIT_AUTHORIZATION - sqlite3_xauth xAuth; /* Saved xAuth pointer */ + tdsqlite3_xauth xAuth; /* Saved xAuth pointer */ #endif assert( pTable ); #ifndef SQLITE_OMIT_VIRTUALTABLE - if( sqlite3VtabCallConnect(pParse, pTable) ){ - return SQLITE_ERROR; + db->nSchemaLock++; + rc = tdsqlite3VtabCallConnect(pParse, pTable); + db->nSchemaLock--; + if( rc ){ + return 1; } if( IsVirtual(pTable) ) return 0; #endif @@ -103553,50 +115338,58 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ ** SELECT * FROM temp.ex1; */ if( pTable->nCol<0 ){ - sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); + tdsqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); return 1; } assert( pTable->nCol>=0 ); /* If we get this far, it means we need to compute the table names. - ** Note that the call to sqlite3ResultSetOfSelect() will expand any + ** Note that the call to tdsqlite3ResultSetOfSelect() will expand any ** "*" elements in the results set of the view and will assign cursors ** to the elements of the FROM clause. But we do not want these changes ** to be permanent. So the computation is done on a copy of the SELECT ** statement that defines the view. */ assert( pTable->pSelect ); - pSel = sqlite3SelectDup(db, pTable->pSelect, 0); + pSel = tdsqlite3SelectDup(db, pTable->pSelect, 0); if( pSel ){ +#ifndef SQLITE_OMIT_ALTERTABLE + u8 eParseMode = pParse->eParseMode; + pParse->eParseMode = PARSE_MODE_NORMAL; +#endif n = pParse->nTab; - sqlite3SrcListAssignCursors(pParse, pSel->pSrc); + tdsqlite3SrcListAssignCursors(pParse, pSel->pSrc); pTable->nCol = -1; - db->lookaside.bDisable++; + DisableLookaside; #ifndef SQLITE_OMIT_AUTHORIZATION xAuth = db->xAuth; db->xAuth = 0; - pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); + pSelTab = tdsqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); db->xAuth = xAuth; #else - pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); + pSelTab = tdsqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); #endif pParse->nTab = n; - if( pTable->pCheck ){ + if( pSelTab==0 ){ + pTable->nCol = 0; + nErr++; + }else if( pTable->pCheck ){ /* CREATE VIEW name(arglist) AS ... ** The names of the columns in the table are taken from ** arglist which is stored in pTable->pCheck. The pCheck field ** normally holds CHECK constraints on an ordinary table, but for ** a VIEW it holds the list of column names. */ - sqlite3ColumnsFromExprList(pParse, pTable->pCheck, + tdsqlite3ColumnsFromExprList(pParse, pTable->pCheck, &pTable->nCol, &pTable->aCol); if( db->mallocFailed==0 && pParse->nErr==0 && pTable->nCol==pSel->pEList->nExpr ){ - sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel); + tdsqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel, + SQLITE_AFF_NONE); } - }else if( pSelTab ){ + }else{ /* CREATE VIEW name AS... without an argument list. Construct ** the column names from the SELECT statement that defines the view. */ @@ -103605,18 +115398,24 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ pTable->aCol = pSelTab->aCol; pSelTab->nCol = 0; pSelTab->aCol = 0; - assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); - }else{ - pTable->nCol = 0; - nErr++; + assert( tdsqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); } - sqlite3DeleteTable(db, pSelTab); - sqlite3SelectDelete(db, pSel); - db->lookaside.bDisable--; + pTable->nNVCol = pTable->nCol; + tdsqlite3DeleteTable(db, pSelTab); + tdsqlite3SelectDelete(db, pSel); + EnableLookaside; +#ifndef SQLITE_OMIT_ALTERTABLE + pParse->eParseMode = eParseMode; +#endif } else { nErr++; } pTable->pSchema->schemaFlags |= DB_UnresetViews; + if( db->mallocFailed ){ + tdsqlite3DeleteColumnNames(db, pTable); + pTable->aCol = 0; + pTable->nCol = 0; + } #endif /* SQLITE_OMIT_VIEW */ return nErr; } @@ -103626,14 +115425,14 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ /* ** Clear the column names from every VIEW in database idx. */ -static void sqliteViewResetAll(sqlite3 *db, int idx){ +static void sqliteViewResetAll(tdsqlite3 *db, int idx){ HashElem *i; - assert( sqlite3SchemaMutexHeld(db, idx, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, idx, 0) ); if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ Table *pTab = sqliteHashData(i); if( pTab->pSelect ){ - sqlite3DeleteColumnNames(db, pTab); + tdsqlite3DeleteColumnNames(db, pTab); pTab->aCol = 0; pTab->nCol = 0; } @@ -103662,12 +115461,12 @@ static void sqliteViewResetAll(sqlite3 *db, int idx){ ** in order to be certain that we got the right one. */ #ifndef SQLITE_OMIT_AUTOVACUUM -SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){ +SQLITE_PRIVATE void tdsqlite3RootPageMoved(tdsqlite3 *db, int iDb, int iFrom, int iTo){ HashElem *pElem; Hash *pHash; Db *pDb; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); pDb = &db->aDb[iDb]; pHash = &pDb->pSchema->tblHash; for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ @@ -103693,11 +115492,11 @@ SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iT ** erasing iTable (this can happen with an auto-vacuum database). */ static void destroyRootPage(Parse *pParse, int iTable, int iDb){ - Vdbe *v = sqlite3GetVdbe(pParse); - int r1 = sqlite3GetTempReg(pParse); - assert( iTable>1 ); - sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); - sqlite3MayAbort(pParse); + Vdbe *v = tdsqlite3GetVdbe(pParse); + int r1 = tdsqlite3GetTempReg(pParse); + if( iTable<2 ) tdsqlite3ErrorMsg(pParse, "corrupt schema"); + tdsqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); + tdsqlite3MayAbort(pParse); #ifndef SQLITE_OMIT_AUTOVACUUM /* OP_Destroy stores an in integer r1. If this integer ** is non-zero, then it is the root page number of a table moved to @@ -103708,11 +115507,11 @@ static void destroyRootPage(Parse *pParse, int iTable, int iDb){ ** is in register NNN. See grammar rules associated with the TK_REGISTER ** token for additional information. */ - sqlite3NestedParse(pParse, + tdsqlite3NestedParse(pParse, "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", - pParse->db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), iTable, r1, r1); + pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1); #endif - sqlite3ReleaseTempReg(pParse, r1); + tdsqlite3ReleaseTempReg(pParse, r1); } /* @@ -103722,14 +115521,6 @@ static void destroyRootPage(Parse *pParse, int iTable, int iDb){ ** is also added (this can happen with an auto-vacuum database). */ static void destroyTable(Parse *pParse, Table *pTab){ -#ifdef SQLITE_OMIT_AUTOVACUUM - Index *pIdx; - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - destroyRootPage(pParse, pTab->tnum, iDb); - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - destroyRootPage(pParse, pIdx->tnum, iDb); - } -#else /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM ** is not defined), then it is important to call OP_Destroy on the ** table and index root-pages in order, starting with the numerically @@ -103766,20 +115557,19 @@ static void destroyTable(Parse *pParse, Table *pTab){ if( iLargest==0 ){ return; }else{ - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + int iDb = tdsqlite3SchemaToIndex(pParse->db, pTab->pSchema); assert( iDb>=0 && iDb<pParse->db->nDb ); destroyRootPage(pParse, iLargest, iDb); iDestroyed = iLargest; } } -#endif } /* ** Remove entries from the sqlite_statN tables (for N in (1,2,3)) ** after a DROP INDEX or DROP TABLE command. */ -static void sqlite3ClearStatTables( +static void tdsqlite3ClearStatTables( Parse *pParse, /* The parsing context */ int iDb, /* The database number */ const char *zType, /* "idx" or "tbl" */ @@ -103789,9 +115579,9 @@ static void sqlite3ClearStatTables( const char *zDbName = pParse->db->aDb[iDb].zDbSName; for(i=1; i<=4; i++){ char zTab[24]; - sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); - if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ - sqlite3NestedParse(pParse, + tdsqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); + if( tdsqlite3FindTable(pParse->db, zTab, zDbName) ){ + tdsqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE %s=%Q", zDbName, zTab, zType, zName ); @@ -103802,19 +115592,19 @@ static void sqlite3ClearStatTables( /* ** Generate code to drop a table. */ -SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ +SQLITE_PRIVATE void tdsqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ Vdbe *v; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Trigger *pTrigger; Db *pDb = &db->aDb[iDb]; - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); assert( v!=0 ); - sqlite3BeginWriteOperation(pParse, 1, iDb); + tdsqlite3BeginWriteOperation(pParse, 1, iDb); #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ - sqlite3VdbeAddOp0(v, OP_VBegin); + tdsqlite3VdbeAddOp0(v, OP_VBegin); } #endif @@ -103822,11 +115612,11 @@ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, in ** is generated to remove entries from sqlite_master and/or ** sqlite_temp_master if required. */ - pTrigger = sqlite3TriggerList(pParse, pTab); + pTrigger = tdsqlite3TriggerList(pParse, pTab); while( pTrigger ){ assert( pTrigger->pSchema==pTab->pSchema || pTrigger->pSchema==db->aDb[1].pSchema ); - sqlite3DropTriggerPtr(pParse, pTrigger); + tdsqlite3DropTriggerPtr(pParse, pTrigger); pTrigger = pTrigger->pNext; } @@ -103837,7 +115627,7 @@ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, in ** move as a result of the drop (can happen in auto-vacuum mode). */ if( pTab->tabFlags & TF_Autoincrement ){ - sqlite3NestedParse(pParse, + tdsqlite3NestedParse(pParse, "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", pDb->zDbSName, pTab->zName ); @@ -103851,9 +115641,9 @@ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, in ** created in the temp database that refers to a table in another ** database. */ - sqlite3NestedParse(pParse, + tdsqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", - pDb->zDbSName, SCHEMA_TABLE(iDb), pTab->zName); + pDb->zDbSName, MASTER_NAME, pTab->zName); if( !isView && !IsVirtual(pTab) ){ destroyTable(pParse, pTab); } @@ -103862,21 +115652,53 @@ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, in ** the schema cookie. */ if( IsVirtual(pTab) ){ - sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); + tdsqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); + tdsqlite3MayAbort(pParse); } - sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); - sqlite3ChangeCookie(pParse, iDb); + tdsqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); + tdsqlite3ChangeCookie(pParse, iDb); sqliteViewResetAll(db, iDb); } /* +** Return TRUE if shadow tables should be read-only in the current +** context. +*/ +SQLITE_PRIVATE int tdsqlite3ReadOnlyShadowTables(tdsqlite3 *db){ +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( (db->flags & SQLITE_Defensive)!=0 + && db->pVtabCtx==0 + && db->nVdbeExec==0 + ){ + return 1; + } +#endif + return 0; +} + +/* +** Return true if it is not allowed to drop the given table +*/ +static int tableMayNotBeDropped(tdsqlite3 *db, Table *pTab){ + if( tdsqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ + if( tdsqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0; + if( tdsqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0; + return 1; + } + if( (pTab->tabFlags & TF_Shadow)!=0 && tdsqlite3ReadOnlyShadowTables(db) ){ + return 1; + } + return 0; +} + +/* ** This routine is called to do the work of a DROP TABLE statement. ** pName is the name of the table to be dropped. */ -SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ +SQLITE_PRIVATE void tdsqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ Table *pTab; Vdbe *v; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; int iDb; if( db->mallocFailed ){ @@ -103884,23 +115706,23 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, } assert( pParse->nErr==0 ); assert( pName->nSrc==1 ); - if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; + if( tdsqlite3ReadSchema(pParse) ) goto exit_drop_table; if( noErr ) db->suppressErr++; assert( isView==0 || isView==LOCATE_VIEW ); - pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); + pTab = tdsqlite3LocateTableItem(pParse, isView, &pName->a[0]); if( noErr ) db->suppressErr--; if( pTab==0 ){ - if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); + if( noErr ) tdsqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); goto exit_drop_table; } - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb>=0 && iDb<db->nDb ); /* If pTab is a virtual table, call ViewGetColumnNames() to ensure ** it is initialized. */ - if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ + if( IsVirtual(pTab) && tdsqlite3ViewGetColumnNames(pParse, pTab) ){ goto exit_drop_table; } #ifndef SQLITE_OMIT_AUTHORIZATION @@ -103909,7 +115731,7 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, const char *zTab = SCHEMA_TABLE(iDb); const char *zDb = db->aDb[iDb].zDbSName; const char *zArg2 = 0; - if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ + if( tdsqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ goto exit_drop_table; } if( isView ){ @@ -103921,7 +115743,7 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, #ifndef SQLITE_OMIT_VIRTUALTABLE }else if( IsVirtual(pTab) ){ code = SQLITE_DROP_VTABLE; - zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; + zArg2 = tdsqlite3GetVTable(db, pTab)->pMod->zName; #endif }else{ if( !OMIT_TEMPDB && iDb==1 ){ @@ -103930,17 +115752,16 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, code = SQLITE_DROP_TABLE; } } - if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ + if( tdsqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ goto exit_drop_table; } - if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ + if( tdsqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ goto exit_drop_table; } } #endif - if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 - && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ - sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); + if( tableMayNotBeDropped(db, pTab) ){ + tdsqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); goto exit_drop_table; } @@ -103949,11 +115770,11 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, ** on a table. */ if( isView && pTab->pSelect==0 ){ - sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); + tdsqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); goto exit_drop_table; } if( !isView && pTab->pSelect ){ - sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); + tdsqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); goto exit_drop_table; } #endif @@ -103961,16 +115782,18 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, /* Generate code to remove the table from the master table ** on disk. */ - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( v ){ - sqlite3BeginWriteOperation(pParse, 1, iDb); - sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); - sqlite3FkDropTable(pParse, pName, pTab); - sqlite3CodeDropTable(pParse, pTab, iDb, isView); + tdsqlite3BeginWriteOperation(pParse, 1, iDb); + if( !isView ){ + tdsqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); + tdsqlite3FkDropTable(pParse, pName, pTab); + } + tdsqlite3CodeDropTable(pParse, pTab, iDb, isView); } exit_drop_table: - sqlite3SrcListDelete(db, pName); + tdsqlite3SrcListDelete(db, pName); } /* @@ -103987,16 +115810,16 @@ exit_drop_table: ** under construction in the pParse->pNewTable field. ** ** The foreign key is set for IMMEDIATE processing. A subsequent call -** to sqlite3DeferForeignKey() might change this to DEFERRED. +** to tdsqlite3DeferForeignKey() might change this to DEFERRED. */ -SQLITE_PRIVATE void sqlite3CreateForeignKey( +SQLITE_PRIVATE void tdsqlite3CreateForeignKey( Parse *pParse, /* Parsing context */ ExprList *pFromCol, /* Columns in this table that point to other table */ Token *pTo, /* Name of the other table */ ExprList *pToCol, /* Columns in the other table */ int flags /* Conflict resolution algorithms. */ ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; #ifndef SQLITE_OMIT_FOREIGN_KEY FKey *pFKey = 0; FKey *pNextTo; @@ -104012,14 +115835,14 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey( int iCol = p->nCol-1; if( NEVER(iCol<0) ) goto fk_end; if( pToCol && pToCol->nExpr!=1 ){ - sqlite3ErrorMsg(pParse, "foreign key on %s" + tdsqlite3ErrorMsg(pParse, "foreign key on %s" " should reference only one column of table %T", p->aCol[iCol].zName, pTo); goto fk_end; } nCol = 1; }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "number of columns in foreign key does not match the number of " "columns in the referenced table"); goto fk_end; @@ -104029,10 +115852,10 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey( nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; if( pToCol ){ for(i=0; i<pToCol->nExpr; i++){ - nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1; + nByte += tdsqlite3Strlen30(pToCol->a[i].zEName) + 1; } } - pFKey = sqlite3DbMallocZero(db, nByte ); + pFKey = tdsqlite3DbMallocZero(db, nByte ); if( pFKey==0 ){ goto fk_end; } @@ -104040,9 +115863,12 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey( pFKey->pNextFrom = p->pFKey; z = (char*)&pFKey->aCol[nCol]; pFKey->zTo = z; + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenMap(pParse, (void*)z, pTo); + } memcpy(z, pTo->z, pTo->n); z[pTo->n] = 0; - sqlite3Dequote(z); + tdsqlite3Dequote(z); z += pTo->n+1; pFKey->nCol = nCol; if( pFromCol==0 ){ @@ -104051,24 +115877,30 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey( for(i=0; i<nCol; i++){ int j; for(j=0; j<p->nCol; j++){ - if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ + if( tdsqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){ pFKey->aCol[i].iFrom = j; break; } } if( j>=p->nCol ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "unknown column \"%s\" in foreign key definition", - pFromCol->a[i].zName); + pFromCol->a[i].zEName); goto fk_end; } + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName); + } } } if( pToCol ){ for(i=0; i<nCol; i++){ - int n = sqlite3Strlen30(pToCol->a[i].zName); + int n = tdsqlite3Strlen30(pToCol->a[i].zEName); pFKey->aCol[i].zCol = z; - memcpy(z, pToCol->a[i].zName, n); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName); + } + memcpy(z, pToCol->a[i].zEName, n); z[n] = 0; z += n+1; } @@ -104077,12 +115909,12 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey( pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ - assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); - pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, + assert( tdsqlite3SchemaMutexHeld(db, 0, p->pSchema) ); + pNextTo = (FKey *)tdsqlite3HashInsert(&p->pSchema->fkeyHash, pFKey->zTo, (void *)pFKey ); if( pNextTo==pFKey ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); goto fk_end; } if( pNextTo ){ @@ -104097,10 +115929,10 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey( pFKey = 0; fk_end: - sqlite3DbFree(db, pFKey); + tdsqlite3DbFree(db, pFKey); #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ - sqlite3ExprListDelete(db, pFromCol); - sqlite3ExprListDelete(db, pToCol); + tdsqlite3ExprListDelete(db, pFromCol); + tdsqlite3ExprListDelete(db, pToCol); } /* @@ -104110,7 +115942,7 @@ fk_end: ** The behavior of the most recently created foreign key is adjusted ** accordingly. */ -SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ +SQLITE_PRIVATE void tdsqlite3DeferForeignKey(Parse *pParse, int isDeferred){ #ifndef SQLITE_OMIT_FOREIGN_KEY Table *pTab; FKey *pFKey; @@ -104131,7 +115963,7 @@ SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ ** the index already exists and must be cleared before being refilled and ** the root page number of the index is taken from pIndex->tnum. */ -static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ +static void tdsqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ Table *pTab = pIndex->pTable; /* The table that is indexed */ int iTab = pParse->nTab++; /* Btree cursor used for pTab */ int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ @@ -104143,72 +115975,91 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ Vdbe *v; /* Generate code into this virtual machine */ KeyInfo *pKey; /* KeyInfo for index */ int regRecord; /* Register holding assembled index record */ - sqlite3 *db = pParse->db; /* The database connection */ - int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); + tdsqlite3 *db = pParse->db; /* The database connection */ + int iDb = tdsqlite3SchemaToIndex(db, pIndex->pSchema); #ifndef SQLITE_OMIT_AUTHORIZATION - if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, + if( tdsqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, db->aDb[iDb].zDbSName ) ){ return; } #endif /* Require a write-lock on the table to perform this operation */ - sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); + tdsqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( v==0 ) return; if( memRootPage>=0 ){ tnum = memRootPage; }else{ tnum = pIndex->tnum; } - pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); + pKey = tdsqlite3KeyInfoOfIndex(pParse, pIndex); assert( pKey!=0 || db->mallocFailed || pParse->nErr ); /* Open the sorter cursor if we are to use one. */ iSorter = pParse->nTab++; - sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) - sqlite3KeyInfoRef(pKey), P4_KEYINFO); + tdsqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) + tdsqlite3KeyInfoRef(pKey), P4_KEYINFO); /* Open the table. Loop through all rows of the table, inserting index ** records into the sorter. */ - sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); - addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); - regRecord = sqlite3GetTempReg(pParse); - - sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); - sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); - sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); - sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr1); - if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); - sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, + tdsqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); + addr1 = tdsqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); + regRecord = tdsqlite3GetTempReg(pParse); + tdsqlite3MultiWrite(pParse); + + tdsqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); + tdsqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); + tdsqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); + tdsqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addr1); + if( memRootPage<0 ) tdsqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); + tdsqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, (char *)pKey, P4_KEYINFO); - sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); + tdsqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); - addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); + addr1 = tdsqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); if( IsUniqueIndex(pIndex) ){ - int j2 = sqlite3VdbeCurrentAddr(v) + 3; - sqlite3VdbeGoto(v, j2); - addr2 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, + int j2 = tdsqlite3VdbeGoto(v, 1); + addr2 = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeVerifyAbortable(v, OE_Abort); + tdsqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, pIndex->nKeyCol); VdbeCoverage(v); - sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); - }else{ - addr2 = sqlite3VdbeCurrentAddr(v); + tdsqlite3UniqueConstraint(pParse, OE_Abort, pIndex); + tdsqlite3VdbeJumpHere(v, j2); + }else{ + /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not + ** abort. The exception is if one of the indexed expressions contains a + ** user function that throws an exception when it is evaluated. But the + ** overhead of adding a statement journal to a CREATE INDEX statement is + ** very small (since most of the pages written do not contain content that + ** needs to be restored if the statement aborts), so we call + ** tdsqlite3MayAbort() for all CREATE INDEX statements. */ + tdsqlite3MayAbort(pParse); + addr2 = tdsqlite3VdbeCurrentAddr(v); + } + tdsqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); + if( !pIndex->bAscKeyBug ){ + /* This OP_SeekEnd opcode makes index insert for a REINDEX go much + ** faster by avoiding unnecessary seeks. But the optimization does + ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables + ** with DESC primary keys, since those indexes have there keys in + ** a different order from the main table. + ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf + */ + tdsqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx); } - sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); - sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1); - sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0); - sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); - sqlite3ReleaseTempReg(pParse, regRecord); - sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr1); + tdsqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); + tdsqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + tdsqlite3ReleaseTempReg(pParse, regRecord); + tdsqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp1(v, OP_Close, iTab); - sqlite3VdbeAddOp1(v, OP_Close, iIdx); - sqlite3VdbeAddOp1(v, OP_Close, iSorter); + tdsqlite3VdbeAddOp1(v, OP_Close, iTab); + tdsqlite3VdbeAddOp1(v, OP_Close, iIdx); + tdsqlite3VdbeAddOp1(v, OP_Close, iSorter); } /* @@ -104218,8 +116069,8 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ ** of 8-byte aligned space after the Index object and return a ** pointer to this extra space in *ppExtra. */ -SQLITE_PRIVATE Index *sqlite3AllocateIndexObject( - sqlite3 *db, /* Database connection */ +SQLITE_PRIVATE Index *tdsqlite3AllocateIndexObject( + tdsqlite3 *db, /* Database connection */ i16 nCol, /* Total number of columns in the index */ int nExtra, /* Number of bytes of extra space to alloc */ char **ppExtra /* Pointer to the "extra" space */ @@ -104232,7 +116083,7 @@ SQLITE_PRIVATE Index *sqlite3AllocateIndexObject( ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ sizeof(i16)*nCol + /* Index.aiColumn */ sizeof(u8)*nCol); /* Index.aSortOrder */ - p = sqlite3DbMallocZero(db, nByte + nExtra); + p = tdsqlite3DbMallocZero(db, nByte + nExtra); if( p ){ char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); @@ -104247,6 +116098,27 @@ SQLITE_PRIVATE Index *sqlite3AllocateIndexObject( } /* +** If expression list pList contains an expression that was parsed with +** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in +** pParse and return non-zero. Otherwise, return zero. +*/ +SQLITE_PRIVATE int tdsqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){ + if( pList ){ + int i; + for(i=0; i<pList->nExpr; i++){ + if( pList->a[i].bNulls ){ + u8 sf = pList->a[i].sortFlags; + tdsqlite3ErrorMsg(pParse, "unsupported use of NULLS %s", + (sf==0 || sf==3) ? "FIRST" : "LAST" + ); + return 1; + } + } + } + return 0; +} + +/* ** Create a new index for an SQL table. pName1.pName2 is the name of the index ** and pTblList is the name of the table that is to be indexed. Both will ** be NULL for a primary key or an index that is created to satisfy a @@ -104258,7 +116130,7 @@ SQLITE_PRIVATE Index *sqlite3AllocateIndexObject( ** is a primary key or unique-constraint on the most recent column added ** to the table currently under construction. */ -SQLITE_PRIVATE void sqlite3CreateIndex( +SQLITE_PRIVATE void tdsqlite3CreateIndex( Parse *pParse, /* All information about this parse */ Token *pName1, /* First part of index name. May be NULL */ Token *pName2, /* Second part of index name. May be NULL */ @@ -104278,7 +116150,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex( int i, j; DbFixer sFix; /* For assigning database names to pTable */ int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Db *pDb; /* The specific table containing the indexed database */ int iDb; /* Index of the database that is being written */ Token *pName = 0; /* Unqualified name of the index to create */ @@ -104294,7 +116166,10 @@ SQLITE_PRIVATE void sqlite3CreateIndex( if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){ goto exit_create_index; } - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + if( SQLITE_OK!=tdsqlite3ReadSchema(pParse) ){ + goto exit_create_index; + } + if( tdsqlite3HasExplicitNulls(pParse, pList) ){ goto exit_create_index; } @@ -104308,7 +116183,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex( ** before looking up the table. */ assert( pName1 && pName2 ); - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); + iDb = tdsqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ) goto exit_create_index; assert( pName && pName->z ); @@ -104318,58 +116193,62 @@ SQLITE_PRIVATE void sqlite3CreateIndex( ** if initialising a database schema. */ if( !db->init.busy ){ - pTab = sqlite3SrcListLookup(pParse, pTblName); + pTab = tdsqlite3SrcListLookup(pParse, pTblName); if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ iDb = 1; } } #endif - sqlite3FixInit(&sFix, pParse, iDb, "index", pName); - if( sqlite3FixSrcList(&sFix, pTblName) ){ + tdsqlite3FixInit(&sFix, pParse, iDb, "index", pName); + if( tdsqlite3FixSrcList(&sFix, pTblName) ){ /* Because the parser constructs pTblName from a single identifier, - ** sqlite3FixSrcList can never fail. */ + ** tdsqlite3FixSrcList can never fail. */ assert(0); } - pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); + pTab = tdsqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); assert( db->mallocFailed==0 || pTab==0 ); if( pTab==0 ) goto exit_create_index; if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "cannot create a TEMP index on non-TEMP table \"%s\"", pTab->zName); goto exit_create_index; } - if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); + if( !HasRowid(pTab) ) pPk = tdsqlite3PrimaryKeyIndex(pTab); }else{ assert( pName==0 ); assert( pStart==0 ); pTab = pParse->pNewTable; if( !pTab ) goto exit_create_index; - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); } pDb = &db->aDb[iDb]; assert( pTab!=0 ); assert( pParse->nErr==0 ); - if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 + if( tdsqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 && db->init.busy==0 + && pTblName!=0 #if SQLITE_USER_AUTHENTICATION - && sqlite3UserAuthTable(pTab->zName)==0 + && tdsqlite3UserAuthTable(pTab->zName)==0 +#endif +#ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX + && tdsqlite3StrICmp(&pTab->zName[7],"master")!=0 #endif - && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ - sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); + ){ + tdsqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); goto exit_create_index; } #ifndef SQLITE_OMIT_VIEW if( pTab->pSelect ){ - sqlite3ErrorMsg(pParse, "views may not be indexed"); + tdsqlite3ErrorMsg(pParse, "views may not be indexed"); goto exit_create_index; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ - sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); + tdsqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); goto exit_create_index; } #endif @@ -104388,55 +116267,57 @@ SQLITE_PRIVATE void sqlite3CreateIndex( ** own name. */ if( pName ){ - zName = sqlite3NameFromToken(db, pName); + zName = tdsqlite3NameFromToken(db, pName); if( zName==0 ) goto exit_create_index; assert( pName->z!=0 ); - if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ + if( SQLITE_OK!=tdsqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){ goto exit_create_index; } - if( !db->init.busy ){ - if( sqlite3FindTable(db, zName, 0)!=0 ){ - sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); - goto exit_create_index; + if( !IN_RENAME_OBJECT ){ + if( !db->init.busy ){ + if( tdsqlite3FindTable(db, zName, 0)!=0 ){ + tdsqlite3ErrorMsg(pParse, "there is already a table named %s", zName); + goto exit_create_index; + } } - } - if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ - if( !ifNotExist ){ - sqlite3ErrorMsg(pParse, "index %s already exists", zName); - }else{ - assert( !db->init.busy ); - sqlite3CodeVerifySchema(pParse, iDb); + if( tdsqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ + if( !ifNotExist ){ + tdsqlite3ErrorMsg(pParse, "index %s already exists", zName); + }else{ + assert( !db->init.busy ); + tdsqlite3CodeVerifySchema(pParse, iDb); + } + goto exit_create_index; } - goto exit_create_index; } }else{ int n; Index *pLoop; for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} - zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); + zName = tdsqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); if( zName==0 ){ goto exit_create_index; } - /* Automatic index names generated from within sqlite3_declare_vtab() + /* Automatic index names generated from within tdsqlite3_declare_vtab() ** must have names that are distinct from normal automatic index names. - ** The following statement converts "sqlite3_autoindex..." into - ** "sqlite3_butoindex..." in order to make the names distinct. + ** The following statement converts "tdsqlite3_autoindex..." into + ** "tdsqlite3_butoindex..." in order to make the names distinct. ** The "vtab_err.test" test demonstrates the need of this statement. */ - if( IN_DECLARE_VTAB ) zName[7]++; + if( IN_SPECIAL_PARSE ) zName[7]++; } /* Check for authorization to create an index. */ #ifndef SQLITE_OMIT_AUTHORIZATION - { + if( !IN_RENAME_OBJECT ){ const char *zDb = pDb->zDbSName; - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ + if( tdsqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ goto exit_create_index; } i = SQLITE_CREATE_INDEX; if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; - if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ + if( tdsqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ goto exit_create_index; } } @@ -104448,14 +116329,17 @@ SQLITE_PRIVATE void sqlite3CreateIndex( */ if( pList==0 ){ Token prevCol; - sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName); - pList = sqlite3ExprListAppend(pParse, 0, - sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); + Column *pCol = &pTab->aCol[pTab->nCol-1]; + pCol->colFlags |= COLFLAG_UNIQUE; + tdsqlite3TokenInit(&prevCol, pCol->zName); + pList = tdsqlite3ExprListAppend(pParse, 0, + tdsqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); if( pList==0 ) goto exit_create_index; assert( pList->nExpr==1 ); - sqlite3ExprListSetSortOrder(pList, sortOrder); + tdsqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED); }else{ - sqlite3ExprListCheckLength(pParse, pList, "index"); + tdsqlite3ExprListCheckLength(pParse, pList, "index"); + if( pParse->nErr ) goto exit_create_index; } /* Figure out how many bytes of space are required to store explicitly @@ -104465,16 +116349,17 @@ SQLITE_PRIVATE void sqlite3CreateIndex( Expr *pExpr = pList->a[i].pExpr; assert( pExpr!=0 ); if( pExpr->op==TK_COLLATE ){ - nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); + nExtra += (1 + tdsqlite3Strlen30(pExpr->u.zToken)); } } /* ** Allocate the index structure. */ - nName = sqlite3Strlen30(zName); + nName = tdsqlite3Strlen30(zName); nExtraCol = pPk ? pPk->nKeyCol : 1; - pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, + assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ ); + pIndex = tdsqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, nName + nExtra + 1, &zExtra); if( db->mallocFailed ){ goto exit_create_index; @@ -104491,11 +116376,11 @@ SQLITE_PRIVATE void sqlite3CreateIndex( pIndex->pSchema = db->aDb[iDb].pSchema; pIndex->nKeyCol = pList->nExpr; if( pPIWhere ){ - sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); + tdsqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); pIndex->pPartIdxWhere = pPIWhere; pPIWhere = 0; } - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); /* Check to see if we should honor DESC requests on index columns */ @@ -104514,28 +116399,29 @@ SQLITE_PRIVATE void sqlite3CreateIndex( ** TODO: Issue a warning if the table primary key is used as part of the ** index key. */ - for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){ + pListItem = pList->a; + if( IN_RENAME_OBJECT ){ + pIndex->aColExpr = pList; + pList = 0; + } + for(i=0; i<pIndex->nKeyCol; i++, pListItem++){ Expr *pCExpr; /* The i-th index expression */ int requestedSortOrder; /* ASC or DESC on the i-th expression */ const char *zColl; /* Collation sequence name */ - sqlite3StringToId(pListItem->pExpr); - sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); + tdsqlite3StringToId(pListItem->pExpr); + tdsqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); if( pParse->nErr ) goto exit_create_index; - pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); + pCExpr = tdsqlite3ExprSkipCollate(pListItem->pExpr); if( pCExpr->op!=TK_COLUMN ){ if( pTab==pParse->pNewTable ){ - sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " + tdsqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " "UNIQUE constraints"); goto exit_create_index; } if( pIndex->aColExpr==0 ){ - ExprList *pCopy = sqlite3ExprListDup(db, pList, 0); - pIndex->aColExpr = pCopy; - if( !db->mallocFailed ){ - assert( pCopy!=0 ); - pListItem = &pCopy->a[i]; - } + pIndex->aColExpr = pList; + pList = 0; } j = XN_EXPR; pIndex->aiColumn[i] = XN_EXPR; @@ -104545,8 +116431,13 @@ SQLITE_PRIVATE void sqlite3CreateIndex( assert( j<=0x7fff ); if( j<0 ){ j = pTab->iPKey; - }else if( pTab->aCol[j].notNull==0 ){ - pIndex->uniqNotNull = 0; + }else{ + if( pTab->aCol[j].notNull==0 ){ + pIndex->uniqNotNull = 0; + } + if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){ + pIndex->bHasVCol = 1; + } } pIndex->aiColumn[i] = (i16)j; } @@ -104554,7 +116445,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex( if( pListItem->pExpr->op==TK_COLLATE ){ int nColl; zColl = pListItem->pExpr->u.zToken; - nColl = sqlite3Strlen30(zColl) + 1; + nColl = tdsqlite3Strlen30(zColl) + 1; assert( nExtra>=nColl ); memcpy(zExtra, zColl, nColl); zColl = zExtra; @@ -104563,12 +116454,12 @@ SQLITE_PRIVATE void sqlite3CreateIndex( }else if( j>=0 ){ zColl = pTab->aCol[j].zColl; } - if( !zColl ) zColl = sqlite3StrBINARY; - if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ + if( !zColl ) zColl = tdsqlite3StrBINARY; + if( !db->init.busy && !tdsqlite3LocateCollSeq(pParse, zColl) ){ goto exit_create_index; } pIndex->azColl[i] = zColl; - requestedSortOrder = pListItem->sortOrder & sortOrderMask; + requestedSortOrder = pListItem->sortFlags & sortOrderMask; pIndex->aSortOrder[i] = (u8)requestedSortOrder; } @@ -104580,9 +116471,10 @@ SQLITE_PRIVATE void sqlite3CreateIndex( for(j=0; j<pPk->nKeyCol; j++){ int x = pPk->aiColumn[j]; assert( x>=0 ); - if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){ + if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){ pIndex->nColumn--; }else{ + testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) ); pIndex->aiColumn[i] = x; pIndex->azColl[i] = pPk->azColl[j]; pIndex->aSortOrder[i] = pPk->aSortOrder[j]; @@ -104592,20 +116484,21 @@ SQLITE_PRIVATE void sqlite3CreateIndex( assert( i==pIndex->nColumn ); }else{ pIndex->aiColumn[i] = XN_ROWID; - pIndex->azColl[i] = sqlite3StrBINARY; + pIndex->azColl[i] = tdsqlite3StrBINARY; } - sqlite3DefaultRowEst(pIndex); + tdsqlite3DefaultRowEst(pIndex); if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); /* If this index contains every column of its table, then mark ** it as a covering index */ assert( HasRowid(pTab) - || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 ); + || pTab->iPKey<0 || tdsqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 ); + recomputeColumnsNotIndexed(pIndex); if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){ pIndex->isCovering = 1; for(j=0; j<pTab->nCol; j++){ if( j==pTab->iPKey ) continue; - if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue; + if( tdsqlite3TableColumnToIndex(pIndex,j)>=0 ) continue; pIndex->isCovering = 0; break; } @@ -104648,7 +116541,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex( if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; z1 = pIdx->azColl[k]; z2 = pIndex->azColl[k]; - if( sqlite3StrICmp(z1, z2) ) break; + if( tdsqlite3StrICmp(z1, z2) ) break; } if( k==pIdx->nKeyCol ){ if( pIdx->onError!=pIndex->onError ){ @@ -104660,7 +116553,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex( ** explicitly specified behavior for the index. */ if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "conflicting ON CONFLICT clauses specified", 0); } if( pIdx->onError==OE_Default ){ @@ -104668,134 +116561,151 @@ SQLITE_PRIVATE void sqlite3CreateIndex( } } if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType; + if( IN_RENAME_OBJECT ){ + pIndex->pNext = pParse->pNewIndex; + pParse->pNewIndex = pIndex; + pIndex = 0; + } goto exit_create_index; } } } - /* Link the new Index structure to its table and to the other - ** in-memory database structures. - */ - assert( pParse->nErr==0 ); - if( db->init.busy ){ - Index *p; - assert( !IN_DECLARE_VTAB ); - assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); - p = sqlite3HashInsert(&pIndex->pSchema->idxHash, - pIndex->zName, pIndex); - if( p ){ - assert( p==pIndex ); /* Malloc must have failed */ - sqlite3OomFault(db); - goto exit_create_index; - } - db->flags |= SQLITE_InternChanges; - if( pTblName!=0 ){ - pIndex->tnum = db->init.newTnum; - } - } - - /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the - ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then - ** emit code to allocate the index rootpage on disk and make an entry for - ** the index in the sqlite_master table and populate the index with - ** content. But, do not do this if we are simply reading the sqlite_master - ** table to parse the schema, or if this index is the PRIMARY KEY index - ** of a WITHOUT ROWID table. - ** - ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY - ** or UNIQUE index in a CREATE TABLE statement. Since the table - ** has just been created, it contains no data and the index initialization - ** step can be skipped. - */ - else if( HasRowid(pTab) || pTblName!=0 ){ - Vdbe *v; - char *zStmt; - int iMem = ++pParse->nMem; - - v = sqlite3GetVdbe(pParse); - if( v==0 ) goto exit_create_index; + if( !IN_RENAME_OBJECT ){ - sqlite3BeginWriteOperation(pParse, 1, iDb); - - /* Create the rootpage for the index using CreateIndex. But before - ** doing so, code a Noop instruction and store its address in - ** Index.tnum. This is required in case this index is actually a - ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In - ** that case the convertToWithoutRowidTable() routine will replace - ** the Noop with a Goto to jump over the VDBE code generated below. */ - pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop); - sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); - - /* Gather the complete text of the CREATE INDEX statement into - ** the zStmt variable + /* Link the new Index structure to its table and to the other + ** in-memory database structures. */ - if( pStart ){ - int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; - if( pName->z[n-1]==';' ) n--; - /* A named index with an explicit CREATE INDEX statement */ - zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", - onError==OE_None ? "" : " UNIQUE", n, pName->z); - }else{ - /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ - /* zStmt = sqlite3MPrintf(""); */ - zStmt = 0; + assert( pParse->nErr==0 ); + if( db->init.busy ){ + Index *p; + assert( !IN_SPECIAL_PARSE ); + assert( tdsqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); + if( pTblName!=0 ){ + pIndex->tnum = db->init.newTnum; + if( tdsqlite3IndexHasDuplicateRootPage(pIndex) ){ + tdsqlite3ErrorMsg(pParse, "invalid rootpage"); + pParse->rc = SQLITE_CORRUPT_BKPT; + goto exit_create_index; + } + } + p = tdsqlite3HashInsert(&pIndex->pSchema->idxHash, + pIndex->zName, pIndex); + if( p ){ + assert( p==pIndex ); /* Malloc must have failed */ + tdsqlite3OomFault(db); + goto exit_create_index; + } + db->mDbFlags |= DBFLAG_SchemaChange; } - /* Add an entry in sqlite_master for this index - */ - sqlite3NestedParse(pParse, - "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", - db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), - pIndex->zName, - pTab->zName, - iMem, - zStmt - ); - sqlite3DbFree(db, zStmt); - - /* Fill the index with data and reparse the schema. Code an OP_Expire - ** to invalidate all pre-compiled statements. + /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the + ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then + ** emit code to allocate the index rootpage on disk and make an entry for + ** the index in the sqlite_master table and populate the index with + ** content. But, do not do this if we are simply reading the sqlite_master + ** table to parse the schema, or if this index is the PRIMARY KEY index + ** of a WITHOUT ROWID table. + ** + ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY + ** or UNIQUE index in a CREATE TABLE statement. Since the table + ** has just been created, it contains no data and the index initialization + ** step can be skipped. */ - if( pTblName ){ - sqlite3RefillIndex(pParse, pIndex, iMem); - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddParseSchemaOp(v, iDb, - sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); - sqlite3VdbeAddOp0(v, OP_Expire); - } + else if( HasRowid(pTab) || pTblName!=0 ){ + Vdbe *v; + char *zStmt; + int iMem = ++pParse->nMem; + + v = tdsqlite3GetVdbe(pParse); + if( v==0 ) goto exit_create_index; + + tdsqlite3BeginWriteOperation(pParse, 1, iDb); + + /* Create the rootpage for the index using CreateIndex. But before + ** doing so, code a Noop instruction and store its address in + ** Index.tnum. This is required in case this index is actually a + ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In + ** that case the convertToWithoutRowidTable() routine will replace + ** the Noop with a Goto to jump over the VDBE code generated below. */ + pIndex->tnum = tdsqlite3VdbeAddOp0(v, OP_Noop); + tdsqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY); + + /* Gather the complete text of the CREATE INDEX statement into + ** the zStmt variable + */ + assert( pName!=0 || pStart==0 ); + if( pStart ){ + int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; + if( pName->z[n-1]==';' ) n--; + /* A named index with an explicit CREATE INDEX statement */ + zStmt = tdsqlite3MPrintf(db, "CREATE%s INDEX %.*s", + onError==OE_None ? "" : " UNIQUE", n, pName->z); + }else{ + /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ + /* zStmt = tdsqlite3MPrintf(""); */ + zStmt = 0; + } - sqlite3VdbeJumpHere(v, pIndex->tnum); - } + /* Add an entry in sqlite_master for this index + */ + tdsqlite3NestedParse(pParse, + "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", + db->aDb[iDb].zDbSName, MASTER_NAME, + pIndex->zName, + pTab->zName, + iMem, + zStmt + ); + tdsqlite3DbFree(db, zStmt); - /* When adding an index to the list of indices for a table, make - ** sure all indices labeled OE_Replace come after all those labeled - ** OE_Ignore. This is necessary for the correct constraint check - ** processing (in sqlite3GenerateConstraintChecks()) as part of - ** UPDATE and INSERT statements. - */ - if( db->init.busy || pTblName==0 ){ - if( onError!=OE_Replace || pTab->pIndex==0 - || pTab->pIndex->onError==OE_Replace){ - pIndex->pNext = pTab->pIndex; - pTab->pIndex = pIndex; - }else{ - Index *pOther = pTab->pIndex; - while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ - pOther = pOther->pNext; + /* Fill the index with data and reparse the schema. Code an OP_Expire + ** to invalidate all pre-compiled statements. + */ + if( pTblName ){ + tdsqlite3RefillIndex(pParse, pIndex, iMem); + tdsqlite3ChangeCookie(pParse, iDb); + tdsqlite3VdbeAddParseSchemaOp(v, iDb, + tdsqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); + tdsqlite3VdbeAddOp2(v, OP_Expire, 0, 1); } - pIndex->pNext = pOther->pNext; - pOther->pNext = pIndex; + + tdsqlite3VdbeJumpHere(v, pIndex->tnum); } + } + if( db->init.busy || pTblName==0 ){ + pIndex->pNext = pTab->pIndex; + pTab->pIndex = pIndex; + pIndex = 0; + } + else if( IN_RENAME_OBJECT ){ + assert( pParse->pNewIndex==0 ); + pParse->pNewIndex = pIndex; pIndex = 0; } /* Clean up before exiting */ exit_create_index: - if( pIndex ) freeIndex(db, pIndex); - sqlite3ExprDelete(db, pPIWhere); - sqlite3ExprListDelete(db, pList); - sqlite3SrcListDelete(db, pTblName); - sqlite3DbFree(db, zName); + if( pIndex ) tdsqlite3FreeIndex(db, pIndex); + if( pTab ){ /* Ensure all REPLACE indexes are at the end of the list */ + Index **ppFrom = &pTab->pIndex; + Index *pThis; + for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){ + Index *pNext; + if( pThis->onError!=OE_Replace ) continue; + while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){ + *ppFrom = pNext; + pThis->pNext = pNext->pNext; + pNext->pNext = pThis; + ppFrom = &pNext->pNext; + } + break; + } + } + tdsqlite3ExprDelete(db, pPIWhere); + tdsqlite3ExprListDelete(db, pList); + tdsqlite3SrcListDelete(db, pTblName); + tdsqlite3DbFree(db, zName); } /* @@ -104816,28 +116726,31 @@ exit_create_index: ** how aiRowEst[] should be initialized. The numbers generated here ** are based on typical values found in actual indices. */ -SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){ +SQLITE_PRIVATE void tdsqlite3DefaultRowEst(Index *pIdx){ /* 10, 9, 8, 7, 6 */ LogEst aVal[] = { 33, 32, 30, 28, 26 }; LogEst *a = pIdx->aiRowLogEst; int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); int i; + /* Indexes with default row estimates should not have stat1 data */ + assert( !pIdx->hasStat1 ); + /* Set the first entry (number of rows in the index) to the estimated ** number of rows in the table, or half the number of rows in the table ** for a partial index. But do not let the estimate drop below 10. */ a[0] = pIdx->pTable->nRowLogEst; - if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) ); - if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) ); + if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==tdsqlite3LogEst(2) ); + if( a[0]<33 ) a[0] = 33; assert( 33==tdsqlite3LogEst(10) ); /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is ** 6 and each subsequent value (if any) is 5. */ memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ - a[i] = 23; assert( 23==sqlite3LogEst(5) ); + a[i] = 23; assert( 23==tdsqlite3LogEst(5) ); } - assert( 0==sqlite3LogEst(1) ); + assert( 0==tdsqlite3LogEst(1) ); if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; } @@ -104845,10 +116758,10 @@ SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){ ** This routine will drop an existing named index. This routine ** implements the DROP INDEX statement. */ -SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ +SQLITE_PRIVATE void tdsqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ Index *pIndex; Vdbe *v; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; int iDb; assert( pParse->nErr==0 ); /* Never called with prior errors */ @@ -104856,62 +116769,62 @@ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists goto exit_drop_index; } assert( pName->nSrc==1 ); - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + if( SQLITE_OK!=tdsqlite3ReadSchema(pParse) ){ goto exit_drop_index; } - pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); + pIndex = tdsqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); if( pIndex==0 ){ if( !ifExists ){ - sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); + tdsqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); }else{ - sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); + tdsqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); } pParse->checkSchema = 1; goto exit_drop_index; } if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ - sqlite3ErrorMsg(pParse, "index associated with UNIQUE " + tdsqlite3ErrorMsg(pParse, "index associated with UNIQUE " "or PRIMARY KEY constraint cannot be dropped", 0); goto exit_drop_index; } - iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pIndex->pSchema); #ifndef SQLITE_OMIT_AUTHORIZATION { int code = SQLITE_DROP_INDEX; Table *pTab = pIndex->pTable; const char *zDb = db->aDb[iDb].zDbSName; const char *zTab = SCHEMA_TABLE(iDb); - if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ + if( tdsqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ goto exit_drop_index; } if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; - if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ + if( tdsqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ goto exit_drop_index; } } #endif /* Generate code to remove the index and from the master table */ - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( v ){ - sqlite3BeginWriteOperation(pParse, 1, iDb); - sqlite3NestedParse(pParse, + tdsqlite3BeginWriteOperation(pParse, 1, iDb); + tdsqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", - db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pIndex->zName + db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName ); - sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); - sqlite3ChangeCookie(pParse, iDb); + tdsqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); + tdsqlite3ChangeCookie(pParse, iDb); destroyRootPage(pParse, pIndex->tnum, iDb); - sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); + tdsqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); } exit_drop_index: - sqlite3SrcListDelete(db, pName); + tdsqlite3SrcListDelete(db, pName); } /* ** pArray is a pointer to an array of objects. Each object in the -** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() +** array is szEntry bytes in size. This routine uses tdsqlite3DbRealloc() ** to extend the array so that there is space for a new object at the end. ** ** When this function is called, *pnEntry contains the current size of @@ -104926,18 +116839,18 @@ exit_drop_index: ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains ** unchanged and a copy of pArray returned. */ -SQLITE_PRIVATE void *sqlite3ArrayAllocate( - sqlite3 *db, /* Connection to notify of malloc failures */ +SQLITE_PRIVATE void *tdsqlite3ArrayAllocate( + tdsqlite3 *db, /* Connection to notify of malloc failures */ void *pArray, /* Array of objects. Might be reallocated */ int szEntry, /* Size of each object in the array */ int *pnEntry, /* Number of objects currently in use */ int *pIdx /* Write the index of a new slot here */ ){ char *z; - int n = *pnEntry; + tdsqlite3_int64 n = *pIdx = *pnEntry; if( (n & (n-1))==0 ){ - int sz = (n==0) ? 1 : 2*n; - void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); + tdsqlite3_int64 sz = (n==0) ? 1 : 2*n; + void *pNew = tdsqlite3DbRealloc(db, pArray, sz*szEntry); if( pNew==0 ){ *pIdx = -1; return pArray; @@ -104946,7 +116859,6 @@ SQLITE_PRIVATE void *sqlite3ArrayAllocate( } z = (char*)pArray; memset(&z[n * szEntry], 0, szEntry); - *pIdx = n; ++*pnEntry; return pArray; } @@ -104957,13 +116869,14 @@ SQLITE_PRIVATE void *sqlite3ArrayAllocate( ** ** A new IdList is returned, or NULL if malloc() fails. */ -SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){ +SQLITE_PRIVATE IdList *tdsqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){ + tdsqlite3 *db = pParse->db; int i; if( pList==0 ){ - pList = sqlite3DbMallocZero(db, sizeof(IdList) ); + pList = tdsqlite3DbMallocZero(db, sizeof(IdList) ); if( pList==0 ) return 0; } - pList->a = sqlite3ArrayAllocate( + pList->a = tdsqlite3ArrayAllocate( db, pList->a, sizeof(pList->a[0]), @@ -104971,40 +116884,55 @@ SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pT &i ); if( i<0 ){ - sqlite3IdListDelete(db, pList); + tdsqlite3IdListDelete(db, pList); return 0; } - pList->a[i].zName = sqlite3NameFromToken(db, pToken); + pList->a[i].zName = tdsqlite3NameFromToken(db, pToken); + if( IN_RENAME_OBJECT && pList->a[i].zName ){ + tdsqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken); + } return pList; } /* ** Delete an IdList. */ -SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ +SQLITE_PRIVATE void tdsqlite3IdListDelete(tdsqlite3 *db, IdList *pList){ int i; if( pList==0 ) return; for(i=0; i<pList->nId; i++){ - sqlite3DbFree(db, pList->a[i].zName); + tdsqlite3DbFree(db, pList->a[i].zName); } - sqlite3DbFree(db, pList->a); - sqlite3DbFree(db, pList); + tdsqlite3DbFree(db, pList->a); + tdsqlite3DbFreeNN(db, pList); } /* ** Return the index in pList of the identifier named zId. Return -1 ** if not found. */ -SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){ +SQLITE_PRIVATE int tdsqlite3IdListIndex(IdList *pList, const char *zName){ int i; if( pList==0 ) return -1; for(i=0; i<pList->nId; i++){ - if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; + if( tdsqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; } return -1; } /* +** Maximum size of a SrcList object. +** The SrcList object is used to represent the FROM clause of a +** SELECT statement, and the query planner cannot deal with more +** than 64 tables in a join. So any value larger than 64 here +** is sufficient for most uses. Smaller values, like say 10, are +** appropriate for small and memory-limited applications. +*/ +#ifndef SQLITE_MAX_SRCLIST +# define SQLITE_MAX_SRCLIST 200 +#endif + +/* ** Expand the space allocated for the given SrcList object by ** creating nExtra new slots beginning at iStart. iStart is zero based. ** New slots are zeroed. @@ -105012,7 +116940,7 @@ SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){ ** For example, suppose a SrcList initially contains two entries: A,B. ** To append 3 new entries onto the end, do this: ** -** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); +** tdsqlite3SrcListEnlarge(db, pSrclist, 3, 2); ** ** After the call above it would contain: A, B, nil, nil, nil. ** If the iStart argument had been 1 instead of 2, then the result @@ -105020,11 +116948,12 @@ SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){ ** the iStart value would be 0. The result then would ** be: nil, nil, nil, A, B. ** -** If a memory allocation fails the SrcList is unchanged. The -** db->mallocFailed flag will be set to true. +** If a memory allocation fails or the SrcList becomes too large, leave +** the original SrcList unchanged, return NULL, and leave an error message +** in pParse. */ -SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( - sqlite3 *db, /* Database connection to notify of OOM errors */ +SQLITE_PRIVATE SrcList *tdsqlite3SrcListEnlarge( + Parse *pParse, /* Parsing context into which errors are reported */ SrcList *pSrc, /* The SrcList to be enlarged */ int nExtra, /* Number of new slots to add to pSrc->a[] */ int iStart /* Index in pSrc->a[] of first new slot */ @@ -105040,17 +116969,23 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( /* Allocate additional space if needed */ if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ SrcList *pNew; - int nAlloc = pSrc->nSrc+nExtra; - int nGot; - pNew = sqlite3DbRealloc(db, pSrc, + tdsqlite3_int64 nAlloc = 2*(tdsqlite3_int64)pSrc->nSrc+nExtra; + tdsqlite3 *db = pParse->db; + + if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){ + tdsqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d", + SQLITE_MAX_SRCLIST); + return 0; + } + if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST; + pNew = tdsqlite3DbRealloc(db, pSrc, sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); if( pNew==0 ){ assert( db->mallocFailed ); - return pSrc; + return 0; } pSrc = pNew; - nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; - pSrc->nAlloc = nGot; + pSrc->nAlloc = nAlloc; } /* Move existing slots that come after the newly inserted slots @@ -105075,7 +117010,8 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( ** Append a new table name to the given SrcList. Create a new SrcList if ** need be. A new entry is created in the SrcList even if pTable is NULL. ** -** A SrcList is returned, or NULL if there is an OOM error. The returned +** A SrcList is returned, or NULL if there is an OOM error or if the +** SrcList grows to large. The returned ** SrcList might be the same as the SrcList that was input or it might be ** a new one. If an OOM error does occurs, then the prior value of pList ** that is input to this routine is automatically freed. @@ -105090,59 +117026,67 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( ** ** In other words, if call like this: ** -** sqlite3SrcListAppend(D,A,B,0); +** tdsqlite3SrcListAppend(D,A,B,0); ** ** Then B is a table name and the database name is unspecified. If called ** like this: ** -** sqlite3SrcListAppend(D,A,B,C); +** tdsqlite3SrcListAppend(D,A,B,C); ** ** Then C is the table name and B is the database name. If C is defined ** then so is B. In other words, we never have a case where: ** -** sqlite3SrcListAppend(D,A,0,C); +** tdsqlite3SrcListAppend(D,A,0,C); ** ** Both pTable and pDatabase are assumed to be quoted. They are dequoted ** before being added to the SrcList. */ -SQLITE_PRIVATE SrcList *sqlite3SrcListAppend( - sqlite3 *db, /* Connection to notify of malloc failures */ +SQLITE_PRIVATE SrcList *tdsqlite3SrcListAppend( + Parse *pParse, /* Parsing context, in which errors are reported */ SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ Token *pTable, /* Table to append */ Token *pDatabase /* Database of the table */ ){ struct SrcList_item *pItem; + tdsqlite3 *db; assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ - assert( db!=0 ); + assert( pParse!=0 ); + assert( pParse->db!=0 ); + db = pParse->db; if( pList==0 ){ - pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) ); + pList = tdsqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) ); if( pList==0 ) return 0; pList->nAlloc = 1; - pList->nSrc = 0; - } - pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); - if( db->mallocFailed ){ - sqlite3SrcListDelete(db, pList); - return 0; + pList->nSrc = 1; + memset(&pList->a[0], 0, sizeof(pList->a[0])); + pList->a[0].iCursor = -1; + }else{ + SrcList *pNew = tdsqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc); + if( pNew==0 ){ + tdsqlite3SrcListDelete(db, pList); + return 0; + }else{ + pList = pNew; + } } pItem = &pList->a[pList->nSrc-1]; if( pDatabase && pDatabase->z==0 ){ pDatabase = 0; } if( pDatabase ){ - Token *pTemp = pDatabase; - pDatabase = pTable; - pTable = pTemp; + pItem->zName = tdsqlite3NameFromToken(db, pDatabase); + pItem->zDatabase = tdsqlite3NameFromToken(db, pTable); + }else{ + pItem->zName = tdsqlite3NameFromToken(db, pTable); + pItem->zDatabase = 0; } - pItem->zName = sqlite3NameFromToken(db, pTable); - pItem->zDatabase = sqlite3NameFromToken(db, pDatabase); return pList; } /* ** Assign VdbeCursor index numbers to all tables in a SrcList */ -SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ +SQLITE_PRIVATE void tdsqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ int i; struct SrcList_item *pItem; assert(pList || pParse->db->mallocFailed ); @@ -105151,7 +117095,7 @@ SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ if( pItem->iCursor>=0 ) break; pItem->iCursor = pParse->nTab++; if( pItem->pSelect ){ - sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); + tdsqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); } } } @@ -105160,22 +117104,22 @@ SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ /* ** Delete an entire SrcList including all its substructure. */ -SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ +SQLITE_PRIVATE void tdsqlite3SrcListDelete(tdsqlite3 *db, SrcList *pList){ int i; struct SrcList_item *pItem; if( pList==0 ) return; for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ - sqlite3DbFree(db, pItem->zDatabase); - sqlite3DbFree(db, pItem->zName); - sqlite3DbFree(db, pItem->zAlias); - if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); - if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); - sqlite3DeleteTable(db, pItem->pTab); - sqlite3SelectDelete(db, pItem->pSelect); - sqlite3ExprDelete(db, pItem->pOn); - sqlite3IdListDelete(db, pItem->pUsing); + tdsqlite3DbFree(db, pItem->zDatabase); + tdsqlite3DbFree(db, pItem->zName); + tdsqlite3DbFree(db, pItem->zAlias); + if( pItem->fg.isIndexedBy ) tdsqlite3DbFree(db, pItem->u1.zIndexedBy); + if( pItem->fg.isTabFunc ) tdsqlite3ExprListDelete(db, pItem->u1.pFuncArg); + tdsqlite3DeleteTable(db, pItem->pTab); + tdsqlite3SelectDelete(db, pItem->pSelect); + tdsqlite3ExprDelete(db, pItem->pOn); + tdsqlite3IdListDelete(db, pItem->pUsing); } - sqlite3DbFree(db, pList); + tdsqlite3DbFreeNN(db, pList); } /* @@ -105194,7 +117138,7 @@ SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ ** Return a new SrcList which encodes is the FROM with the new ** term added. */ -SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm( +SQLITE_PRIVATE SrcList *tdsqlite3SrcListAppendFromTerm( Parse *pParse, /* Parsing context */ SrcList *p, /* The left part of the FROM clause already seen */ Token *pTable, /* Name of the table to add to the FROM clause */ @@ -105205,21 +117149,28 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm( IdList *pUsing /* The USING clause of a join */ ){ struct SrcList_item *pItem; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; if( !p && (pOn || pUsing) ){ - sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", + tdsqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", (pOn ? "ON" : "USING") ); goto append_from_error; } - p = sqlite3SrcListAppend(db, p, pTable, pDatabase); - if( p==0 || NEVER(p->nSrc==0) ){ + p = tdsqlite3SrcListAppend(pParse, p, pTable, pDatabase); + if( p==0 ){ goto append_from_error; } + assert( p->nSrc>0 ); pItem = &p->a[p->nSrc-1]; + assert( (pTable==0)==(pDatabase==0) ); + assert( pItem->zName==0 || pDatabase!=0 ); + if( IN_RENAME_OBJECT && pItem->zName ){ + Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable; + tdsqlite3RenameTokenMap(pParse, pItem->zName, pToken); + } assert( pAlias!=0 ); if( pAlias->n ){ - pItem->zAlias = sqlite3NameFromToken(db, pAlias); + pItem->zAlias = tdsqlite3NameFromToken(db, pAlias); } pItem->pSelect = pSubquery; pItem->pOn = pOn; @@ -105228,9 +117179,9 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm( append_from_error: assert( p==0 ); - sqlite3ExprDelete(db, pOn); - sqlite3IdListDelete(db, pUsing); - sqlite3SelectDelete(db, pSubquery); + tdsqlite3ExprDelete(db, pOn); + tdsqlite3IdListDelete(db, pUsing); + tdsqlite3SelectDelete(db, pSubquery); return 0; } @@ -105238,10 +117189,12 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm( ** Add an INDEXED BY or NOT INDEXED clause to the most recently added ** element of the source-list passed as the second argument. */ -SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ +SQLITE_PRIVATE void tdsqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ assert( pIndexedBy!=0 ); - if( p && ALWAYS(p->nSrc>0) ){ - struct SrcList_item *pItem = &p->a[p->nSrc-1]; + if( p && pIndexedBy->n>0 ){ + struct SrcList_item *pItem; + assert( p->nSrc>0 ); + pItem = &p->a[p->nSrc-1]; assert( pItem->fg.notIndexed==0 ); assert( pItem->fg.isIndexedBy==0 ); assert( pItem->fg.isTabFunc==0 ); @@ -105250,8 +117203,8 @@ SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pI ** construct "indexed_opt" for details. */ pItem->fg.notIndexed = 1; }else{ - pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); - pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0); + pItem->u1.zIndexedBy = tdsqlite3NameFromToken(pParse->db, pIndexedBy); + pItem->fg.isIndexedBy = 1; } } } @@ -105260,7 +117213,7 @@ SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pI ** Add the list of function arguments to the SrcList entry for a ** table-valued-function. */ -SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ +SQLITE_PRIVATE void tdsqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ if( p ){ struct SrcList_item *pItem = &p->a[p->nSrc-1]; assert( pItem->fg.notIndexed==0 ); @@ -105269,7 +117222,7 @@ SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList * pItem->u1.pFuncArg = pList; pItem->fg.isTabFunc = 1; }else{ - sqlite3ExprListDelete(pParse->db, pList); + tdsqlite3ExprListDelete(pParse->db, pList); } } @@ -105288,7 +117241,7 @@ SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList * ** in p->a[0] and p->a[1], respectively. The parser initially stores the ** operator with A. This routine shifts that operator over to B. */ -SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){ +SQLITE_PRIVATE void tdsqlite3SrcListShiftJoinType(SrcList *p){ if( p ){ int i; for(i=p->nSrc-1; i>0; i--){ @@ -105301,59 +117254,48 @@ SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){ /* ** Generate VDBE code for a BEGIN statement. */ -SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){ - sqlite3 *db; +SQLITE_PRIVATE void tdsqlite3BeginTransaction(Parse *pParse, int type){ + tdsqlite3 *db; Vdbe *v; int i; assert( pParse!=0 ); db = pParse->db; assert( db!=0 ); - if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ + if( tdsqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ return; } - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( !v ) return; if( type!=TK_DEFERRED ){ for(i=0; i<db->nDb; i++){ - sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); - sqlite3VdbeUsesBtree(v, i); + tdsqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); + tdsqlite3VdbeUsesBtree(v, i); } } - sqlite3VdbeAddOp0(v, OP_AutoCommit); -} - -/* -** Generate VDBE code for a COMMIT statement. -*/ -SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){ - Vdbe *v; - - assert( pParse!=0 ); - assert( pParse->db!=0 ); - if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){ - return; - } - v = sqlite3GetVdbe(pParse); - if( v ){ - sqlite3VdbeAddOp1(v, OP_AutoCommit, 1); - } + tdsqlite3VdbeAddOp0(v, OP_AutoCommit); } /* -** Generate VDBE code for a ROLLBACK statement. +** Generate VDBE code for a COMMIT or ROLLBACK statement. +** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise +** code is generated for a COMMIT. */ -SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){ +SQLITE_PRIVATE void tdsqlite3EndTransaction(Parse *pParse, int eType){ Vdbe *v; + int isRollback; assert( pParse!=0 ); assert( pParse->db!=0 ); - if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){ + assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK ); + isRollback = eType==TK_ROLLBACK; + if( tdsqlite3AuthCheck(pParse, SQLITE_TRANSACTION, + isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){ return; } - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); + tdsqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback); } } @@ -105361,19 +117303,19 @@ SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){ ** This function is called by the parser when it parses a command to create, ** release or rollback an SQL savepoint. */ -SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ - char *zName = sqlite3NameFromToken(pParse->db, pName); +SQLITE_PRIVATE void tdsqlite3Savepoint(Parse *pParse, int op, Token *pName){ + char *zName = tdsqlite3NameFromToken(pParse->db, pName); if( zName ){ - Vdbe *v = sqlite3GetVdbe(pParse); + Vdbe *v = tdsqlite3GetVdbe(pParse); #ifndef SQLITE_OMIT_AUTHORIZATION static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); #endif - if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ - sqlite3DbFree(pParse->db, zName); + if( !v || tdsqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ + tdsqlite3DbFree(pParse->db, zName); return; } - sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); + tdsqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); } } @@ -105381,8 +117323,8 @@ SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ ** Make sure the TEMP database is open and available for use. Return ** the number of errors. Leave any error messages in the pParse structure. */ -SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){ - sqlite3 *db = pParse->db; +SQLITE_PRIVATE int tdsqlite3OpenTempDatabase(Parse *pParse){ + tdsqlite3 *db = pParse->db; if( db->aDb[1].pBt==0 && !pParse->explain ){ int rc; Btree *pBt; @@ -105393,17 +117335,17 @@ SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){ SQLITE_OPEN_DELETEONCLOSE | SQLITE_OPEN_TEMP_DB; - rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); + rc = tdsqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); if( rc!=SQLITE_OK ){ - sqlite3ErrorMsg(pParse, "unable to open a temporary database " + tdsqlite3ErrorMsg(pParse, "unable to open a temporary database " "file for storing temporary tables"); pParse->rc = rc; return 1; } db->aDb[1].pBt = pBt; assert( db->aDb[1].pSchema ); - if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ - sqlite3OomFault(db); + if( SQLITE_NOMEM==tdsqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){ + tdsqlite3OomFault(db); return 1; } } @@ -105414,34 +117356,34 @@ SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){ ** Record the fact that the schema cookie will need to be verified ** for database iDb. The code to actually verify the schema cookie ** will occur at the end of the top-level VDBE and will be generated -** later, by sqlite3FinishCoding(). +** later, by tdsqlite3FinishCoding(). */ -SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); +SQLITE_PRIVATE void tdsqlite3CodeVerifySchema(Parse *pParse, int iDb){ + Parse *pToplevel = tdsqlite3ParseToplevel(pParse); assert( iDb>=0 && iDb<pParse->db->nDb ); assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 ); assert( iDb<SQLITE_MAX_ATTACHED+2 ); - assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(pParse->db, iDb, 0) ); if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ DbMaskSet(pToplevel->cookieMask, iDb); if( !OMIT_TEMPDB && iDb==1 ){ - sqlite3OpenTempDatabase(pToplevel); + tdsqlite3OpenTempDatabase(pToplevel); } } } /* -** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each +** If argument zDb is NULL, then call tdsqlite3CodeVerifySchema() for each ** attached database. Otherwise, invoke it for the database named zDb only. */ -SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ - sqlite3 *db = pParse->db; +SQLITE_PRIVATE void tdsqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ + tdsqlite3 *db = pParse->db; int i; for(i=0; i<db->nDb; i++){ Db *pDb = &db->aDb[i]; - if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){ - sqlite3CodeVerifySchema(pParse, i); + if( pDb->pBt && (!zDb || 0==tdsqlite3StrICmp(zDb, pDb->zDbSName)) ){ + tdsqlite3CodeVerifySchema(pParse, i); } } } @@ -105459,9 +117401,9 @@ SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb) ** can be checked before any changes are made to the database, it is never ** necessary to undo a write and the checkpoint should not be set. */ -SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - sqlite3CodeVerifySchema(pParse, iDb); +SQLITE_PRIVATE void tdsqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ + Parse *pToplevel = tdsqlite3ParseToplevel(pParse); + tdsqlite3CodeVerifySchema(pParse, iDb); DbMaskSet(pToplevel->writeMask, iDb); pToplevel->isMultiWrite |= setStatement; } @@ -105473,8 +117415,8 @@ SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, ** If an abort occurs after some of these writes have completed, then it will ** be necessary to undo the completed writes. */ -SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); +SQLITE_PRIVATE void tdsqlite3MultiWrite(Parse *pParse){ + Parse *pToplevel = tdsqlite3ParseToplevel(pParse); pToplevel->isMultiWrite = 1; } @@ -105491,11 +117433,11 @@ SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){ ** go a little faster. But taking advantage of this time dependency ** makes it more difficult to prove that the code is correct (in ** particular, it prevents us from writing an effective -** implementation of sqlite3AssertMayAbort()) and so we have chosen +** implementation of tdsqlite3AssertMayAbort()) and so we have chosen ** to take the safe route and skip the optimization. */ -SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); +SQLITE_PRIVATE void tdsqlite3MayAbort(Parse *pParse){ + Parse *pToplevel = tdsqlite3ParseToplevel(pParse); pToplevel->mayAbort = 1; } @@ -105504,7 +117446,7 @@ SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){ ** error. The onError parameter determines which (if any) of the statement ** and/or current transaction is rolled back. */ -SQLITE_PRIVATE void sqlite3HaltConstraint( +SQLITE_PRIVATE void tdsqlite3HaltConstraint( Parse *pParse, /* Parsing context */ int errCode, /* extended error code */ int onError, /* Constraint type */ @@ -105512,19 +117454,19 @@ SQLITE_PRIVATE void sqlite3HaltConstraint( i8 p4type, /* P4_STATIC or P4_TRANSIENT */ u8 p5Errmsg /* P5_ErrMsg type */ ){ - Vdbe *v = sqlite3GetVdbe(pParse); + Vdbe *v = tdsqlite3GetVdbe(pParse); assert( (errCode&0xff)==SQLITE_CONSTRAINT ); if( onError==OE_Abort ){ - sqlite3MayAbort(pParse); + tdsqlite3MayAbort(pParse); } - sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); - sqlite3VdbeChangeP5(v, p5Errmsg); + tdsqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); + tdsqlite3VdbeChangeP5(v, p5Errmsg); } /* ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. */ -SQLITE_PRIVATE void sqlite3UniqueConstraint( +SQLITE_PRIVATE void tdsqlite3UniqueConstraint( Parse *pParse, /* Parsing context */ int onError, /* Constraint type */ Index *pIdx /* The index that triggers the constraint */ @@ -105534,20 +117476,23 @@ SQLITE_PRIVATE void sqlite3UniqueConstraint( StrAccum errMsg; Table *pTab = pIdx->pTable; - sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200); + tdsqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, + pParse->db->aLimit[SQLITE_LIMIT_LENGTH]); if( pIdx->aColExpr ){ - sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName); + tdsqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName); }else{ for(j=0; j<pIdx->nKeyCol; j++){ char *zCol; assert( pIdx->aiColumn[j]>=0 ); zCol = pTab->aCol[pIdx->aiColumn[j]].zName; - if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2); - sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol); + if( j ) tdsqlite3_str_append(&errMsg, ", ", 2); + tdsqlite3_str_appendall(&errMsg, pTab->zName); + tdsqlite3_str_append(&errMsg, ".", 1); + tdsqlite3_str_appendall(&errMsg, zCol); } } - zErr = sqlite3StrAccumFinish(&errMsg); - sqlite3HaltConstraint(pParse, + zErr = tdsqlite3StrAccumFinish(&errMsg); + tdsqlite3HaltConstraint(pParse, IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY : SQLITE_CONSTRAINT_UNIQUE, onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); @@ -105557,7 +117502,7 @@ SQLITE_PRIVATE void sqlite3UniqueConstraint( /* ** Code an OP_Halt due to non-unique rowid. */ -SQLITE_PRIVATE void sqlite3RowidConstraint( +SQLITE_PRIVATE void tdsqlite3RowidConstraint( Parse *pParse, /* Parsing context */ int onError, /* Conflict resolution algorithm */ Table *pTab /* The table with the non-unique rowid */ @@ -105565,14 +117510,14 @@ SQLITE_PRIVATE void sqlite3RowidConstraint( char *zMsg; int rc; if( pTab->iPKey>=0 ){ - zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, + zMsg = tdsqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, pTab->aCol[pTab->iPKey].zName); rc = SQLITE_CONSTRAINT_PRIMARYKEY; }else{ - zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); + zMsg = tdsqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); rc = SQLITE_CONSTRAINT_ROWID; } - sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, + tdsqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, P5_ConstraintUnique); } @@ -105587,7 +117532,7 @@ static int collationMatch(const char *zColl, Index *pIndex){ for(i=0; i<pIndex->nColumn; i++){ const char *z = pIndex->azColl[i]; assert( z!=0 || pIndex->aiColumn[i]<0 ); - if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ + if( pIndex->aiColumn[i]>=0 && 0==tdsqlite3StrICmp(z, zColl) ){ return 1; } } @@ -105601,13 +117546,15 @@ static int collationMatch(const char *zColl, Index *pIndex){ */ #ifndef SQLITE_OMIT_REINDEX static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ - Index *pIndex; /* An index associated with pTab */ + if( !IsVirtual(pTab) ){ + Index *pIndex; /* An index associated with pTab */ - for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ - if( zColl==0 || collationMatch(zColl, pIndex) ){ - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3RefillIndex(pParse, pIndex, -1); + for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ + if( zColl==0 || collationMatch(zColl, pIndex) ){ + int iDb = tdsqlite3SchemaToIndex(pParse->db, pTab->pSchema); + tdsqlite3BeginWriteOperation(pParse, 0, iDb); + tdsqlite3RefillIndex(pParse, pIndex, -1); + } } } } @@ -105622,11 +117569,11 @@ static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ static void reindexDatabases(Parse *pParse, char const *zColl){ Db *pDb; /* A single database */ int iDb; /* The database index number */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ HashElem *k; /* For looping over tables in pDb */ Table *pTab; /* A table in the database */ - assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ + assert( tdsqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ assert( pDb!=0 ); for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ @@ -105651,19 +117598,19 @@ static void reindexDatabases(Parse *pParse, char const *zColl){ ** indices associated with the named table. */ #ifndef SQLITE_OMIT_REINDEX -SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ +SQLITE_PRIVATE void tdsqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ char *z; /* Name of a table or index */ const char *zDb; /* Name of the database */ Table *pTab; /* A table in the database */ Index *pIndex; /* An index associated with pTab */ int iDb; /* The database index number */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ Token *pObjName; /* Name of the table or index to be reindexed */ /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + if( SQLITE_OK!=tdsqlite3ReadSchema(pParse) ){ return; } @@ -105673,65 +117620,78 @@ SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ }else if( NEVER(pName2==0) || pName2->z==0 ){ char *zColl; assert( pName1->z ); - zColl = sqlite3NameFromToken(pParse->db, pName1); + zColl = tdsqlite3NameFromToken(pParse->db, pName1); if( !zColl ) return; - pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); + pColl = tdsqlite3FindCollSeq(db, ENC(db), zColl, 0); if( pColl ){ reindexDatabases(pParse, zColl); - sqlite3DbFree(db, zColl); + tdsqlite3DbFree(db, zColl); return; } - sqlite3DbFree(db, zColl); + tdsqlite3DbFree(db, zColl); } - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); + iDb = tdsqlite3TwoPartName(pParse, pName1, pName2, &pObjName); if( iDb<0 ) return; - z = sqlite3NameFromToken(db, pObjName); + z = tdsqlite3NameFromToken(db, pObjName); if( z==0 ) return; zDb = db->aDb[iDb].zDbSName; - pTab = sqlite3FindTable(db, z, zDb); + pTab = tdsqlite3FindTable(db, z, zDb); if( pTab ){ reindexTable(pParse, pTab, 0); - sqlite3DbFree(db, z); + tdsqlite3DbFree(db, z); return; } - pIndex = sqlite3FindIndex(db, z, zDb); - sqlite3DbFree(db, z); + pIndex = tdsqlite3FindIndex(db, z, zDb); + tdsqlite3DbFree(db, z); if( pIndex ){ - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3RefillIndex(pParse, pIndex, -1); + tdsqlite3BeginWriteOperation(pParse, 0, iDb); + tdsqlite3RefillIndex(pParse, pIndex, -1); return; } - sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); + tdsqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); } #endif /* ** Return a KeyInfo structure that is appropriate for the given Index. ** -** The caller should invoke sqlite3KeyInfoUnref() on the returned object +** The caller should invoke tdsqlite3KeyInfoUnref() on the returned object ** when it has finished using it. */ -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ +SQLITE_PRIVATE KeyInfo *tdsqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ int i; int nCol = pIdx->nColumn; int nKey = pIdx->nKeyCol; KeyInfo *pKey; if( pParse->nErr ) return 0; if( pIdx->uniqNotNull ){ - pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); + pKey = tdsqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); }else{ - pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); + pKey = tdsqlite3KeyInfoAlloc(pParse->db, nCol, 0); } if( pKey ){ - assert( sqlite3KeyInfoIsWriteable(pKey) ); + assert( tdsqlite3KeyInfoIsWriteable(pKey) ); for(i=0; i<nCol; i++){ const char *zColl = pIdx->azColl[i]; - pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 : - sqlite3LocateCollSeq(pParse, zColl); - pKey->aSortOrder[i] = pIdx->aSortOrder[i]; + pKey->aColl[i] = zColl==tdsqlite3StrBINARY ? 0 : + tdsqlite3LocateCollSeq(pParse, zColl); + pKey->aSortFlags[i] = pIdx->aSortOrder[i]; + assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) ); } if( pParse->nErr ){ - sqlite3KeyInfoUnref(pKey); + assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ ); + if( pIdx->bNoQuery==0 ){ + /* Deactivate the index because it contains an unknown collating + ** sequence. The only way to reactive the index is to reload the + ** schema. Adding the missing collating sequence later does not + ** reactive the index. The application had the chance to register + ** the missing index using the collation-needed callback. For + ** simplicity, SQLite will not give the application a second chance. + */ + pIdx->bNoQuery = 1; + pParse->rc = SQLITE_ERROR_RETRY; + } + tdsqlite3KeyInfoUnref(pKey); pKey = 0; } } @@ -105743,41 +117703,41 @@ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ ** This routine is invoked once per CTE by the parser while parsing a ** WITH clause. */ -SQLITE_PRIVATE With *sqlite3WithAdd( +SQLITE_PRIVATE With *tdsqlite3WithAdd( Parse *pParse, /* Parsing context */ With *pWith, /* Existing WITH clause, or NULL */ Token *pName, /* Name of the common-table */ ExprList *pArglist, /* Optional column name list for the table */ Select *pQuery /* Query used to initialize the table */ ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; With *pNew; char *zName; /* Check that the CTE name is unique within this WITH clause. If ** not, store an error in the Parse structure. */ - zName = sqlite3NameFromToken(pParse->db, pName); + zName = tdsqlite3NameFromToken(pParse->db, pName); if( zName && pWith ){ int i; for(i=0; i<pWith->nCte; i++){ - if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ - sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); + if( tdsqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ + tdsqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); } } } if( pWith ){ - int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); - pNew = sqlite3DbRealloc(db, pWith, nByte); + tdsqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); + pNew = tdsqlite3DbRealloc(db, pWith, nByte); }else{ - pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); + pNew = tdsqlite3DbMallocZero(db, sizeof(*pWith)); } assert( (pNew!=0 && zName!=0) || db->mallocFailed ); if( db->mallocFailed ){ - sqlite3ExprListDelete(db, pArglist); - sqlite3SelectDelete(db, pQuery); - sqlite3DbFree(db, zName); + tdsqlite3ExprListDelete(db, pArglist); + tdsqlite3SelectDelete(db, pQuery); + tdsqlite3DbFree(db, zName); pNew = pWith; }else{ pNew->a[pNew->nCte].pSelect = pQuery; @@ -105793,16 +117753,16 @@ SQLITE_PRIVATE With *sqlite3WithAdd( /* ** Free the contents of the With object passed as the second argument. */ -SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){ +SQLITE_PRIVATE void tdsqlite3WithDelete(tdsqlite3 *db, With *pWith){ if( pWith ){ int i; for(i=0; i<pWith->nCte; i++){ struct Cte *pCte = &pWith->a[i]; - sqlite3ExprListDelete(db, pCte->pCols); - sqlite3SelectDelete(db, pCte->pSelect); - sqlite3DbFree(db, pCte->zName); + tdsqlite3ExprListDelete(db, pCte->pCols); + tdsqlite3SelectDelete(db, pCte->pSelect); + tdsqlite3DbFree(db, pCte->zName); } - sqlite3DbFree(db, pWith); + tdsqlite3DbFree(db, pWith); } } #endif /* !defined(SQLITE_OMIT_CTE) */ @@ -105831,24 +117791,24 @@ SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){ ** Invoke the 'collation needed' callback to request a collation sequence ** in the encoding enc of name zName, length nName. */ -static void callCollNeeded(sqlite3 *db, int enc, const char *zName){ +static void callCollNeeded(tdsqlite3 *db, int enc, const char *zName){ assert( !db->xCollNeeded || !db->xCollNeeded16 ); if( db->xCollNeeded ){ - char *zExternal = sqlite3DbStrDup(db, zName); + char *zExternal = tdsqlite3DbStrDup(db, zName); if( !zExternal ) return; db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal); - sqlite3DbFree(db, zExternal); + tdsqlite3DbFree(db, zExternal); } #ifndef SQLITE_OMIT_UTF16 if( db->xCollNeeded16 ){ char const *zExternal; - sqlite3_value *pTmp = sqlite3ValueNew(db); - sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC); - zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE); + tdsqlite3_value *pTmp = tdsqlite3ValueNew(db); + tdsqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC); + zExternal = tdsqlite3ValueText(pTmp, SQLITE_UTF16NATIVE); if( zExternal ){ db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal); } - sqlite3ValueFree(pTmp); + tdsqlite3ValueFree(pTmp); } #endif } @@ -105860,13 +117820,13 @@ static void callCollNeeded(sqlite3 *db, int enc, const char *zName){ ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if ** possible. */ -static int synthCollSeq(sqlite3 *db, CollSeq *pColl){ +static int synthCollSeq(tdsqlite3 *db, CollSeq *pColl){ CollSeq *pColl2; char *z = pColl->zName; int i; static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 }; for(i=0; i<3; i++){ - pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0); + pColl2 = tdsqlite3FindCollSeq(db, aEnc[i], z, 0); if( pColl2->xCmp!=0 ){ memcpy(pColl, pColl2, sizeof(CollSeq)); pColl->xDel = 0; /* Do not copy the destructor */ @@ -105877,65 +117837,21 @@ static int synthCollSeq(sqlite3 *db, CollSeq *pColl){ } /* -** This function is responsible for invoking the collation factory callback -** or substituting a collation sequence of a different encoding when the -** requested collation sequence is not available in the desired encoding. -** -** If it is not NULL, then pColl must point to the database native encoding -** collation sequence with name zName, length nName. -** -** The return value is either the collation sequence to be used in database -** db for collation type name zName, length nName, or NULL, if no collation -** sequence can be found. If no collation is found, leave an error message. -** -** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq() -*/ -SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq( - Parse *pParse, /* Parsing context */ - u8 enc, /* The desired encoding for the collating sequence */ - CollSeq *pColl, /* Collating sequence with native encoding, or NULL */ - const char *zName /* Collating sequence name */ -){ - CollSeq *p; - sqlite3 *db = pParse->db; - - p = pColl; - if( !p ){ - p = sqlite3FindCollSeq(db, enc, zName, 0); - } - if( !p || !p->xCmp ){ - /* No collation sequence of this type for this encoding is registered. - ** Call the collation factory to see if it can supply us with one. - */ - callCollNeeded(db, enc, zName); - p = sqlite3FindCollSeq(db, enc, zName, 0); - } - if( p && !p->xCmp && synthCollSeq(db, p) ){ - p = 0; - } - assert( !p || p->xCmp ); - if( p==0 ){ - sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName); - } - return p; -} - -/* ** This routine is called on a collation sequence before it is used to ** check that it is defined. An undefined collation sequence exists when ** a database is loaded that contains references to collation sequences -** that have not been defined by sqlite3_create_collation() etc. +** that have not been defined by tdsqlite3_create_collation() etc. ** ** If required, this routine calls the 'collation needed' callback to ** request a definition of the collating sequence. If this doesn't work, ** an equivalent collating sequence that uses a text encoding different ** from the main database is substituted, if one is available. */ -SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){ - if( pColl ){ +SQLITE_PRIVATE int tdsqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){ + if( pColl && pColl->xCmp==0 ){ const char *zName = pColl->zName; - sqlite3 *db = pParse->db; - CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName); + tdsqlite3 *db = pParse->db; + CollSeq *p = tdsqlite3GetCollSeq(pParse, ENC(db), pColl, zName); if( !p ){ return SQLITE_ERROR; } @@ -105960,16 +117876,16 @@ SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){ ** each collation sequence structure. */ static CollSeq *findCollSeqEntry( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ const char *zName, /* Name of the collating sequence */ int create /* Create a new entry if true */ ){ CollSeq *pColl; - pColl = sqlite3HashFind(&db->aCollSeq, zName); + pColl = tdsqlite3HashFind(&db->aCollSeq, zName); if( 0==pColl && create ){ - int nName = sqlite3Strlen30(zName); - pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1); + int nName = tdsqlite3Strlen30(zName) + 1; + pColl = tdsqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName); if( pColl ){ CollSeq *pDel = 0; pColl[0].zName = (char*)&pColl[3]; @@ -105979,17 +117895,16 @@ static CollSeq *findCollSeqEntry( pColl[2].zName = (char*)&pColl[3]; pColl[2].enc = SQLITE_UTF16BE; memcpy(pColl[0].zName, zName, nName); - pColl[0].zName[nName] = 0; - pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl); + pDel = tdsqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl); - /* If a malloc() failure occurred in sqlite3HashInsert(), it will + /* If a malloc() failure occurred in tdsqlite3HashInsert(), it will ** return the pColl pointer to be deleted (because it wasn't added ** to the hash table). */ assert( pDel==0 || pDel==pColl ); if( pDel!=0 ){ - sqlite3OomFault(db); - sqlite3DbFree(db, pDel); + tdsqlite3OomFault(db); + tdsqlite3DbFree(db, pDel); pColl = 0; } } @@ -106005,18 +117920,18 @@ static CollSeq *findCollSeqEntry( ** If the entry specified is not found and 'create' is true, then create a ** new entry. Otherwise return NULL. ** -** A separate function sqlite3LocateCollSeq() is a wrapper around -** this routine. sqlite3LocateCollSeq() invokes the collation factory +** A separate function tdsqlite3LocateCollSeq() is a wrapper around +** this routine. tdsqlite3LocateCollSeq() invokes the collation factory ** if necessary and generates an error message if the collating sequence ** cannot be found. ** -** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq() +** See also: tdsqlite3LocateCollSeq(), tdsqlite3GetCollSeq() */ -SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq( - sqlite3 *db, - u8 enc, - const char *zName, - int create +SQLITE_PRIVATE CollSeq *tdsqlite3FindCollSeq( + tdsqlite3 *db, /* Database connection to search */ + u8 enc, /* Desired text encoding */ + const char *zName, /* Name of the collating sequence. Might be NULL */ + int create /* True to create CollSeq if doesn't already exist */ ){ CollSeq *pColl; if( zName ){ @@ -106030,6 +117945,85 @@ SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq( return pColl; } +/* +** This function is responsible for invoking the collation factory callback +** or substituting a collation sequence of a different encoding when the +** requested collation sequence is not available in the desired encoding. +** +** If it is not NULL, then pColl must point to the database native encoding +** collation sequence with name zName, length nName. +** +** The return value is either the collation sequence to be used in database +** db for collation type name zName, length nName, or NULL, if no collation +** sequence can be found. If no collation is found, leave an error message. +** +** See also: tdsqlite3LocateCollSeq(), tdsqlite3FindCollSeq() +*/ +SQLITE_PRIVATE CollSeq *tdsqlite3GetCollSeq( + Parse *pParse, /* Parsing context */ + u8 enc, /* The desired encoding for the collating sequence */ + CollSeq *pColl, /* Collating sequence with native encoding, or NULL */ + const char *zName /* Collating sequence name */ +){ + CollSeq *p; + tdsqlite3 *db = pParse->db; + + p = pColl; + if( !p ){ + p = tdsqlite3FindCollSeq(db, enc, zName, 0); + } + if( !p || !p->xCmp ){ + /* No collation sequence of this type for this encoding is registered. + ** Call the collation factory to see if it can supply us with one. + */ + callCollNeeded(db, enc, zName); + p = tdsqlite3FindCollSeq(db, enc, zName, 0); + } + if( p && !p->xCmp && synthCollSeq(db, p) ){ + p = 0; + } + assert( !p || p->xCmp ); + if( p==0 ){ + tdsqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName); + pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ; + } + return p; +} + +/* +** This function returns the collation sequence for database native text +** encoding identified by the string zName. +** +** If the requested collation sequence is not available, or not available +** in the database native encoding, the collation factory is invoked to +** request it. If the collation factory does not supply such a sequence, +** and the sequence is available in another text encoding, then that is +** returned instead. +** +** If no versions of the requested collations sequence are available, or +** another error occurs, NULL is returned and an error message written into +** pParse. +** +** This routine is a wrapper around tdsqlite3FindCollSeq(). This routine +** invokes the collation factory if the named collation cannot be found +** and generates an error message. +** +** See also: tdsqlite3FindCollSeq(), tdsqlite3GetCollSeq() +*/ +SQLITE_PRIVATE CollSeq *tdsqlite3LocateCollSeq(Parse *pParse, const char *zName){ + tdsqlite3 *db = pParse->db; + u8 enc = ENC(db); + u8 initbusy = db->init.busy; + CollSeq *pColl; + + pColl = tdsqlite3FindCollSeq(db, enc, zName, initbusy); + if( !initbusy && (!pColl || !pColl->xCmp) ){ + pColl = tdsqlite3GetCollSeq(pParse, enc, pColl, zName); + } + + return pColl; +} + /* During the search for the best function definition, this procedure ** is called to test how well the function passed as the first argument ** matches the request for a function with nArg arguments in a system @@ -106065,12 +118059,13 @@ static int matchQuality( u8 enc /* Desired text encoding */ ){ int match; - - /* nArg of -2 is a special case */ - if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH; + assert( p->nArg>=-1 ); /* Wrong number of arguments means "no match" */ - if( p->nArg!=nArg && p->nArg>=0 ) return 0; + if( p->nArg!=nArg ){ + if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH; + if( p->nArg>=0 ) return 0; + } /* Give a better score to a function with a specific number of arguments ** than to function that accepts any number of arguments. */ @@ -106094,13 +118089,13 @@ static int matchQuality( ** Search a FuncDefHash for a function with the given name. Return ** a pointer to the matching FuncDef if found, or 0 if there is no match. */ -static FuncDef *functionSearch( +SQLITE_PRIVATE FuncDef *tdsqlite3FunctionSearch( int h, /* Hash of the name */ const char *zFunc /* Name of function */ ){ FuncDef *p; - for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){ - if( sqlite3StrICmp(p->zName, zFunc)==0 ){ + for(p=tdsqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){ + if( tdsqlite3StrICmp(p->zName, zFunc)==0 ){ return p; } } @@ -106110,7 +118105,7 @@ static FuncDef *functionSearch( /* ** Insert a new FuncDef into a FuncDefHash hash table. */ -SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs( +SQLITE_PRIVATE void tdsqlite3InsertBuiltinFuncs( FuncDef *aDef, /* List of global functions to be inserted */ int nDef /* Length of the apDef[] list */ ){ @@ -106118,17 +118113,18 @@ SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs( for(i=0; i<nDef; i++){ FuncDef *pOther; const char *zName = aDef[i].zName; - int nName = sqlite3Strlen30(zName); - int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ; - pOther = functionSearch(h, zName); + int nName = tdsqlite3Strlen30(zName); + int h = SQLITE_FUNC_HASH(zName[0], nName); + assert( zName[0]>='a' && zName[0]<='z' ); + pOther = tdsqlite3FunctionSearch(h, zName); if( pOther ){ assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] ); aDef[i].pNext = pOther->pNext; pOther->pNext = &aDef[i]; }else{ aDef[i].pNext = 0; - aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h]; - sqlite3BuiltinFunctions.a[h] = &aDef[i]; + aDef[i].u.pHash = tdsqlite3BuiltinFunctions.a[h]; + tdsqlite3BuiltinFunctions.a[h] = &aDef[i]; } } } @@ -106154,8 +118150,8 @@ SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs( ** number of arguments may be returned even if the eTextRep flag does not ** match that requested. */ -SQLITE_PRIVATE FuncDef *sqlite3FindFunction( - sqlite3 *db, /* An open database */ +SQLITE_PRIVATE FuncDef *tdsqlite3FindFunction( + tdsqlite3 *db, /* An open database */ const char *zName, /* Name of the function. zero-terminated */ int nArg, /* Number of arguments. -1 means any number */ u8 enc, /* Preferred text encoding */ @@ -106169,11 +118165,11 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction( assert( nArg>=(-2) ); assert( nArg>=(-1) || createFlag==0 ); - nName = sqlite3Strlen30(zName); + nName = tdsqlite3Strlen30(zName); /* First search for a match amongst the application-defined functions. */ - p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName); + p = (FuncDef*)tdsqlite3HashFind(&db->aFunc, zName); while( p ){ int score = matchQuality(p, nArg, enc); if( score>bestScore ){ @@ -106185,7 +118181,7 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction( /* If no match is found, search the built-in functions. ** - ** If the SQLITE_PreferBuiltin flag is set, then search the built-in + ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in ** functions even if a prior app-defined function was found. And give ** priority to built-in functions. ** @@ -106195,10 +118191,10 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction( ** new function. But the FuncDefs for built-in functions are read-only. ** So we must not search for built-ins when creating a new function. */ - if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){ + if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){ bestScore = 0; - h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ; - p = functionSearch(h, zName); + h = SQLITE_FUNC_HASH(tdsqlite3UpperToLower[(u8)zName[0]], nName); + p = tdsqlite3FunctionSearch(h, zName); while( p ){ int score = matchQuality(p, nArg, enc); if( score>bestScore ){ @@ -106214,16 +118210,18 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction( ** new entry to the hash table and return it. */ if( createFlag && bestScore<FUNC_PERFECT_MATCH && - (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){ + (pBest = tdsqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){ FuncDef *pOther; + u8 *z; pBest->zName = (const char*)&pBest[1]; pBest->nArg = (u16)nArg; pBest->funcFlags = enc; memcpy((char*)&pBest[1], zName, nName+1); - pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest); + for(z=(u8*)pBest->zName; *z; z++) *z = tdsqlite3UpperToLower[*z]; + pOther = (FuncDef*)tdsqlite3HashInsert(&db->aFunc, pBest->zName, pBest); if( pOther==pBest ){ - sqlite3DbFree(db, pBest); - sqlite3OomFault(db); + tdsqlite3DbFree(db, pBest); + tdsqlite3OomFault(db); return 0; }else{ pBest->pNext = pOther; @@ -106238,13 +118236,13 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction( /* ** Free all resources held by the schema structure. The void* argument points -** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the +** at a Schema struct. This function does not call tdsqlite3DbFree(db, ) on the ** pointer itself, it just cleans up subsidiary resources (i.e. the contents ** of the schema hash tables). ** ** The Schema.cache_size variable is not cleared. */ -SQLITE_PRIVATE void sqlite3SchemaClear(void *p){ +SQLITE_PRIVATE void tdsqlite3SchemaClear(void *p){ Hash temp1; Hash temp2; HashElem *pElem; @@ -106252,44 +118250,44 @@ SQLITE_PRIVATE void sqlite3SchemaClear(void *p){ temp1 = pSchema->tblHash; temp2 = pSchema->trigHash; - sqlite3HashInit(&pSchema->trigHash); - sqlite3HashClear(&pSchema->idxHash); + tdsqlite3HashInit(&pSchema->trigHash); + tdsqlite3HashClear(&pSchema->idxHash); for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){ - sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem)); + tdsqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem)); } - sqlite3HashClear(&temp2); - sqlite3HashInit(&pSchema->tblHash); + tdsqlite3HashClear(&temp2); + tdsqlite3HashInit(&pSchema->tblHash); for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){ Table *pTab = sqliteHashData(pElem); - sqlite3DeleteTable(0, pTab); + tdsqlite3DeleteTable(0, pTab); } - sqlite3HashClear(&temp1); - sqlite3HashClear(&pSchema->fkeyHash); + tdsqlite3HashClear(&temp1); + tdsqlite3HashClear(&pSchema->fkeyHash); pSchema->pSeqTab = 0; if( pSchema->schemaFlags & DB_SchemaLoaded ){ pSchema->iGeneration++; - pSchema->schemaFlags &= ~DB_SchemaLoaded; } + pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted); } /* ** Find and return the schema associated with a BTree. Create ** a new one if necessary. */ -SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){ +SQLITE_PRIVATE Schema *tdsqlite3SchemaGet(tdsqlite3 *db, Btree *pBt){ Schema * p; if( pBt ){ - p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear); + p = (Schema *)tdsqlite3BtreeSchema(pBt, sizeof(Schema), tdsqlite3SchemaClear); }else{ - p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema)); + p = (Schema *)tdsqlite3DbMallocZero(0, sizeof(Schema)); } if( !p ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); }else if ( 0==p->file_format ){ - sqlite3HashInit(&p->tblHash); - sqlite3HashInit(&p->idxHash); - sqlite3HashInit(&p->trigHash); - sqlite3HashInit(&p->fkeyHash); + tdsqlite3HashInit(&p->tblHash); + tdsqlite3HashInit(&p->idxHash); + tdsqlite3HashInit(&p->trigHash); + tdsqlite3HashInit(&p->fkeyHash); p->enc = SQLITE_UTF8; } return p; @@ -106327,51 +118325,64 @@ SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){ ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one ** */ -SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ +SQLITE_PRIVATE Table *tdsqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ struct SrcList_item *pItem = pSrc->a; Table *pTab; assert( pItem && pSrc->nSrc==1 ); - pTab = sqlite3LocateTableItem(pParse, 0, pItem); - sqlite3DeleteTable(pParse->db, pItem->pTab); + pTab = tdsqlite3LocateTableItem(pParse, 0, pItem); + tdsqlite3DeleteTable(pParse->db, pItem->pTab); pItem->pTab = pTab; if( pTab ){ - pTab->nRef++; + pTab->nTabRef++; } - if( sqlite3IndexedByLookup(pParse, pItem) ){ + if( tdsqlite3IndexedByLookup(pParse, pItem) ){ pTab = 0; } return pTab; } +/* Return true if table pTab is read-only. +** +** A table is read-only if any of the following are true: +** +** 1) It is a virtual table and no implementation of the xUpdate method +** has been provided +** +** 2) It is a system table (i.e. sqlite_master), this call is not +** part of a nested parse and writable_schema pragma has not +** been specified +** +** 3) The table is a shadow table, the database connection is in +** defensive mode, and the current tdsqlite3_prepare() +** is for a top-level SQL statement. +*/ +static int tabIsReadOnly(Parse *pParse, Table *pTab){ + tdsqlite3 *db; + if( IsVirtual(pTab) ){ + return tdsqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0; + } + if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0; + db = pParse->db; + if( (pTab->tabFlags & TF_Readonly)!=0 ){ + return tdsqlite3WritableSchema(db)==0 && pParse->nested==0; + } + assert( pTab->tabFlags & TF_Shadow ); + return tdsqlite3ReadOnlyShadowTables(db); +} + /* ** Check to make sure the given table is writable. If it is not ** writable, generate an error message and return 1. If it is ** writable return 0; */ -SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ - /* A table is not writable under the following circumstances: - ** - ** 1) It is a virtual table and no implementation of the xUpdate method - ** has been provided, or - ** 2) It is a system table (i.e. sqlite_master), this call is not - ** part of a nested parse and writable_schema pragma has not - ** been specified. - ** - ** In either case leave an error message in pParse and return non-zero. - */ - if( ( IsVirtual(pTab) - && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ) - || ( (pTab->tabFlags & TF_Readonly)!=0 - && (pParse->db->flags & SQLITE_WriteSchema)==0 - && pParse->nested==0 ) - ){ - sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); +SQLITE_PRIVATE int tdsqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ + if( tabIsReadOnly(pParse, pTab) ){ + tdsqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); return 1; } - #ifndef SQLITE_OMIT_VIEW if( !viewOk && pTab->pSelect ){ - sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName); + tdsqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName); return 1; } #endif @@ -106385,31 +118396,33 @@ SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ ** pWhere argument is an optional WHERE clause that restricts the ** set of rows in the view that are to be added to the ephemeral table. */ -SQLITE_PRIVATE void sqlite3MaterializeView( +SQLITE_PRIVATE void tdsqlite3MaterializeView( Parse *pParse, /* Parsing context */ Table *pView, /* View definition */ Expr *pWhere, /* Optional WHERE clause to be added */ + ExprList *pOrderBy, /* Optional ORDER BY clause */ + Expr *pLimit, /* Optional LIMIT clause */ int iCur /* Cursor number for ephemeral table */ ){ SelectDest dest; Select *pSel; SrcList *pFrom; - sqlite3 *db = pParse->db; - int iDb = sqlite3SchemaToIndex(db, pView->pSchema); - pWhere = sqlite3ExprDup(db, pWhere, 0); - pFrom = sqlite3SrcListAppend(db, 0, 0, 0); + tdsqlite3 *db = pParse->db; + int iDb = tdsqlite3SchemaToIndex(db, pView->pSchema); + pWhere = tdsqlite3ExprDup(db, pWhere, 0); + pFrom = tdsqlite3SrcListAppend(pParse, 0, 0, 0); if( pFrom ){ assert( pFrom->nSrc==1 ); - pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName); - pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName); + pFrom->a[0].zName = tdsqlite3DbStrDup(db, pView->zName); + pFrom->a[0].zDatabase = tdsqlite3DbStrDup(db, db->aDb[iDb].zDbSName); assert( pFrom->a[0].pOn==0 ); assert( pFrom->a[0].pUsing==0 ); } - pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, - SF_IncludeHidden, 0, 0); - sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); - sqlite3Select(pParse, pSel, &dest); - sqlite3SelectDelete(db, pSel); + pSel = tdsqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy, + SF_IncludeHidden, pLimit); + tdsqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); + tdsqlite3Select(pParse, pSel, &dest); + tdsqlite3SelectDelete(db, pSel); } #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */ @@ -106422,35 +118435,35 @@ SQLITE_PRIVATE void sqlite3MaterializeView( ** \__________________________/ ** pLimitWhere (pInClause) */ -SQLITE_PRIVATE Expr *sqlite3LimitWhere( +SQLITE_PRIVATE Expr *tdsqlite3LimitWhere( Parse *pParse, /* The parser context */ SrcList *pSrc, /* the FROM clause -- which tables to scan */ Expr *pWhere, /* The WHERE clause. May be null */ ExprList *pOrderBy, /* The ORDER BY clause. May be null */ Expr *pLimit, /* The LIMIT clause. May be null */ - Expr *pOffset, /* The OFFSET clause. May be null */ char *zStmtType /* Either DELETE or UPDATE. For err msgs. */ ){ - Expr *pWhereRowid = NULL; /* WHERE rowid .. */ + tdsqlite3 *db = pParse->db; + Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */ Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */ - Expr *pSelectRowid = NULL; /* SELECT rowid ... */ ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */ SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */ Select *pSelect = NULL; /* Complete SELECT tree */ + Table *pTab; /* Check that there isn't an ORDER BY without a LIMIT clause. */ - if( pOrderBy && (pLimit == 0) ) { - sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); - goto limit_where_cleanup; + if( pOrderBy && pLimit==0 ) { + tdsqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); + tdsqlite3ExprDelete(pParse->db, pWhere); + tdsqlite3ExprListDelete(pParse->db, pOrderBy); + return 0; } /* We only need to generate a select expression if there ** is a limit/offset term to enforce. */ if( pLimit == 0 ) { - /* if pLimit is null, pOffset will always be null as well. */ - assert( pOffset == 0 ); return pWhere; } @@ -106463,36 +118476,47 @@ SQLITE_PRIVATE Expr *sqlite3LimitWhere( ** ); */ - pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0); - if( pSelectRowid == 0 ) goto limit_where_cleanup; - pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid); - if( pEList == 0 ) goto limit_where_cleanup; + pTab = pSrc->a[0].pTab; + if( HasRowid(pTab) ){ + pLhs = tdsqlite3PExpr(pParse, TK_ROW, 0, 0); + pEList = tdsqlite3ExprListAppend( + pParse, 0, tdsqlite3PExpr(pParse, TK_ROW, 0, 0) + ); + }else{ + Index *pPk = tdsqlite3PrimaryKeyIndex(pTab); + if( pPk->nKeyCol==1 ){ + const char *zName = pTab->aCol[pPk->aiColumn[0]].zName; + pLhs = tdsqlite3Expr(db, TK_ID, zName); + pEList = tdsqlite3ExprListAppend(pParse, 0, tdsqlite3Expr(db, TK_ID, zName)); + }else{ + int i; + for(i=0; i<pPk->nKeyCol; i++){ + Expr *p = tdsqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName); + pEList = tdsqlite3ExprListAppend(pParse, pEList, p); + } + pLhs = tdsqlite3PExpr(pParse, TK_VECTOR, 0, 0); + if( pLhs ){ + pLhs->x.pList = tdsqlite3ExprListDup(db, pEList, 0); + } + } + } /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree ** and the SELECT subtree. */ - pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0); - if( pSelectSrc == 0 ) { - sqlite3ExprListDelete(pParse->db, pEList); - goto limit_where_cleanup; - } + pSrc->a[0].pTab = 0; + pSelectSrc = tdsqlite3SrcListDup(pParse->db, pSrc, 0); + pSrc->a[0].pTab = pTab; + pSrc->a[0].pIBIndex = 0; /* generate the SELECT expression tree. */ - pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0, - pOrderBy,0,pLimit,pOffset); - if( pSelect == 0 ) return 0; + pSelect = tdsqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0, + pOrderBy,0,pLimit + ); /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ - pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0); - pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0; - sqlite3PExprAddSelect(pParse, pInClause, pSelect); + pInClause = tdsqlite3PExpr(pParse, TK_IN, pLhs, 0); + tdsqlite3PExprAddSelect(pParse, pInClause, pSelect); return pInClause; - -limit_where_cleanup: - sqlite3ExprDelete(pParse->db, pWhere); - sqlite3ExprListDelete(pParse->db, pOrderBy); - sqlite3ExprDelete(pParse->db, pLimit); - sqlite3ExprDelete(pParse->db, pOffset); - return 0; } #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */ /* && !defined(SQLITE_OMIT_SUBQUERY) */ @@ -106504,10 +118528,12 @@ limit_where_cleanup: ** \________/ \________________/ ** pTabList pWhere */ -SQLITE_PRIVATE void sqlite3DeleteFrom( +SQLITE_PRIVATE void tdsqlite3DeleteFrom( Parse *pParse, /* The parser context */ SrcList *pTabList, /* The table from which we should delete things */ - Expr *pWhere /* The WHERE clause. May be null */ + Expr *pWhere, /* The WHERE clause. May be null */ + ExprList *pOrderBy, /* ORDER BY clause. May be null */ + Expr *pLimit /* LIMIT clause. May be null */ ){ Vdbe *v; /* The virtual database engine */ Table *pTab; /* The table from which records will be deleted */ @@ -106518,11 +118544,11 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( int iDataCur = 0; /* VDBE cursor for the canonical data source */ int iIdxCur = 0; /* Cursor number of the first index */ int nIdx; /* Number of indices */ - sqlite3 *db; /* Main database structure */ + tdsqlite3 *db; /* Main database structure */ AuthContext sContext; /* Authorization context */ NameContext sNC; /* Name context to resolve expressions in */ int iDb; /* Database number */ - int memCnt = -1; /* Memory cell used for change counting */ + int memCnt = 0; /* Memory cell used for change counting */ int rcauth; /* Value returned by authorization callback */ int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */ int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ @@ -106552,42 +118578,53 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( } assert( pTabList->nSrc==1 ); + /* Locate the table which we want to delete. This table has to be ** put in an SrcList structure because some of the subroutines we ** will be calling are designed to work with multiple tables and expect ** an SrcList* parameter instead of just a Table* parameter. */ - pTab = sqlite3SrcListLookup(pParse, pTabList); + pTab = tdsqlite3SrcListLookup(pParse, pTabList); if( pTab==0 ) goto delete_from_cleanup; /* Figure out if we have any triggers and if the table being ** deleted from is a view */ #ifndef SQLITE_OMIT_TRIGGER - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); + pTrigger = tdsqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); isView = pTab->pSelect!=0; - bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0); #else # define pTrigger 0 # define isView 0 #endif + bComplex = pTrigger || tdsqlite3FkRequired(pParse, pTab, 0, 0); #ifdef SQLITE_OMIT_VIEW # undef isView # define isView 0 #endif +#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT + if( !isView ){ + pWhere = tdsqlite3LimitWhere( + pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE" + ); + pOrderBy = 0; + pLimit = 0; + } +#endif + /* If pTab is really a view, make sure it has been initialized. */ - if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + if( tdsqlite3ViewGetColumnNames(pParse, pTab) ){ goto delete_from_cleanup; } - if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){ + if( tdsqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){ goto delete_from_cleanup; } - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb<db->nDb ); - rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, + rcauth = tdsqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, db->aDb[iDb].zDbSName); assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE ); if( rcauth==SQLITE_DENY ){ @@ -106606,25 +118643,29 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( /* Start the view context */ if( isView ){ - sqlite3AuthContextPush(pParse, &sContext, pTab->zName); + tdsqlite3AuthContextPush(pParse, &sContext, pTab->zName); } /* Begin generating code. */ - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( v==0 ){ goto delete_from_cleanup; } - if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); - sqlite3BeginWriteOperation(pParse, 1, iDb); + if( pParse->nested==0 ) tdsqlite3VdbeCountChanges(v); + tdsqlite3BeginWriteOperation(pParse, bComplex, iDb); /* If we are trying to delete from a view, realize that view into ** an ephemeral table. */ #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) if( isView ){ - sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur); + tdsqlite3MaterializeView(pParse, pTab, + pWhere, pOrderBy, pLimit, iTabCur + ); iDataCur = iIdxCur = iTabCur; + pOrderBy = 0; + pLimit = 0; } #endif @@ -106633,23 +118674,33 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; - if( sqlite3ResolveExprNames(&sNC, pWhere) ){ + if( tdsqlite3ResolveExprNames(&sNC, pWhere) ){ goto delete_from_cleanup; } /* Initialize the counter of the number of rows deleted, if ** we are counting rows. */ - if( db->flags & SQLITE_CountRows ){ + if( (db->flags & SQLITE_CountRows)!=0 + && !pParse->nested + && !pParse->pTriggerTab + ){ memCnt = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); } #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION /* Special case: A DELETE without a WHERE clause deletes everything. ** It is easier just to erase the whole table. Prior to version 3.6.5, ** this optimization caused the row change count (the value returned by - ** API function sqlite3_count_changes) to be set incorrectly. */ + ** API function tdsqlite3_count_changes) to be set incorrectly. + ** + ** The "rcauth==SQLITE_OK" terms is the + ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and + ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but + ** the truncate optimization is disabled and all rows are deleted + ** individually. + */ if( rcauth==SQLITE_OK && pWhere==0 && !bComplex @@ -106659,14 +118710,14 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( #endif ){ assert( !isView ); - sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); + tdsqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); if( HasRowid(pTab) ){ - sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt, + tdsqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1, pTab->zName, P4_STATIC); } for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ assert( pIdx->pSchema==pTab->pSchema ); - sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); + tdsqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); } }else #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ @@ -106679,18 +118730,18 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( pPk = 0; nPk = 1; iRowSet = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); }else{ /* For a WITHOUT ROWID table, create an ephemeral table used to ** hold all primary keys for rows to be deleted. */ - pPk = sqlite3PrimaryKeyIndex(pTab); + pPk = tdsqlite3PrimaryKeyIndex(pTab); assert( pPk!=0 ); nPk = pPk->nKeyCol; iPk = pParse->nMem+1; pParse->nMem += nPk; iEphCur = pParse->nTab++; - addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk); - sqlite3VdbeSetP4KeyInfo(pParse, pPk); + addrEphOpen = tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk); + tdsqlite3VdbeSetP4KeyInfo(pParse, pPk); } /* Construct a query to find the rowid or primary key for every row @@ -106701,29 +118752,29 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( ** ONEPASS_SINGLE: One-pass approach - at most one row deleted. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted. */ - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1); + pWInfo = tdsqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1); if( pWInfo==0 ) goto delete_from_cleanup; - eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); + eOnePass = tdsqlite3WhereOkOnePass(pWInfo, aiCurOnePass); assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI ); assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF ); + if( eOnePass!=ONEPASS_SINGLE ) tdsqlite3MultiWrite(pParse); /* Keep track of the number of rows to be deleted */ - if( db->flags & SQLITE_CountRows ){ - sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); + if( memCnt ){ + tdsqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); } /* Extract the rowid or primary key for the current row */ if( pPk ){ for(i=0; i<nPk; i++){ assert( pPk->aiColumn[i]>=0 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, pPk->aiColumn[i], iPk+i); } iKey = iPk; }else{ - iKey = pParse->nMem + 1; - iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0); - if( iKey>pParse->nMem ) pParse->nMem = iKey; + iKey = ++pParse->nMem; + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey); } if( eOnePass!=ONEPASS_OFF ){ @@ -106731,37 +118782,37 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( ** one, so just keep it in its register(s) and fall through to the ** delete code. */ nKey = nPk; /* OP_Found will use an unpacked key */ - aToOpen = sqlite3DbMallocRawNN(db, nIdx+2); + aToOpen = tdsqlite3DbMallocRawNN(db, nIdx+2); if( aToOpen==0 ){ - sqlite3WhereEnd(pWInfo); + tdsqlite3WhereEnd(pWInfo); goto delete_from_cleanup; } memset(aToOpen, 1, nIdx+1); aToOpen[nIdx+1] = 0; if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0; if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0; - if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen); + if( addrEphOpen ) tdsqlite3VdbeChangeToNoop(v, addrEphOpen); }else{ if( pPk ){ /* Add the PK key for this row to the temporary table */ iKey = ++pParse->nMem; nKey = 0; /* Zero tells OP_Found to use a composite key */ - sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey, - sqlite3IndexAffinityStr(pParse->db, pPk), nPk); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey); + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey, + tdsqlite3IndexAffinityStr(pParse->db, pPk), nPk); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk); }else{ /* Add the rowid of the row to be deleted to the RowSet */ - nKey = 1; /* OP_Seek always uses a single rowid */ - sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey); + nKey = 1; /* OP_DeferredSeek always uses a single rowid */ + tdsqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey); } } /* If this DELETE cannot use the ONEPASS strategy, this is the ** end of the WHERE loop */ if( eOnePass!=ONEPASS_OFF ){ - addrBypass = sqlite3VdbeMakeLabel(v); + addrBypass = tdsqlite3VdbeMakeLabel(pParse); }else{ - sqlite3WhereEnd(pWInfo); + tdsqlite3WhereEnd(pWInfo); } /* Unless this is a view, open cursors for the table we are @@ -106772,14 +118823,14 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( if( !isView ){ int iAddrOnce = 0; if( eOnePass==ONEPASS_MULTI ){ - iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); + iAddrOnce = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } testcase( IsVirtual(pTab) ); - sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE, + tdsqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE, iTabCur, aToOpen, &iDataCur, &iIdxCur); assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur ); assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 ); - if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce); + if( eOnePass==ONEPASS_MULTI ) tdsqlite3VdbeJumpHere(v, iAddrOnce); } /* Set up a loop over the rowids/primary-keys that were found in the @@ -106789,15 +118840,19 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( assert( nKey==nPk ); /* OP_Found will use an unpacked key */ if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){ assert( pPk!=0 || pTab->pSelect!=0 ); - sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey); + tdsqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey); VdbeCoverage(v); } }else if( pPk ){ - addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey); + addrLoop = tdsqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v); + if( IsVirtual(pTab) ){ + tdsqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey); + }else{ + tdsqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey); + } assert( nKey==0 ); /* OP_Found will use a composite key */ }else{ - addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey); + addrLoop = tdsqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey); VdbeCoverage(v); assert( nKey==1 ); } @@ -106805,46 +118860,37 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( /* Delete the row */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ - const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); - sqlite3VtabMakeWritable(pParse, pTab); - sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB); - sqlite3VdbeChangeP5(v, OE_Abort); + const char *pVTab = (const char *)tdsqlite3GetVTable(db, pTab); + tdsqlite3VtabMakeWritable(pParse, pTab); assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); - sqlite3MayAbort(pParse); - if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){ - pParse->isMultiWrite = 0; + tdsqlite3MayAbort(pParse); + if( eOnePass==ONEPASS_SINGLE ){ + tdsqlite3VdbeAddOp1(v, OP_Close, iTabCur); + if( tdsqlite3IsToplevel(pParse) ){ + pParse->isMultiWrite = 0; + } } + tdsqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB); + tdsqlite3VdbeChangeP5(v, OE_Abort); }else #endif { int count = (pParse->nested==0); /* True to count changes */ - int iIdxNoSeek = -1; - if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){ - iIdxNoSeek = aiCurOnePass[1]; - } - sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, - iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek); + tdsqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, + iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]); } /* End of the loop over all rowids/primary-keys. */ if( eOnePass!=ONEPASS_OFF ){ - sqlite3VdbeResolveLabel(v, addrBypass); - sqlite3WhereEnd(pWInfo); + tdsqlite3VdbeResolveLabel(v, addrBypass); + tdsqlite3WhereEnd(pWInfo); }else if( pPk ){ - sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addrLoop); + tdsqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addrLoop); }else{ - sqlite3VdbeGoto(v, addrLoop); - sqlite3VdbeJumpHere(v, addrLoop); + tdsqlite3VdbeGoto(v, addrLoop); + tdsqlite3VdbeJumpHere(v, addrLoop); } - - /* Close the cursors open on the table and its indexes. */ - if( !isView && !IsVirtual(pTab) ){ - if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur); - for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ - sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i); - } - } } /* End non-truncate path */ /* Update the sqlite_sequence table by storing the content of the @@ -106852,24 +118898,28 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( ** autoincrement tables. */ if( pParse->nested==0 && pParse->pTriggerTab==0 ){ - sqlite3AutoincrementEnd(pParse); + tdsqlite3AutoincrementEnd(pParse); } /* Return the number of rows that were deleted. If this routine is - ** generating code because of a call to sqlite3NestedParse(), do not + ** generating code because of a call to tdsqlite3NestedParse(), do not ** invoke the callback function. */ - if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); + if( memCnt ){ + tdsqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); + tdsqlite3VdbeSetNumCols(v, 1); + tdsqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); } delete_from_cleanup: - sqlite3AuthContextPop(&sContext); - sqlite3SrcListDelete(db, pTabList); - sqlite3ExprDelete(db, pWhere); - sqlite3DbFree(db, aToOpen); + tdsqlite3AuthContextPop(&sContext); + tdsqlite3SrcListDelete(db, pTabList); + tdsqlite3ExprDelete(db, pWhere); +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) + tdsqlite3ExprListDelete(db, pOrderBy); + tdsqlite3ExprDelete(db, pLimit); +#endif + tdsqlite3DbFree(db, aToOpen); return; } /* Make sure "isView" and other macros defined above are undefined. Otherwise @@ -106911,17 +118961,19 @@ delete_from_cleanup: ** ** If eMode is ONEPASS_MULTI, then this call is being made as part ** of a ONEPASS delete that affects multiple rows. In this case, if -** iIdxNoSeek is a valid cursor number (>=0), then its position should -** be preserved following the delete operation. Or, if iIdxNoSeek is not -** a valid cursor number, the position of iDataCur should be preserved -** instead. +** iIdxNoSeek is a valid cursor number (>=0) and is not the same as +** iDataCur, then its position should be preserved following the delete +** operation. Or, if iIdxNoSeek is not a valid cursor number, the +** position of iDataCur should be preserved instead. ** ** iIdxNoSeek: -** If iIdxNoSeek is a valid cursor number (>=0), then it identifies an -** index cursor (from within array of cursors starting at iIdxCur) that -** already points to the index entry to be deleted. +** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur, +** then it identifies an index cursor (from within array of cursors +** starting at iIdxCur) that already points to the index entry to be deleted. +** Except, this optimization is disabled if there are BEFORE triggers since +** the trigger body might have moved the cursor. */ -SQLITE_PRIVATE void sqlite3GenerateRowDelete( +SQLITE_PRIVATE void tdsqlite3GenerateRowDelete( Parse *pParse, /* Parsing context */ Table *pTab, /* Table containing the row to be deleted */ Trigger *pTrigger, /* List of triggers to (potentially) fire */ @@ -106947,62 +118999,68 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete( /* Seek cursor iCur to the row to delete. If this row no longer exists ** (this can happen if a trigger program has already deleted it), do ** not attempt to delete it or fire any DELETE triggers. */ - iLabel = sqlite3VdbeMakeLabel(v); + iLabel = tdsqlite3VdbeMakeLabel(pParse); opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound; if( eMode==ONEPASS_OFF ){ - sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); + tdsqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); VdbeCoverageIf(v, opSeek==OP_NotExists); VdbeCoverageIf(v, opSeek==OP_NotFound); } /* If there are any triggers to fire, allocate a range of registers to ** use for the old.* references in the triggers. */ - if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){ + if( tdsqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){ u32 mask; /* Mask of OLD.* columns in use */ int iCol; /* Iterator used while populating OLD.* */ int addrStart; /* Start of BEFORE trigger programs */ /* TODO: Could use temporary registers here. Also could attempt to ** avoid copying the contents of the rowid register. */ - mask = sqlite3TriggerColmask( + mask = tdsqlite3TriggerColmask( pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf ); - mask |= sqlite3FkOldmask(pParse, pTab); + mask |= tdsqlite3FkOldmask(pParse, pTab); iOld = pParse->nMem+1; pParse->nMem += (1 + pTab->nCol); /* Populate the OLD.* pseudo-table register array. These values will be ** used by any BEFORE and AFTER triggers that exist. */ - sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld); + tdsqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld); for(iCol=0; iCol<pTab->nCol; iCol++){ testcase( mask!=0xffffffff && iCol==31 ); testcase( mask!=0xffffffff && iCol==32 ); if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){ - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1); + int kk = tdsqlite3TableColumnToStorage(pTab, iCol); + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1); } } /* Invoke BEFORE DELETE trigger programs. */ - addrStart = sqlite3VdbeCurrentAddr(v); - sqlite3CodeRowTrigger(pParse, pTrigger, + addrStart = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel ); /* If any BEFORE triggers were coded, then seek the cursor to the ** row to be deleted again. It may be that the BEFORE triggers moved - ** the cursor or of already deleted the row that the cursor was + ** the cursor or already deleted the row that the cursor was ** pointing to. + ** + ** Also disable the iIdxNoSeek optimization since the BEFORE trigger + ** may have moved that cursor. */ - if( addrStart<sqlite3VdbeCurrentAddr(v) ){ - sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); + if( addrStart<tdsqlite3VdbeCurrentAddr(v) ){ + tdsqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); VdbeCoverageIf(v, opSeek==OP_NotExists); VdbeCoverageIf(v, opSeek==OP_NotFound); + testcase( iIdxNoSeek>=0 ); + iIdxNoSeek = -1; } /* Do FK processing. This call checks that any FK constraints that ** refer to this table (i.e. constraints attached to other tables) ** are not violated by deleting this row. */ - sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0); + tdsqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0); } /* Delete the index and table entries. Skip this step if pTab is really @@ -107017,33 +119075,35 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete( */ if( pTab->pSelect==0 ){ u8 p5 = 0; - sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek); - sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0)); - sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE); + tdsqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek); + tdsqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0)); + if( pParse->nested==0 || 0==tdsqlite3_stricmp(pTab->zName, "sqlite_stat1") ){ + tdsqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE); + } if( eMode!=ONEPASS_OFF ){ - sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE); + tdsqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE); } - if( iIdxNoSeek>=0 ){ - sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek); + if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){ + tdsqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek); } if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION; - sqlite3VdbeChangeP5(v, p5); + tdsqlite3VdbeChangeP5(v, p5); } /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just deleted. */ - sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0); + tdsqlite3FkActions(pParse, pTab, 0, iOld, 0, 0); /* Invoke AFTER DELETE trigger programs. */ - sqlite3CodeRowTrigger(pParse, pTrigger, + tdsqlite3CodeRowTrigger(pParse, pTrigger, TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel ); /* Jump here if the row had already been deleted before any BEFORE ** trigger programs were invoked. Or if a trigger program throws a ** RAISE(IGNORE) exception. */ - sqlite3VdbeResolveLabel(v, iLabel); + tdsqlite3VdbeResolveLabel(v, iLabel); VdbeModuleComment((v, "END: GenRowDel()")); } @@ -107065,7 +119125,7 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete( ** 3. The "iDataCur" cursor must be already be positioned on the row ** that is to be deleted. */ -SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( +SQLITE_PRIVATE void tdsqlite3GenerateRowIndexDelete( Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Table containing the row to be deleted */ int iDataCur, /* Cursor of table holding data. */ @@ -107082,18 +119142,18 @@ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */ v = pParse->pVdbe; - pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); + pPk = HasRowid(pTab) ? 0 : tdsqlite3PrimaryKeyIndex(pTab); for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ assert( iIdxCur+i!=iDataCur || pPk==pIdx ); if( aRegIdx!=0 && aRegIdx[i]==0 ) continue; if( pIdx==pPk ) continue; if( iIdxCur+i==iIdxNoSeek ) continue; VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName)); - r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1, + r1 = tdsqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1, &iPartIdxLabel, pPrior, r1); - sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, + tdsqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn); - sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); + tdsqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); pPrior = pIdx; } } @@ -107112,11 +119172,11 @@ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( ** ** If *piPartIdxLabel is not NULL, fill it in with a label and jump ** to that label if pIdx is a partial index that should be skipped. -** The label should be resolved using sqlite3ResolvePartIdxLabel(). +** The label should be resolved using tdsqlite3ResolvePartIdxLabel(). ** A partial index should be skipped if its WHERE clause evaluates ** to false or null. If pIdx is not a partial index, *piPartIdxLabel ** will be set to zero which is an empty label that is ignored by -** sqlite3ResolvePartIdxLabel(). +** tdsqlite3ResolvePartIdxLabel(). ** ** The pPrior and regPrior parameters are used to implement a cache to ** avoid unnecessary register loads. If pPrior is not NULL, then it is @@ -107129,7 +119189,7 @@ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( ** on a table with multiple indices, and especially with the ROWID or ** PRIMARY KEY columns of the index. */ -SQLITE_PRIVATE int sqlite3GenerateIndexKey( +SQLITE_PRIVATE int tdsqlite3GenerateIndexKey( Parse *pParse, /* Parsing context */ Index *pIdx, /* The index for which to generate a key */ int iDataCur, /* Cursor number from which to take column data */ @@ -107146,17 +119206,19 @@ SQLITE_PRIVATE int sqlite3GenerateIndexKey( if( piPartIdxLabel ){ if( pIdx->pPartIdxWhere ){ - *piPartIdxLabel = sqlite3VdbeMakeLabel(v); - pParse->iSelfTab = iDataCur; - sqlite3ExprCachePush(pParse); - sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, + *piPartIdxLabel = tdsqlite3VdbeMakeLabel(pParse); + pParse->iSelfTab = iDataCur + 1; + tdsqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, SQLITE_JUMPIFNULL); + pParse->iSelfTab = 0; + pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02; + ** pPartIdxWhere may have corrupted regPrior registers */ }else{ *piPartIdxLabel = 0; } } nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn; - regBase = sqlite3GetTempRange(pParse, nCol); + regBase = tdsqlite3GetTempRange(pParse, nCol); if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0; for(j=0; j<nCol; j++){ if( pPrior @@ -107166,31 +119228,34 @@ SQLITE_PRIVATE int sqlite3GenerateIndexKey( /* This column was already computed by the previous index */ continue; } - sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j); + tdsqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j); /* If the column affinity is REAL but the number is an integer, then it ** might be stored in the table as an integer (using a compact ** representation) then converted to REAL by an OP_RealAffinity opcode. ** But we are getting ready to store this value back into an index, where ** it should be converted by to INTEGER again. So omit the OP_RealAffinity ** opcode if it is present */ - sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity); + tdsqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity); } if( regOut ){ - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut); + if( pIdx->pTable->pSelect ){ + const char *zAff = tdsqlite3IndexAffinityStr(pParse->db, pIdx); + tdsqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT); + } } - sqlite3ReleaseTempRange(pParse, regBase, nCol); + tdsqlite3ReleaseTempRange(pParse, regBase, nCol); return regBase; } /* -** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label +** If a prior call to tdsqlite3GenerateIndexKey() generated a jump-over label ** because it was a partial index, then this routine should be called to ** resolve that label. */ -SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){ +SQLITE_PRIVATE void tdsqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){ if( iLabel ){ - sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel); - sqlite3ExprCachePop(pParse); + tdsqlite3VdbeResolveLabel(pParse->pVdbe, iLabel); } } @@ -107214,12 +119279,15 @@ SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){ /* #include "sqliteInt.h" */ /* #include <stdlib.h> */ /* #include <assert.h> */ +#ifndef SQLITE_OMIT_FLOATING_POINT +/* #include <math.h> */ +#endif /* #include "vdbeInt.h" */ /* ** Return the collating function associated with a function. */ -static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ +static CollSeq *tdsqlite3GetFuncCollSeq(tdsqlite3_context *context){ VdbeOp *pOp; assert( context->pVdbe!=0 ); pOp = &context->pVdbe->aOp[context->iOp-1]; @@ -107232,7 +119300,9 @@ static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ ** Indicate that the accumulator load should be skipped on this ** iteration of the aggregate loop. */ -static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ +static void tdsqlite3SkipAccumulatorLoad(tdsqlite3_context *context){ + assert( context->isError<=0 ); + context->isError = -1; context->skipFlag = 1; } @@ -107240,9 +119310,9 @@ static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ ** Implementation of the non-aggregate min() and max() functions */ static void minmaxFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ int i; int mask; /* 0 for min() or 0xffffffff for max() */ @@ -107250,40 +119320,44 @@ static void minmaxFunc( CollSeq *pColl; assert( argc>1 ); - mask = sqlite3_user_data(context)==0 ? 0 : -1; - pColl = sqlite3GetFuncCollSeq(context); + mask = tdsqlite3_user_data(context)==0 ? 0 : -1; + pColl = tdsqlite3GetFuncCollSeq(context); assert( pColl ); assert( mask==-1 || mask==0 ); iBest = 0; - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; + if( tdsqlite3_value_type(argv[0])==SQLITE_NULL ) return; for(i=1; i<argc; i++){ - if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return; - if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){ + if( tdsqlite3_value_type(argv[i])==SQLITE_NULL ) return; + if( (tdsqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){ testcase( mask==0 ); iBest = i; } } - sqlite3_result_value(context, argv[iBest]); + tdsqlite3_result_value(context, argv[iBest]); } /* ** Return the type of the argument. */ static void typeofFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **argv + tdsqlite3_value **argv ){ - const char *z = 0; + static const char *azType[] = { "integer", "real", "text", "blob", "null" }; + int i = tdsqlite3_value_type(argv[0]) - 1; UNUSED_PARAMETER(NotUsed); - switch( sqlite3_value_type(argv[0]) ){ - case SQLITE_INTEGER: z = "integer"; break; - case SQLITE_TEXT: z = "text"; break; - case SQLITE_FLOAT: z = "real"; break; - case SQLITE_BLOB: z = "blob"; break; - default: z = "null"; break; - } - sqlite3_result_text(context, z, -1, SQLITE_STATIC); + assert( i>=0 && i<ArraySize(azType) ); + assert( SQLITE_INTEGER==1 ); + assert( SQLITE_FLOAT==2 ); + assert( SQLITE_TEXT==3 ); + assert( SQLITE_BLOB==4 ); + assert( SQLITE_NULL==5 ); + /* EVIDENCE-OF: R-01470-60482 The tdsqlite3_value_type(V) interface returns + ** the datatype code for the initial datatype of the tdsqlite3_value object + ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT, + ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */ + tdsqlite3_result_text(context, azType[i], -1, SQLITE_STATIC); } @@ -107291,34 +119365,36 @@ static void typeofFunc( ** Implementation of the length() function */ static void lengthFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ - int len; - assert( argc==1 ); UNUSED_PARAMETER(argc); - switch( sqlite3_value_type(argv[0]) ){ + switch( tdsqlite3_value_type(argv[0]) ){ case SQLITE_BLOB: case SQLITE_INTEGER: case SQLITE_FLOAT: { - sqlite3_result_int(context, sqlite3_value_bytes(argv[0])); + tdsqlite3_result_int(context, tdsqlite3_value_bytes(argv[0])); break; } case SQLITE_TEXT: { - const unsigned char *z = sqlite3_value_text(argv[0]); + const unsigned char *z = tdsqlite3_value_text(argv[0]); + const unsigned char *z0; + unsigned char c; if( z==0 ) return; - len = 0; - while( *z ){ - len++; - SQLITE_SKIP_UTF8(z); + z0 = z; + while( (c = *z)!=0 ){ + z++; + if( c>=0xc0 ){ + while( (*z & 0xc0)==0x80 ){ z++; z0++; } + } } - sqlite3_result_int(context, len); + tdsqlite3_result_int(context, (int)(z-z0)); break; } default: { - sqlite3_result_null(context); + tdsqlite3_result_null(context); break; } } @@ -107330,39 +119406,39 @@ static void lengthFunc( ** IMP: R-23979-26855 The abs(X) function returns the absolute value of ** the numeric argument X. */ -static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ +static void absFunc(tdsqlite3_context *context, int argc, tdsqlite3_value **argv){ assert( argc==1 ); UNUSED_PARAMETER(argc); - switch( sqlite3_value_type(argv[0]) ){ + switch( tdsqlite3_value_type(argv[0]) ){ case SQLITE_INTEGER: { - i64 iVal = sqlite3_value_int64(argv[0]); + i64 iVal = tdsqlite3_value_int64(argv[0]); if( iVal<0 ){ if( iVal==SMALLEST_INT64 ){ /* IMP: R-31676-45509 If X is the integer -9223372036854775808 ** then abs(X) throws an integer overflow error since there is no ** equivalent positive 64-bit two complement value. */ - sqlite3_result_error(context, "integer overflow", -1); + tdsqlite3_result_error(context, "integer overflow", -1); return; } iVal = -iVal; } - sqlite3_result_int64(context, iVal); + tdsqlite3_result_int64(context, iVal); break; } case SQLITE_NULL: { /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ - sqlite3_result_null(context); + tdsqlite3_result_null(context); break; } default: { - /* Because sqlite3_value_double() returns 0.0 if the argument is not + /* Because tdsqlite3_value_double() returns 0.0 if the argument is not ** something that can be converted into a number, we have: ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob ** that cannot be converted to a numeric value. */ - double rVal = sqlite3_value_double(argv[0]); + double rVal = tdsqlite3_value_double(argv[0]); if( rVal<0 ) rVal = -rVal; - sqlite3_result_double(context, rVal); + tdsqlite3_result_double(context, rVal); break; } } @@ -107380,9 +119456,9 @@ static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ ** or 0 if needle never occurs in haystack. */ static void instrFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ const unsigned char *zHaystack; const unsigned char *zNeedle; @@ -107391,58 +119467,82 @@ static void instrFunc( int typeHaystack, typeNeedle; int N = 1; int isText; + unsigned char firstChar; + tdsqlite3_value *pC1 = 0; + tdsqlite3_value *pC2 = 0; UNUSED_PARAMETER(argc); - typeHaystack = sqlite3_value_type(argv[0]); - typeNeedle = sqlite3_value_type(argv[1]); + typeHaystack = tdsqlite3_value_type(argv[0]); + typeNeedle = tdsqlite3_value_type(argv[1]); if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; - nHaystack = sqlite3_value_bytes(argv[0]); - nNeedle = sqlite3_value_bytes(argv[1]); - if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ - zHaystack = sqlite3_value_blob(argv[0]); - zNeedle = sqlite3_value_blob(argv[1]); - isText = 0; - }else{ - zHaystack = sqlite3_value_text(argv[0]); - zNeedle = sqlite3_value_text(argv[1]); - isText = 1; - if( zNeedle==0 ) return; - assert( zHaystack ); - } - while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){ - N++; - do{ - nHaystack--; - zHaystack++; - }while( isText && (zHaystack[0]&0xc0)==0x80 ); + nHaystack = tdsqlite3_value_bytes(argv[0]); + nNeedle = tdsqlite3_value_bytes(argv[1]); + if( nNeedle>0 ){ + if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ + zHaystack = tdsqlite3_value_blob(argv[0]); + zNeedle = tdsqlite3_value_blob(argv[1]); + isText = 0; + }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){ + zHaystack = tdsqlite3_value_text(argv[0]); + zNeedle = tdsqlite3_value_text(argv[1]); + isText = 1; + }else{ + pC1 = tdsqlite3_value_dup(argv[0]); + zHaystack = tdsqlite3_value_text(pC1); + if( zHaystack==0 ) goto endInstrOOM; + nHaystack = tdsqlite3_value_bytes(pC1); + pC2 = tdsqlite3_value_dup(argv[1]); + zNeedle = tdsqlite3_value_text(pC2); + if( zNeedle==0 ) goto endInstrOOM; + nNeedle = tdsqlite3_value_bytes(pC2); + isText = 1; + } + if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM; + firstChar = zNeedle[0]; + while( nNeedle<=nHaystack + && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0) + ){ + N++; + do{ + nHaystack--; + zHaystack++; + }while( isText && (zHaystack[0]&0xc0)==0x80 ); + } + if( nNeedle>nHaystack ) N = 0; } - if( nNeedle>nHaystack ) N = 0; - sqlite3_result_int(context, N); + tdsqlite3_result_int(context, N); +endInstr: + tdsqlite3_value_free(pC1); + tdsqlite3_value_free(pC2); + return; +endInstrOOM: + tdsqlite3_result_error_nomem(context); + goto endInstr; } /* ** Implementation of the printf() function. */ static void printfFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ PrintfArguments x; StrAccum str; const char *zFormat; int n; - sqlite3 *db = sqlite3_context_db_handle(context); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); - if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){ + if( argc>=1 && (zFormat = (const char*)tdsqlite3_value_text(argv[0]))!=0 ){ x.nArg = argc-1; x.nUsed = 0; x.apArg = argv+1; - sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); + tdsqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); str.printfFlags = SQLITE_PRINTF_SQLFUNC; - sqlite3XPrintf(&str, zFormat, &x); + tdsqlite3_str_appendf(&str, zFormat, &x); n = str.nChar; - sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, + tdsqlite3_result_text(context, tdsqlite3StrAccumFinish(&str), n, SQLITE_DYNAMIC); } } @@ -107460,9 +119560,9 @@ static void printfFunc( ** If p2 is negative, return the p2 characters preceding p1. */ static void substrFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ const unsigned char *z; const unsigned char *z2; @@ -107472,20 +119572,20 @@ static void substrFunc( int negP2 = 0; assert( argc==3 || argc==2 ); - if( sqlite3_value_type(argv[1])==SQLITE_NULL - || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) + if( tdsqlite3_value_type(argv[1])==SQLITE_NULL + || (argc==3 && tdsqlite3_value_type(argv[2])==SQLITE_NULL) ){ return; } - p0type = sqlite3_value_type(argv[0]); - p1 = sqlite3_value_int(argv[1]); + p0type = tdsqlite3_value_type(argv[0]); + p1 = tdsqlite3_value_int(argv[1]); if( p0type==SQLITE_BLOB ){ - len = sqlite3_value_bytes(argv[0]); - z = sqlite3_value_blob(argv[0]); + len = tdsqlite3_value_bytes(argv[0]); + z = tdsqlite3_value_blob(argv[0]); if( z==0 ) return; - assert( len==sqlite3_value_bytes(argv[0]) ); + assert( len==tdsqlite3_value_bytes(argv[0]) ); }else{ - z = sqlite3_value_text(argv[0]); + z = tdsqlite3_value_text(argv[0]); if( z==0 ) return; len = 0; if( p1<0 ){ @@ -107503,13 +119603,13 @@ static void substrFunc( if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */ #endif if( argc==3 ){ - p2 = sqlite3_value_int(argv[2]); + p2 = tdsqlite3_value_int(argv[2]); if( p2<0 ){ p2 = -p2; negP2 = 1; } }else{ - p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; + p2 = tdsqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; } if( p1<0 ){ p1 += len; @@ -107539,14 +119639,14 @@ static void substrFunc( for(z2=z; *z2 && p2; p2--){ SQLITE_SKIP_UTF8(z2); } - sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, + tdsqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, SQLITE_UTF8); }else{ if( p1+p2>len ){ p2 = len-p1; if( p2<0 ) p2 = 0; } - sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); + tdsqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); } } @@ -107554,60 +119654,60 @@ static void substrFunc( ** Implementation of the round() function */ #ifndef SQLITE_OMIT_FLOATING_POINT -static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ +static void roundFunc(tdsqlite3_context *context, int argc, tdsqlite3_value **argv){ int n = 0; double r; char *zBuf; assert( argc==1 || argc==2 ); if( argc==2 ){ - if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; - n = sqlite3_value_int(argv[1]); + if( SQLITE_NULL==tdsqlite3_value_type(argv[1]) ) return; + n = tdsqlite3_value_int(argv[1]); if( n>30 ) n = 30; if( n<0 ) n = 0; } - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - r = sqlite3_value_double(argv[0]); + if( tdsqlite3_value_type(argv[0])==SQLITE_NULL ) return; + r = tdsqlite3_value_double(argv[0]); /* If Y==0 and X will fit in a 64-bit int, ** handle the rounding directly, ** otherwise use printf. */ - if( n==0 && r>=0 && r<LARGEST_INT64-1 ){ - r = (double)((sqlite_int64)(r+0.5)); - }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){ - r = -(double)((sqlite_int64)((-r)+0.5)); + if( r<-4503599627370496.0 || r>+4503599627370496.0 ){ + /* The value has no fractional part so there is nothing to round */ + }else if( n==0 ){ + r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5))); }else{ - zBuf = sqlite3_mprintf("%.*f",n,r); + zBuf = tdsqlite3_mprintf("%.*f",n,r); if( zBuf==0 ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); return; } - sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8); - sqlite3_free(zBuf); + tdsqlite3AtoF(zBuf, &r, tdsqlite3Strlen30(zBuf), SQLITE_UTF8); + tdsqlite3_free(zBuf); } - sqlite3_result_double(context, r); + tdsqlite3_result_double(context, r); } #endif /* -** Allocate nByte bytes of space using sqlite3Malloc(). If the -** allocation fails, call sqlite3_result_error_nomem() to notify +** Allocate nByte bytes of space using tdsqlite3Malloc(). If the +** allocation fails, call tdsqlite3_result_error_nomem() to notify ** the database handle that malloc() has failed and return NULL. ** If nByte is larger than the maximum string or blob length, then ** raise an SQLITE_TOOBIG exception and return NULL. */ -static void *contextMalloc(sqlite3_context *context, i64 nByte){ +static void *contextMalloc(tdsqlite3_context *context, i64 nByte){ char *z; - sqlite3 *db = sqlite3_context_db_handle(context); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); assert( nByte>0 ); testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - sqlite3_result_error_toobig(context); + tdsqlite3_result_error_toobig(context); z = 0; }else{ - z = sqlite3Malloc(nByte); + z = tdsqlite3Malloc(nByte); if( !z ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); } } return z; @@ -107616,41 +119716,41 @@ static void *contextMalloc(sqlite3_context *context, i64 nByte){ /* ** Implementation of the upper() and lower() SQL functions. */ -static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ +static void upperFunc(tdsqlite3_context *context, int argc, tdsqlite3_value **argv){ char *z1; const char *z2; int i, n; UNUSED_PARAMETER(argc); - z2 = (char*)sqlite3_value_text(argv[0]); - n = sqlite3_value_bytes(argv[0]); + z2 = (char*)tdsqlite3_value_text(argv[0]); + n = tdsqlite3_value_bytes(argv[0]); /* Verify that the call to _bytes() does not invalidate the _text() pointer */ - assert( z2==(char*)sqlite3_value_text(argv[0]) ); + assert( z2==(char*)tdsqlite3_value_text(argv[0]) ); if( z2 ){ z1 = contextMalloc(context, ((i64)n)+1); if( z1 ){ for(i=0; i<n; i++){ - z1[i] = (char)sqlite3Toupper(z2[i]); + z1[i] = (char)tdsqlite3Toupper(z2[i]); } - sqlite3_result_text(context, z1, n, sqlite3_free); + tdsqlite3_result_text(context, z1, n, tdsqlite3_free); } } } -static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ +static void lowerFunc(tdsqlite3_context *context, int argc, tdsqlite3_value **argv){ char *z1; const char *z2; int i, n; UNUSED_PARAMETER(argc); - z2 = (char*)sqlite3_value_text(argv[0]); - n = sqlite3_value_bytes(argv[0]); + z2 = (char*)tdsqlite3_value_text(argv[0]); + n = tdsqlite3_value_bytes(argv[0]); /* Verify that the call to _bytes() does not invalidate the _text() pointer */ - assert( z2==(char*)sqlite3_value_text(argv[0]) ); + assert( z2==(char*)tdsqlite3_value_text(argv[0]) ); if( z2 ){ z1 = contextMalloc(context, ((i64)n)+1); if( z1 ){ for(i=0; i<n; i++){ - z1[i] = sqlite3Tolower(z2[i]); + z1[i] = tdsqlite3Tolower(z2[i]); } - sqlite3_result_text(context, z1, n, sqlite3_free); + tdsqlite3_result_text(context, z1, n, tdsqlite3_free); } } } @@ -107669,13 +119769,13 @@ static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ ** Implementation of random(). Return a random integer. */ static void randomFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **NotUsed2 + tdsqlite3_value **NotUsed2 ){ sqlite_int64 r; UNUSED_PARAMETER2(NotUsed, NotUsed2); - sqlite3_randomness(sizeof(r), &r); + tdsqlite3_randomness(sizeof(r), &r); if( r<0 ){ /* We need to prevent a random number of 0x8000000000000000 ** (or -9223372036854775808) since when you do abs() of that @@ -107687,7 +119787,7 @@ static void randomFunc( */ r = -(r & LARGEST_INT64); } - sqlite3_result_int64(context, r); + tdsqlite3_result_int64(context, r); } /* @@ -107695,73 +119795,73 @@ static void randomFunc( ** that is N bytes long. */ static void randomBlob( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ - int n; + tdsqlite3_int64 n; unsigned char *p; assert( argc==1 ); UNUSED_PARAMETER(argc); - n = sqlite3_value_int(argv[0]); + n = tdsqlite3_value_int64(argv[0]); if( n<1 ){ n = 1; } p = contextMalloc(context, n); if( p ){ - sqlite3_randomness(n, p); - sqlite3_result_blob(context, (char*)p, n, sqlite3_free); + tdsqlite3_randomness(n, p); + tdsqlite3_result_blob(context, (char*)p, n, tdsqlite3_free); } } /* ** Implementation of the last_insert_rowid() SQL function. The return -** value is the same as the sqlite3_last_insert_rowid() API function. +** value is the same as the tdsqlite3_last_insert_rowid() API function. */ static void last_insert_rowid( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **NotUsed2 + tdsqlite3_value **NotUsed2 ){ - sqlite3 *db = sqlite3_context_db_handle(context); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a - ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface + ** wrapper around the tdsqlite3_last_insert_rowid() C/C++ interface ** function. */ - sqlite3_result_int64(context, sqlite3_last_insert_rowid(db)); + tdsqlite3_result_int64(context, tdsqlite3_last_insert_rowid(db)); } /* ** Implementation of the changes() SQL function. ** ** IMP: R-62073-11209 The changes() SQL function is a wrapper -** around the sqlite3_changes() C/C++ function and hence follows the same +** around the tdsqlite3_changes() C/C++ function and hence follows the same ** rules for counting changes. */ static void changes( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **NotUsed2 + tdsqlite3_value **NotUsed2 ){ - sqlite3 *db = sqlite3_context_db_handle(context); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); UNUSED_PARAMETER2(NotUsed, NotUsed2); - sqlite3_result_int(context, sqlite3_changes(db)); + tdsqlite3_result_int(context, tdsqlite3_changes(db)); } /* ** Implementation of the total_changes() SQL function. The return value is -** the same as the sqlite3_total_changes() API function. +** the same as the tdsqlite3_total_changes() API function. */ static void total_changes( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **NotUsed2 + tdsqlite3_value **NotUsed2 ){ - sqlite3 *db = sqlite3_context_db_handle(context); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-52756-41993 This function is a wrapper around the - ** sqlite3_total_changes() C/C++ interface. */ - sqlite3_result_int(context, sqlite3_total_changes(db)); + ** tdsqlite3_total_changes() C/C++ interface. */ + tdsqlite3_result_int(context, tdsqlite3_total_changes(db)); } /* @@ -107781,10 +119881,10 @@ struct compareInfo { ** the next character is ASCII. */ #if defined(SQLITE_EBCDIC) -# define sqlite3Utf8Read(A) (*((*A)++)) +# define tdsqlite3Utf8Read(A) (*((*A)++)) # define Utf8Read(A) (*(A++)) #else -# define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A)) +# define Utf8Read(A) (A[0]<0x80?*(A++):tdsqlite3Utf8Read(&A)) #endif static const struct compareInfo globInfo = { '*', '?', '[', 0 }; @@ -107796,9 +119896,19 @@ static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 }; static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 }; /* -** Compare two UTF-8 strings for equality where the first string can -** potentially be a "glob" or "like" expression. Return true (1) if they -** are the same and false (0) if they are different. +** Possible error returns from patternMatch() +*/ +#define SQLITE_MATCH 0 +#define SQLITE_NOMATCH 1 +#define SQLITE_NOWILDCARDMATCH 2 + +/* +** Compare two UTF-8 strings for equality where the first string is +** a GLOB or LIKE expression. Return values: +** +** SQLITE_MATCH: Match +** SQLITE_NOMATCH: No match +** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards. ** ** Globbing rules: ** @@ -107848,31 +119958,32 @@ static int patternCompare( ** are also "?" characters, skip those as well, but consume a ** single character of the input string for each "?" skipped */ while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){ - if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ - return 0; + if( c==matchOne && tdsqlite3Utf8Read(&zString)==0 ){ + return SQLITE_NOWILDCARDMATCH; } } if( c==0 ){ - return 1; /* "*" at the end of the pattern matches */ + return SQLITE_MATCH; /* "*" at the end of the pattern matches */ }else if( c==matchOther ){ if( pInfo->matchSet==0 ){ - c = sqlite3Utf8Read(&zPattern); - if( c==0 ) return 0; + c = tdsqlite3Utf8Read(&zPattern); + if( c==0 ) return SQLITE_NOWILDCARDMATCH; }else{ /* "[...]" immediately follows the "*". We have to do a slow ** recursive search in this case, but it is an unusual case. */ assert( matchOther<0x80 ); /* '[' is a single-byte character */ - while( *zString - && patternCompare(&zPattern[-1],zString,pInfo,matchOther)==0 ){ + while( *zString ){ + int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther); + if( bMatch!=SQLITE_NOMATCH ) return bMatch; SQLITE_SKIP_UTF8(zString); } - return *zString!=0; + return SQLITE_NOWILDCARDMATCH; } } /* At this point variable c contains the first character of the ** pattern string past the "*". Search in the input string for the - ** first matching character and recursively contine the match from + ** first matching character and recursively continue the match from ** that point. ** ** For a case-insensitive search, set variable cx to be the same as @@ -107880,48 +119991,56 @@ static int patternCompare( ** c or cx. */ if( c<=0x80 ){ - u32 cx; + char zStop[3]; + int bMatch; if( noCase ){ - cx = sqlite3Toupper(c); - c = sqlite3Tolower(c); + zStop[0] = tdsqlite3Toupper(c); + zStop[1] = tdsqlite3Tolower(c); + zStop[2] = 0; }else{ - cx = c; + zStop[0] = c; + zStop[1] = 0; } - while( (c2 = *(zString++))!=0 ){ - if( c2!=c && c2!=cx ) continue; - if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1; + while(1){ + zString += strcspn((const char*)zString, zStop); + if( zString[0]==0 ) break; + zString++; + bMatch = patternCompare(zPattern,zString,pInfo,matchOther); + if( bMatch!=SQLITE_NOMATCH ) return bMatch; } }else{ + int bMatch; while( (c2 = Utf8Read(zString))!=0 ){ if( c2!=c ) continue; - if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1; + bMatch = patternCompare(zPattern,zString,pInfo,matchOther); + if( bMatch!=SQLITE_NOMATCH ) return bMatch; } } - return 0; + return SQLITE_NOWILDCARDMATCH; } if( c==matchOther ){ if( pInfo->matchSet==0 ){ - c = sqlite3Utf8Read(&zPattern); - if( c==0 ) return 0; + c = tdsqlite3Utf8Read(&zPattern); + if( c==0 ) return SQLITE_NOMATCH; zEscaped = zPattern; }else{ u32 prior_c = 0; int seen = 0; int invert = 0; - c = sqlite3Utf8Read(&zString); - if( c==0 ) return 0; - c2 = sqlite3Utf8Read(&zPattern); + c = tdsqlite3Utf8Read(&zString); + if( c==0 ) return SQLITE_NOMATCH; + c2 = tdsqlite3Utf8Read(&zPattern); if( c2=='^' ){ invert = 1; - c2 = sqlite3Utf8Read(&zPattern); + c2 = tdsqlite3Utf8Read(&zPattern); } if( c2==']' ){ if( c==']' ) seen = 1; - c2 = sqlite3Utf8Read(&zPattern); + c2 = tdsqlite3Utf8Read(&zPattern); } while( c2 && c2!=']' ){ if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ - c2 = sqlite3Utf8Read(&zPattern); + c2 = tdsqlite3Utf8Read(&zPattern); if( c>=prior_c && c<=c2 ) seen = 1; prior_c = 0; }else{ @@ -107930,37 +120049,39 @@ static int patternCompare( } prior_c = c2; } - c2 = sqlite3Utf8Read(&zPattern); + c2 = tdsqlite3Utf8Read(&zPattern); } if( c2==0 || (seen ^ invert)==0 ){ - return 0; + return SQLITE_NOMATCH; } continue; } } c2 = Utf8Read(zString); if( c==c2 ) continue; - if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){ + if( noCase && tdsqlite3Tolower(c)==tdsqlite3Tolower(c2) && c<0x80 && c2<0x80 ){ continue; } if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue; - return 0; + return SQLITE_NOMATCH; } - return *zString==0; + return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH; } /* -** The sqlite3_strglob() interface. +** The tdsqlite3_strglob() interface. Return 0 on a match (like strcmp()) and +** non-zero if there is no match. */ -SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){ - return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[')==0; +SQLITE_API int tdsqlite3_strglob(const char *zGlobPattern, const char *zString){ + return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '['); } /* -** The sqlite3_strlike() interface. +** The tdsqlite3_strlike() interface. Return 0 on a match and non-zero for +** a miss - like strcmp(). */ -SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){ - return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0; +SQLITE_API int tdsqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){ + return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc); } /* @@ -107969,7 +120090,7 @@ SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned ** only. */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_like_count = 0; +SQLITE_API int tdsqlite3_like_count = 0; #endif @@ -107986,62 +120107,61 @@ SQLITE_API int sqlite3_like_count = 0; ** the GLOB operator. */ static void likeFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ const unsigned char *zA, *zB; u32 escape; int nPat; - sqlite3 *db = sqlite3_context_db_handle(context); - struct compareInfo *pInfo = sqlite3_user_data(context); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); + struct compareInfo *pInfo = tdsqlite3_user_data(context); #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS - if( sqlite3_value_type(argv[0])==SQLITE_BLOB - || sqlite3_value_type(argv[1])==SQLITE_BLOB + if( tdsqlite3_value_type(argv[0])==SQLITE_BLOB + || tdsqlite3_value_type(argv[1])==SQLITE_BLOB ){ #ifdef SQLITE_TEST - sqlite3_like_count++; + tdsqlite3_like_count++; #endif - sqlite3_result_int(context, 0); + tdsqlite3_result_int(context, 0); return; } #endif - zB = sqlite3_value_text(argv[0]); - zA = sqlite3_value_text(argv[1]); /* Limit the length of the LIKE or GLOB pattern to avoid problems ** of deep recursion and N*N behavior in patternCompare(). */ - nPat = sqlite3_value_bytes(argv[0]); + nPat = tdsqlite3_value_bytes(argv[0]); testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ - sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); + tdsqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); return; } - assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */ - if( argc==3 ){ /* The escape character string must consist of a single UTF-8 character. ** Otherwise, return an error. */ - const unsigned char *zEsc = sqlite3_value_text(argv[2]); + const unsigned char *zEsc = tdsqlite3_value_text(argv[2]); if( zEsc==0 ) return; - if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ - sqlite3_result_error(context, + if( tdsqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ + tdsqlite3_result_error(context, "ESCAPE expression must be a single character", -1); return; } - escape = sqlite3Utf8Read(&zEsc); + escape = tdsqlite3Utf8Read(&zEsc); }else{ escape = pInfo->matchSet; } + zB = tdsqlite3_value_text(argv[0]); + zA = tdsqlite3_value_text(argv[1]); if( zA && zB ){ #ifdef SQLITE_TEST - sqlite3_like_count++; + tdsqlite3_like_count++; #endif - sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape)); + tdsqlite3_result_int(context, + patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH); } } @@ -108051,14 +120171,14 @@ static void likeFunc( ** arguments are equal to each other. */ static void nullifFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **argv + tdsqlite3_value **argv ){ - CollSeq *pColl = sqlite3GetFuncCollSeq(context); + CollSeq *pColl = tdsqlite3GetFuncCollSeq(context); UNUSED_PARAMETER(NotUsed); - if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ - sqlite3_result_value(context, argv[0]); + if( tdsqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ + tdsqlite3_result_value(context, argv[0]); } } @@ -108067,14 +120187,14 @@ static void nullifFunc( ** of the SQLite library that is running. */ static void versionFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **NotUsed2 + tdsqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-48699-48617 This function is an SQL wrapper around the - ** sqlite3_libversion() C-interface. */ - sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); + ** tdsqlite3_libversion() C-interface. */ + tdsqlite3_result_text(context, tdsqlite3_libversion(), -1, SQLITE_STATIC); } /* @@ -108083,29 +120203,29 @@ static void versionFunc( ** SQLite. */ static void sourceidFunc( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **NotUsed2 + tdsqlite3_value **NotUsed2 ){ UNUSED_PARAMETER2(NotUsed, NotUsed2); /* IMP: R-24470-31136 This function is an SQL wrapper around the - ** sqlite3_sourceid() C interface. */ - sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); + ** tdsqlite3_sourceid() C interface. */ + tdsqlite3_result_text(context, tdsqlite3_sourceid(), -1, SQLITE_STATIC); } /* ** Implementation of the sqlite_log() function. This is a wrapper around -** sqlite3_log(). The return value is NULL. The function exists purely for +** tdsqlite3_log(). The return value is NULL. The function exists purely for ** its side-effects. */ static void errlogFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ UNUSED_PARAMETER(argc); UNUSED_PARAMETER(context); - sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); + tdsqlite3_log(tdsqlite3_value_int(argv[0]), "%s", tdsqlite3_value_text(argv[1])); } /* @@ -108115,19 +120235,19 @@ static void errlogFunc( */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS static void compileoptionusedFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ const char *zOptName; assert( argc==1 ); UNUSED_PARAMETER(argc); /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL - ** function is a wrapper around the sqlite3_compileoption_used() C/C++ + ** function is a wrapper around the tdsqlite3_compileoption_used() C/C++ ** function. */ - if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ - sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); + if( (zOptName = (const char*)tdsqlite3_value_text(argv[0]))!=0 ){ + tdsqlite3_result_int(context, tdsqlite3_compileoption_used(zOptName)); } } #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ @@ -108139,18 +120259,18 @@ static void compileoptionusedFunc( */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS static void compileoptiongetFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ int n; assert( argc==1 ); UNUSED_PARAMETER(argc); /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function - ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. + ** is a wrapper around the tdsqlite3_compileoption_get() C/C++ function. */ - n = sqlite3_value_int(argv[0]); - sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC); + n = tdsqlite3_value_int(argv[0]); + tdsqlite3_result_text(context, tdsqlite3_compileoption_get(n), -1, SQLITE_STATIC); } #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ @@ -108168,31 +120288,31 @@ static const char hexdigits[] = { ** "NULL". Otherwise, the argument is enclosed in single quotes with ** single-quote escapes. */ -static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ +static void quoteFunc(tdsqlite3_context *context, int argc, tdsqlite3_value **argv){ assert( argc==1 ); UNUSED_PARAMETER(argc); - switch( sqlite3_value_type(argv[0]) ){ + switch( tdsqlite3_value_type(argv[0]) ){ case SQLITE_FLOAT: { double r1, r2; char zBuf[50]; - r1 = sqlite3_value_double(argv[0]); - sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1); - sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8); + r1 = tdsqlite3_value_double(argv[0]); + tdsqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1); + tdsqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8); if( r1!=r2 ){ - sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1); + tdsqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1); } - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + tdsqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); break; } case SQLITE_INTEGER: { - sqlite3_result_value(context, argv[0]); + tdsqlite3_result_value(context, argv[0]); break; } case SQLITE_BLOB: { char *zText = 0; - char const *zBlob = sqlite3_value_blob(argv[0]); - int nBlob = sqlite3_value_bytes(argv[0]); - assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ + char const *zBlob = tdsqlite3_value_blob(argv[0]); + int nBlob = tdsqlite3_value_bytes(argv[0]); + assert( zBlob==tdsqlite3_value_blob(argv[0]) ); /* No encoding change */ zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); if( zText ){ int i; @@ -108204,15 +120324,15 @@ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ zText[(nBlob*2)+3] = '\0'; zText[0] = 'X'; zText[1] = '\''; - sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); - sqlite3_free(zText); + tdsqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); + tdsqlite3_free(zText); } break; } case SQLITE_TEXT: { int i,j; u64 n; - const unsigned char *zArg = sqlite3_value_text(argv[0]); + const unsigned char *zArg = tdsqlite3_value_text(argv[0]); char *z; if( zArg==0 ) return; @@ -108228,13 +120348,13 @@ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ } z[j++] = '\''; z[j] = 0; - sqlite3_result_text(context, z, j, sqlite3_free); + tdsqlite3_result_text(context, z, j, tdsqlite3_free); } break; } default: { - assert( sqlite3_value_type(argv[0])==SQLITE_NULL ); - sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC); + assert( tdsqlite3_value_type(argv[0])==SQLITE_NULL ); + tdsqlite3_result_text(context, "NULL", 4, SQLITE_STATIC); break; } } @@ -108245,13 +120365,13 @@ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ ** for the first character of the input string. */ static void unicodeFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ - const unsigned char *z = sqlite3_value_text(argv[0]); + const unsigned char *z = tdsqlite3_value_text(argv[0]); (void)argc; - if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); + if( z && z[0] ) tdsqlite3_result_int(context, tdsqlite3Utf8Read(&z)); } /* @@ -108260,21 +120380,21 @@ static void unicodeFunc( ** is the unicode character for the corresponding integer argument. */ static void charFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ unsigned char *z, *zOut; int i; - zOut = z = sqlite3_malloc64( argc*4+1 ); + zOut = z = tdsqlite3_malloc64( argc*4+1 ); if( z==0 ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); return; } for(i=0; i<argc; i++){ - sqlite3_int64 x; + tdsqlite3_int64 x; unsigned c; - x = sqlite3_value_int64(argv[i]); + x = tdsqlite3_value_int64(argv[i]); if( x<0 || x>0x10ffff ) x = 0xfffd; c = (unsigned)(x & 0x1fffff); if( c<0x00080 ){ @@ -108293,7 +120413,7 @@ static void charFunc( *zOut++ = 0x80 + (u8)(c & 0x3F); } \ } - sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8); + tdsqlite3_result_text64(context, (char*)z, zOut-z, tdsqlite3_free, SQLITE_UTF8); } /* @@ -108301,18 +120421,18 @@ static void charFunc( ** a hexadecimal rendering as text. */ static void hexFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ int i, n; const unsigned char *pBlob; char *zHex, *z; assert( argc==1 ); UNUSED_PARAMETER(argc); - pBlob = sqlite3_value_blob(argv[0]); - n = sqlite3_value_bytes(argv[0]); - assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ + pBlob = tdsqlite3_value_blob(argv[0]); + n = tdsqlite3_value_bytes(argv[0]); + assert( pBlob==tdsqlite3_value_blob(argv[0]) ); /* No encoding change */ z = zHex = contextMalloc(context, ((i64)n)*2 + 1); if( zHex ){ for(i=0; i<n; i++, pBlob++){ @@ -108321,7 +120441,7 @@ static void hexFunc( *(z++) = hexdigits[c&0xf]; } *z = 0; - sqlite3_result_text(context, zHex, n*2, sqlite3_free); + tdsqlite3_result_text(context, zHex, n*2, tdsqlite3_free); } } @@ -108329,19 +120449,19 @@ static void hexFunc( ** The zeroblob(N) function returns a zero-filled blob of size N bytes. */ static void zeroblobFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ i64 n; int rc; assert( argc==1 ); UNUSED_PARAMETER(argc); - n = sqlite3_value_int64(argv[0]); + n = tdsqlite3_value_int64(argv[0]); if( n<0 ) n = 0; - rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */ + rc = tdsqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */ if( rc ){ - sqlite3_result_error_code(context, rc); + tdsqlite3_result_error_code(context, rc); } } @@ -108352,9 +120472,9 @@ static void zeroblobFunc( ** must be exact. Collating sequences are not used. */ static void replaceFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ const unsigned char *zStr; /* The input string A */ const unsigned char *zPattern; /* The pattern string B */ @@ -108366,30 +120486,32 @@ static void replaceFunc( i64 nOut; /* Maximum size of zOut */ int loopLimit; /* Last zStr[] that might match zPattern[] */ int i, j; /* Loop counters */ + unsigned cntExpand; /* Number zOut expansions */ + tdsqlite3 *db = tdsqlite3_context_db_handle(context); assert( argc==3 ); UNUSED_PARAMETER(argc); - zStr = sqlite3_value_text(argv[0]); + zStr = tdsqlite3_value_text(argv[0]); if( zStr==0 ) return; - nStr = sqlite3_value_bytes(argv[0]); - assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */ - zPattern = sqlite3_value_text(argv[1]); + nStr = tdsqlite3_value_bytes(argv[0]); + assert( zStr==tdsqlite3_value_text(argv[0]) ); /* No encoding change */ + zPattern = tdsqlite3_value_text(argv[1]); if( zPattern==0 ){ - assert( sqlite3_value_type(argv[1])==SQLITE_NULL - || sqlite3_context_db_handle(context)->mallocFailed ); + assert( tdsqlite3_value_type(argv[1])==SQLITE_NULL + || tdsqlite3_context_db_handle(context)->mallocFailed ); return; } if( zPattern[0]==0 ){ - assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); - sqlite3_result_value(context, argv[0]); + assert( tdsqlite3_value_type(argv[1])!=SQLITE_NULL ); + tdsqlite3_result_value(context, argv[0]); return; } - nPattern = sqlite3_value_bytes(argv[1]); - assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ - zRep = sqlite3_value_text(argv[2]); + nPattern = tdsqlite3_value_bytes(argv[1]); + assert( zPattern==tdsqlite3_value_text(argv[1]) ); /* No encoding change */ + zRep = tdsqlite3_value_text(argv[2]); if( zRep==0 ) return; - nRep = sqlite3_value_bytes(argv[2]); - assert( zRep==sqlite3_value_text(argv[2]) ); + nRep = tdsqlite3_value_bytes(argv[2]); + assert( zRep==tdsqlite3_value_text(argv[2]) ); nOut = nStr + 1; assert( nOut<SQLITE_MAX_LENGTH ); zOut = contextMalloc(context, (i64)nOut); @@ -108397,38 +120519,45 @@ static void replaceFunc( return; } loopLimit = nStr - nPattern; + cntExpand = 0; for(i=j=0; i<=loopLimit; i++){ if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){ zOut[j++] = zStr[i]; }else{ - u8 *zOld; - sqlite3 *db = sqlite3_context_db_handle(context); - nOut += nRep - nPattern; - testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); - testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); - if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - sqlite3_result_error_toobig(context); - sqlite3_free(zOut); - return; - } - zOld = zOut; - zOut = sqlite3_realloc64(zOut, (int)nOut); - if( zOut==0 ){ - sqlite3_result_error_nomem(context); - sqlite3_free(zOld); - return; + if( nRep>nPattern ){ + nOut += nRep - nPattern; + testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); + testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); + if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ + tdsqlite3_result_error_toobig(context); + tdsqlite3_free(zOut); + return; + } + cntExpand++; + if( (cntExpand&(cntExpand-1))==0 ){ + /* Grow the size of the output buffer only on substitutions + ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */ + u8 *zOld; + zOld = zOut; + zOut = tdsqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1)); + if( zOut==0 ){ + tdsqlite3_result_error_nomem(context); + tdsqlite3_free(zOld); + return; + } + } } memcpy(&zOut[j], zRep, nRep); j += nRep; i += nPattern-1; } } - assert( j+nStr-i+1==nOut ); + assert( j+nStr-i+1<=nOut ); memcpy(&zOut[j], &zStr[i], nStr-i); j += nStr - i; assert( j<=nOut ); zOut[j] = 0; - sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); + tdsqlite3_result_text(context, (char*)zOut, j, tdsqlite3_free); } /* @@ -108436,9 +120565,9 @@ static void replaceFunc( ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. */ static void trimFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ const unsigned char *zIn; /* Input string */ const unsigned char *zCharSet; /* Set of characters to trim */ @@ -108449,13 +120578,13 @@ static void trimFunc( unsigned char **azChar = 0; /* Individual characters in zCharSet */ int nChar; /* Number of characters in zCharSet */ - if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ + if( tdsqlite3_value_type(argv[0])==SQLITE_NULL ){ return; } - zIn = sqlite3_value_text(argv[0]); + zIn = tdsqlite3_value_text(argv[0]); if( zIn==0 ) return; - nIn = sqlite3_value_bytes(argv[0]); - assert( zIn==sqlite3_value_text(argv[0]) ); + nIn = tdsqlite3_value_bytes(argv[0]); + assert( zIn==tdsqlite3_value_text(argv[0]) ); if( argc==1 ){ static const unsigned char lenOne[] = { 1 }; static unsigned char * const azOne[] = { (u8*)" " }; @@ -108463,7 +120592,7 @@ static void trimFunc( aLen = (u8*)lenOne; azChar = (unsigned char **)azOne; zCharSet = 0; - }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ + }else if( (zCharSet = tdsqlite3_value_text(argv[1]))==0 ){ return; }else{ const unsigned char *z; @@ -108484,7 +120613,7 @@ static void trimFunc( } } if( nChar>0 ){ - flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); + flags = SQLITE_PTR_TO_INT(tdsqlite3_user_data(context)); if( flags & 1 ){ while( nIn>0 ){ int len = 0; @@ -108509,10 +120638,10 @@ static void trimFunc( } } if( zCharSet ){ - sqlite3_free(azChar); + tdsqlite3_free(azChar); } } - sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); + tdsqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); } @@ -108521,15 +120650,15 @@ static void trimFunc( ** The "unknown" function is automatically substituted in place of ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used. -** When the "sqlite3" command-line shell is built using this functionality, +** When the "tdsqlite3" command-line shell is built using this functionality, ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries ** involving application-defined functions to be examined in a generic -** sqlite3 shell. +** tdsqlite3 shell. */ static void unknownFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ /* no-op */ } @@ -108548,9 +120677,9 @@ static void unknownFunc( ** soundex encoding of the string X. */ static void soundexFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ char zResult[8]; const u8 *zIn; @@ -108566,12 +120695,12 @@ static void soundexFunc( 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, }; assert( argc==1 ); - zIn = (u8*)sqlite3_value_text(argv[0]); + zIn = (u8*)tdsqlite3_value_text(argv[0]); if( zIn==0 ) zIn = (u8*)""; - for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} + for(i=0; zIn[i] && !tdsqlite3Isalpha(zIn[i]); i++){} if( zIn[i] ){ u8 prevcode = iCode[zIn[i]&0x7f]; - zResult[0] = sqlite3Toupper(zIn[i]); + zResult[0] = tdsqlite3Toupper(zIn[i]); for(j=1; j<4 && zIn[i]; i++){ int code = iCode[zIn[i]&0x7f]; if( code>0 ){ @@ -108587,11 +120716,11 @@ static void soundexFunc( zResult[j++] = '0'; } zResult[j] = 0; - sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); + tdsqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); }else{ /* IMP: R-64894-50321 The string "?000" is returned if the argument ** is NULL or contains no ASCII alphabetic characters. */ - sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); + tdsqlite3_result_text(context, "?000", 4, SQLITE_STATIC); } } #endif /* SQLITE_SOUNDEX */ @@ -108600,28 +120729,28 @@ static void soundexFunc( /* ** A function that loads a shared-library extension then returns NULL. */ -static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ - const char *zFile = (const char *)sqlite3_value_text(argv[0]); +static void loadExt(tdsqlite3_context *context, int argc, tdsqlite3_value **argv){ + const char *zFile = (const char *)tdsqlite3_value_text(argv[0]); const char *zProc; - sqlite3 *db = sqlite3_context_db_handle(context); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); char *zErrMsg = 0; /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc - ** flag is set. See the sqlite3_enable_load_extension() API. + ** flag is set. See the tdsqlite3_enable_load_extension() API. */ if( (db->flags & SQLITE_LoadExtFunc)==0 ){ - sqlite3_result_error(context, "not authorized", -1); + tdsqlite3_result_error(context, "not authorized", -1); return; } if( argc==2 ){ - zProc = (const char *)sqlite3_value_text(argv[1]); + zProc = (const char *)tdsqlite3_value_text(argv[1]); }else{ zProc = 0; } - if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ - sqlite3_result_error(context, zErrMsg, -1); - sqlite3_free(zErrMsg); + if( zFile && tdsqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ + tdsqlite3_result_error(context, zErrMsg, -1); + tdsqlite3_free(zErrMsg); } } #endif @@ -108650,52 +120779,78 @@ struct SumCtx { ** value. TOTAL never fails, but SUM might through an exception if ** it overflows an integer. */ -static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ +static void sumStep(tdsqlite3_context *context, int argc, tdsqlite3_value **argv){ SumCtx *p; int type; assert( argc==1 ); UNUSED_PARAMETER(argc); - p = sqlite3_aggregate_context(context, sizeof(*p)); - type = sqlite3_value_numeric_type(argv[0]); + p = tdsqlite3_aggregate_context(context, sizeof(*p)); + type = tdsqlite3_value_numeric_type(argv[0]); if( p && type!=SQLITE_NULL ){ p->cnt++; if( type==SQLITE_INTEGER ){ - i64 v = sqlite3_value_int64(argv[0]); + i64 v = tdsqlite3_value_int64(argv[0]); p->rSum += v; - if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){ - p->overflow = 1; + if( (p->approx|p->overflow)==0 && tdsqlite3AddInt64(&p->iSum, v) ){ + p->approx = p->overflow = 1; } }else{ - p->rSum += sqlite3_value_double(argv[0]); + p->rSum += tdsqlite3_value_double(argv[0]); p->approx = 1; } } } -static void sumFinalize(sqlite3_context *context){ +#ifndef SQLITE_OMIT_WINDOWFUNC +static void sumInverse(tdsqlite3_context *context, int argc, tdsqlite3_value**argv){ SumCtx *p; - p = sqlite3_aggregate_context(context, 0); + int type; + assert( argc==1 ); + UNUSED_PARAMETER(argc); + p = tdsqlite3_aggregate_context(context, sizeof(*p)); + type = tdsqlite3_value_numeric_type(argv[0]); + /* p is always non-NULL because sumStep() will have been called first + ** to initialize it */ + if( ALWAYS(p) && type!=SQLITE_NULL ){ + assert( p->cnt>0 ); + p->cnt--; + assert( type==SQLITE_INTEGER || p->approx ); + if( type==SQLITE_INTEGER && p->approx==0 ){ + i64 v = tdsqlite3_value_int64(argv[0]); + p->rSum -= v; + p->iSum -= v; + }else{ + p->rSum -= tdsqlite3_value_double(argv[0]); + } + } +} +#else +# define sumInverse 0 +#endif /* SQLITE_OMIT_WINDOWFUNC */ +static void sumFinalize(tdsqlite3_context *context){ + SumCtx *p; + p = tdsqlite3_aggregate_context(context, 0); if( p && p->cnt>0 ){ if( p->overflow ){ - sqlite3_result_error(context,"integer overflow",-1); + tdsqlite3_result_error(context,"integer overflow",-1); }else if( p->approx ){ - sqlite3_result_double(context, p->rSum); + tdsqlite3_result_double(context, p->rSum); }else{ - sqlite3_result_int64(context, p->iSum); + tdsqlite3_result_int64(context, p->iSum); } } } -static void avgFinalize(sqlite3_context *context){ +static void avgFinalize(tdsqlite3_context *context){ SumCtx *p; - p = sqlite3_aggregate_context(context, 0); + p = tdsqlite3_aggregate_context(context, 0); if( p && p->cnt>0 ){ - sqlite3_result_double(context, p->rSum/(double)p->cnt); + tdsqlite3_result_double(context, p->rSum/(double)p->cnt); } } -static void totalFinalize(sqlite3_context *context){ +static void totalFinalize(tdsqlite3_context *context){ SumCtx *p; - p = sqlite3_aggregate_context(context, 0); + p = tdsqlite3_aggregate_context(context, 0); /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ - sqlite3_result_double(context, p ? p->rSum : (double)0); + tdsqlite3_result_double(context, p ? p->rSum : (double)0); } /* @@ -108705,219 +120860,298 @@ static void totalFinalize(sqlite3_context *context){ typedef struct CountCtx CountCtx; struct CountCtx { i64 n; +#ifdef SQLITE_DEBUG + int bInverse; /* True if xInverse() ever called */ +#endif }; /* ** Routines to implement the count() aggregate function. */ -static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ +static void countStep(tdsqlite3_context *context, int argc, tdsqlite3_value **argv){ CountCtx *p; - p = sqlite3_aggregate_context(context, sizeof(*p)); - if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ + p = tdsqlite3_aggregate_context(context, sizeof(*p)); + if( (argc==0 || SQLITE_NULL!=tdsqlite3_value_type(argv[0])) && p ){ p->n++; } #ifndef SQLITE_OMIT_DEPRECATED - /* The sqlite3_aggregate_count() function is deprecated. But just to make + /* The tdsqlite3_aggregate_count() function is deprecated. But just to make ** sure it still operates correctly, verify that its count agrees with our ** internal count when using count(*) and when the total count can be ** expressed as a 32-bit integer. */ - assert( argc==1 || p==0 || p->n>0x7fffffff - || p->n==sqlite3_aggregate_count(context) ); + assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse + || p->n==tdsqlite3_aggregate_count(context) ); #endif } -static void countFinalize(sqlite3_context *context){ +static void countFinalize(tdsqlite3_context *context){ CountCtx *p; - p = sqlite3_aggregate_context(context, 0); - sqlite3_result_int64(context, p ? p->n : 0); + p = tdsqlite3_aggregate_context(context, 0); + tdsqlite3_result_int64(context, p ? p->n : 0); } +#ifndef SQLITE_OMIT_WINDOWFUNC +static void countInverse(tdsqlite3_context *ctx, int argc, tdsqlite3_value **argv){ + CountCtx *p; + p = tdsqlite3_aggregate_context(ctx, sizeof(*p)); + /* p is always non-NULL since countStep() will have been called first */ + if( (argc==0 || SQLITE_NULL!=tdsqlite3_value_type(argv[0])) && ALWAYS(p) ){ + p->n--; +#ifdef SQLITE_DEBUG + p->bInverse = 1; +#endif + } +} +#else +# define countInverse 0 +#endif /* SQLITE_OMIT_WINDOWFUNC */ /* ** Routines to implement min() and max() aggregate functions. */ static void minmaxStep( - sqlite3_context *context, + tdsqlite3_context *context, int NotUsed, - sqlite3_value **argv + tdsqlite3_value **argv ){ Mem *pArg = (Mem *)argv[0]; Mem *pBest; UNUSED_PARAMETER(NotUsed); - pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); + pBest = (Mem *)tdsqlite3_aggregate_context(context, sizeof(*pBest)); if( !pBest ) return; - if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ - if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); + if( tdsqlite3_value_type(pArg)==SQLITE_NULL ){ + if( pBest->flags ) tdsqlite3SkipAccumulatorLoad(context); }else if( pBest->flags ){ int max; int cmp; - CollSeq *pColl = sqlite3GetFuncCollSeq(context); + CollSeq *pColl = tdsqlite3GetFuncCollSeq(context); /* This step function is used for both the min() and max() aggregates, ** the only difference between the two being that the sense of the ** comparison is inverted. For the max() aggregate, the - ** sqlite3_user_data() function returns (void *)-1. For min() it - ** returns (void *)db, where db is the sqlite3* database pointer. + ** tdsqlite3_user_data() function returns (void *)-1. For min() it + ** returns (void *)db, where db is the tdsqlite3* database pointer. ** Therefore the next statement sets variable 'max' to 1 for the max() ** aggregate, or 0 for min(). */ - max = sqlite3_user_data(context)!=0; - cmp = sqlite3MemCompare(pBest, pArg, pColl); + max = tdsqlite3_user_data(context)!=0; + cmp = tdsqlite3MemCompare(pBest, pArg, pColl); if( (max && cmp<0) || (!max && cmp>0) ){ - sqlite3VdbeMemCopy(pBest, pArg); + tdsqlite3VdbeMemCopy(pBest, pArg); }else{ - sqlite3SkipAccumulatorLoad(context); + tdsqlite3SkipAccumulatorLoad(context); } }else{ - pBest->db = sqlite3_context_db_handle(context); - sqlite3VdbeMemCopy(pBest, pArg); + pBest->db = tdsqlite3_context_db_handle(context); + tdsqlite3VdbeMemCopy(pBest, pArg); } } -static void minMaxFinalize(sqlite3_context *context){ - sqlite3_value *pRes; - pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); +static void minMaxValueFinalize(tdsqlite3_context *context, int bValue){ + tdsqlite3_value *pRes; + pRes = (tdsqlite3_value *)tdsqlite3_aggregate_context(context, 0); if( pRes ){ if( pRes->flags ){ - sqlite3_result_value(context, pRes); + tdsqlite3_result_value(context, pRes); } - sqlite3VdbeMemRelease(pRes); + if( bValue==0 ) tdsqlite3VdbeMemRelease(pRes); } } +#ifndef SQLITE_OMIT_WINDOWFUNC +static void minMaxValue(tdsqlite3_context *context){ + minMaxValueFinalize(context, 1); +} +#else +# define minMaxValue 0 +#endif /* SQLITE_OMIT_WINDOWFUNC */ +static void minMaxFinalize(tdsqlite3_context *context){ + minMaxValueFinalize(context, 0); +} /* ** group_concat(EXPR, ?SEPARATOR?) */ static void groupConcatStep( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ const char *zVal; StrAccum *pAccum; const char *zSep; int nVal, nSep; assert( argc==1 || argc==2 ); - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); + if( tdsqlite3_value_type(argv[0])==SQLITE_NULL ) return; + pAccum = (StrAccum*)tdsqlite3_aggregate_context(context, sizeof(*pAccum)); if( pAccum ){ - sqlite3 *db = sqlite3_context_db_handle(context); + tdsqlite3 *db = tdsqlite3_context_db_handle(context); int firstTerm = pAccum->mxAlloc==0; pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; if( !firstTerm ){ if( argc==2 ){ - zSep = (char*)sqlite3_value_text(argv[1]); - nSep = sqlite3_value_bytes(argv[1]); + zSep = (char*)tdsqlite3_value_text(argv[1]); + nSep = tdsqlite3_value_bytes(argv[1]); }else{ zSep = ","; nSep = 1; } - if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep); + if( zSep ) tdsqlite3_str_append(pAccum, zSep, nSep); } - zVal = (char*)sqlite3_value_text(argv[0]); - nVal = sqlite3_value_bytes(argv[0]); - if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal); + zVal = (char*)tdsqlite3_value_text(argv[0]); + nVal = tdsqlite3_value_bytes(argv[0]); + if( zVal ) tdsqlite3_str_append(pAccum, zVal, nVal); } } -static void groupConcatFinalize(sqlite3_context *context){ +#ifndef SQLITE_OMIT_WINDOWFUNC +static void groupConcatInverse( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + int n; StrAccum *pAccum; - pAccum = sqlite3_aggregate_context(context, 0); + assert( argc==1 || argc==2 ); + if( tdsqlite3_value_type(argv[0])==SQLITE_NULL ) return; + pAccum = (StrAccum*)tdsqlite3_aggregate_context(context, sizeof(*pAccum)); + /* pAccum is always non-NULL since groupConcatStep() will have always + ** run frist to initialize it */ + if( ALWAYS(pAccum) ){ + n = tdsqlite3_value_bytes(argv[0]); + if( argc==2 ){ + n += tdsqlite3_value_bytes(argv[1]); + }else{ + n++; + } + if( n>=(int)pAccum->nChar ){ + pAccum->nChar = 0; + }else{ + pAccum->nChar -= n; + memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar); + } + if( pAccum->nChar==0 ) pAccum->mxAlloc = 0; + } +} +#else +# define groupConcatInverse 0 +#endif /* SQLITE_OMIT_WINDOWFUNC */ +static void groupConcatFinalize(tdsqlite3_context *context){ + StrAccum *pAccum; + pAccum = tdsqlite3_aggregate_context(context, 0); + if( pAccum ){ + if( pAccum->accError==SQLITE_TOOBIG ){ + tdsqlite3_result_error_toobig(context); + }else if( pAccum->accError==SQLITE_NOMEM ){ + tdsqlite3_result_error_nomem(context); + }else{ + tdsqlite3_result_text(context, tdsqlite3StrAccumFinish(pAccum), -1, + tdsqlite3_free); + } + } +} +#ifndef SQLITE_OMIT_WINDOWFUNC +static void groupConcatValue(tdsqlite3_context *context){ + tdsqlite3_str *pAccum; + pAccum = (tdsqlite3_str*)tdsqlite3_aggregate_context(context, 0); if( pAccum ){ - if( pAccum->accError==STRACCUM_TOOBIG ){ - sqlite3_result_error_toobig(context); - }else if( pAccum->accError==STRACCUM_NOMEM ){ - sqlite3_result_error_nomem(context); + if( pAccum->accError==SQLITE_TOOBIG ){ + tdsqlite3_result_error_toobig(context); + }else if( pAccum->accError==SQLITE_NOMEM ){ + tdsqlite3_result_error_nomem(context); }else{ - sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, - sqlite3_free); + const char *zText = tdsqlite3_str_value(pAccum); + tdsqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); } } } +#else +# define groupConcatValue 0 +#endif /* SQLITE_OMIT_WINDOWFUNC */ /* ** This routine does per-connection function registration. Most ** of the built-in functions above are part of the global function set. ** This routine only deals with those that are not global. */ -SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){ - int rc = sqlite3_overload_function(db, "MATCH", 2); -/* BEGIN SQLCIPHER */ -#ifdef SQLITE_HAS_CODEC -#ifndef OMIT_EXPORT - extern void sqlcipher_exportFunc(sqlite3_context *, int, sqlite3_value **); -#endif -#endif -/* END SQLCIPHER */ +SQLITE_PRIVATE void tdsqlite3RegisterPerConnectionBuiltinFunctions(tdsqlite3 *db){ + int rc = tdsqlite3_overload_function(db, "MATCH", 2); assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); } /* BEGIN SQLCIPHER */ #ifdef SQLITE_HAS_CODEC #ifndef OMIT_EXPORT - sqlite3CreateFunc(db, "sqlcipher_export", 1, SQLITE_TEXT, 0, sqlcipher_exportFunc, 0, 0, 0); + { + tdsqlite3CreateFunc(db, "sqlcipher_export", -1, SQLITE_TEXT, 0, sqlcipher_exportFunc, 0, 0, 0, 0, 0); + } +#endif +#ifdef SQLCIPHER_EXT +#include "sqlcipher_funcs_init.h" #endif #endif /* END SQLCIPHER */ } /* -** Set the LIKEOPT flag on the 2-argument function with the given name. -*/ -static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){ - FuncDef *pDef; - pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0); - if( ALWAYS(pDef) ){ - pDef->funcFlags |= flagVal; - } -} - -/* -** Register the built-in LIKE and GLOB functions. The caseSensitive +** Re-register the built-in LIKE functions. The caseSensitive ** parameter determines whether or not the LIKE operator is case -** sensitive. GLOB is always case sensitive. +** sensitive. */ -SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ +SQLITE_PRIVATE void tdsqlite3RegisterLikeFunctions(tdsqlite3 *db, int caseSensitive){ struct compareInfo *pInfo; + int flags; if( caseSensitive ){ pInfo = (struct compareInfo*)&likeInfoAlt; + flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE; }else{ pInfo = (struct compareInfo*)&likeInfoNorm; + flags = SQLITE_FUNC_LIKE; } - sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); - sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); - sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, - (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0); - setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE); - setLikeOptFlag(db, "like", - caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE); + tdsqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0); + tdsqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0); + tdsqlite3FindFunction(db, "like", 2, SQLITE_UTF8, 0)->funcFlags |= flags; + tdsqlite3FindFunction(db, "like", 3, SQLITE_UTF8, 0)->funcFlags |= flags; } /* ** pExpr points to an expression which implements a function. If ** it is appropriate to apply the LIKE optimization to that function -** then set aWc[0] through aWc[2] to the wildcard characters and -** return TRUE. If the function is not a LIKE-style function then -** return FALSE. +** then set aWc[0] through aWc[2] to the wildcard characters and the +** escape character and then return TRUE. If the function is not a +** LIKE-style function then return FALSE. +** +** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE +** operator if c is a string literal that is exactly one byte in length. +** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is +** no ESCAPE clause. ** ** *pIsNocase is set to true if uppercase and lowercase are equivalent for ** the function (default for LIKE). If the function makes the distinction ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to ** false. */ -SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ +SQLITE_PRIVATE int tdsqlite3IsLikeFunction(tdsqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ FuncDef *pDef; - if( pExpr->op!=TK_FUNCTION - || !pExpr->x.pList - || pExpr->x.pList->nExpr!=2 - ){ + int nExpr; + if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){ return 0; } assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0); + nExpr = pExpr->x.pList->nExpr; + pDef = tdsqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0); if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ return 0; } + if( nExpr<3 ){ + aWc[3] = 0; + }else{ + Expr *pEscape = pExpr->x.pList->a[2].pExpr; + char *zEscape; + if( pEscape->op!=TK_STRING ) return 0; + zEscape = pEscape->u.zToken; + if( zEscape[0]==0 || zEscape[1]!=0 ) return 0; + aWc[3] = zEscape[0]; + } /* The memcpy() statement assumes that the wildcard characters are ** the first three statements in the compareInfo structure. The @@ -108934,11 +121168,11 @@ SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocas /* ** All of the FuncDef structures in the aBuiltinFunc[] array above ** to the global function hash table. This occurs at start-time (as -** a consequence of calling sqlite3_initialize()). +** a consequence of calling tdsqlite3_initialize()). ** ** After this routine runs */ -SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ +SQLITE_PRIVATE void tdsqlite3RegisterBuiltinFunctions(void){ /* ** The following array holds FuncDef structures for all of the functions ** defined in this file. @@ -108950,23 +121184,35 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ ** For peak efficiency, put the most frequently used function last. */ static FuncDef aBuiltinFunc[] = { +/***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/ + TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0), + TEST_FUNC(expr_compare, 2, INLINEFUNC_expr_compare, 0), + TEST_FUNC(expr_implies_expr, 2, INLINEFUNC_expr_implies_expr, 0), +#ifdef SQLITE_DEBUG + TEST_FUNC(affinity, 1, INLINEFUNC_affinity, 0), +#endif +/***** Regular functions *****/ #ifdef SQLITE_SOUNDEX FUNCTION(soundex, 1, 0, 0, soundexFunc ), #endif #ifndef SQLITE_OMIT_LOAD_EXTENSION - VFUNCTION(load_extension, 1, 0, 0, loadExt ), - VFUNCTION(load_extension, 2, 0, 0, loadExt ), + SFUNCTION(load_extension, 1, 0, 0, loadExt ), + SFUNCTION(load_extension, 2, 0, 0, loadExt ), #endif #if SQLITE_USER_AUTHENTICATION - FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ), + FUNCTION(sqlite_crypt, 2, 0, 0, tdsqlite3CryptFunc ), #endif #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ - FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), - FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), - FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), + INLINE_FUNC(unlikely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), + INLINE_FUNC(likelihood, 2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), + INLINE_FUNC(likely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), +#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC + FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET| + SQLITE_FUNC_TYPEOF), +#endif FUNCTION(ltrim, 1, 1, 0, trimFunc ), FUNCTION(ltrim, 2, 1, 0, trimFunc ), FUNCTION(rtrim, 1, 2, 0, trimFunc ), @@ -108975,11 +121221,11 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ FUNCTION(trim, 2, 3, 0, trimFunc ), FUNCTION(min, -1, 0, 1, minmaxFunc ), FUNCTION(min, 0, 0, 1, 0 ), - AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize, + WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, SQLITE_FUNC_MINMAX ), FUNCTION(max, -1, 1, 1, minmaxFunc ), FUNCTION(max, 0, 1, 1, 0 ), - AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize, + WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, SQLITE_FUNC_MINMAX ), FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH), @@ -108995,7 +121241,7 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ FUNCTION(upper, 1, 0, 0, upperFunc ), FUNCTION(lower, 1, 0, 0, lowerFunc ), FUNCTION(hex, 1, 0, 0, hexFunc ), - FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), + INLINE_FUNC(ifnull, 2, INLINEFUNC_coalesce, SQLITE_FUNC_COALESCE), VFUNCTION(random, 0, 0, 0, randomFunc ), VFUNCTION(randomblob, 1, 0, 0, randomBlob ), FUNCTION(nullif, 2, 0, 1, nullifFunc ), @@ -109010,14 +121256,17 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ), FUNCTION(substr, 2, 0, 0, substrFunc ), FUNCTION(substr, 3, 0, 0, substrFunc ), - AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ), - AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ), - AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ), - AGGREGATE2(count, 0, 0, 0, countStep, countFinalize, - SQLITE_FUNC_COUNT ), - AGGREGATE(count, 1, 0, 0, countStep, countFinalize ), - AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize), - AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize), + WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0), + WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0), + WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0), + WAGGREGATE(count, 0,0,0, countStep, + countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT ), + WAGGREGATE(count, 1,0,0, countStep, + countFinalize, countFinalize, countInverse, 0 ), + WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep, + groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), + WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep, + groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), #ifdef SQLITE_CASE_SENSITIVE_LIKE @@ -109032,16 +121281,14 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ #endif FUNCTION(coalesce, 1, 0, 0, 0 ), FUNCTION(coalesce, 0, 0, 0, 0 ), - FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), + INLINE_FUNC(coalesce, -1, INLINEFUNC_coalesce, SQLITE_FUNC_COALESCE), }; #ifndef SQLITE_OMIT_ALTERTABLE - sqlite3AlterFunctions(); -#endif -#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4) - sqlite3AnalyzeFunctions(); + tdsqlite3AlterFunctions(); #endif - sqlite3RegisterDateTimeFunctions(); - sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc)); + tdsqlite3WindowFunctions(); + tdsqlite3RegisterDateTimeFunctions(); + tdsqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc)); #if 0 /* Enable to print out how the built-in functions are hashed */ { @@ -109049,8 +121296,8 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ FuncDef *p; for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){ printf("FUNC-HASH %02d:", i); - for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){ - int n = sqlite3Strlen30(p->zName); + for(p=tdsqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){ + int n = tdsqlite3Strlen30(p->zName); int h = p->zName[0] + n; printf(" %s(%d)", p->zName, h); } @@ -109175,16 +121422,16 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ ** coding an INSERT operation. The functions used by the UPDATE/DELETE ** generation code to query for this information are: ** -** sqlite3FkRequired() - Test to see if FK processing is required. -** sqlite3FkOldmask() - Query for the set of required old.* columns. +** tdsqlite3FkRequired() - Test to see if FK processing is required. +** tdsqlite3FkOldmask() - Query for the set of required old.* columns. ** ** ** Externally accessible module functions ** -------------------------------------- ** -** sqlite3FkCheck() - Check for foreign key violations. -** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions. -** sqlite3FkDelete() - Delete an FKey structure. +** tdsqlite3FkCheck() - Check for foreign key violations. +** tdsqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions. +** tdsqlite3FkDelete() - Delete an FKey structure. */ /* @@ -109244,7 +121491,7 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ ** into pParse. If an OOM error occurs, non-zero is returned and the ** pParse->db->mallocFailed flag is set. */ -SQLITE_PRIVATE int sqlite3FkLocateIndex( +SQLITE_PRIVATE int tdsqlite3FkLocateIndex( Parse *pParse, /* Parse context to store any error in */ Table *pParent, /* Parent table of FK constraint pFKey */ FKey *pFKey, /* Foreign key to find index for */ @@ -109279,17 +121526,17 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex( */ if( pParent->iPKey>=0 ){ if( !zKey ) return 0; - if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0; + if( !tdsqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0; } }else if( paiCol ){ assert( nCol>1 ); - aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int)); + aiCol = (int *)tdsqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int)); if( !aiCol ) return 1; *paiCol = aiCol; } for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){ - if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){ + if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){ /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number ** of columns. If each indexed column corresponds to a foreign key ** column of pFKey, then this index is a winner. */ @@ -109322,12 +121569,12 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex( ** the default collation sequence for the column, this index is ** unusable. Bail out early in this case. */ zDfltColl = pParent->aCol[iCol].zColl; - if( !zDfltColl ) zDfltColl = sqlite3StrBINARY; - if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break; + if( !zDfltColl ) zDfltColl = tdsqlite3StrBINARY; + if( tdsqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break; zIdxCol = pParent->aCol[iCol].zName; for(j=0; j<nCol; j++){ - if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){ + if( tdsqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){ if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom; break; } @@ -109341,11 +121588,11 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex( if( !pIdx ){ if( !pParse->disableTriggers ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "foreign key mismatch - \"%w\" referencing \"%w\"", pFKey->pFrom->zName, pFKey->zTo); } - sqlite3DbFree(pParse->db, aiCol); + tdsqlite3DbFree(pParse->db, aiCol); return 1; } @@ -109391,9 +121638,15 @@ static void fkLookupParent( int isIgnore /* If true, pretend pTab contains all NULL values */ ){ int i; /* Iterator variable */ - Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */ + Vdbe *v = tdsqlite3GetVdbe(pParse); /* Vdbe to add code to */ int iCur = pParse->nTab - 1; /* Cursor number to use */ - int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */ + int iOk = tdsqlite3VdbeMakeLabel(pParse); /* jump here if parent key found */ + + tdsqlite3VdbeVerifyAbortable(v, + (!pFKey->isDeferred + && !(pParse->db->flags & SQLITE_DeferFKs) + && !pParse->pToplevel + && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore); /* If nIncr is less than zero, then check at runtime if there are any ** outstanding constraints to resolve. If there are not, there is no need @@ -109403,12 +121656,12 @@ static void fkLookupParent( ** any are, then the constraint is considered satisfied. No need to ** search for a matching row in the parent table. */ if( nIncr<0 ){ - sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk); + tdsqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk); VdbeCoverage(v); } for(i=0; i<pFKey->nCol; i++){ - int iReg = aiCol[i] + regData + 1; - sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v); + int iReg = tdsqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1; + tdsqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v); } if( isIgnore==0 ){ @@ -109416,15 +121669,16 @@ static void fkLookupParent( /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY ** column of the parent table (table pTab). */ int iMustBeInt; /* Address of MustBeInt instruction */ - int regTemp = sqlite3GetTempReg(pParse); + int regTemp = tdsqlite3GetTempReg(pParse); /* Invoke MustBeInt to coerce the child key value to an integer (i.e. ** apply the affinity of the parent key). If this fails, then there ** is no matching parent key. Before using MustBeInt, make a copy of ** the value. Otherwise, the value inserted into the child key column ** will have INTEGER affinity applied to it, which may not be correct. */ - sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp); - iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0); + tdsqlite3VdbeAddOp2(v, OP_SCopy, + tdsqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp); + iMustBeInt = tdsqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0); VdbeCoverage(v); /* If the parent table is the same as the child table, and we are about @@ -109432,25 +121686,27 @@ static void fkLookupParent( ** then check if the row being inserted matches itself. If so, do not ** increment the constraint-counter. */ if( pTab==pFKey->pFrom && nIncr==1 ){ - sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); + tdsqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v); + tdsqlite3VdbeChangeP5(v, SQLITE_NOTNULL); } - sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v); - sqlite3VdbeGoto(v, iOk); - sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); - sqlite3VdbeJumpHere(v, iMustBeInt); - sqlite3ReleaseTempReg(pParse, regTemp); + tdsqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); + tdsqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v); + tdsqlite3VdbeGoto(v, iOk); + tdsqlite3VdbeJumpHere(v, tdsqlite3VdbeCurrentAddr(v)-2); + tdsqlite3VdbeJumpHere(v, iMustBeInt); + tdsqlite3ReleaseTempReg(pParse, regTemp); }else{ int nCol = pFKey->nCol; - int regTemp = sqlite3GetTempRange(pParse, nCol); - int regRec = sqlite3GetTempReg(pParse); + int regTemp = tdsqlite3GetTempRange(pParse, nCol); + int regRec = tdsqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); + tdsqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); + tdsqlite3VdbeSetP4KeyInfo(pParse, pIdx); for(i=0; i<nCol; i++){ - sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i); + tdsqlite3VdbeAddOp2(v, OP_Copy, + tdsqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData, + regTemp+i); } /* If the parent table is the same as the child table, and we are about @@ -109464,28 +121720,31 @@ static void fkLookupParent( ** none of the child key values are). */ if( pTab==pFKey->pFrom && nIncr==1 ){ - int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1; + int iJump = tdsqlite3VdbeCurrentAddr(v) + nCol + 1; for(i=0; i<nCol; i++){ - int iChild = aiCol[i]+1+regData; - int iParent = pIdx->aiColumn[i]+1+regData; + int iChild = tdsqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + +1+regData; + int iParent = 1+regData; + iParent += tdsqlite3TableColumnToStorage(pIdx->pTable, + pIdx->aiColumn[i]); assert( pIdx->aiColumn[i]>=0 ); assert( aiCol[i]!=pTab->iPKey ); if( pIdx->aiColumn[i]==pTab->iPKey ){ /* The parent key is a composite key that includes the IPK column */ iParent = regData; } - sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); + tdsqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v); + tdsqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); } - sqlite3VdbeGoto(v, iOk); + tdsqlite3VdbeGoto(v, iOk); } - sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec, - sqlite3IndexAffinityStr(pParse->db,pIdx), nCol); - sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v); + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec, + tdsqlite3IndexAffinityStr(pParse->db,pIdx), nCol); + tdsqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, regRec); - sqlite3ReleaseTempRange(pParse, regTemp, nCol); + tdsqlite3ReleaseTempReg(pParse, regRec); + tdsqlite3ReleaseTempRange(pParse, regTemp, nCol); } } @@ -109498,17 +121757,17 @@ static void fkLookupParent( ** incrementing a counter. This is necessary as the VM code is being ** generated for will not open a statement transaction. */ assert( nIncr==1 ); - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, + tdsqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, OE_Abort, 0, P4_STATIC, P5_ConstraintFK); }else{ if( nIncr>0 && pFKey->isDeferred==0 ){ - sqlite3MayAbort(pParse); + tdsqlite3MayAbort(pParse); } - sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); + tdsqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); } - sqlite3VdbeResolveLabel(v, iOk); - sqlite3VdbeAddOp1(v, OP_Close, iCur); + tdsqlite3VdbeResolveLabel(v, iOk); + tdsqlite3VdbeAddOp1(v, OP_Close, iCur); } @@ -109529,20 +121788,20 @@ static Expr *exprTableRegister( Expr *pExpr; Column *pCol; const char *zColl; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; - pExpr = sqlite3Expr(db, TK_REGISTER, 0); + pExpr = tdsqlite3Expr(db, TK_REGISTER, 0); if( pExpr ){ if( iCol>=0 && iCol!=pTab->iPKey ){ pCol = &pTab->aCol[iCol]; - pExpr->iTable = regBase + iCol + 1; - pExpr->affinity = pCol->affinity; + pExpr->iTable = regBase + tdsqlite3TableColumnToStorage(pTab,iCol) + 1; + pExpr->affExpr = pCol->affinity; zColl = pCol->zColl; if( zColl==0 ) zColl = db->pDfltColl->zName; - pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl); + pExpr = tdsqlite3ExprAddCollateString(pParse, pExpr, zColl); }else{ pExpr->iTable = regBase; - pExpr->affinity = SQLITE_AFF_INTEGER; + pExpr->affExpr = SQLITE_AFF_INTEGER; } } return pExpr; @@ -109553,14 +121812,14 @@ static Expr *exprTableRegister( ** has cursor iCur. */ static Expr *exprTableColumn( - sqlite3 *db, /* The database connection */ + tdsqlite3 *db, /* The database connection */ Table *pTab, /* The table whose column is desired */ int iCursor, /* The open cursor on the table */ i16 iCol /* The column that is wanted */ ){ - Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0); + Expr *pExpr = tdsqlite3Expr(db, TK_COLUMN, 0); if( pExpr ){ - pExpr->pTab = pTab; + pExpr->y.pTab = pTab; pExpr->iTable = iCursor; pExpr->iColumn = iCol; } @@ -109609,13 +121868,13 @@ static void fkScanChildren( int regData, /* Parent row data starts here */ int nIncr /* Amount to increment deferred counter by */ ){ - sqlite3 *db = pParse->db; /* Database handle */ + tdsqlite3 *db = pParse->db; /* Database handle */ int i; /* Iterator variable */ Expr *pWhere = 0; /* WHERE clause to scan with */ NameContext sNameContext; /* Context used to resolve WHERE clause */ - WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */ + WhereInfo *pWInfo; /* Context used by tdsqlite3WhereXXX() */ int iFkIfZero = 0; /* Address of OP_FkIfZero */ - Vdbe *v = sqlite3GetVdbe(pParse); + Vdbe *v = tdsqlite3GetVdbe(pParse); assert( pIdx==0 || pIdx->pTable==pTab ); assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol ); @@ -109623,7 +121882,7 @@ static void fkScanChildren( assert( pIdx!=0 || HasRowid(pTab) ); if( nIncr<0 ){ - iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0); + iFkIfZero = tdsqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0); VdbeCoverage(v); } @@ -109647,9 +121906,9 @@ static void fkScanChildren( iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; assert( iCol>=0 ); zCol = pFKey->pFrom->aCol[iCol].zName; - pRight = sqlite3Expr(db, TK_ID, zCol); - pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); - pWhere = sqlite3ExprAnd(db, pWhere, pEq); + pRight = tdsqlite3Expr(db, TK_ID, zCol); + pEq = tdsqlite3PExpr(pParse, TK_EQ, pLeft, pRight); + pWhere = tdsqlite3ExprAnd(pParse, pWhere, pEq); } /* If the child table is the same as the parent table, then add terms @@ -109660,8 +121919,11 @@ static void fkScanChildren( ** NOT( $current_a==a AND $current_b==b AND ... ) ** ** The first form is used for rowid tables. The second form is used - ** for WITHOUT ROWID tables. In the second form, the primary key is - ** (a,b,...) + ** for WITHOUT ROWID tables. In the second form, the *parent* key is + ** (a,b,...). Either the parent or primary key could be used to + ** uniquely identify the current row, but the parent key is more convenient + ** as the required values have already been loaded into registers + ** by the caller. */ if( pTab==pFKey->pFrom && nIncr>0 ){ Expr *pNe; /* Expression (pLeft != pRight) */ @@ -109670,43 +121932,44 @@ static void fkScanChildren( if( HasRowid(pTab) ){ pLeft = exprTableRegister(pParse, pTab, regData, -1); pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1); - pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0); + pNe = tdsqlite3PExpr(pParse, TK_NE, pLeft, pRight); }else{ Expr *pEq, *pAll = 0; - Index *pPk = sqlite3PrimaryKeyIndex(pTab); assert( pIdx!=0 ); - for(i=0; i<pPk->nKeyCol; i++){ + for(i=0; i<pIdx->nKeyCol; i++){ i16 iCol = pIdx->aiColumn[i]; assert( iCol>=0 ); pLeft = exprTableRegister(pParse, pTab, regData, iCol); - pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol); - pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0); - pAll = sqlite3ExprAnd(db, pAll, pEq); + pRight = tdsqlite3Expr(db, TK_ID, pTab->aCol[iCol].zName); + pEq = tdsqlite3PExpr(pParse, TK_IS, pLeft, pRight); + pAll = tdsqlite3ExprAnd(pParse, pAll, pEq); } - pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0); + pNe = tdsqlite3PExpr(pParse, TK_NOT, pAll, 0); } - pWhere = sqlite3ExprAnd(db, pWhere, pNe); + pWhere = tdsqlite3ExprAnd(pParse, pWhere, pNe); } /* Resolve the references in the WHERE clause. */ memset(&sNameContext, 0, sizeof(NameContext)); sNameContext.pSrcList = pSrc; sNameContext.pParse = pParse; - sqlite3ResolveExprNames(&sNameContext, pWhere); + tdsqlite3ResolveExprNames(&sNameContext, pWhere); /* Create VDBE to loop through the entries in pSrc that match the WHERE ** clause. For each row found, increment either the deferred or immediate ** foreign key constraint counter. */ - pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0); - sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); - if( pWInfo ){ - sqlite3WhereEnd(pWInfo); + if( pParse->nErr==0 ){ + pWInfo = tdsqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0); + tdsqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); + if( pWInfo ){ + tdsqlite3WhereEnd(pWInfo); + } } /* Clean up the WHERE clause constructed above. */ - sqlite3ExprDelete(db, pWhere); + tdsqlite3ExprDelete(db, pWhere); if( iFkIfZero ){ - sqlite3VdbeJumpHere(v, iFkIfZero); + tdsqlite3VdbeJumpHere(v, iFkIfZero); } } @@ -109724,8 +121987,8 @@ static void fkScanChildren( ** NULL pointer (as there are no FK constraints for which t2 is the parent ** table). */ -SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){ - return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName); +SQLITE_PRIVATE FKey *tdsqlite3FkReferences(Table *pTab){ + return (FKey *)tdsqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName); } /* @@ -109736,14 +121999,14 @@ SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){ ** The Trigger structure or any of its sub-components may be allocated from ** the lookaside buffer belonging to database handle dbMem. */ -static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ +static void fkTriggerDelete(tdsqlite3 *dbMem, Trigger *p){ if( p ){ TriggerStep *pStep = p->step_list; - sqlite3ExprDelete(dbMem, pStep->pWhere); - sqlite3ExprListDelete(dbMem, pStep->pExprList); - sqlite3SelectDelete(dbMem, pStep->pSelect); - sqlite3ExprDelete(dbMem, p->pWhen); - sqlite3DbFree(dbMem, p); + tdsqlite3ExprDelete(dbMem, pStep->pWhere); + tdsqlite3ExprListDelete(dbMem, pStep->pExprList); + tdsqlite3SelectDelete(dbMem, pStep->pSelect); + tdsqlite3ExprDelete(dbMem, p->pWhen); + tdsqlite3DbFree(dbMem, p); } } @@ -109764,14 +122027,15 @@ static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ ** the table from the database. Triggers are disabled while running this ** DELETE, but foreign key actions are not. */ -SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){ - sqlite3 *db = pParse->db; - if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){ +SQLITE_PRIVATE void tdsqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){ + tdsqlite3 *db = pParse->db; + if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){ int iSkip = 0; - Vdbe *v = sqlite3GetVdbe(pParse); + Vdbe *v = tdsqlite3GetVdbe(pParse); assert( v ); /* VDBE has already been allocated */ - if( sqlite3FkReferences(pTab)==0 ){ + assert( pTab->pSelect==0 ); /* Not a view */ + if( tdsqlite3FkReferences(pTab)==0 ){ /* Search for a deferred foreign key constraint for which this table ** is the child table. If one cannot be found, return without ** generating any VDBE code. If one can be found, then jump over @@ -109782,12 +122046,12 @@ SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTa if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break; } if( !p ) return; - iSkip = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v); + iSkip = tdsqlite3VdbeMakeLabel(pParse); + tdsqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v); } pParse->disableTriggers = 1; - sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0); + tdsqlite3DeleteFrom(pParse, tdsqlite3SrcListDup(db, pName, 0), 0, 0, 0); pParse->disableTriggers = 0; /* If the DELETE has generated immediate foreign key constraint @@ -109800,14 +122064,15 @@ SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTa ** constraints are violated. */ if( (db->flags & SQLITE_DeferFKs)==0 ){ - sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2); + tdsqlite3VdbeVerifyAbortable(v, OE_Abort); + tdsqlite3VdbeAddOp2(v, OP_FkIfZero, 0, tdsqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, + tdsqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, OE_Abort, 0, P4_STATIC, P5_ConstraintFK); } if( iSkip ){ - sqlite3VdbeResolveLabel(v, iSkip); + tdsqlite3VdbeResolveLabel(v, iSkip); } } } @@ -109866,7 +122131,7 @@ static int fkParentIsModified( if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){ Column *pCol = &pTab->aCol[iKey]; if( zKey ){ - if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1; + if( 0==tdsqlite3StrICmp(pCol->zName, zKey) ) return 1; }else if( pCol->colFlags & COLFLAG_PRIMKEY ){ return 1; } @@ -109882,7 +122147,7 @@ static int fkParentIsModified( ** to trigger pFKey. */ static int isSetNullAction(Parse *pParse, FKey *pFKey){ - Parse *pTop = sqlite3ParseToplevel(pParse); + Parse *pTop = tdsqlite3ParseToplevel(pParse); if( pTop->pTriggerPrg ){ Trigger *p = pTop->pTriggerPrg->pTrigger; if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull) @@ -109914,7 +122179,7 @@ static int isSetNullAction(Parse *pParse, FKey *pFKey){ ** described for DELETE. Then again after the original record is deleted ** but before the new record is inserted using the INSERT convention. */ -SQLITE_PRIVATE void sqlite3FkCheck( +SQLITE_PRIVATE void tdsqlite3FkCheck( Parse *pParse, /* Parse context */ Table *pTab, /* Row is being deleted from this table */ int regOld, /* Previous row data is stored here */ @@ -109922,7 +122187,7 @@ SQLITE_PRIVATE void sqlite3FkCheck( int *aChange, /* Array indicating UPDATEd columns (or 0) */ int bChngRowid /* True if rowid is UPDATEd */ ){ - sqlite3 *db = pParse->db; /* Database handle */ + tdsqlite3 *db = pParse->db; /* Database handle */ FKey *pFKey; /* Used to iterate through FKs */ int iDb; /* Index of database containing pTab */ const char *zDb; /* Name of database containing pTab */ @@ -109934,7 +122199,7 @@ SQLITE_PRIVATE void sqlite3FkCheck( /* If foreign-keys are disabled, this function is a no-op. */ if( (db->flags&SQLITE_ForeignKeys)==0 ) return; - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); zDb = db->aDb[iDb].zDbSName; /* Loop through all the foreign key constraints for which pTab is the @@ -109949,7 +122214,7 @@ SQLITE_PRIVATE void sqlite3FkCheck( int bIgnore = 0; if( aChange - && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0 + && tdsqlite3_stricmp(pTab->zName, pFKey->zTo)!=0 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){ continue; @@ -109960,11 +122225,11 @@ SQLITE_PRIVATE void sqlite3FkCheck( ** schema items cannot be located, set an error in pParse and return ** early. */ if( pParse->disableTriggers ){ - pTo = sqlite3FindTable(db, pFKey->zTo, zDb); + pTo = tdsqlite3FindTable(db, pFKey->zTo, zDb); }else{ - pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); + pTo = tdsqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); } - if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){ + if( !pTo || tdsqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){ assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) ); if( !isIgnoreErrors || db->mallocFailed ) return; if( pTo==0 ){ @@ -109975,13 +122240,15 @@ SQLITE_PRIVATE void sqlite3FkCheck( ** missing, behave as if it is empty. i.e. decrement the relevant ** FK counter for each row of the current table with non-NULL keys. */ - Vdbe *v = sqlite3GetVdbe(pParse); - int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1; + Vdbe *v = tdsqlite3GetVdbe(pParse); + int iJump = tdsqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1; for(i=0; i<pFKey->nCol; i++){ - int iReg = pFKey->aCol[i].iFrom + regOld + 1; - sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v); + int iFromCol, iReg; + iFromCol = pFKey->aCol[i].iFrom; + iReg = tdsqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1; + tdsqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v); } - sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1); + tdsqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1); } continue; } @@ -110005,7 +122272,7 @@ SQLITE_PRIVATE void sqlite3FkCheck( if( db->xAuth ){ int rcauth; char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName; - rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb); + rcauth = tdsqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb); bIgnore = (rcauth==SQLITE_IGNORE); } #endif @@ -110014,7 +122281,7 @@ SQLITE_PRIVATE void sqlite3FkCheck( /* Take a shared-cache advisory read-lock on the parent table. Allocate ** a cursor to use to search the unique index on the parent key columns ** in the parent table. */ - sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName); + tdsqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName); pParse->nTab++; if( regOld!=0 ){ @@ -110035,12 +122302,12 @@ SQLITE_PRIVATE void sqlite3FkCheck( fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore); } - sqlite3DbFree(db, aiFree); + tdsqlite3DbFree(db, aiFree); } /* Loop through all the foreign key constraints that refer to this table. ** (the "child" constraints) */ - for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ + for(pFKey = tdsqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ Index *pIdx = 0; /* Foreign key index for pFKey */ SrcList *pSrc; int *aiCol = 0; @@ -110058,20 +122325,20 @@ SQLITE_PRIVATE void sqlite3FkCheck( continue; } - if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){ + if( tdsqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){ if( !isIgnoreErrors || db->mallocFailed ) return; continue; } assert( aiCol || pFKey->nCol==1 ); /* Create a SrcList structure containing the child table. We need the - ** child table as a SrcList for sqlite3WhereBegin() */ - pSrc = sqlite3SrcListAppend(db, 0, 0, 0); + ** child table as a SrcList for tdsqlite3WhereBegin() */ + pSrc = tdsqlite3SrcListAppend(pParse, 0, 0, 0); if( pSrc ){ struct SrcList_item *pItem = pSrc->a; pItem->pTab = pFKey->pFrom; pItem->zName = pFKey->pFrom->zName; - pItem->pTab->nRef++; + pItem->pTab->nTabRef++; pItem->iCursor = pParse->nTab++; if( regNew!=0 ){ @@ -110098,13 +122365,13 @@ SQLITE_PRIVATE void sqlite3FkCheck( ** might be set incorrectly if any OP_FkCounter related scans are ** omitted. */ if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){ - sqlite3MayAbort(pParse); + tdsqlite3MayAbort(pParse); } } pItem->zName = 0; - sqlite3SrcListDelete(db, pSrc); + tdsqlite3SrcListDelete(db, pSrc); } - sqlite3DbFree(db, aiCol); + tdsqlite3DbFree(db, aiCol); } } @@ -110114,7 +122381,7 @@ SQLITE_PRIVATE void sqlite3FkCheck( ** This function is called before generating code to update or delete a ** row contained in table pTab. */ -SQLITE_PRIVATE u32 sqlite3FkOldmask( +SQLITE_PRIVATE u32 tdsqlite3FkOldmask( Parse *pParse, /* Parse context */ Table *pTab /* Table being modified */ ){ @@ -110125,9 +122392,9 @@ SQLITE_PRIVATE u32 sqlite3FkOldmask( for(p=pTab->pFKey; p; p=p->pNextFrom){ for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom); } - for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ + for(p=tdsqlite3FkReferences(pTab); p; p=p->pNextTo){ Index *pIdx = 0; - sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0); + tdsqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0); if( pIdx ){ for(i=0; i<pIdx->nKeyCol; i++){ assert( pIdx->aiColumn[i]>=0 ); @@ -110151,21 +122418,30 @@ SQLITE_PRIVATE u32 sqlite3FkOldmask( ** UPDATE statement modifies the rowid fields of the table. ** ** If any foreign key processing will be required, this function returns -** true. If there is no foreign key related processing, this function -** returns false. +** non-zero. If there is no foreign key related processing, this function +** returns zero. +** +** For an UPDATE, this function returns 2 if: +** +** * There are any FKs for which pTab is the child and the parent table, or +** * the UPDATE modifies one or more parent keys for which the action is +** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL). +** +** Or, assuming some other foreign key processing is required, 1. */ -SQLITE_PRIVATE int sqlite3FkRequired( +SQLITE_PRIVATE int tdsqlite3FkRequired( Parse *pParse, /* Parse context */ Table *pTab, /* Table being modified */ int *aChange, /* Non-NULL for UPDATE operations */ int chngRowid /* True for UPDATE that affects rowid */ ){ + int eRet = 0; if( pParse->db->flags&SQLITE_ForeignKeys ){ if( !aChange ){ /* A DELETE operation. Foreign key processing is required if the ** table in question is either the child or parent table for any ** foreign key constraint. */ - return (sqlite3FkReferences(pTab) || pTab->pFKey); + eRet = (tdsqlite3FkReferences(pTab) || pTab->pFKey); }else{ /* This is an UPDATE. Foreign key processing is only required if the ** operation modifies one or more child or parent key columns. */ @@ -110173,16 +122449,22 @@ SQLITE_PRIVATE int sqlite3FkRequired( /* Check if any child key columns are being modified. */ for(p=pTab->pFKey; p; p=p->pNextFrom){ - if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1; + if( 0==tdsqlite3_stricmp(pTab->zName, p->zTo) ) return 2; + if( fkChildIsModified(pTab, p, aChange, chngRowid) ){ + eRet = 1; + } } /* Check if any parent key columns are being modified. */ - for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ - if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1; + for(p=tdsqlite3FkReferences(pTab); p; p=p->pNextTo){ + if( fkParentIsModified(pTab, p, aChange, chngRowid) ){ + if( p->aAction[1]!=OE_None ) return 2; + eRet = 1; + } } } } - return 0; + return eRet; } /* @@ -110212,7 +122494,7 @@ SQLITE_PRIVATE int sqlite3FkRequired( ** ** The returned pointer is cached as part of the foreign key object. It ** is eventually freed along with the rest of the foreign key object by -** sqlite3FkDelete(). +** tdsqlite3FkDelete(). */ static Trigger *fkActionTrigger( Parse *pParse, /* Parse context */ @@ -110220,7 +122502,7 @@ static Trigger *fkActionTrigger( FKey *pFKey, /* Foreign key to get action for */ ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */ ){ - sqlite3 *db = pParse->db; /* Database handle */ + tdsqlite3 *db = pParse->db; /* Database handle */ int action; /* One of OE_None, OE_Cascade etc. */ Trigger *pTrigger; /* Trigger definition to return */ int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */ @@ -110243,7 +122525,7 @@ static Trigger *fkActionTrigger( int i; /* Iterator variable */ Expr *pWhen = 0; /* WHEN clause for the trigger */ - if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; + if( tdsqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; assert( aiCol || pFKey->nCol==1 ); for(i=0; i<pFKey->nCol; i++){ @@ -110258,22 +122540,21 @@ static Trigger *fkActionTrigger( assert( iFromCol>=0 ); assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) ); assert( pIdx==0 || pIdx->aiColumn[i]>=0 ); - sqlite3TokenInit(&tToCol, + tdsqlite3TokenInit(&tToCol, pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName); - sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName); + tdsqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName); /* Create the expression "OLD.zToCol = zFromCol". It is important ** that the "OLD.zToCol" term is on the LHS of the = operator, so ** that the affinity and collation sequence associated with the ** parent table are used for the comparison. */ - pEq = sqlite3PExpr(pParse, TK_EQ, - sqlite3PExpr(pParse, TK_DOT, - sqlite3ExprAlloc(db, TK_ID, &tOld, 0), - sqlite3ExprAlloc(db, TK_ID, &tToCol, 0) - , 0), - sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0) - , 0); - pWhere = sqlite3ExprAnd(db, pWhere, pEq); + pEq = tdsqlite3PExpr(pParse, TK_EQ, + tdsqlite3PExpr(pParse, TK_DOT, + tdsqlite3ExprAlloc(db, TK_ID, &tOld, 0), + tdsqlite3ExprAlloc(db, TK_ID, &tToCol, 0)), + tdsqlite3ExprAlloc(db, TK_ID, &tFromCol, 0) + ); + pWhere = tdsqlite3ExprAnd(pParse, pWhere, pEq); /* For ON UPDATE, construct the next term of the WHEN clause. ** The final WHEN clause will be like this: @@ -110281,44 +122562,49 @@ static Trigger *fkActionTrigger( ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) */ if( pChanges ){ - pEq = sqlite3PExpr(pParse, TK_IS, - sqlite3PExpr(pParse, TK_DOT, - sqlite3ExprAlloc(db, TK_ID, &tOld, 0), - sqlite3ExprAlloc(db, TK_ID, &tToCol, 0), - 0), - sqlite3PExpr(pParse, TK_DOT, - sqlite3ExprAlloc(db, TK_ID, &tNew, 0), - sqlite3ExprAlloc(db, TK_ID, &tToCol, 0), - 0), - 0); - pWhen = sqlite3ExprAnd(db, pWhen, pEq); + pEq = tdsqlite3PExpr(pParse, TK_IS, + tdsqlite3PExpr(pParse, TK_DOT, + tdsqlite3ExprAlloc(db, TK_ID, &tOld, 0), + tdsqlite3ExprAlloc(db, TK_ID, &tToCol, 0)), + tdsqlite3PExpr(pParse, TK_DOT, + tdsqlite3ExprAlloc(db, TK_ID, &tNew, 0), + tdsqlite3ExprAlloc(db, TK_ID, &tToCol, 0)) + ); + pWhen = tdsqlite3ExprAnd(pParse, pWhen, pEq); } if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){ Expr *pNew; if( action==OE_Cascade ){ - pNew = sqlite3PExpr(pParse, TK_DOT, - sqlite3ExprAlloc(db, TK_ID, &tNew, 0), - sqlite3ExprAlloc(db, TK_ID, &tToCol, 0) - , 0); + pNew = tdsqlite3PExpr(pParse, TK_DOT, + tdsqlite3ExprAlloc(db, TK_ID, &tNew, 0), + tdsqlite3ExprAlloc(db, TK_ID, &tToCol, 0)); }else if( action==OE_SetDflt ){ - Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt; + Column *pCol = pFKey->pFrom->aCol + iFromCol; + Expr *pDflt; + if( pCol->colFlags & COLFLAG_GENERATED ){ + testcase( pCol->colFlags & COLFLAG_VIRTUAL ); + testcase( pCol->colFlags & COLFLAG_STORED ); + pDflt = 0; + }else{ + pDflt = pCol->pDflt; + } if( pDflt ){ - pNew = sqlite3ExprDup(db, pDflt, 0); + pNew = tdsqlite3ExprDup(db, pDflt, 0); }else{ - pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0); + pNew = tdsqlite3ExprAlloc(db, TK_NULL, 0, 0); } }else{ - pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0); + pNew = tdsqlite3ExprAlloc(db, TK_NULL, 0, 0); } - pList = sqlite3ExprListAppend(pParse, pList, pNew); - sqlite3ExprListSetName(pParse, pList, &tFromCol, 0); + pList = tdsqlite3ExprListAppend(pParse, pList, pNew); + tdsqlite3ExprListSetName(pParse, pList, &tFromCol, 0); } } - sqlite3DbFree(db, aiCol); + tdsqlite3DbFree(db, aiCol); zFrom = pFKey->pFrom->zName; - nFrom = sqlite3Strlen30(zFrom); + nFrom = tdsqlite3Strlen30(zFrom); if( action==OE_Restrict ){ Token tFrom; @@ -110326,23 +122612,23 @@ static Trigger *fkActionTrigger( tFrom.z = zFrom; tFrom.n = nFrom; - pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed"); + pRaise = tdsqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed"); if( pRaise ){ - pRaise->affinity = OE_Abort; + pRaise->affExpr = OE_Abort; } - pSelect = sqlite3SelectNew(pParse, - sqlite3ExprListAppend(pParse, 0, pRaise), - sqlite3SrcListAppend(db, 0, &tFrom, 0), + pSelect = tdsqlite3SelectNew(pParse, + tdsqlite3ExprListAppend(pParse, 0, pRaise), + tdsqlite3SrcListAppend(pParse, 0, &tFrom, 0), pWhere, - 0, 0, 0, 0, 0, 0 + 0, 0, 0, 0, 0 ); pWhere = 0; } /* Disable lookaside memory allocation */ - db->lookaside.bDisable++; + DisableLookaside; - pTrigger = (Trigger *)sqlite3DbMallocZero(db, + pTrigger = (Trigger *)tdsqlite3DbMallocZero(db, sizeof(Trigger) + /* struct Trigger */ sizeof(TriggerStep) + /* Single step in trigger program */ nFrom + 1 /* Space for pStep->zTarget */ @@ -110352,27 +122638,28 @@ static Trigger *fkActionTrigger( pStep->zTarget = (char *)&pStep[1]; memcpy((char *)pStep->zTarget, zFrom, nFrom); - pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); - pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); - pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + pStep->pWhere = tdsqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + pStep->pExprList = tdsqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); + pStep->pSelect = tdsqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); if( pWhen ){ - pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0); - pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); + pWhen = tdsqlite3PExpr(pParse, TK_NOT, pWhen, 0); + pTrigger->pWhen = tdsqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); } } /* Re-enable the lookaside buffer, if it was disabled earlier. */ - db->lookaside.bDisable--; + EnableLookaside; - sqlite3ExprDelete(db, pWhere); - sqlite3ExprDelete(db, pWhen); - sqlite3ExprListDelete(db, pList); - sqlite3SelectDelete(db, pSelect); + tdsqlite3ExprDelete(db, pWhere); + tdsqlite3ExprDelete(db, pWhen); + tdsqlite3ExprListDelete(db, pList); + tdsqlite3SelectDelete(db, pSelect); if( db->mallocFailed==1 ){ fkTriggerDelete(db, pTrigger); return 0; } assert( pStep!=0 ); + assert( pTrigger!=0 ); switch( action ){ case OE_Restrict: @@ -110400,7 +122687,7 @@ static Trigger *fkActionTrigger( ** This function is called when deleting or updating a row to implement ** any required CASCADE, SET NULL or SET DEFAULT actions. */ -SQLITE_PRIVATE void sqlite3FkActions( +SQLITE_PRIVATE void tdsqlite3FkActions( Parse *pParse, /* Parse context */ Table *pTab, /* Table being updated or deleted from */ ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */ @@ -110414,11 +122701,11 @@ SQLITE_PRIVATE void sqlite3FkActions( ** trigger sub-program. */ if( pParse->db->flags&SQLITE_ForeignKeys ){ FKey *pFKey; /* Iterator variable */ - for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ + for(pFKey = tdsqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){ Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges); if( pAct ){ - sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0); + tdsqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0); } } } @@ -110432,12 +122719,12 @@ SQLITE_PRIVATE void sqlite3FkActions( ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash ** hash table. */ -SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){ +SQLITE_PRIVATE void tdsqlite3FkDelete(tdsqlite3 *db, Table *pTab){ FKey *pFKey; /* Iterator variable */ FKey *pNext; /* Copy of pFKey->pNextFrom */ assert( db==0 || IsVirtual(pTab) - || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) ); + || tdsqlite3SchemaMutexHeld(db, 0, pTab->pSchema) ); for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){ /* Remove the FK from the fkeyHash hash table. */ @@ -110447,7 +122734,7 @@ SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){ }else{ void *p = (void *)pFKey->pNextTo; const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo); - sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p); + tdsqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p); } if( pFKey->pNextTo ){ pFKey->pNextTo->pPrevTo = pFKey->pPrevTo; @@ -110466,7 +122753,7 @@ SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){ #endif pNext = pFKey->pNextFrom; - sqlite3DbFree(db, pFKey); + tdsqlite3DbFree(db, pFKey); } } #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */ @@ -110498,7 +122785,7 @@ SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){ ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index ** for that table that is actually opened. */ -SQLITE_PRIVATE void sqlite3OpenTable( +SQLITE_PRIVATE void tdsqlite3OpenTable( Parse *pParse, /* Generate code into this VDBE */ int iCur, /* The cursor number of the table */ int iDb, /* The database index in sqlite3.aDb[] */ @@ -110507,19 +122794,19 @@ SQLITE_PRIVATE void sqlite3OpenTable( ){ Vdbe *v; assert( !IsVirtual(pTab) ); - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); - sqlite3TableLock(pParse, iDb, pTab->tnum, + tdsqlite3TableLock(pParse, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName); if( HasRowid(pTab) ){ - sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol); + tdsqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol); VdbeComment((v, "%s", pTab->zName)); }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); + Index *pPk = tdsqlite3PrimaryKeyIndex(pTab); assert( pPk!=0 ); assert( pPk->tnum==pTab->tnum ); - sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pPk); + tdsqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); + tdsqlite3VdbeSetP4KeyInfo(pParse, pPk); VdbeComment((v, "%s", pTab->zName)); } } @@ -110542,9 +122829,9 @@ SQLITE_PRIVATE void sqlite3OpenTable( ** ** Memory for the buffer containing the column index affinity string ** is managed along with the rest of the Index structure. It will be -** released when sqlite3DeleteIndex() is called. +** released when tdsqlite3DeleteIndex() is called. */ -SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ +SQLITE_PRIVATE const char *tdsqlite3IndexAffinityStr(tdsqlite3 *db, Index *pIdx){ if( !pIdx->zColAff ){ /* The first time a column affinity string for a particular index is ** required, it is allocated and populated here. It is then stored as @@ -110556,25 +122843,26 @@ SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ */ int n; Table *pTab = pIdx->pTable; - pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); + pIdx->zColAff = (char *)tdsqlite3DbMallocRaw(0, pIdx->nColumn+1); if( !pIdx->zColAff ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); return 0; } for(n=0; n<pIdx->nColumn; n++){ i16 x = pIdx->aiColumn[n]; + char aff; if( x>=0 ){ - pIdx->zColAff[n] = pTab->aCol[x].affinity; + aff = pTab->aCol[x].affinity; }else if( x==XN_ROWID ){ - pIdx->zColAff[n] = SQLITE_AFF_INTEGER; + aff = SQLITE_AFF_INTEGER; }else{ - char aff; assert( x==XN_EXPR ); assert( pIdx->aColExpr!=0 ); - aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); - if( aff==0 ) aff = SQLITE_AFF_BLOB; - pIdx->zColAff[n] = aff; + aff = tdsqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); } + if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB; + if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC; + pIdx->zColAff[n] = aff; } pIdx->zColAff[n] = 0; } @@ -110602,31 +122890,35 @@ SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ ** 'D' INTEGER ** 'E' REAL */ -SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ - int i; +SQLITE_PRIVATE void tdsqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ + int i, j; char *zColAff = pTab->zColAff; if( zColAff==0 ){ - sqlite3 *db = sqlite3VdbeDb(v); - zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); + tdsqlite3 *db = tdsqlite3VdbeDb(v); + zColAff = (char *)tdsqlite3DbMallocRaw(0, pTab->nCol+1); if( !zColAff ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); return; } - for(i=0; i<pTab->nCol; i++){ - zColAff[i] = pTab->aCol[i].affinity; + for(i=j=0; i<pTab->nCol; i++){ + assert( pTab->aCol[i].affinity!=0 ); + if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){ + zColAff[j++] = pTab->aCol[i].affinity; + } } do{ - zColAff[i--] = 0; - }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB ); + zColAff[j--] = 0; + }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB ); pTab->zColAff = zColAff; } - i = sqlite3Strlen30(zColAff); + assert( zColAff!=0 ); + i = tdsqlite3Strlen30NN(zColAff); if( i ){ if( iReg ){ - sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); + tdsqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); }else{ - sqlite3VdbeChangeP4(v, -1, zColAff, i); + tdsqlite3VdbeChangeP4(v, -1, zColAff, i); } } } @@ -110638,15 +122930,15 @@ SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ ** run without using a temporary table for the results of the SELECT. */ static int readsTable(Parse *p, int iDb, Table *pTab){ - Vdbe *v = sqlite3GetVdbe(p); + Vdbe *v = tdsqlite3GetVdbe(p); int i; - int iEnd = sqlite3VdbeCurrentAddr(v); + int iEnd = tdsqlite3VdbeCurrentAddr(v); #ifndef SQLITE_OMIT_VIRTUALTABLE - VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; + VTable *pVTab = IsVirtual(pTab) ? tdsqlite3GetVTable(p->db, pTab) : 0; #endif for(i=1; i<iEnd; i++){ - VdbeOp *pOp = sqlite3VdbeGetOp(v, i); + VdbeOp *pOp = tdsqlite3VdbeGetOp(v, i); assert( pOp!=0 ); if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ Index *pIndex; @@ -110671,6 +122963,119 @@ static int readsTable(Parse *p, int iDb, Table *pTab){ return 0; } +/* This walker callback will compute the union of colFlags flags for all +** referenced columns in a CHECK constraint or generated column expression. +*/ +static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){ + if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){ + assert( pExpr->iColumn < pWalker->u.pTab->nCol ); + pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags; + } + return WRC_Continue; +} + +#ifndef SQLITE_OMIT_GENERATED_COLUMNS +/* +** All regular columns for table pTab have been puts into registers +** starting with iRegStore. The registers that correspond to STORED +** or VIRTUAL columns have not yet been initialized. This routine goes +** back and computes the values for those columns based on the previously +** computed normal columns. +*/ +SQLITE_PRIVATE void tdsqlite3ComputeGeneratedColumns( + Parse *pParse, /* Parsing context */ + int iRegStore, /* Register holding the first column */ + Table *pTab /* The table */ +){ + int i; + Walker w; + Column *pRedo; + int eProgress; + VdbeOp *pOp; + + assert( pTab->tabFlags & TF_HasGenerated ); + testcase( pTab->tabFlags & TF_HasVirtual ); + testcase( pTab->tabFlags & TF_HasStored ); + + /* Before computing generated columns, first go through and make sure + ** that appropriate affinity has been applied to the regular columns + */ + tdsqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore); + if( (pTab->tabFlags & TF_HasStored)!=0 + && (pOp = tdsqlite3VdbeGetOp(pParse->pVdbe,-1))->opcode==OP_Affinity + ){ + /* Change the OP_Affinity argument to '@' (NONE) for all stored + ** columns. '@' is the no-op affinity and those columns have not + ** yet been computed. */ + int ii, jj; + char *zP4 = pOp->p4.z; + assert( zP4!=0 ); + assert( pOp->p4type==P4_DYNAMIC ); + for(ii=jj=0; zP4[jj]; ii++){ + if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){ + continue; + } + if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){ + zP4[jj] = SQLITE_AFF_NONE; + } + jj++; + } + } + + /* Because there can be multiple generated columns that refer to one another, + ** this is a two-pass algorithm. On the first pass, mark all generated + ** columns as "not available". + */ + for(i=0; i<pTab->nCol; i++){ + if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ + testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); + testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); + pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL; + } + } + + w.u.pTab = pTab; + w.xExprCallback = exprColumnFlagUnion; + w.xSelectCallback = 0; + w.xSelectCallback2 = 0; + + /* On the second pass, compute the value of each NOT-AVAILABLE column. + ** Companion code in the TK_COLUMN case of tdsqlite3ExprCodeTarget() will + ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as + ** they are needed. + */ + pParse->iSelfTab = -iRegStore; + do{ + eProgress = 0; + pRedo = 0; + for(i=0; i<pTab->nCol; i++){ + Column *pCol = pTab->aCol + i; + if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){ + int x; + pCol->colFlags |= COLFLAG_BUSY; + w.eCode = 0; + tdsqlite3WalkExpr(&w, pCol->pDflt); + pCol->colFlags &= ~COLFLAG_BUSY; + if( w.eCode & COLFLAG_NOTAVAIL ){ + pRedo = pCol; + continue; + } + eProgress = 1; + assert( pCol->colFlags & COLFLAG_GENERATED ); + x = tdsqlite3TableColumnToStorage(pTab, i) + iRegStore; + tdsqlite3ExprCodeGeneratedColumn(pParse, pCol, x); + pCol->colFlags &= ~COLFLAG_NOTAVAIL; + } + } + }while( pRedo && eProgress ); + if( pRedo ){ + tdsqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zName); + } + pParse->iSelfTab = 0; +} +#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ + + #ifndef SQLITE_OMIT_AUTOINCREMENT /* ** Locate or create an AutoincInfo structure associated with table pTab @@ -110685,11 +123090,12 @@ static int readsTable(Parse *p, int iDb, Table *pTab){ ** first use of table pTab. On 2nd and subsequent uses, the original ** AutoincInfo structure is used. ** -** Three memory locations are allocated: +** Four consecutive registers are allocated: ** -** (1) Register to hold the name of the pTab table. -** (2) Register to hold the maximum ROWID of pTab. -** (3) Register to hold the rowid in sqlite_sequence of pTab +** (1) The name of the pTab table. +** (2) The maximum ROWID of pTab. +** (3) The rowid in sqlite_sequence of pTab +** (4) The original value of the max ROWID in pTab, or NULL if none ** ** The 2nd register is the one that is returned. That is all the ** insert routine needs to know about. @@ -110700,16 +123106,31 @@ static int autoIncBegin( Table *pTab /* The table we are writing to */ ){ int memId = 0; /* Register holding maximum rowid */ + assert( pParse->db->aDb[iDb].pSchema!=0 ); if( (pTab->tabFlags & TF_Autoincrement)!=0 - && (pParse->db->flags & SQLITE_Vacuum)==0 + && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0 ){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); + Parse *pToplevel = tdsqlite3ParseToplevel(pParse); AutoincInfo *pInfo; + Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab; + + /* Verify that the sqlite_sequence table exists and is an ordinary + ** rowid table with exactly two columns. + ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */ + if( pSeqTab==0 + || !HasRowid(pSeqTab) + || IsVirtual(pSeqTab) + || pSeqTab->nCol!=2 + ){ + pParse->nErr++; + pParse->rc = SQLITE_CORRUPT_SEQUENCE; + return 0; + } pInfo = pToplevel->pAinc; while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } if( pInfo==0 ){ - pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); + pInfo = tdsqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); if( pInfo==0 ) return 0; pInfo->pNext = pToplevel->pAinc; pToplevel->pAinc = pInfo; @@ -110717,7 +123138,7 @@ static int autoIncBegin( pInfo->iDb = iDb; pToplevel->nMem++; /* Register to hold name of table */ pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ - pToplevel->nMem++; /* Rowid in sqlite_sequence */ + pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */ } memId = pInfo->regCtr; } @@ -110728,9 +123149,9 @@ static int autoIncBegin( ** This routine generates code that will initialize all of the ** register used by the autoincrement tracker. */ -SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){ +SQLITE_PRIVATE void tdsqlite3AutoincrementBegin(Parse *pParse){ AutoincInfo *p; /* Information about an AUTOINCREMENT */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ Db *pDb; /* Database only autoinc table */ int memId; /* Register holding max rowid */ Vdbe *v = pParse->pVdbe; /* VDBE under construction */ @@ -110738,40 +123159,46 @@ SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){ /* This routine is never called during trigger-generation. It is ** only called from the top-level */ assert( pParse->pTriggerTab==0 ); - assert( sqlite3IsToplevel(pParse) ); + assert( tdsqlite3IsToplevel(pParse) ); assert( v ); /* We failed long ago if this is not so */ for(p = pParse->pAinc; p; p = p->pNext){ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList autoInc[] = { /* 0 */ {OP_Null, 0, 0, 0}, - /* 1 */ {OP_Rewind, 0, 9, 0}, + /* 1 */ {OP_Rewind, 0, 10, 0}, /* 2 */ {OP_Column, 0, 0, 0}, - /* 3 */ {OP_Ne, 0, 7, 0}, + /* 3 */ {OP_Ne, 0, 9, 0}, /* 4 */ {OP_Rowid, 0, 0, 0}, /* 5 */ {OP_Column, 0, 1, 0}, - /* 6 */ {OP_Goto, 0, 9, 0}, - /* 7 */ {OP_Next, 0, 2, 0}, - /* 8 */ {OP_Integer, 0, 0, 0}, - /* 9 */ {OP_Close, 0, 0, 0} + /* 6 */ {OP_AddImm, 0, 0, 0}, + /* 7 */ {OP_Copy, 0, 0, 0}, + /* 8 */ {OP_Goto, 0, 11, 0}, + /* 9 */ {OP_Next, 0, 2, 0}, + /* 10 */ {OP_Integer, 0, 0, 0}, + /* 11 */ {OP_Close, 0, 0, 0} }; VdbeOp *aOp; pDb = &db->aDb[p->iDb]; memId = p->regCtr; - assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); - sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); - sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); - aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); + assert( tdsqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); + tdsqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); + tdsqlite3VdbeLoadString(v, memId-1, p->pTab->zName); + aOp = tdsqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); if( aOp==0 ) break; aOp[0].p2 = memId; - aOp[0].p3 = memId+1; + aOp[0].p3 = memId+2; aOp[2].p3 = memId; aOp[3].p1 = memId-1; aOp[3].p3 = memId; aOp[3].p5 = SQLITE_JUMPIFNULL; aOp[4].p2 = memId+1; aOp[5].p3 = memId; - aOp[8].p2 = memId; + aOp[6].p1 = memId; + aOp[7].p2 = memId+2; + aOp[7].p1 = memId; + aOp[10].p2 = memId; + if( pParse->nTab==0 ) pParse->nTab = 1; } } @@ -110785,7 +123212,7 @@ SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){ */ static void autoIncStep(Parse *pParse, int memId, int regRowid){ if( memId>0 ){ - sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); + tdsqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); } } @@ -110799,7 +123226,7 @@ static void autoIncStep(Parse *pParse, int memId, int regRowid){ static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ AutoincInfo *p; Vdbe *v = pParse->pVdbe; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; assert( v ); for(p = pParse->pAinc; p; p = p->pNext){ @@ -110816,10 +123243,12 @@ static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ int iRec; int memId = p->regCtr; - iRec = sqlite3GetTempReg(pParse); - assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); - sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); - aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); + iRec = tdsqlite3GetTempReg(pParse); + assert( tdsqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); + tdsqlite3VdbeAddOp3(v, OP_Le, memId+2, tdsqlite3VdbeCurrentAddr(v)+7, memId); + VdbeCoverage(v); + tdsqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); + aOp = tdsqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); if( aOp==0 ) break; aOp[0].p1 = memId+1; aOp[1].p2 = memId+1; @@ -110828,10 +123257,10 @@ static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ aOp[3].p2 = iRec; aOp[3].p3 = memId+1; aOp[3].p5 = OPFLAG_APPEND; - sqlite3ReleaseTempReg(pParse, iRec); + tdsqlite3ReleaseTempReg(pParse, iRec); } } -SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){ +SQLITE_PRIVATE void tdsqlite3AutoincrementEnd(Parse *pParse){ if( pParse->pAinc ) autoIncrementEnd(pParse); } #else @@ -110950,17 +123379,17 @@ static int xferOptimization( ** end loop ** D: cleanup */ -SQLITE_PRIVATE void sqlite3Insert( +SQLITE_PRIVATE void tdsqlite3Insert( Parse *pParse, /* Parser context */ SrcList *pTabList, /* Name of table into which we are inserting */ Select *pSelect, /* A SELECT statement to use as the data source */ - IdList *pColumn, /* Column names corresponding to IDLIST. */ - int onError /* How to handle constraint errors */ + IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */ + int onError, /* How to handle constraint errors */ + Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */ ){ - sqlite3 *db; /* The main database structure */ + tdsqlite3 *db; /* The main database structure */ Table *pTab; /* The table to insert into. aka TABLE */ - char *zTab; /* Name of the table into which we are inserting */ - int i, j, idx; /* Loop counters */ + int i, j; /* Loop counters */ Vdbe *v; /* Generate code into this virtual machine */ Index *pIdx; /* For looping over indices of the table */ int nColumn; /* Number of columns in the data */ @@ -110979,6 +123408,7 @@ SQLITE_PRIVATE void sqlite3Insert( u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ u8 bIdListInOrder; /* True if IDLIST is in table order */ ExprList *pList = 0; /* List of VALUES() to be inserted */ + int iRegStore; /* Register in which to store next column */ /* Register allocations */ int regFromSelect = 0;/* Base register for data coming from SELECT */ @@ -110996,10 +123426,10 @@ SQLITE_PRIVATE void sqlite3Insert( #endif db = pParse->db; - memset(&dest, 0, sizeof(dest)); if( pParse->nErr || db->mallocFailed ){ goto insert_cleanup; } + dest.iSDParm = 0; /* Suppress a harmless compiler warning */ /* If the Select object is really just a simple VALUES() list with a ** single row (the common case) then keep that one row of values @@ -111008,22 +123438,20 @@ SQLITE_PRIVATE void sqlite3Insert( if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ pList = pSelect->pEList; pSelect->pEList = 0; - sqlite3SelectDelete(db, pSelect); + tdsqlite3SelectDelete(db, pSelect); pSelect = 0; } /* Locate the table into which we will be inserting new information. */ assert( pTabList->nSrc==1 ); - zTab = pTabList->a[0].zName; - if( NEVER(zTab==0) ) goto insert_cleanup; - pTab = sqlite3SrcListLookup(pParse, pTabList); + pTab = tdsqlite3SrcListLookup(pParse, pTabList); if( pTab==0 ){ goto insert_cleanup; } - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); assert( iDb<db->nDb ); - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, + if( tdsqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, db->aDb[iDb].zDbSName) ){ goto insert_cleanup; } @@ -111033,7 +123461,7 @@ SQLITE_PRIVATE void sqlite3Insert( ** inserted into is a view */ #ifndef SQLITE_OMIT_TRIGGER - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); + pTrigger = tdsqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); isView = pTab->pSelect!=0; #else # define pTrigger 0 @@ -111049,22 +123477,22 @@ SQLITE_PRIVATE void sqlite3Insert( /* If pTab is really a view, make sure it has been initialized. ** ViewGetColumnNames() is a no-op if pTab is not a view. */ - if( sqlite3ViewGetColumnNames(pParse, pTab) ){ + if( tdsqlite3ViewGetColumnNames(pParse, pTab) ){ goto insert_cleanup; } /* Cannot insert into a read-only table. */ - if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ + if( tdsqlite3IsReadOnly(pParse, pTab, tmask) ){ goto insert_cleanup; } /* Allocate a VDBE */ - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( v==0 ) goto insert_cleanup; - if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); - sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); + if( pParse->nested==0 ) tdsqlite3VdbeCountChanges(v); + tdsqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); #ifndef SQLITE_OMIT_XFER_OPT /* If the statement is of the form @@ -111088,8 +123516,8 @@ SQLITE_PRIVATE void sqlite3Insert( */ regAutoinc = autoIncBegin(pParse, iDb, pTab); - /* Allocate registers for holding the rowid of the new row, - ** the content of the new row, and the assembled row record. + /* Allocate a block registers to hold the rowid and the values + ** for all columns of the new row. */ regRowid = regIns = pParse->nMem+1; pParse->nMem += pTab->nCol + 1; @@ -111108,30 +123536,46 @@ SQLITE_PRIVATE void sqlite3Insert( ** the index into IDLIST of the primary key column. ipkColumn is ** the index of the primary key as it appears in IDLIST, not as ** is appears in the original table. (The index of the INTEGER - ** PRIMARY KEY in the original table is pTab->iPKey.) + ** PRIMARY KEY in the original table is pTab->iPKey.) After this + ** loop, if ipkColumn==(-1), that means that integer primary key + ** is unspecified, and hence the table is either WITHOUT ROWID or + ** it will automatically generated an integer primary key. + ** + ** bIdListInOrder is true if the columns in IDLIST are in storage + ** order. This enables an optimization that avoids shuffling the + ** columns into storage order. False negatives are harmless, + ** but false positives will cause database corruption. */ - bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0; + bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0; if( pColumn ){ for(i=0; i<pColumn->nId; i++){ pColumn->a[i].idx = -1; } for(i=0; i<pColumn->nId; i++){ for(j=0; j<pTab->nCol; j++){ - if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ + if( tdsqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ pColumn->a[i].idx = j; if( i!=j ) bIdListInOrder = 0; if( j==pTab->iPKey ){ ipkColumn = i; assert( !withoutRowid ); } +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){ + tdsqlite3ErrorMsg(pParse, + "cannot INSERT into generated column \"%s\"", + pTab->aCol[j].zName); + goto insert_cleanup; + } +#endif break; } } if( j>=pTab->nCol ){ - if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ + if( tdsqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ ipkColumn = i; bIdListInOrder = 0; }else{ - sqlite3ErrorMsg(pParse, "table %S has no column named %s", + tdsqlite3ErrorMsg(pParse, "table %S has no column named %s", pTabList, 0, pColumn->a[i].zName); pParse->checkSchema = 1; goto insert_cleanup; @@ -111153,16 +123597,16 @@ SQLITE_PRIVATE void sqlite3Insert( int rc; /* Result code */ regYield = ++pParse->nMem; - addrTop = sqlite3VdbeCurrentAddr(v) + 1; - sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); - sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); + addrTop = tdsqlite3VdbeCurrentAddr(v) + 1; + tdsqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); + tdsqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); dest.iSdst = bIdListInOrder ? regData : 0; dest.nSdst = pTab->nCol; - rc = sqlite3Select(pParse, pSelect, &dest); + rc = tdsqlite3Select(pParse, pSelect, &dest); regFromSelect = dest.iSdst; if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; - sqlite3VdbeEndCoroutine(v, regYield); - sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ + tdsqlite3VdbeEndCoroutine(v, regYield); + tdsqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ assert( pSelect->pEList ); nColumn = pSelect->pEList->nExpr; @@ -111195,17 +123639,17 @@ SQLITE_PRIVATE void sqlite3Insert( int addrL; /* Label "L" */ srcTab = pParse->nTab++; - regRec = sqlite3GetTempReg(pParse); - regTempRowid = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); - addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); - sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); - sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); - sqlite3VdbeGoto(v, addrL); - sqlite3VdbeJumpHere(v, addrL); - sqlite3ReleaseTempReg(pParse, regRec); - sqlite3ReleaseTempReg(pParse, regTempRowid); + regRec = tdsqlite3GetTempReg(pParse); + regTempRowid = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); + addrL = tdsqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); + tdsqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); + tdsqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); + tdsqlite3VdbeGoto(v, addrL); + tdsqlite3VdbeJumpHere(v, addrL); + tdsqlite3ReleaseTempReg(pParse, regRec); + tdsqlite3ReleaseTempReg(pParse, regTempRowid); } }else{ /* This is the case if the data for the INSERT is coming from a @@ -111218,7 +123662,7 @@ SQLITE_PRIVATE void sqlite3Insert( assert( useTempTable==0 ); if( pList ){ nColumn = pList->nExpr; - if( sqlite3ResolveExprListNames(&sNC, pList) ){ + if( tdsqlite3ResolveExprListNames(&sNC, pList) ){ goto insert_cleanup; } }else{ @@ -111232,45 +123676,89 @@ SQLITE_PRIVATE void sqlite3Insert( */ if( pColumn==0 && nColumn>0 ){ ipkColumn = pTab->iPKey; +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){ + testcase( pTab->tabFlags & TF_HasVirtual ); + testcase( pTab->tabFlags & TF_HasStored ); + for(i=ipkColumn-1; i>=0; i--){ + if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ + testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); + testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); + ipkColumn--; + } + } + } +#endif } /* Make sure the number of columns in the source data matches the number ** of columns to be inserted into the table. */ for(i=0; i<pTab->nCol; i++){ - nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); + if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++; } if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "table %S has %d columns but %d values were supplied", pTabList, 0, pTab->nCol-nHidden, nColumn); goto insert_cleanup; } if( pColumn!=0 && nColumn!=pColumn->nId ){ - sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); + tdsqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); goto insert_cleanup; } /* Initialize the count of rows to be inserted */ - if( db->flags & SQLITE_CountRows ){ + if( (db->flags & SQLITE_CountRows)!=0 + && !pParse->nested + && !pParse->pTriggerTab + ){ regRowCount = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); } /* If this is not a view, open the table and and all indices */ if( !isView ){ int nIdx; - nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, + nIdx = tdsqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, &iDataCur, &iIdxCur); - aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1)); + aRegIdx = tdsqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2)); if( aRegIdx==0 ){ goto insert_cleanup; } - for(i=0; i<nIdx; i++){ + for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){ + assert( pIdx ); aRegIdx[i] = ++pParse->nMem; + pParse->nMem += pIdx->nColumn; + } + aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */ + } +#ifndef SQLITE_OMIT_UPSERT + if( pUpsert ){ + if( IsVirtual(pTab) ){ + tdsqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"", + pTab->zName); + goto insert_cleanup; + } + if( pTab->pSelect ){ + tdsqlite3ErrorMsg(pParse, "cannot UPSERT a view"); + goto insert_cleanup; + } + if( tdsqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){ + goto insert_cleanup; + } + pTabList->a[0].iCursor = iDataCur; + pUpsert->pUpsertSrc = pTabList; + pUpsert->regData = regData; + pUpsert->iDataCur = iDataCur; + pUpsert->iIdxCur = iIdxCur; + if( pUpsert->pUpsertTarget ){ + tdsqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert); } } +#endif + /* This is the top of the main insertion loop */ if( useTempTable ){ @@ -111283,8 +123771,8 @@ SQLITE_PRIVATE void sqlite3Insert( ** end loop ** D: ... */ - addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); - addrCont = sqlite3VdbeCurrentAddr(v); + addrInsTop = tdsqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); + addrCont = tdsqlite3VdbeCurrentAddr(v); }else if( pSelect ){ /* This block codes the top of loop only. The complete loop is the ** following pseudocode (template 3): @@ -111294,15 +123782,96 @@ SQLITE_PRIVATE void sqlite3Insert( ** goto C ** D: ... */ - addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); + tdsqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0); + addrInsTop = addrCont = tdsqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); + if( ipkColumn>=0 ){ + /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the + ** SELECT, go ahead and copy the value into the rowid slot now, so that + ** the value does not get overwritten by a NULL at tag-20191021-002. */ + tdsqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); + } + } + + /* Compute data for ordinary columns of the new entry. Values + ** are written in storage order into registers starting with regData. + ** Only ordinary columns are computed in this loop. The rowid + ** (if there is one) is computed later and generated columns are + ** computed after the rowid since they might depend on the value + ** of the rowid. + */ + nHidden = 0; + iRegStore = regData; assert( regData==regRowid+1 ); + for(i=0; i<pTab->nCol; i++, iRegStore++){ + int k; + u32 colFlags; + assert( i>=nHidden ); + if( i==pTab->iPKey ){ + /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled + ** using the rowid. So put a NULL in the IPK slot of the record to avoid + ** using excess space. The file format definition requires this extra + ** NULL - we cannot optimize further by skipping the column completely */ + tdsqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); + continue; + } + if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){ + nHidden++; + if( (colFlags & COLFLAG_VIRTUAL)!=0 ){ + /* Virtual columns do not participate in OP_MakeRecord. So back up + ** iRegStore by one slot to compensate for the iRegStore++ in the + ** outer for() loop */ + iRegStore--; + continue; + }else if( (colFlags & COLFLAG_STORED)!=0 ){ + /* Stored columns are computed later. But if there are BEFORE + ** triggers, the slots used for stored columns will be OP_Copy-ed + ** to a second block of registers, so the register needs to be + ** initialized to NULL to avoid an uninitialized register read */ + if( tmask & TRIGGER_BEFORE ){ + tdsqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); + } + continue; + }else if( pColumn==0 ){ + /* Hidden columns that are not explicitly named in the INSERT + ** get there default value */ + tdsqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); + continue; + } + } + if( pColumn ){ + for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){} + if( j>=pColumn->nId ){ + /* A column not named in the insert column list gets its + ** default value */ + tdsqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); + continue; + } + k = j; + }else if( nColumn==0 ){ + /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */ + tdsqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); + continue; + }else{ + k = i - nHidden; + } + + if( useTempTable ){ + tdsqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore); + }else if( pSelect ){ + if( regFromSelect!=regData ){ + tdsqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore); + } + }else{ + tdsqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore); + } } + /* Run the BEFORE and INSTEAD OF triggers, if there are any */ - endOfLoop = sqlite3VdbeMakeLabel(v); + endOfLoop = tdsqlite3VdbeMakeLabel(pParse); if( tmask & TRIGGER_BEFORE ){ - int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); + int regCols = tdsqlite3GetTempRange(pParse, pTab->nCol+1); /* build the NEW.* reference row. Note that if there is an INTEGER ** PRIMARY KEY into which a NULL is being inserted, that NULL will be @@ -111311,20 +123880,20 @@ SQLITE_PRIVATE void sqlite3Insert( ** not happened yet) so we substitute a rowid of -1 */ if( ipkColumn<0 ){ - sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); + tdsqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); }else{ int addr1; assert( !withoutRowid ); if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); + tdsqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); }else{ assert( pSelect==0 ); /* Otherwise useTempTable is true */ - sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); + tdsqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); } - addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); - sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); + addr1 = tdsqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); + tdsqlite3VdbeJumpHere(v, addr1); + tdsqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); } /* Cannot have triggers on a virtual table. If it were possible, @@ -111332,25 +123901,21 @@ SQLITE_PRIVATE void sqlite3Insert( */ assert( !IsVirtual(pTab) ); - /* Create the new column data - */ - for(i=j=0; i<pTab->nCol; i++){ - if( pColumn ){ - for(j=0; j<pColumn->nId; j++){ - if( pColumn->a[j].idx==i ) break; - } - } - if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) - || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){ - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); - }else if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); - }else{ - assert( pSelect==0 ); /* Otherwise useTempTable is true */ - sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); - } - if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++; + /* Copy the new data already generated. */ + assert( pTab->nNVCol>0 ); + tdsqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1); + +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + /* Compute the new value for generated columns after all other + ** columns have already been computed. This must be done after + ** computing the ROWID in case one of the generated columns + ** refers to the ROWID. */ + if( pTab->tabFlags & TF_HasGenerated ){ + testcase( pTab->tabFlags & TF_HasVirtual ); + testcase( pTab->tabFlags & TF_HasStored ); + tdsqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab); } +#endif /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, ** do not attempt any conversions before assembling the record. @@ -111358,39 +123923,34 @@ SQLITE_PRIVATE void sqlite3Insert( ** table column affinities. */ if( !isView ){ - sqlite3TableAffinity(v, pTab, regCols+1); + tdsqlite3TableAffinity(v, pTab, regCols+1); } /* Fire BEFORE or INSTEAD OF triggers */ - sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, + tdsqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, pTab, regCols-pTab->nCol-1, onError, endOfLoop); - sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); + tdsqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); } - /* Compute the content of the next row to insert into a range of - ** registers beginning at regIns. - */ if( !isView ){ if( IsVirtual(pTab) ){ /* The row that the VUpdate opcode will delete: none */ - sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, regIns); } if( ipkColumn>=0 ){ + /* Compute the new rowid */ if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); + tdsqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); }else if( pSelect ){ - sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); + /* Rowid already initialized at tag-20191021-001 */ }else{ - VdbeOp *pOp; - sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); - pOp = sqlite3VdbeGetOp(v, -1); - if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ + Expr *pIpk = pList->a[ipkColumn].pExpr; + if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){ + tdsqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); appendFlag = 1; - pOp->opcode = OP_NewRowid; - pOp->p1 = iDataCur; - pOp->p2 = regRowid; - pOp->p3 = regAutoinc; + }else{ + tdsqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); } } /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid @@ -111399,117 +123959,100 @@ SQLITE_PRIVATE void sqlite3Insert( if( !appendFlag ){ int addr1; if( !IsVirtual(pTab) ){ - addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); - sqlite3VdbeJumpHere(v, addr1); + addr1 = tdsqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); + tdsqlite3VdbeJumpHere(v, addr1); }else{ - addr1 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); + addr1 = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); } - sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); + tdsqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); } }else if( IsVirtual(pTab) || withoutRowid ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); }else{ - sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); + tdsqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); appendFlag = 1; } autoIncStep(pParse, regAutoinc, regRowid); - /* Compute data for all columns of the new entry, beginning - ** with the first column. - */ - nHidden = 0; - for(i=0; i<pTab->nCol; i++){ - int iRegStore = regRowid+1+i; - if( i==pTab->iPKey ){ - /* The value of the INTEGER PRIMARY KEY column is always a NULL. - ** Whenever this column is read, the rowid will be substituted - ** in its place. Hence, fill this column with a NULL to avoid - ** taking up data space with information that will never be used. - ** As there may be shallow copies of this value, make it a soft-NULL */ - sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); - continue; - } - if( pColumn==0 ){ - if( IsHiddenColumn(&pTab->aCol[i]) ){ - j = -1; - nHidden++; - }else{ - j = i - nHidden; - } - }else{ - for(j=0; j<pColumn->nId; j++){ - if( pColumn->a[j].idx==i ) break; - } - } - if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ - sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); - }else if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); - }else if( pSelect ){ - if( regFromSelect!=regData ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); - } - }else{ - sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); - } +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + /* Compute the new value for generated columns after all other + ** columns have already been computed. This must be done after + ** computing the ROWID in case one of the generated columns + ** is derived from the INTEGER PRIMARY KEY. */ + if( pTab->tabFlags & TF_HasGenerated ){ + tdsqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab); } +#endif /* Generate code to check constraints and generate index keys and ** do the insertion. */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ - const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); - sqlite3VtabMakeWritable(pParse, pTab); - sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); - sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); - sqlite3MayAbort(pParse); + const char *pVTab = (const char *)tdsqlite3GetVTable(db, pTab); + tdsqlite3VtabMakeWritable(pParse, pTab); + tdsqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); + tdsqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); + tdsqlite3MayAbort(pParse); }else #endif { int isReplace; /* Set to true if constraints may cause a replace */ - sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, - regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0 + int bUseSeek; /* True to use OPFLAG_SEEKRESULT */ + tdsqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, + regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert + ); + tdsqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); + + /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE + ** constraints or (b) there are no triggers and this table is not a + ** parent table in a foreign key constraint. It is safe to set the + ** flag in the second case as if any REPLACE constraint is hit, an + ** OP_Delete or OP_IdxDelete instruction will be executed on each + ** cursor that is disturbed. And these instructions both clear the + ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT + ** functionality. */ + bUseSeek = (isReplace==0 || !tdsqlite3VdbeHasSubProgram(v)); + tdsqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, + regIns, aRegIdx, 0, appendFlag, bUseSeek ); - sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); - sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, - regIns, aRegIdx, 0, appendFlag, isReplace==0); } } /* Update the count of rows that are inserted */ - if( (db->flags & SQLITE_CountRows)!=0 ){ - sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); + if( regRowCount ){ + tdsqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); } if( pTrigger ){ /* Code AFTER triggers */ - sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, + tdsqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, pTab, regData-2-pTab->nCol, onError, endOfLoop); } /* The bottom of the main insertion loop, if the data source ** is a SELECT statement. */ - sqlite3VdbeResolveLabel(v, endOfLoop); + tdsqlite3VdbeResolveLabel(v, endOfLoop); if( useTempTable ){ - sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addrInsTop); - sqlite3VdbeAddOp1(v, OP_Close, srcTab); + tdsqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addrInsTop); + tdsqlite3VdbeAddOp1(v, OP_Close, srcTab); }else if( pSelect ){ - sqlite3VdbeGoto(v, addrCont); - sqlite3VdbeJumpHere(v, addrInsTop); - } - - if( !IsVirtual(pTab) && !isView ){ - /* Close all tables opened */ - if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur); - for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ - sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur); + tdsqlite3VdbeGoto(v, addrCont); +#ifdef SQLITE_DEBUG + /* If we are jumping back to an OP_Yield that is preceded by an + ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the + ** OP_ReleaseReg will be included in the loop. */ + if( tdsqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){ + assert( tdsqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield ); + tdsqlite3VdbeChangeP5(v, 1); } +#endif + tdsqlite3VdbeJumpHere(v, addrInsTop); } insert_end: @@ -111518,26 +124061,27 @@ insert_end: ** autoincrement tables. */ if( pParse->nested==0 && pParse->pTriggerTab==0 ){ - sqlite3AutoincrementEnd(pParse); + tdsqlite3AutoincrementEnd(pParse); } /* ** Return the number of rows inserted. If this routine is - ** generating code because of a call to sqlite3NestedParse(), do not + ** generating code because of a call to tdsqlite3NestedParse(), do not ** invoke the callback function. */ - if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); + if( regRowCount ){ + tdsqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); + tdsqlite3VdbeSetNumCols(v, 1); + tdsqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); } insert_cleanup: - sqlite3SrcListDelete(db, pTabList); - sqlite3ExprListDelete(db, pList); - sqlite3SelectDelete(db, pSelect); - sqlite3IdListDelete(db, pColumn); - sqlite3DbFree(db, aRegIdx); + tdsqlite3SrcListDelete(db, pTabList); + tdsqlite3ExprListDelete(db, pList); + tdsqlite3UpsertDelete(db, pUpsert); + tdsqlite3SelectDelete(db, pSelect); + tdsqlite3IdListDelete(db, pColumn); + tdsqlite3DbFree(db, aRegIdx); } /* Make sure "isView" and other macros defined above are undefined. Otherwise @@ -111554,14 +124098,15 @@ insert_cleanup: #endif /* -** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged() +** Meanings of bits in of pWalker->eCode for +** tdsqlite3ExprReferencesUpdatedColumn() */ #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */ #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */ -/* This is the Walker callback from checkConstraintUnchanged(). Set -** bit 0x01 of pWalker->eCode if -** pWalker->eCode to 0 if this expression node references any of the +/* This is the Walker callback from tdsqlite3ExprReferencesUpdatedColumn(). +* Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this +** expression node references any of the ** columns that are being modifed by an UPDATE statement. */ static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ @@ -111583,18 +124128,27 @@ static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ ** only columns that are modified by the UPDATE are those for which ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true. ** -** Return true if CHECK constraint pExpr does not use any of the +** Return true if CHECK constraint pExpr uses any of the ** changing columns (or the rowid if it is changing). In other words, -** return true if this CHECK constraint can be skipped when validating +** return true if this CHECK constraint must be validated for ** the new row in the UPDATE statement. +** +** 2018-09-15: pExpr might also be an expression for an index-on-expressions. +** The operation of this routine is the same - return true if an only if +** the expression uses one or more of columns identified by the second and +** third arguments. */ -static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){ +SQLITE_PRIVATE int tdsqlite3ExprReferencesUpdatedColumn( + Expr *pExpr, /* The expression to be checked */ + int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */ + int chngRowid /* True if UPDATE changes the rowid */ +){ Walker w; memset(&w, 0, sizeof(w)); w.eCode = 0; w.xExprCallback = checkConstraintExprNode; w.u.aiCol = aiChng; - sqlite3WalkExpr(&w, pExpr); + tdsqlite3WalkExpr(&w, pExpr); if( !chngRowid ){ testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 ); w.eCode &= ~CKCNSTRNT_ROWID; @@ -111603,7 +124157,7 @@ static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){ testcase( w.eCode==CKCNSTRNT_COLUMN ); testcase( w.eCode==CKCNSTRNT_ROWID ); testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) ); - return !w.eCode; + return w.eCode!=0; } /* @@ -111641,6 +124195,14 @@ static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){ ** the same as the order of indices on the linked list of indices ** at pTab->pIndex. ** +** (2019-05-07) The generated code also creates a new record for the +** main table, if pTab is a rowid table, and stores that record in the +** register identified by aRegIdx[nIdx] - in other words in the first +** entry of aRegIdx[] past the last index. It is important that the +** record be generated during constraint checks to avoid affinity changes +** to the register content that occur after constraint checks but before +** the new record is inserted. +** ** The caller must have already opened writeable cursors on the main ** table and all applicable indices (that is to say, all indices for which ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when @@ -111657,12 +124219,12 @@ static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){ ** Constraint type Action What Happens ** --------------- ---------- ---------------------------------------- ** any ROLLBACK The current transaction is rolled back and -** sqlite3_step() returns immediately with a +** tdsqlite3_step() returns immediately with a ** return code of SQLITE_CONSTRAINT. ** ** any ABORT Back out changes from the current command ** only (do not do a complete rollback) then -** cause sqlite3_step() to return immediately +** cause tdsqlite3_step() to return immediately ** with SQLITE_CONSTRAINT. ** ** any FAIL Sqlite3_step() returns immediately with a @@ -111689,7 +124251,7 @@ static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){ ** is used. Or if pParse->onError==OE_Default then the onError value ** for the constraint is used. */ -SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( +SQLITE_PRIVATE void tdsqlite3GenerateConstraintChecks( Parse *pParse, /* The parser context */ Table *pTab, /* The table being inserted or updated */ int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ @@ -111701,28 +124263,37 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( u8 overrideError, /* Override onError to this if not OE_Default */ int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */ - int *aiChng /* column i is unchanged if aiChng[i]<0 */ + int *aiChng, /* column i is unchanged if aiChng[i]<0 */ + Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */ ){ Vdbe *v; /* VDBE under constrution */ Index *pIdx; /* Pointer to one of the indices */ Index *pPk = 0; /* The PRIMARY KEY index */ - sqlite3 *db; /* Database connection */ + tdsqlite3 *db; /* Database connection */ int i; /* loop counter */ int ix; /* Index loop counter */ int nCol; /* Number of columns */ int onError; /* Conflict resolution strategy */ - int addr1; /* Address of jump instruction */ int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ - int ipkTop = 0; /* Top of the rowid change constraint check */ - int ipkBottom = 0; /* Bottom of the rowid change constraint check */ + Index *pUpIdx = 0; /* Index to which to apply the upsert */ u8 isUpdate; /* True if this is an UPDATE operation */ u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ - int regRowid = -1; /* Register holding ROWID value */ + int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */ + int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */ + int ipkTop = 0; /* Top of the IPK uniqueness check */ + int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */ + /* Variables associated with retesting uniqueness constraints after + ** replace triggers fire have run */ + int regTrigCnt; /* Register used to count replace trigger invocations */ + int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */ + int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */ + Trigger *pTrigger; /* List of DELETE triggers on the table pTab */ + int nReplaceTrig = 0; /* Number of replace triggers coded */ isUpdate = regOldData!=0; db = pParse->db; - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); assert( v!=0 ); assert( pTab->pSelect==0 ); /* This table is not a VIEW */ nCol = pTab->nCol; @@ -111735,7 +124306,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( pPk = 0; nPkField = 1; }else{ - pPk = sqlite3PrimaryKeyIndex(pTab); + pPk = tdsqlite3PrimaryKeyIndex(pTab); nPkField = pPk->nKeyCol; } @@ -111745,89 +124316,233 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( /* Test all NOT NULL constraints. */ - for(i=0; i<nCol; i++){ - if( i==pTab->iPKey ){ - continue; /* ROWID is never NULL */ - } - if( aiChng && aiChng[i]<0 ){ - /* Don't bother checking for NOT NULL on columns that do not change */ - continue; - } - onError = pTab->aCol[i].notNull; - if( onError==OE_None ) continue; /* This column is allowed to be NULL */ - if( overrideError!=OE_Default ){ - onError = overrideError; - }else if( onError==OE_Default ){ - onError = OE_Abort; - } - if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ - onError = OE_Abort; - } - assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail - || onError==OE_Ignore || onError==OE_Replace ); - switch( onError ){ - case OE_Abort: - sqlite3MayAbort(pParse); - /* Fall through */ - case OE_Rollback: - case OE_Fail: { - char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, - pTab->aCol[i].zName); - sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, - regNewData+1+i, zMsg, P4_DYNAMIC); - sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); - VdbeCoverage(v); - break; - } - case OE_Ignore: { - sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); - VdbeCoverage(v); + if( pTab->tabFlags & TF_HasNotNull ){ + int b2ndPass = 0; /* True if currently running 2nd pass */ + int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */ + int nGenerated = 0; /* Number of generated columns with NOT NULL */ + while(1){ /* Make 2 passes over columns. Exit loop via "break" */ + for(i=0; i<nCol; i++){ + int iReg; /* Register holding column value */ + Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */ + int isGenerated; /* non-zero if column is generated */ + onError = pCol->notNull; + if( onError==OE_None ) continue; /* No NOT NULL on this column */ + if( i==pTab->iPKey ){ + continue; /* ROWID is never NULL */ + } + isGenerated = pCol->colFlags & COLFLAG_GENERATED; + if( isGenerated && !b2ndPass ){ + nGenerated++; + continue; /* Generated columns processed on 2nd pass */ + } + if( aiChng && aiChng[i]<0 && !isGenerated ){ + /* Do not check NOT NULL on columns that do not change */ + continue; + } + if( overrideError!=OE_Default ){ + onError = overrideError; + }else if( onError==OE_Default ){ + onError = OE_Abort; + } + if( onError==OE_Replace ){ + if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */ + || pCol->pDflt==0 /* REPLACE is ABORT if no DEFAULT value */ + ){ + testcase( pCol->colFlags & COLFLAG_VIRTUAL ); + testcase( pCol->colFlags & COLFLAG_STORED ); + testcase( pCol->colFlags & COLFLAG_GENERATED ); + onError = OE_Abort; + }else{ + assert( !isGenerated ); + } + }else if( b2ndPass && !isGenerated ){ + continue; + } + assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail + || onError==OE_Ignore || onError==OE_Replace ); + testcase( i!=tdsqlite3TableColumnToStorage(pTab, i) ); + iReg = tdsqlite3TableColumnToStorage(pTab, i) + regNewData + 1; + switch( onError ){ + case OE_Replace: { + int addr1 = tdsqlite3VdbeAddOp1(v, OP_NotNull, iReg); + VdbeCoverage(v); + assert( (pCol->colFlags & COLFLAG_GENERATED)==0 ); + nSeenReplace++; + tdsqlite3ExprCode(pParse, pCol->pDflt, iReg); + tdsqlite3VdbeJumpHere(v, addr1); + break; + } + case OE_Abort: + tdsqlite3MayAbort(pParse); + /* Fall through */ + case OE_Rollback: + case OE_Fail: { + char *zMsg = tdsqlite3MPrintf(db, "%s.%s", pTab->zName, + pCol->zName); + tdsqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, + onError, iReg); + tdsqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC); + tdsqlite3VdbeChangeP5(v, P5_ConstraintNotNull); + VdbeCoverage(v); + break; + } + default: { + assert( onError==OE_Ignore ); + tdsqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest); + VdbeCoverage(v); + break; + } + } /* end switch(onError) */ + } /* end loop i over columns */ + if( nGenerated==0 && nSeenReplace==0 ){ + /* If there are no generated columns with NOT NULL constraints + ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single + ** pass is sufficient */ break; } - default: { - assert( onError==OE_Replace ); - addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); - VdbeCoverage(v); - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); - sqlite3VdbeJumpHere(v, addr1); - break; + if( b2ndPass ) break; /* Never need more than 2 passes */ + b2ndPass = 1; +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){ + /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the + ** first pass, recomputed values for all generated columns, as + ** those values might depend on columns affected by the REPLACE. + */ + tdsqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab); } - } - } +#endif + } /* end of 2-pass loop */ + } /* end if( has-not-null-constraints ) */ /* Test all CHECK constraints */ #ifndef SQLITE_OMIT_CHECK if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ ExprList *pCheck = pTab->pCheck; - pParse->ckBase = regNewData+1; + pParse->iSelfTab = -(regNewData+1); onError = overrideError!=OE_Default ? overrideError : OE_Abort; for(i=0; i<pCheck->nExpr; i++){ int allOk; Expr *pExpr = pCheck->a[i].pExpr; - if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue; - allOk = sqlite3VdbeMakeLabel(v); - sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL); + if( aiChng + && !tdsqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng) + ){ + /* The check constraints do not reference any of the columns being + ** updated so there is no point it verifying the check constraint */ + continue; + } + allOk = tdsqlite3VdbeMakeLabel(pParse); + tdsqlite3VdbeVerifyAbortable(v, onError); + tdsqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL); if( onError==OE_Ignore ){ - sqlite3VdbeGoto(v, ignoreDest); + tdsqlite3VdbeGoto(v, ignoreDest); }else{ - char *zName = pCheck->a[i].zName; + char *zName = pCheck->a[i].zEName; if( zName==0 ) zName = pTab->zName; - if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, + if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */ + tdsqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, onError, zName, P4_TRANSIENT, P5_ConstraintCheck); } - sqlite3VdbeResolveLabel(v, allOk); + tdsqlite3VdbeResolveLabel(v, allOk); } + pParse->iSelfTab = 0; } #endif /* !defined(SQLITE_OMIT_CHECK) */ + /* UNIQUE and PRIMARY KEY constraints should be handled in the following + ** order: + ** + ** (1) OE_Update + ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore + ** (3) OE_Replace + ** + ** OE_Fail and OE_Ignore must happen before any changes are made. + ** OE_Update guarantees that only a single row will change, so it + ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback + ** could happen in any order, but they are grouped up front for + ** convenience. + ** + ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43 + ** The order of constraints used to have OE_Update as (2) and OE_Abort + ** and so forth as (1). But apparently PostgreSQL checks the OE_Update + ** constraint before any others, so it had to be moved. + ** + ** Constraint checking code is generated in this order: + ** (A) The rowid constraint + ** (B) Unique index constraints that do not have OE_Replace as their + ** default conflict resolution strategy + ** (C) Unique index that do use OE_Replace by default. + ** + ** The ordering of (2) and (3) is accomplished by making sure the linked + ** list of indexes attached to a table puts all OE_Replace indexes last + ** in the list. See tdsqlite3CreateIndex() for where that happens. + */ + + if( pUpsert ){ + if( pUpsert->pUpsertTarget==0 ){ + /* An ON CONFLICT DO NOTHING clause, without a constraint-target. + ** Make all unique constraint resolution be OE_Ignore */ + assert( pUpsert->pUpsertSet==0 ); + overrideError = OE_Ignore; + pUpsert = 0; + }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){ + /* If the constraint-target uniqueness check must be run first. + ** Jump to that uniqueness check now */ + upsertJump = tdsqlite3VdbeAddOp0(v, OP_Goto); + VdbeComment((v, "UPSERT constraint goes first")); + } + } + + /* Determine if it is possible that triggers (either explicitly coded + ** triggers or FK resolution actions) might run as a result of deletes + ** that happen when OE_Replace conflict resolution occurs. (Call these + ** "replace triggers".) If any replace triggers run, we will need to + ** recheck all of the uniqueness constraints after they have all run. + ** But on the recheck, the resolution is OE_Abort instead of OE_Replace. + ** + ** If replace triggers are a possibility, then + ** + ** (1) Allocate register regTrigCnt and initialize it to zero. + ** That register will count the number of replace triggers that + ** fire. Constraint recheck only occurs if the number is positive. + ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab. + ** (3) Initialize addrRecheck and lblRecheckOk + ** + ** The uniqueness rechecking code will create a series of tests to run + ** in a second pass. The addrRecheck and lblRecheckOk variables are + ** used to link together these tests which are separated from each other + ** in the generate bytecode. + */ + if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){ + /* There are not DELETE triggers nor FK constraints. No constraint + ** rechecks are needed. */ + pTrigger = 0; + regTrigCnt = 0; + }else{ + if( db->flags&SQLITE_RecTriggers ){ + pTrigger = tdsqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); + regTrigCnt = pTrigger!=0 || tdsqlite3FkRequired(pParse, pTab, 0, 0); + }else{ + pTrigger = 0; + regTrigCnt = tdsqlite3FkRequired(pParse, pTab, 0, 0); + } + if( regTrigCnt ){ + /* Replace triggers might exist. Allocate the counter and + ** initialize it to zero. */ + regTrigCnt = ++pParse->nMem; + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt); + VdbeComment((v, "trigger count")); + lblRecheckOk = tdsqlite3VdbeMakeLabel(pParse); + addrRecheck = lblRecheckOk; + } + } + /* If rowid is changing, make sure the new rowid does not previously ** exist in the table. */ if( pkChng && pPk==0 ){ - int addrRowidOk = sqlite3VdbeMakeLabel(v); + int addrRowidOk = tdsqlite3VdbeMakeLabel(pParse); /* Figure out what action to take in case of a rowid collision */ onError = pTab->keyConf; @@ -111837,13 +124552,13 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( onError = OE_Abort; } - if( isUpdate ){ - /* pkChng!=0 does not mean that the rowid has change, only that - ** it might have changed. Skip the conflict logic below if the rowid - ** is unchanged. */ - sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); - VdbeCoverage(v); + /* figure out whether or not upsert applies in this case */ + if( pUpsert && pUpsert->pUpsertIdx==0 ){ + if( pUpsert->pUpsertSet==0 ){ + onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ + }else{ + onError = OE_Update; /* DO UPDATE */ + } } /* If the response to a rowid conflict is REPLACE but the response @@ -111851,21 +124566,30 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( ** to defer the running of the rowid conflict checking until after ** the UNIQUE constraints have run. */ - if( onError==OE_Replace && overrideError!=OE_Replace ){ - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ - ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); - break; - } - } + if( onError==OE_Replace /* IPK rule is REPLACE */ + && onError!=overrideError /* Rules for other contraints are different */ + && pTab->pIndex /* There exist other constraints */ + ){ + ipkTop = tdsqlite3VdbeAddOp0(v, OP_Goto)+1; + VdbeComment((v, "defer IPK REPLACE until last")); + } + + if( isUpdate ){ + /* pkChng!=0 does not mean that the rowid has changed, only that + ** it might have changed. Skip the conflict logic below if the rowid + ** is unchanged. */ + tdsqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); + tdsqlite3VdbeChangeP5(v, SQLITE_NOTNULL); + VdbeCoverage(v); } /* Check to see if the new rowid already exists in the table. Skip ** the following conflict logic if it does not. */ - sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); + VdbeNoopComment((v, "uniqueness check for ROWID")); + tdsqlite3VdbeVerifyAbortable(v, onError); + tdsqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); VdbeCoverage(v); - /* Generate code that deals with a rowid collision */ switch( onError ){ default: { onError = OE_Abort; @@ -111874,7 +124598,10 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( case OE_Rollback: case OE_Abort: case OE_Fail: { - sqlite3RowidConstraint(pParse, onError, pTab); + testcase( onError==OE_Rollback ); + testcase( onError==OE_Abort ); + testcase( onError==OE_Fail ); + tdsqlite3RowidConstraint(pParse, onError, pTab); break; } case OE_Replace: { @@ -111892,7 +124619,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, ** also invoke MultiWrite() to indicate that this VDBE may require ** statement rollback (if the statement is aborted after the delete - ** takes place). Earlier versions called sqlite3MultiWrite() regardless, + ** takes place). Earlier versions called tdsqlite3MultiWrite() regardless, ** but being more selective here allows statements like: ** ** REPLACE INTO t(rowid) VALUES($newrowid) @@ -111900,43 +124627,46 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( ** to run without a statement journal if there are no indexes on the ** table. */ - Trigger *pTrigger = 0; - if( db->flags&SQLITE_RecTriggers ){ - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); - } - if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ - sqlite3MultiWrite(pParse); - sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, + if( regTrigCnt ){ + tdsqlite3MultiWrite(pParse); + tdsqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, regNewData, 1, 0, OE_Replace, 1, -1); + tdsqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ + nReplaceTrig++; }else{ #ifdef SQLITE_ENABLE_PREUPDATE_HOOK - if( HasRowid(pTab) ){ - /* This OP_Delete opcode fires the pre-update-hook only. It does - ** not modify the b-tree. It is more efficient to let the coming - ** OP_Insert replace the existing entry than it is to delete the - ** existing entry and then insert a new one. */ - sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); - sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE); - } + assert( HasRowid(pTab) ); + /* This OP_Delete opcode fires the pre-update-hook only. It does + ** not modify the b-tree. It is more efficient to let the coming + ** OP_Insert replace the existing entry than it is to delete the + ** existing entry and then insert a new one. */ + tdsqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); + tdsqlite3VdbeAppendP4(v, pTab, P4_TABLE); #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ if( pTab->pIndex ){ - sqlite3MultiWrite(pParse); - sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); + tdsqlite3MultiWrite(pParse); + tdsqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); } } seenReplace = 1; break; } +#ifndef SQLITE_OMIT_UPSERT + case OE_Update: { + tdsqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur); + /* Fall through */ + } +#endif case OE_Ignore: { - /*assert( seenReplace==0 );*/ - sqlite3VdbeGoto(v, ignoreDest); + testcase( onError==OE_Ignore ); + tdsqlite3VdbeGoto(v, ignoreDest); break; } } - sqlite3VdbeResolveLabel(v, addrRowidOk); + tdsqlite3VdbeResolveLabel(v, addrRowidOk); if( ipkTop ){ - ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); - sqlite3VdbeJumpHere(v, ipkTop); + ipkBottom = tdsqlite3VdbeAddOp0(v, OP_Goto); + tdsqlite3VdbeJumpHere(v, ipkTop-1); } } @@ -111952,66 +124682,79 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( int regR; /* Range of registers holding conflicting PK */ int iThisCur; /* Cursor for this UNIQUE index */ int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ + int addrConflictCk; /* First opcode in the conflict check logic */ if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ - if( bAffinityDone==0 ){ - sqlite3TableAffinity(v, pTab, regNewData+1); + if( pUpIdx==pIdx ){ + addrUniqueOk = upsertJump+1; + upsertBypass = tdsqlite3VdbeGoto(v, 0); + VdbeComment((v, "Skip upsert subroutine")); + tdsqlite3VdbeJumpHere(v, upsertJump); + }else{ + addrUniqueOk = tdsqlite3VdbeMakeLabel(pParse); + } + if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){ + tdsqlite3TableAffinity(v, pTab, regNewData+1); bAffinityDone = 1; } + VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName)); iThisCur = iIdxCur+ix; - addrUniqueOk = sqlite3VdbeMakeLabel(v); + /* Skip partial indices for which the WHERE clause is not true */ if( pIdx->pPartIdxWhere ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); - pParse->ckBase = regNewData+1; - sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, + tdsqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); + pParse->iSelfTab = -(regNewData+1); + tdsqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, SQLITE_JUMPIFNULL); - pParse->ckBase = 0; + pParse->iSelfTab = 0; } /* Create a record for this index entry as it should appear after ** the insert or update. Store that record in the aRegIdx[ix] register */ - regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn); + regIdx = aRegIdx[ix]+1; for(i=0; i<pIdx->nColumn; i++){ int iField = pIdx->aiColumn[i]; int x; if( iField==XN_EXPR ){ - pParse->ckBase = regNewData+1; - sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); - pParse->ckBase = 0; + pParse->iSelfTab = -(regNewData+1); + tdsqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); + pParse->iSelfTab = 0; VdbeComment((v, "%s column %d", pIdx->zName, i)); + }else if( iField==XN_ROWID || iField==pTab->iPKey ){ + x = regNewData; + tdsqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i); + VdbeComment((v, "rowid")); }else{ - if( iField==XN_ROWID || iField==pTab->iPKey ){ - if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */ - x = regNewData; - regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i; - }else{ - x = iField + regNewData + 1; - } - sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i); - VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName)); + testcase( tdsqlite3TableColumnToStorage(pTab, iField)!=iField ); + x = tdsqlite3TableColumnToStorage(pTab, iField) + regNewData + 1; + tdsqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i); + VdbeComment((v, "%s", pTab->aCol[iField].zName)); } } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); VdbeComment((v, "for %s", pIdx->zName)); - sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn); +#ifdef SQLITE_ENABLE_NULL_TRIM + if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ + tdsqlite3SetMakeRecordP5(v, pIdx->pTable); + } +#endif + tdsqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0); /* In an UPDATE operation, if this index is the PRIMARY KEY index ** of a WITHOUT ROWID table and there has been no change the ** primary key, then no collision is possible. The collision detection ** logic below can all be skipped. */ if( isUpdate && pPk==pIdx && pkChng==0 ){ - sqlite3VdbeResolveLabel(v, addrUniqueOk); + tdsqlite3VdbeResolveLabel(v, addrUniqueOk); continue; } /* Find out what action to take in case there is a uniqueness conflict */ onError = pIdx->onError; if( onError==OE_None ){ - sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); - sqlite3VdbeResolveLabel(v, addrUniqueOk); + tdsqlite3VdbeResolveLabel(v, addrUniqueOk); continue; /* pIdx is not a UNIQUE index */ } if( overrideError!=OE_Default ){ @@ -112019,21 +124762,56 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( }else if( onError==OE_Default ){ onError = OE_Abort; } - + + /* Figure out if the upsert clause applies to this index */ + if( pUpIdx==pIdx ){ + if( pUpsert->pUpsertSet==0 ){ + onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ + }else{ + onError = OE_Update; /* DO UPDATE */ + } + } + + /* Collision detection may be omitted if all of the following are true: + ** (1) The conflict resolution algorithm is REPLACE + ** (2) The table is a WITHOUT ROWID table + ** (3) There are no secondary indexes on the table + ** (4) No delete triggers need to be fired if there is a conflict + ** (5) No FK constraint counters need to be updated if a conflict occurs. + ** + ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row + ** must be explicitly deleted in order to ensure any pre-update hook + ** is invoked. */ +#ifndef SQLITE_ENABLE_PREUPDATE_HOOK + if( (ix==0 && pIdx->pNext==0) /* Condition 3 */ + && pPk==pIdx /* Condition 2 */ + && onError==OE_Replace /* Condition 1 */ + && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */ + 0==tdsqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0)) + && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */ + (0==pTab->pFKey && 0==tdsqlite3FkReferences(pTab))) + ){ + tdsqlite3VdbeResolveLabel(v, addrUniqueOk); + continue; + } +#endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */ + /* Check to see if the new index entry will be unique */ - sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, - regIdx, pIdx->nKeyCol); VdbeCoverage(v); + tdsqlite3VdbeVerifyAbortable(v, onError); + addrConflictCk = + tdsqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, + regIdx, pIdx->nKeyCol); VdbeCoverage(v); /* Generate code to handle collisions */ - regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); + regR = (pIdx==pPk) ? regIdx : tdsqlite3GetTempRange(pParse, nPkField); if( isUpdate || onError==OE_Replace ){ if( HasRowid(pTab) ){ - sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); + tdsqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); /* Conflict only if the rowid of the existing index entry ** is different from old-rowid */ if( isUpdate ){ - sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); + tdsqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); + tdsqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v); } }else{ @@ -112043,8 +124821,8 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( if( pIdx!=pPk ){ for(i=0; i<pPk->nKeyCol; i++){ assert( pPk->aiColumn[i]>=0 ); - x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]); - sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); + x = tdsqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]); + tdsqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); VdbeComment((v, "%s.%s", pTab->zName, pTab->aCol[pPk->aiColumn[i]].zName)); } @@ -112057,22 +124835,23 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( ** For a UNIQUE index, only conflict if the PRIMARY KEY values ** of the matched index row are different from the original PRIMARY ** KEY values of this row before the update. */ - int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; + int addrJump = tdsqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; int op = OP_Ne; int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); for(i=0; i<pPk->nKeyCol; i++){ - char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); + char *p4 = (char*)tdsqlite3LocateCollSeq(pParse, pPk->azColl[i]); x = pPk->aiColumn[i]; assert( x>=0 ); if( i==(pPk->nKeyCol-1) ){ addrJump = addrUniqueOk; op = OP_Eq; } - sqlite3VdbeAddOp4(v, op, + x = tdsqlite3TableColumnToStorage(pTab, x); + tdsqlite3VdbeAddOp4(v, op, regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ ); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); + tdsqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverageIf(v, op==OP_Eq); VdbeCoverageIf(v, op==OP_Ne); } @@ -112082,103 +124861,241 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( /* Generate code that executes if the new index entry is not unique */ assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail - || onError==OE_Ignore || onError==OE_Replace ); + || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update ); switch( onError ){ case OE_Rollback: case OE_Abort: case OE_Fail: { - sqlite3UniqueConstraint(pParse, onError, pIdx); + testcase( onError==OE_Rollback ); + testcase( onError==OE_Abort ); + testcase( onError==OE_Fail ); + tdsqlite3UniqueConstraint(pParse, onError, pIdx); break; } +#ifndef SQLITE_OMIT_UPSERT + case OE_Update: { + tdsqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix); + /* Fall through */ + } +#endif case OE_Ignore: { - sqlite3VdbeGoto(v, ignoreDest); + testcase( onError==OE_Ignore ); + tdsqlite3VdbeGoto(v, ignoreDest); break; } default: { - Trigger *pTrigger = 0; + int nConflictCk; /* Number of opcodes in conflict check logic */ + assert( onError==OE_Replace ); - sqlite3MultiWrite(pParse); - if( db->flags&SQLITE_RecTriggers ){ - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); + nConflictCk = tdsqlite3VdbeCurrentAddr(v) - addrConflictCk; + assert( nConflictCk>0 ); + testcase( nConflictCk>1 ); + if( regTrigCnt ){ + tdsqlite3MultiWrite(pParse); + nReplaceTrig++; + } + if( pTrigger && isUpdate ){ + tdsqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur); } - sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, + tdsqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, regR, nPkField, 0, OE_Replace, - (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1); + (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur); + if( pTrigger && isUpdate ){ + tdsqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur); + } + if( regTrigCnt ){ + int addrBypass; /* Jump destination to bypass recheck logic */ + + tdsqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ + addrBypass = tdsqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */ + VdbeComment((v, "bypass recheck")); + + /* Here we insert code that will be invoked after all constraint + ** checks have run, if and only if one or more replace triggers + ** fired. */ + tdsqlite3VdbeResolveLabel(v, lblRecheckOk); + lblRecheckOk = tdsqlite3VdbeMakeLabel(pParse); + if( pIdx->pPartIdxWhere ){ + /* Bypass the recheck if this partial index is not defined + ** for the current row */ + tdsqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk); + VdbeCoverage(v); + } + /* Copy the constraint check code from above, except change + ** the constraint-ok jump destination to be the address of + ** the next retest block */ + while( nConflictCk>0 ){ + VdbeOp x; /* Conflict check opcode to copy */ + /* The tdsqlite3VdbeAddOp4() call might reallocate the opcode array. + ** Hence, make a complete copy of the opcode, rather than using + ** a pointer to the opcode. */ + x = *tdsqlite3VdbeGetOp(v, addrConflictCk); + if( x.opcode!=OP_IdxRowid ){ + int p2; /* New P2 value for copied conflict check opcode */ + if( tdsqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){ + p2 = lblRecheckOk; + }else{ + p2 = x.p2; + } + tdsqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, x.p4.z, x.p4type); + tdsqlite3VdbeChangeP5(v, x.p5); + VdbeCoverageIf(v, p2!=x.p2); + } + nConflictCk--; + addrConflictCk++; + } + /* If the retest fails, issue an abort */ + tdsqlite3UniqueConstraint(pParse, OE_Abort, pIdx); + + tdsqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */ + } seenReplace = 1; break; } } - sqlite3VdbeResolveLabel(v, addrUniqueOk); - sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn); - if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); + if( pUpIdx==pIdx ){ + tdsqlite3VdbeGoto(v, upsertJump+1); + tdsqlite3VdbeJumpHere(v, upsertBypass); + }else{ + tdsqlite3VdbeResolveLabel(v, addrUniqueOk); + } + if( regR!=regIdx ) tdsqlite3ReleaseTempRange(pParse, regR, nPkField); } + + /* If the IPK constraint is a REPLACE, run it last */ if( ipkTop ){ - sqlite3VdbeGoto(v, ipkTop+1); - sqlite3VdbeJumpHere(v, ipkBottom); + tdsqlite3VdbeGoto(v, ipkTop); + VdbeComment((v, "Do IPK REPLACE")); + tdsqlite3VdbeJumpHere(v, ipkBottom); + } + + /* Recheck all uniqueness constraints after replace triggers have run */ + testcase( regTrigCnt!=0 && nReplaceTrig==0 ); + assert( regTrigCnt!=0 || nReplaceTrig==0 ); + if( nReplaceTrig ){ + tdsqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v); + if( !pPk ){ + if( isUpdate ){ + tdsqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData); + tdsqlite3VdbeChangeP5(v, SQLITE_NOTNULL); + VdbeCoverage(v); + } + tdsqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData); + VdbeCoverage(v); + tdsqlite3RowidConstraint(pParse, OE_Abort, pTab); + }else{ + tdsqlite3VdbeGoto(v, addrRecheck); + } + tdsqlite3VdbeResolveLabel(v, lblRecheckOk); } - + + /* Generate the table record */ + if( HasRowid(pTab) ){ + int regRec = aRegIdx[ix]; + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec); + tdsqlite3SetMakeRecordP5(v, pTab); + if( !bAffinityDone ){ + tdsqlite3TableAffinity(v, pTab, 0); + } + } + *pbMayReplace = seenReplace; VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); } +#ifdef SQLITE_ENABLE_NULL_TRIM +/* +** Change the P5 operand on the last opcode (which should be an OP_MakeRecord) +** to be the number of columns in table pTab that must not be NULL-trimmed. +** +** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero. +*/ +SQLITE_PRIVATE void tdsqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){ + u16 i; + + /* Records with omitted columns are only allowed for schema format + ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */ + if( pTab->pSchema->file_format<2 ) return; + + for(i=pTab->nCol-1; i>0; i--){ + if( pTab->aCol[i].pDflt!=0 ) break; + if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break; + } + tdsqlite3VdbeChangeP5(v, i+1); +} +#endif + /* ** This routine generates code to finish the INSERT or UPDATE operation -** that was started by a prior call to sqlite3GenerateConstraintChecks. +** that was started by a prior call to tdsqlite3GenerateConstraintChecks. ** A consecutive range of registers starting at regNewData contains the ** rowid and the content to be inserted. ** ** The arguments to this routine should be the same as the first six -** arguments to sqlite3GenerateConstraintChecks. +** arguments to tdsqlite3GenerateConstraintChecks. */ -SQLITE_PRIVATE void sqlite3CompleteInsertion( +SQLITE_PRIVATE void tdsqlite3CompleteInsertion( Parse *pParse, /* The parser context */ Table *pTab, /* the table into which we are inserting */ int iDataCur, /* Cursor of the canonical data source */ int iIdxCur, /* First index cursor */ int regNewData, /* Range of content */ int *aRegIdx, /* Register used by each index. 0 for unused indices */ - int isUpdate, /* True for UPDATE, False for INSERT */ + int update_flags, /* True for UPDATE, False for INSERT */ int appendBias, /* True if this is likely to be an append */ int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ ){ Vdbe *v; /* Prepared statements under construction */ Index *pIdx; /* An index being inserted or updated */ u8 pik_flags; /* flag values passed to the btree insert */ - int regData; /* Content registers (after the rowid) */ - int regRec; /* Register holding assembled record for the table */ int i; /* Loop counter */ - u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ - v = sqlite3GetVdbe(pParse); + assert( update_flags==0 + || update_flags==OPFLAG_ISUPDATE + || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION) + ); + + v = tdsqlite3GetVdbe(pParse); assert( v!=0 ); assert( pTab->pSelect==0 ); /* This table is not a VIEW */ for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + /* All REPLACE indexes are at the end of the list */ + assert( pIdx->onError!=OE_Replace + || pIdx->pNext==0 + || pIdx->pNext->onError==OE_Replace ); if( aRegIdx[i]==0 ) continue; - bAffinityDone = 1; if( pIdx->pPartIdxWhere ){ - sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); + tdsqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], tdsqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); } - sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]); - pik_flags = 0; - if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT; + pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0); if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ assert( pParse->nested==0 ); pik_flags |= OPFLAG_NCHANGE; + pik_flags |= (update_flags & OPFLAG_SAVEPOSITION); +#ifdef SQLITE_ENABLE_PREUPDATE_HOOK + if( update_flags==0 ){ + int r = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, r); + tdsqlite3VdbeAddOp4(v, OP_Insert, + iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE + ); + tdsqlite3VdbeChangeP5(v, OPFLAG_ISNOOP); + tdsqlite3ReleaseTempReg(pParse, r); + } +#endif } - sqlite3VdbeChangeP5(v, pik_flags); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i], + aRegIdx[i]+1, + pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn); + tdsqlite3VdbeChangeP5(v, pik_flags); } if( !HasRowid(pTab) ) return; - regData = regNewData + 1; - regRec = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); - if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0); - sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); if( pParse->nested ){ pik_flags = 0; }else{ pik_flags = OPFLAG_NCHANGE; - pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); + pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID); } if( appendBias ){ pik_flags |= OPFLAG_APPEND; @@ -112186,11 +125103,11 @@ SQLITE_PRIVATE void sqlite3CompleteInsertion( if( useSeekResult ){ pik_flags |= OPFLAG_USESEEKRESULT; } - sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData); + tdsqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData); if( !pParse->nested ){ - sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE); + tdsqlite3VdbeAppendP4(v, pTab, P4_TABLE); } - sqlite3VdbeChangeP5(v, pik_flags); + tdsqlite3VdbeChangeP5(v, pik_flags); } /* @@ -112214,7 +125131,7 @@ SQLITE_PRIVATE void sqlite3CompleteInsertion( ** If pTab is a virtual table, then this routine is a no-op and the ** *piDataCur and *piIdxCur values are left uninitialized. */ -SQLITE_PRIVATE int sqlite3OpenTableAndIndices( +SQLITE_PRIVATE int tdsqlite3OpenTableAndIndices( Parse *pParse, /* Parsing context */ Table *pTab, /* Table to be opened */ int op, /* OP_OpenRead or OP_OpenWrite */ @@ -112238,16 +125155,16 @@ SQLITE_PRIVATE int sqlite3OpenTableAndIndices( ** can detect if they are used by mistake in the caller. */ return 0; } - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - v = sqlite3GetVdbe(pParse); + iDb = tdsqlite3SchemaToIndex(pParse->db, pTab->pSchema); + v = tdsqlite3GetVdbe(pParse); assert( v!=0 ); if( iBase<0 ) iBase = pParse->nTab; iDataCur = iBase++; if( piDataCur ) *piDataCur = iDataCur; if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ - sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); + tdsqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); }else{ - sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); + tdsqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); } if( piIdxCur ) *piIdxCur = iBase; for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ @@ -112258,9 +125175,9 @@ SQLITE_PRIVATE int sqlite3OpenTableAndIndices( p5 = 0; } if( aToOpen==0 || aToOpen[i+1] ){ - sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); - sqlite3VdbeChangeP5(v, p5); + tdsqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); + tdsqlite3VdbeSetP4KeyInfo(pParse, pIdx); + tdsqlite3VdbeChangeP5(v, p5); VdbeComment((v, "%s", pIdx->zName)); } } @@ -112276,7 +125193,7 @@ SQLITE_PRIVATE int sqlite3OpenTableAndIndices( ** purposes only - to make sure the transfer optimization really ** is happening when it is supposed to. */ -SQLITE_API int sqlite3_xferopt_count; +SQLITE_API int tdsqlite3_xferopt_count; #endif /* SQLITE_TEST */ @@ -112296,7 +125213,7 @@ static int xferCompatibleIndex(Index *pDest, Index *pSrc){ int i; assert( pDest && pSrc ); assert( pDest->pTable!=pSrc->pTable ); - if( pDest->nKeyCol!=pSrc->nKeyCol ){ + if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){ return 0; /* Different number of columns */ } if( pDest->onError!=pSrc->onError ){ @@ -112308,7 +125225,7 @@ static int xferCompatibleIndex(Index *pDest, Index *pSrc){ } if( pSrc->aiColumn[i]==XN_EXPR ){ assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); - if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr, + if( tdsqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr, pDest->aColExpr->a[i].pExpr, -1)!=0 ){ return 0; /* Different expressions in the index */ } @@ -112316,11 +125233,11 @@ static int xferCompatibleIndex(Index *pDest, Index *pSrc){ if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ return 0; /* Different sort orders */ } - if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ + if( tdsqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ return 0; /* Different collating sequences */ } } - if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ + if( tdsqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ return 0; /* Different WHERE clauses */ } @@ -112360,7 +125277,7 @@ static int xferOptimization( int onError, /* How to handle constraint errors */ int iDbDest /* The database of pDest */ ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; ExprList *pEList; /* The result set of the SELECT */ Table *pSrc; /* The table in the FROM clause of SELECT */ Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ @@ -112385,11 +125302,11 @@ static int xferOptimization( ** error if pSelect reads from a CTE named "xxx". */ return 0; } - if( sqlite3TriggerList(pParse, pDest) ){ + if( tdsqlite3TriggerList(pParse, pDest) ){ return 0; /* tab1 must not have triggers */ } #ifndef SQLITE_OMIT_VIRTUALTABLE - if( pDest->tabFlags & TF_Virtual ){ + if( IsVirtual(pDest) ){ return 0; /* tab1 must not be a virtual table */ } #endif @@ -112418,7 +125335,6 @@ static int xferOptimization( if( pSelect->pLimit ){ return 0; /* SELECT may not have a LIMIT clause */ } - assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ if( pSelect->pPrior ){ return 0; /* SELECT may not be a compound query */ } @@ -112440,18 +125356,19 @@ static int xferOptimization( ** we have to check the semantics. */ pItem = pSelect->pSrc->a; - pSrc = sqlite3LocateTableItem(pParse, 0, pItem); + pSrc = tdsqlite3LocateTableItem(pParse, 0, pItem); if( pSrc==0 ){ return 0; /* FROM clause does not contain a real table */ } - if( pSrc==pDest ){ + if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){ + testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */ return 0; /* tab1 and tab2 may not be the same table */ } if( HasRowid(pDest)!=HasRowid(pSrc) ){ return 0; /* source and destination must both be WITHOUT ROWID or not */ } #ifndef SQLITE_OMIT_VIRTUALTABLE - if( pSrc->tabFlags & TF_Virtual ){ + if( IsVirtual(pSrc) ){ return 0; /* tab2 must not be a virtual table */ } #endif @@ -112468,23 +125385,56 @@ static int xferOptimization( Column *pDestCol = &pDest->aCol[i]; Column *pSrcCol = &pSrc->aCol[i]; #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS - if( (db->flags & SQLITE_Vacuum)==0 + if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN ){ return 0; /* Neither table may have __hidden__ columns */ } #endif +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + /* Even if tables t1 and t2 have identical schemas, if they contain + ** generated columns, then this statement is semantically incorrect: + ** + ** INSERT INTO t2 SELECT * FROM t1; + ** + ** The reason is that generated column values are returned by the + ** the SELECT statement on the right but the INSERT statement on the + ** left wants them to be omitted. + ** + ** Nevertheless, this is a useful notational shorthand to tell SQLite + ** to do a bulk transfer all of the content from t1 over to t2. + ** + ** We could, in theory, disable this (except for internal use by the + ** VACUUM command where it is actually needed). But why do that? It + ** seems harmless enough, and provides a useful service. + */ + if( (pDestCol->colFlags & COLFLAG_GENERATED) != + (pSrcCol->colFlags & COLFLAG_GENERATED) ){ + return 0; /* Both columns have the same generated-column type */ + } + /* But the transfer is only allowed if both the source and destination + ** tables have the exact same expressions for generated columns. + ** This requirement could be relaxed for VIRTUAL columns, I suppose. + */ + if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){ + if( tdsqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){ + testcase( pDestCol->colFlags & COLFLAG_VIRTUAL ); + testcase( pDestCol->colFlags & COLFLAG_STORED ); + return 0; /* Different generator expressions */ + } + } +#endif if( pDestCol->affinity!=pSrcCol->affinity ){ return 0; /* Affinity must be the same on all columns */ } - if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ + if( tdsqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ return 0; /* Collating sequence must be the same on all columns */ } if( pDestCol->notNull && !pSrcCol->notNull ){ return 0; /* tab2 must be NOT NULL if tab1 is */ } /* Default values for second and subsequent columns need to match. */ - if( i>0 ){ + if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){ assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) @@ -112505,9 +125455,16 @@ static int xferOptimization( if( pSrcIdx==0 ){ return 0; /* pDestIdx has no corresponding index in pSrc */ } + if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema + && tdsqlite3FaultSim(411)==SQLITE_OK ){ + /* The tdsqlite3FaultSim() call allows this corruption test to be + ** bypassed during testing, in order to exercise other corruption tests + ** further downstream. */ + return 0; /* Corrupt schema - two indexes on the same btree */ + } } #ifndef SQLITE_OMIT_CHECK - if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ + if( pDest->pCheck && tdsqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ return 0; /* Tables have different CHECK constraints. Ticket #2252 */ } #endif @@ -112532,27 +125489,27 @@ static int xferOptimization( ** table (tab1) is initially empty. */ #ifdef SQLITE_TEST - sqlite3_xferopt_count++; + tdsqlite3_xferopt_count++; #endif - iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); - v = sqlite3GetVdbe(pParse); - sqlite3CodeVerifySchema(pParse, iDbSrc); + iDbSrc = tdsqlite3SchemaToIndex(db, pSrc->pSchema); + v = tdsqlite3GetVdbe(pParse); + tdsqlite3CodeVerifySchema(pParse, iDbSrc); iSrc = pParse->nTab++; iDest = pParse->nTab++; regAutoinc = autoIncBegin(pParse, iDbDest, pDest); - regData = sqlite3GetTempReg(pParse); - regRowid = sqlite3GetTempReg(pParse); - sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); + regData = tdsqlite3GetTempReg(pParse); + regRowid = tdsqlite3GetTempReg(pParse); + tdsqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); assert( HasRowid(pDest) || destHasUniqueIdx ); - if( (db->flags & SQLITE_Vacuum)==0 && ( + if( (db->mDbFlags & DBFLAG_Vacuum)==0 && ( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ || destHasUniqueIdx /* (2) */ || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ )){ /* In some circumstances, we are able to run the xfer optimization ** only if the destination table is initially empty. Unless the - ** SQLITE_Vacuum flag is set, this block generates code to make - ** that determination. If SQLITE_Vacuum is set, then the destination + ** DBFLAG_Vacuum flag is set, this block generates code to make + ** that determination. If DBFLAG_Vacuum is set, then the destination ** table is always empty. ** ** Conditions under which the destination must be empty: @@ -112566,36 +125523,45 @@ static int xferOptimization( ** ** (3) onError is something other than OE_Abort and OE_Rollback. */ - addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); - emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); - sqlite3VdbeJumpHere(v, addr1); + addr1 = tdsqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); + emptyDestTest = tdsqlite3VdbeAddOp0(v, OP_Goto); + tdsqlite3VdbeJumpHere(v, addr1); } if( HasRowid(pSrc) ){ - sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); - emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); + u8 insFlags; + tdsqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); + emptySrcTest = tdsqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); if( pDest->iPKey>=0 ){ - addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); - addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); + addr1 = tdsqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); + tdsqlite3VdbeVerifyAbortable(v, onError); + addr2 = tdsqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); VdbeCoverage(v); - sqlite3RowidConstraint(pParse, onError, pDest); - sqlite3VdbeJumpHere(v, addr2); + tdsqlite3RowidConstraint(pParse, onError, pDest); + tdsqlite3VdbeJumpHere(v, addr2); autoIncStep(pParse, regAutoinc, regRowid); - }else if( pDest->pIndex==0 ){ - addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); + }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){ + addr1 = tdsqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); }else{ - addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); + addr1 = tdsqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); assert( (pDest->tabFlags & TF_Autoincrement)==0 ); } - sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); - sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, + tdsqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); + if( db->mDbFlags & DBFLAG_Vacuum ){ + tdsqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); + insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID| + OPFLAG_APPEND|OPFLAG_USESEEKRESULT; + }else{ + insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND; + } + tdsqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, (char*)pDest, P4_TABLE); - sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); - sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + tdsqlite3VdbeChangeP5(v, insFlags); + tdsqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + tdsqlite3VdbeAddOp2(v, OP_Close, iDest, 0); }else{ - sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); - sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); + tdsqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); + tdsqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); } for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ u8 idxInsFlags = 0; @@ -112603,22 +125569,22 @@ static int xferOptimization( if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; } assert( pSrcIdx ); - sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); - sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); + tdsqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); + tdsqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); VdbeComment((v, "%s", pSrcIdx->zName)); - sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); - sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); - sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); + tdsqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); + tdsqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); + tdsqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); VdbeComment((v, "%s", pDestIdx->zName)); - addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); - if( db->flags & SQLITE_Vacuum ){ + addr1 = tdsqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); + if( db->mDbFlags & DBFLAG_Vacuum ){ /* This INSERT command is part of a VACUUM operation, which guarantees ** that the destination table is empty. If all indexed columns use ** collation sequence BINARY, then it can also be assumed that the ** index will be populated by inserting keys in strictly sorted ** order. In this case, instead of seeking within the b-tree as part - ** of every OP_IdxInsert opcode, an OP_Last is added before the + ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the ** OP_IdxInsert to seek to the point within the b-tree where each key ** should be inserted. This is faster. ** @@ -112629,33 +125595,31 @@ static int xferOptimization( ** sorted order. */ for(i=0; i<pSrcIdx->nColumn; i++){ const char *zColl = pSrcIdx->azColl[i]; - assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0 - || sqlite3StrBINARY==zColl ); - if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; + if( tdsqlite3_stricmp(tdsqlite3StrBINARY, zColl) ) break; } if( i==pSrcIdx->nColumn ){ idxInsFlags = OPFLAG_USESEEKRESULT; - sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1); + tdsqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); } } - if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ + if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ idxInsFlags |= OPFLAG_NCHANGE; } - sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); - sqlite3VdbeChangeP5(v, idxInsFlags); - sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + tdsqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData); + tdsqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND); + tdsqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addr1); + tdsqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + tdsqlite3VdbeAddOp2(v, OP_Close, iDest, 0); } - if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); - sqlite3ReleaseTempReg(pParse, regRowid); - sqlite3ReleaseTempReg(pParse, regData); + if( emptySrcTest ) tdsqlite3VdbeJumpHere(v, emptySrcTest); + tdsqlite3ReleaseTempReg(pParse, regRowid); + tdsqlite3ReleaseTempReg(pParse, regData); if( emptyDestTest ){ - sqlite3AutoincrementEnd(pParse); - sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); - sqlite3VdbeJumpHere(v, emptyDestTest); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + tdsqlite3AutoincrementEnd(pParse); + tdsqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); + tdsqlite3VdbeJumpHere(v, emptyDestTest); + tdsqlite3VdbeAddOp2(v, OP_Close, iDest, 0); return 0; }else{ return 1; @@ -112694,30 +125658,30 @@ static int xferOptimization( ** argument to xCallback(). If xCallback=NULL then no callback ** is invoked, even for queries. */ -SQLITE_API int sqlite3_exec( - sqlite3 *db, /* The database on which the SQL executes */ +SQLITE_API int tdsqlite3_exec( + tdsqlite3 *db, /* The database on which the SQL executes */ const char *zSql, /* The SQL to be executed */ - sqlite3_callback xCallback, /* Invoke this callback routine */ + tdsqlite3_callback xCallback, /* Invoke this callback routine */ void *pArg, /* First argument to xCallback() */ char **pzErrMsg /* Write error messages here */ ){ int rc = SQLITE_OK; /* Return code */ const char *zLeftover; /* Tail of unprocessed SQL */ - sqlite3_stmt *pStmt = 0; /* The current SQL statement */ + tdsqlite3_stmt *pStmt = 0; /* The current SQL statement */ char **azCols = 0; /* Names of result columns */ int callbackIsInit; /* True if callback data is initialized */ - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; if( zSql==0 ) zSql = ""; - sqlite3_mutex_enter(db->mutex); - sqlite3Error(db, SQLITE_OK); + tdsqlite3_mutex_enter(db->mutex); + tdsqlite3Error(db, SQLITE_OK); while( rc==SQLITE_OK && zSql[0] ){ - int nCol; + int nCol = 0; char **azVals = 0; pStmt = 0; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); + rc = tdsqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); assert( rc==SQLITE_OK || pStmt==0 ); if( rc!=SQLITE_OK ){ continue; @@ -112727,27 +125691,26 @@ SQLITE_API int sqlite3_exec( zSql = zLeftover; continue; } - callbackIsInit = 0; - nCol = sqlite3_column_count(pStmt); while( 1 ){ int i; - rc = sqlite3_step(pStmt); + rc = tdsqlite3_step(pStmt); /* Invoke the callback function if required */ if( xCallback && (SQLITE_ROW==rc || (SQLITE_DONE==rc && !callbackIsInit && db->flags&SQLITE_NullCallback)) ){ if( !callbackIsInit ){ - azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); + nCol = tdsqlite3_column_count(pStmt); + azCols = tdsqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*)); if( azCols==0 ){ goto exec_out; } for(i=0; i<nCol; i++){ - azCols[i] = (char *)sqlite3_column_name(pStmt, i); - /* sqlite3VdbeSetColName() installs column names as UTF8 - ** strings so there is no way for sqlite3_column_name() to fail. */ + azCols[i] = (char *)tdsqlite3_column_name(pStmt, i); + /* tdsqlite3VdbeSetColName() installs column names as UTF8 + ** strings so there is no way for tdsqlite3_column_name() to fail. */ assert( azCols[i]!=0 ); } callbackIsInit = 1; @@ -112755,58 +125718,56 @@ SQLITE_API int sqlite3_exec( if( rc==SQLITE_ROW ){ azVals = &azCols[nCol]; for(i=0; i<nCol; i++){ - azVals[i] = (char *)sqlite3_column_text(pStmt, i); - if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){ - sqlite3OomFault(db); + azVals[i] = (char *)tdsqlite3_column_text(pStmt, i); + if( !azVals[i] && tdsqlite3_column_type(pStmt, i)!=SQLITE_NULL ){ + tdsqlite3OomFault(db); goto exec_out; } } + azVals[i] = 0; } if( xCallback(pArg, nCol, azVals, azCols) ){ /* EVIDENCE-OF: R-38229-40159 If the callback function to - ** sqlite3_exec() returns non-zero, then sqlite3_exec() will + ** tdsqlite3_exec() returns non-zero, then tdsqlite3_exec() will ** return SQLITE_ABORT. */ rc = SQLITE_ABORT; - sqlite3VdbeFinalize((Vdbe *)pStmt); + tdsqlite3VdbeFinalize((Vdbe *)pStmt); pStmt = 0; - sqlite3Error(db, SQLITE_ABORT); + tdsqlite3Error(db, SQLITE_ABORT); goto exec_out; } } if( rc!=SQLITE_ROW ){ - rc = sqlite3VdbeFinalize((Vdbe *)pStmt); + rc = tdsqlite3VdbeFinalize((Vdbe *)pStmt); pStmt = 0; zSql = zLeftover; - while( sqlite3Isspace(zSql[0]) ) zSql++; + while( tdsqlite3Isspace(zSql[0]) ) zSql++; break; } } - sqlite3DbFree(db, azCols); + tdsqlite3DbFree(db, azCols); azCols = 0; } exec_out: - if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt); - sqlite3DbFree(db, azCols); + if( pStmt ) tdsqlite3VdbeFinalize((Vdbe *)pStmt); + tdsqlite3DbFree(db, azCols); - rc = sqlite3ApiExit(db, rc); + rc = tdsqlite3ApiExit(db, rc); if( rc!=SQLITE_OK && pzErrMsg ){ - int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db)); - *pzErrMsg = sqlite3Malloc(nErrMsg); - if( *pzErrMsg ){ - memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg); - }else{ + *pzErrMsg = tdsqlite3DbStrDup(0, tdsqlite3_errmsg(db)); + if( *pzErrMsg==0 ){ rc = SQLITE_NOMEM_BKPT; - sqlite3Error(db, SQLITE_NOMEM); + tdsqlite3Error(db, SQLITE_NOMEM); } }else if( pzErrMsg ){ *pzErrMsg = 0; } assert( (rc&db->errMask)==rc ); - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -112828,10 +125789,10 @@ exec_out: */ #ifndef SQLITE_CORE - #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ + #define SQLITE_CORE 1 /* Disable the API redefinition in tdsqlite3ext.h */ #endif -/************** Include sqlite3ext.h in the middle of loadext.c **************/ -/************** Begin file sqlite3ext.h **************************************/ +/************** Include tdsqlite3ext.h in the middle of loadext.c **************/ +/************** Begin file tdsqlite3ext.h **************************************/ /* ** 2006 June 7 ** @@ -112863,526 +125824,616 @@ exec_out: ** versions of SQLite will not be able to load each other's shared ** libraries! */ -struct sqlite3_api_routines { - void * (*aggregate_context)(sqlite3_context*,int nBytes); - int (*aggregate_count)(sqlite3_context*); - int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); - int (*bind_double)(sqlite3_stmt*,int,double); - int (*bind_int)(sqlite3_stmt*,int,int); - int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); - int (*bind_null)(sqlite3_stmt*,int); - int (*bind_parameter_count)(sqlite3_stmt*); - int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); - const char * (*bind_parameter_name)(sqlite3_stmt*,int); - int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); - int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); - int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); - int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); - int (*busy_timeout)(sqlite3*,int ms); - int (*changes)(sqlite3*); - int (*close)(sqlite3*); - int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, +struct tdsqlite3_api_routines { + void * (*aggregate_context)(tdsqlite3_context*,int nBytes); + int (*aggregate_count)(tdsqlite3_context*); + int (*bind_blob)(tdsqlite3_stmt*,int,const void*,int n,void(*)(void*)); + int (*bind_double)(tdsqlite3_stmt*,int,double); + int (*bind_int)(tdsqlite3_stmt*,int,int); + int (*bind_int64)(tdsqlite3_stmt*,int,sqlite_int64); + int (*bind_null)(tdsqlite3_stmt*,int); + int (*bind_parameter_count)(tdsqlite3_stmt*); + int (*bind_parameter_index)(tdsqlite3_stmt*,const char*zName); + const char * (*bind_parameter_name)(tdsqlite3_stmt*,int); + int (*bind_text)(tdsqlite3_stmt*,int,const char*,int n,void(*)(void*)); + int (*bind_text16)(tdsqlite3_stmt*,int,const void*,int,void(*)(void*)); + int (*bind_value)(tdsqlite3_stmt*,int,const tdsqlite3_value*); + int (*busy_handler)(tdsqlite3*,int(*)(void*,int),void*); + int (*busy_timeout)(tdsqlite3*,int ms); + int (*changes)(tdsqlite3*); + int (*close)(tdsqlite3*); + int (*collation_needed)(tdsqlite3*,void*,void(*)(void*,tdsqlite3*, int eTextRep,const char*)); - int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, + int (*collation_needed16)(tdsqlite3*,void*,void(*)(void*,tdsqlite3*, int eTextRep,const void*)); - const void * (*column_blob)(sqlite3_stmt*,int iCol); - int (*column_bytes)(sqlite3_stmt*,int iCol); - int (*column_bytes16)(sqlite3_stmt*,int iCol); - int (*column_count)(sqlite3_stmt*pStmt); - const char * (*column_database_name)(sqlite3_stmt*,int); - const void * (*column_database_name16)(sqlite3_stmt*,int); - const char * (*column_decltype)(sqlite3_stmt*,int i); - const void * (*column_decltype16)(sqlite3_stmt*,int); - double (*column_double)(sqlite3_stmt*,int iCol); - int (*column_int)(sqlite3_stmt*,int iCol); - sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); - const char * (*column_name)(sqlite3_stmt*,int); - const void * (*column_name16)(sqlite3_stmt*,int); - const char * (*column_origin_name)(sqlite3_stmt*,int); - const void * (*column_origin_name16)(sqlite3_stmt*,int); - const char * (*column_table_name)(sqlite3_stmt*,int); - const void * (*column_table_name16)(sqlite3_stmt*,int); - const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); - const void * (*column_text16)(sqlite3_stmt*,int iCol); - int (*column_type)(sqlite3_stmt*,int iCol); - sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); - void * (*commit_hook)(sqlite3*,int(*)(void*),void*); + const void * (*column_blob)(tdsqlite3_stmt*,int iCol); + int (*column_bytes)(tdsqlite3_stmt*,int iCol); + int (*column_bytes16)(tdsqlite3_stmt*,int iCol); + int (*column_count)(tdsqlite3_stmt*pStmt); + const char * (*column_database_name)(tdsqlite3_stmt*,int); + const void * (*column_database_name16)(tdsqlite3_stmt*,int); + const char * (*column_decltype)(tdsqlite3_stmt*,int i); + const void * (*column_decltype16)(tdsqlite3_stmt*,int); + double (*column_double)(tdsqlite3_stmt*,int iCol); + int (*column_int)(tdsqlite3_stmt*,int iCol); + sqlite_int64 (*column_int64)(tdsqlite3_stmt*,int iCol); + const char * (*column_name)(tdsqlite3_stmt*,int); + const void * (*column_name16)(tdsqlite3_stmt*,int); + const char * (*column_origin_name)(tdsqlite3_stmt*,int); + const void * (*column_origin_name16)(tdsqlite3_stmt*,int); + const char * (*column_table_name)(tdsqlite3_stmt*,int); + const void * (*column_table_name16)(tdsqlite3_stmt*,int); + const unsigned char * (*column_text)(tdsqlite3_stmt*,int iCol); + const void * (*column_text16)(tdsqlite3_stmt*,int iCol); + int (*column_type)(tdsqlite3_stmt*,int iCol); + tdsqlite3_value* (*column_value)(tdsqlite3_stmt*,int iCol); + void * (*commit_hook)(tdsqlite3*,int(*)(void*),void*); int (*complete)(const char*sql); int (*complete16)(const void*sql); - int (*create_collation)(sqlite3*,const char*,int,void*, + int (*create_collation)(tdsqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*)); - int (*create_collation16)(sqlite3*,const void*,int,void*, + int (*create_collation16)(tdsqlite3*,const void*,int,void*, int(*)(void*,int,const void*,int,const void*)); - int (*create_function)(sqlite3*,const char*,int,int,void*, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*)); - int (*create_function16)(sqlite3*,const void*,int,int,void*, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*)); - int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); - int (*data_count)(sqlite3_stmt*pStmt); - sqlite3 * (*db_handle)(sqlite3_stmt*); - int (*declare_vtab)(sqlite3*,const char*); + int (*create_function)(tdsqlite3*,const char*,int,int,void*, + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*)); + int (*create_function16)(tdsqlite3*,const void*,int,int,void*, + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*)); + int (*create_module)(tdsqlite3*,const char*,const tdsqlite3_module*,void*); + int (*data_count)(tdsqlite3_stmt*pStmt); + tdsqlite3 * (*db_handle)(tdsqlite3_stmt*); + int (*declare_vtab)(tdsqlite3*,const char*); int (*enable_shared_cache)(int); - int (*errcode)(sqlite3*db); - const char * (*errmsg)(sqlite3*); - const void * (*errmsg16)(sqlite3*); - int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); - int (*expired)(sqlite3_stmt*); - int (*finalize)(sqlite3_stmt*pStmt); + int (*errcode)(tdsqlite3*db); + const char * (*errmsg)(tdsqlite3*); + const void * (*errmsg16)(tdsqlite3*); + int (*exec)(tdsqlite3*,const char*,tdsqlite3_callback,void*,char**); + int (*expired)(tdsqlite3_stmt*); + int (*finalize)(tdsqlite3_stmt*pStmt); void (*free)(void*); void (*free_table)(char**result); - int (*get_autocommit)(sqlite3*); - void * (*get_auxdata)(sqlite3_context*,int); - int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); + int (*get_autocommit)(tdsqlite3*); + void * (*get_auxdata)(tdsqlite3_context*,int); + int (*get_table)(tdsqlite3*,const char*,char***,int*,int*,char**); int (*global_recover)(void); - void (*interruptx)(sqlite3*); - sqlite_int64 (*last_insert_rowid)(sqlite3*); + void (*interruptx)(tdsqlite3*); + sqlite_int64 (*last_insert_rowid)(tdsqlite3*); const char * (*libversion)(void); int (*libversion_number)(void); void *(*malloc)(int); char * (*mprintf)(const char*,...); - int (*open)(const char*,sqlite3**); - int (*open16)(const void*,sqlite3**); - int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); - int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); - void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); - void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); + int (*open)(const char*,tdsqlite3**); + int (*open16)(const void*,tdsqlite3**); + int (*prepare)(tdsqlite3*,const char*,int,tdsqlite3_stmt**,const char**); + int (*prepare16)(tdsqlite3*,const void*,int,tdsqlite3_stmt**,const void**); + void * (*profile)(tdsqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); + void (*progress_handler)(tdsqlite3*,int,int(*)(void*),void*); void *(*realloc)(void*,int); - int (*reset)(sqlite3_stmt*pStmt); - void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_double)(sqlite3_context*,double); - void (*result_error)(sqlite3_context*,const char*,int); - void (*result_error16)(sqlite3_context*,const void*,int); - void (*result_int)(sqlite3_context*,int); - void (*result_int64)(sqlite3_context*,sqlite_int64); - void (*result_null)(sqlite3_context*); - void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); - void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_value)(sqlite3_context*,sqlite3_value*); - void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); - int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, + int (*reset)(tdsqlite3_stmt*pStmt); + void (*result_blob)(tdsqlite3_context*,const void*,int,void(*)(void*)); + void (*result_double)(tdsqlite3_context*,double); + void (*result_error)(tdsqlite3_context*,const char*,int); + void (*result_error16)(tdsqlite3_context*,const void*,int); + void (*result_int)(tdsqlite3_context*,int); + void (*result_int64)(tdsqlite3_context*,sqlite_int64); + void (*result_null)(tdsqlite3_context*); + void (*result_text)(tdsqlite3_context*,const char*,int,void(*)(void*)); + void (*result_text16)(tdsqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16be)(tdsqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16le)(tdsqlite3_context*,const void*,int,void(*)(void*)); + void (*result_value)(tdsqlite3_context*,tdsqlite3_value*); + void * (*rollback_hook)(tdsqlite3*,void(*)(void*),void*); + int (*set_authorizer)(tdsqlite3*,int(*)(void*,int,const char*,const char*, const char*,const char*),void*); - void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); - char * (*snprintf)(int,char*,const char*,...); - int (*step)(sqlite3_stmt*); - int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, + void (*set_auxdata)(tdsqlite3_context*,int,void*,void (*)(void*)); + char * (*xsnprintf)(int,char*,const char*,...); + int (*step)(tdsqlite3_stmt*); + int (*table_column_metadata)(tdsqlite3*,const char*,const char*,const char*, char const**,char const**,int*,int*,int*); void (*thread_cleanup)(void); - int (*total_changes)(sqlite3*); - void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); - int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); - void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, + int (*total_changes)(tdsqlite3*); + void * (*trace)(tdsqlite3*,void(*xTrace)(void*,const char*),void*); + int (*transfer_bindings)(tdsqlite3_stmt*,tdsqlite3_stmt*); + void * (*update_hook)(tdsqlite3*,void(*)(void*,int ,char const*,char const*, sqlite_int64),void*); - void * (*user_data)(sqlite3_context*); - const void * (*value_blob)(sqlite3_value*); - int (*value_bytes)(sqlite3_value*); - int (*value_bytes16)(sqlite3_value*); - double (*value_double)(sqlite3_value*); - int (*value_int)(sqlite3_value*); - sqlite_int64 (*value_int64)(sqlite3_value*); - int (*value_numeric_type)(sqlite3_value*); - const unsigned char * (*value_text)(sqlite3_value*); - const void * (*value_text16)(sqlite3_value*); - const void * (*value_text16be)(sqlite3_value*); - const void * (*value_text16le)(sqlite3_value*); - int (*value_type)(sqlite3_value*); + void * (*user_data)(tdsqlite3_context*); + const void * (*value_blob)(tdsqlite3_value*); + int (*value_bytes)(tdsqlite3_value*); + int (*value_bytes16)(tdsqlite3_value*); + double (*value_double)(tdsqlite3_value*); + int (*value_int)(tdsqlite3_value*); + sqlite_int64 (*value_int64)(tdsqlite3_value*); + int (*value_numeric_type)(tdsqlite3_value*); + const unsigned char * (*value_text)(tdsqlite3_value*); + const void * (*value_text16)(tdsqlite3_value*); + const void * (*value_text16be)(tdsqlite3_value*); + const void * (*value_text16le)(tdsqlite3_value*); + int (*value_type)(tdsqlite3_value*); char *(*vmprintf)(const char*,va_list); /* Added ??? */ - int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); + int (*overload_function)(tdsqlite3*, const char *zFuncName, int nArg); /* Added by 3.3.13 */ - int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); - int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); - int (*clear_bindings)(sqlite3_stmt*); + int (*prepare_v2)(tdsqlite3*,const char*,int,tdsqlite3_stmt**,const char**); + int (*prepare16_v2)(tdsqlite3*,const void*,int,tdsqlite3_stmt**,const void**); + int (*clear_bindings)(tdsqlite3_stmt*); /* Added by 3.4.1 */ - int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, + int (*create_module_v2)(tdsqlite3*,const char*,const tdsqlite3_module*,void*, void (*xDestroy)(void *)); /* Added by 3.5.0 */ - int (*bind_zeroblob)(sqlite3_stmt*,int,int); - int (*blob_bytes)(sqlite3_blob*); - int (*blob_close)(sqlite3_blob*); - int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, - int,sqlite3_blob**); - int (*blob_read)(sqlite3_blob*,void*,int,int); - int (*blob_write)(sqlite3_blob*,const void*,int,int); - int (*create_collation_v2)(sqlite3*,const char*,int,void*, + int (*bind_zeroblob)(tdsqlite3_stmt*,int,int); + int (*blob_bytes)(tdsqlite3_blob*); + int (*blob_close)(tdsqlite3_blob*); + int (*blob_open)(tdsqlite3*,const char*,const char*,const char*,tdsqlite3_int64, + int,tdsqlite3_blob**); + int (*blob_read)(tdsqlite3_blob*,void*,int,int); + int (*blob_write)(tdsqlite3_blob*,const void*,int,int); + int (*create_collation_v2)(tdsqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*), void(*)(void*)); - int (*file_control)(sqlite3*,const char*,int,void*); - sqlite3_int64 (*memory_highwater)(int); - sqlite3_int64 (*memory_used)(void); - sqlite3_mutex *(*mutex_alloc)(int); - void (*mutex_enter)(sqlite3_mutex*); - void (*mutex_free)(sqlite3_mutex*); - void (*mutex_leave)(sqlite3_mutex*); - int (*mutex_try)(sqlite3_mutex*); - int (*open_v2)(const char*,sqlite3**,int,const char*); + int (*file_control)(tdsqlite3*,const char*,int,void*); + tdsqlite3_int64 (*memory_highwater)(int); + tdsqlite3_int64 (*memory_used)(void); + tdsqlite3_mutex *(*mutex_alloc)(int); + void (*mutex_enter)(tdsqlite3_mutex*); + void (*mutex_free)(tdsqlite3_mutex*); + void (*mutex_leave)(tdsqlite3_mutex*); + int (*mutex_try)(tdsqlite3_mutex*); + int (*open_v2)(const char*,tdsqlite3**,int,const char*); int (*release_memory)(int); - void (*result_error_nomem)(sqlite3_context*); - void (*result_error_toobig)(sqlite3_context*); + void (*result_error_nomem)(tdsqlite3_context*); + void (*result_error_toobig)(tdsqlite3_context*); int (*sleep)(int); void (*soft_heap_limit)(int); - sqlite3_vfs *(*vfs_find)(const char*); - int (*vfs_register)(sqlite3_vfs*,int); - int (*vfs_unregister)(sqlite3_vfs*); + tdsqlite3_vfs *(*vfs_find)(const char*); + int (*vfs_register)(tdsqlite3_vfs*,int); + int (*vfs_unregister)(tdsqlite3_vfs*); int (*xthreadsafe)(void); - void (*result_zeroblob)(sqlite3_context*,int); - void (*result_error_code)(sqlite3_context*,int); + void (*result_zeroblob)(tdsqlite3_context*,int); + void (*result_error_code)(tdsqlite3_context*,int); int (*test_control)(int, ...); void (*randomness)(int,void*); - sqlite3 *(*context_db_handle)(sqlite3_context*); - int (*extended_result_codes)(sqlite3*,int); - int (*limit)(sqlite3*,int,int); - sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); - const char *(*sql)(sqlite3_stmt*); + tdsqlite3 *(*context_db_handle)(tdsqlite3_context*); + int (*extended_result_codes)(tdsqlite3*,int); + int (*limit)(tdsqlite3*,int,int); + tdsqlite3_stmt *(*next_stmt)(tdsqlite3*,tdsqlite3_stmt*); + const char *(*sql)(tdsqlite3_stmt*); int (*status)(int,int*,int*,int); - int (*backup_finish)(sqlite3_backup*); - sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); - int (*backup_pagecount)(sqlite3_backup*); - int (*backup_remaining)(sqlite3_backup*); - int (*backup_step)(sqlite3_backup*,int); + int (*backup_finish)(tdsqlite3_backup*); + tdsqlite3_backup *(*backup_init)(tdsqlite3*,const char*,tdsqlite3*,const char*); + int (*backup_pagecount)(tdsqlite3_backup*); + int (*backup_remaining)(tdsqlite3_backup*); + int (*backup_step)(tdsqlite3_backup*,int); const char *(*compileoption_get)(int); int (*compileoption_used)(const char*); - int (*create_function_v2)(sqlite3*,const char*,int,int,void*, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*), + int (*create_function_v2)(tdsqlite3*,const char*,int,int,void*, + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*), void(*xDestroy)(void*)); - int (*db_config)(sqlite3*,int,...); - sqlite3_mutex *(*db_mutex)(sqlite3*); - int (*db_status)(sqlite3*,int,int*,int*,int); - int (*extended_errcode)(sqlite3*); + int (*db_config)(tdsqlite3*,int,...); + tdsqlite3_mutex *(*db_mutex)(tdsqlite3*); + int (*db_status)(tdsqlite3*,int,int*,int*,int); + int (*extended_errcode)(tdsqlite3*); void (*log)(int,const char*,...); - sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); + tdsqlite3_int64 (*soft_heap_limit64)(tdsqlite3_int64); const char *(*sourceid)(void); - int (*stmt_status)(sqlite3_stmt*,int,int); + int (*stmt_status)(tdsqlite3_stmt*,int,int); int (*strnicmp)(const char*,const char*,int); - int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); - int (*wal_autocheckpoint)(sqlite3*,int); - int (*wal_checkpoint)(sqlite3*,const char*); - void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); - int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); - int (*vtab_config)(sqlite3*,int op,...); - int (*vtab_on_conflict)(sqlite3*); + int (*unlock_notify)(tdsqlite3*,void(*)(void**,int),void*); + int (*wal_autocheckpoint)(tdsqlite3*,int); + int (*wal_checkpoint)(tdsqlite3*,const char*); + void *(*wal_hook)(tdsqlite3*,int(*)(void*,tdsqlite3*,const char*,int),void*); + int (*blob_reopen)(tdsqlite3_blob*,tdsqlite3_int64); + int (*vtab_config)(tdsqlite3*,int op,...); + int (*vtab_on_conflict)(tdsqlite3*); /* Version 3.7.16 and later */ - int (*close_v2)(sqlite3*); - const char *(*db_filename)(sqlite3*,const char*); - int (*db_readonly)(sqlite3*,const char*); - int (*db_release_memory)(sqlite3*); + int (*close_v2)(tdsqlite3*); + const char *(*db_filename)(tdsqlite3*,const char*); + int (*db_readonly)(tdsqlite3*,const char*); + int (*db_release_memory)(tdsqlite3*); const char *(*errstr)(int); - int (*stmt_busy)(sqlite3_stmt*); - int (*stmt_readonly)(sqlite3_stmt*); + int (*stmt_busy)(tdsqlite3_stmt*); + int (*stmt_readonly)(tdsqlite3_stmt*); int (*stricmp)(const char*,const char*); int (*uri_boolean)(const char*,const char*,int); - sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); + tdsqlite3_int64 (*uri_int64)(const char*,const char*,tdsqlite3_int64); const char *(*uri_parameter)(const char*,const char*); - char *(*vsnprintf)(int,char*,const char*,va_list); - int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); + char *(*xvsnprintf)(int,char*,const char*,va_list); + int (*wal_checkpoint_v2)(tdsqlite3*,const char*,int,int*,int*); /* Version 3.8.7 and later */ int (*auto_extension)(void(*)(void)); - int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64, + int (*bind_blob64)(tdsqlite3_stmt*,int,const void*,tdsqlite3_uint64, void(*)(void*)); - int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64, + int (*bind_text64)(tdsqlite3_stmt*,int,const char*,tdsqlite3_uint64, void(*)(void*),unsigned char); int (*cancel_auto_extension)(void(*)(void)); - int (*load_extension)(sqlite3*,const char*,const char*,char**); - void *(*malloc64)(sqlite3_uint64); - sqlite3_uint64 (*msize)(void*); - void *(*realloc64)(void*,sqlite3_uint64); + int (*load_extension)(tdsqlite3*,const char*,const char*,char**); + void *(*malloc64)(tdsqlite3_uint64); + tdsqlite3_uint64 (*msize)(void*); + void *(*realloc64)(void*,tdsqlite3_uint64); void (*reset_auto_extension)(void); - void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64, + void (*result_blob64)(tdsqlite3_context*,const void*,tdsqlite3_uint64, void(*)(void*)); - void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64, + void (*result_text64)(tdsqlite3_context*,const char*,tdsqlite3_uint64, void(*)(void*), unsigned char); int (*strglob)(const char*,const char*); /* Version 3.8.11 and later */ - sqlite3_value *(*value_dup)(const sqlite3_value*); - void (*value_free)(sqlite3_value*); - int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64); - int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64); + tdsqlite3_value *(*value_dup)(const tdsqlite3_value*); + void (*value_free)(tdsqlite3_value*); + int (*result_zeroblob64)(tdsqlite3_context*,tdsqlite3_uint64); + int (*bind_zeroblob64)(tdsqlite3_stmt*, int, tdsqlite3_uint64); /* Version 3.9.0 and later */ - unsigned int (*value_subtype)(sqlite3_value*); - void (*result_subtype)(sqlite3_context*,unsigned int); + unsigned int (*value_subtype)(tdsqlite3_value*); + void (*result_subtype)(tdsqlite3_context*,unsigned int); /* Version 3.10.0 and later */ - int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int); + int (*status64)(int,tdsqlite3_int64*,tdsqlite3_int64*,int); int (*strlike)(const char*,const char*,unsigned int); - int (*db_cacheflush)(sqlite3*); + int (*db_cacheflush)(tdsqlite3*); /* Version 3.12.0 and later */ - int (*system_errno)(sqlite3*); + int (*system_errno)(tdsqlite3*); /* Version 3.14.0 and later */ - int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); - char *(*expanded_sql)(sqlite3_stmt*); + int (*trace_v2)(tdsqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); + char *(*expanded_sql)(tdsqlite3_stmt*); + /* Version 3.18.0 and later */ + void (*set_last_insert_rowid)(tdsqlite3*,tdsqlite3_int64); + /* Version 3.20.0 and later */ + int (*prepare_v3)(tdsqlite3*,const char*,int,unsigned int, + tdsqlite3_stmt**,const char**); + int (*prepare16_v3)(tdsqlite3*,const void*,int,unsigned int, + tdsqlite3_stmt**,const void**); + int (*bind_pointer)(tdsqlite3_stmt*,int,void*,const char*,void(*)(void*)); + void (*result_pointer)(tdsqlite3_context*,void*,const char*,void(*)(void*)); + void *(*value_pointer)(tdsqlite3_value*,const char*); + int (*vtab_nochange)(tdsqlite3_context*); + int (*value_nochange)(tdsqlite3_value*); + const char *(*vtab_collation)(tdsqlite3_index_info*,int); + /* Version 3.24.0 and later */ + int (*keyword_count)(void); + int (*keyword_name)(int,const char**,int*); + int (*keyword_check)(const char*,int); + tdsqlite3_str *(*str_new)(tdsqlite3*); + char *(*str_finish)(tdsqlite3_str*); + void (*str_appendf)(tdsqlite3_str*, const char *zFormat, ...); + void (*str_vappendf)(tdsqlite3_str*, const char *zFormat, va_list); + void (*str_append)(tdsqlite3_str*, const char *zIn, int N); + void (*str_appendall)(tdsqlite3_str*, const char *zIn); + void (*str_appendchar)(tdsqlite3_str*, int N, char C); + void (*str_reset)(tdsqlite3_str*); + int (*str_errcode)(tdsqlite3_str*); + int (*str_length)(tdsqlite3_str*); + char *(*str_value)(tdsqlite3_str*); + /* Version 3.25.0 and later */ + int (*create_window_function)(tdsqlite3*,const char*,int,int,void*, + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*), + void (*xValue)(tdsqlite3_context*), + void (*xInv)(tdsqlite3_context*,int,tdsqlite3_value**), + void(*xDestroy)(void*)); + /* Version 3.26.0 and later */ + const char *(*normalized_sql)(tdsqlite3_stmt*); + /* Version 3.28.0 and later */ + int (*stmt_isexplain)(tdsqlite3_stmt*); + int (*value_frombind)(tdsqlite3_value*); + /* Version 3.30.0 and later */ + int (*drop_modules)(tdsqlite3*,const char**); + /* Version 3.31.0 and later */ + tdsqlite3_int64 (*hard_heap_limit64)(tdsqlite3_int64); + const char *(*uri_key)(const char*,int); + const char *(*filename_database)(const char*); + const char *(*filename_journal)(const char*); + const char *(*filename_wal)(const char*); }; /* ** This is the function signature used for all extension entry points. It ** is also defined in the file "loadext.c". */ -typedef int (*sqlite3_loadext_entry)( - sqlite3 *db, /* Handle to the database. */ +typedef int (*tdsqlite3_loadext_entry)( + tdsqlite3 *db, /* Handle to the database. */ char **pzErrMsg, /* Used to set error string on failure. */ - const sqlite3_api_routines *pThunk /* Extension API function pointers. */ + const tdsqlite3_api_routines *pThunk /* Extension API function pointers. */ ); /* ** The following macros redefine the API routines so that they are -** redirected through the global sqlite3_api structure. +** redirected through the global tdsqlite3_api structure. ** ** This header file is also used by the loadext.c source file ** (part of the main SQLite library - not an extension) so that -** it can get access to the sqlite3_api_routines structure +** it can get access to the tdsqlite3_api_routines structure ** definition. But the main library does not want to redefine ** the API. So the redefinition macros are only valid if the ** SQLITE_CORE macros is undefined. */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) -#define sqlite3_aggregate_context sqlite3_api->aggregate_context +#define tdsqlite3_aggregate_context tdsqlite3_api->aggregate_context #ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_aggregate_count sqlite3_api->aggregate_count -#endif -#define sqlite3_bind_blob sqlite3_api->bind_blob -#define sqlite3_bind_double sqlite3_api->bind_double -#define sqlite3_bind_int sqlite3_api->bind_int -#define sqlite3_bind_int64 sqlite3_api->bind_int64 -#define sqlite3_bind_null sqlite3_api->bind_null -#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count -#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index -#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name -#define sqlite3_bind_text sqlite3_api->bind_text -#define sqlite3_bind_text16 sqlite3_api->bind_text16 -#define sqlite3_bind_value sqlite3_api->bind_value -#define sqlite3_busy_handler sqlite3_api->busy_handler -#define sqlite3_busy_timeout sqlite3_api->busy_timeout -#define sqlite3_changes sqlite3_api->changes -#define sqlite3_close sqlite3_api->close -#define sqlite3_collation_needed sqlite3_api->collation_needed -#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 -#define sqlite3_column_blob sqlite3_api->column_blob -#define sqlite3_column_bytes sqlite3_api->column_bytes -#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 -#define sqlite3_column_count sqlite3_api->column_count -#define sqlite3_column_database_name sqlite3_api->column_database_name -#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 -#define sqlite3_column_decltype sqlite3_api->column_decltype -#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 -#define sqlite3_column_double sqlite3_api->column_double -#define sqlite3_column_int sqlite3_api->column_int -#define sqlite3_column_int64 sqlite3_api->column_int64 -#define sqlite3_column_name sqlite3_api->column_name -#define sqlite3_column_name16 sqlite3_api->column_name16 -#define sqlite3_column_origin_name sqlite3_api->column_origin_name -#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 -#define sqlite3_column_table_name sqlite3_api->column_table_name -#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 -#define sqlite3_column_text sqlite3_api->column_text -#define sqlite3_column_text16 sqlite3_api->column_text16 -#define sqlite3_column_type sqlite3_api->column_type -#define sqlite3_column_value sqlite3_api->column_value -#define sqlite3_commit_hook sqlite3_api->commit_hook -#define sqlite3_complete sqlite3_api->complete -#define sqlite3_complete16 sqlite3_api->complete16 -#define sqlite3_create_collation sqlite3_api->create_collation -#define sqlite3_create_collation16 sqlite3_api->create_collation16 -#define sqlite3_create_function sqlite3_api->create_function -#define sqlite3_create_function16 sqlite3_api->create_function16 -#define sqlite3_create_module sqlite3_api->create_module -#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 -#define sqlite3_data_count sqlite3_api->data_count -#define sqlite3_db_handle sqlite3_api->db_handle -#define sqlite3_declare_vtab sqlite3_api->declare_vtab -#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache -#define sqlite3_errcode sqlite3_api->errcode -#define sqlite3_errmsg sqlite3_api->errmsg -#define sqlite3_errmsg16 sqlite3_api->errmsg16 -#define sqlite3_exec sqlite3_api->exec +#define tdsqlite3_aggregate_count tdsqlite3_api->aggregate_count +#endif +#define tdsqlite3_bind_blob tdsqlite3_api->bind_blob +#define tdsqlite3_bind_double tdsqlite3_api->bind_double +#define tdsqlite3_bind_int tdsqlite3_api->bind_int +#define tdsqlite3_bind_int64 tdsqlite3_api->bind_int64 +#define tdsqlite3_bind_null tdsqlite3_api->bind_null +#define tdsqlite3_bind_parameter_count tdsqlite3_api->bind_parameter_count +#define tdsqlite3_bind_parameter_index tdsqlite3_api->bind_parameter_index +#define tdsqlite3_bind_parameter_name tdsqlite3_api->bind_parameter_name +#define tdsqlite3_bind_text tdsqlite3_api->bind_text +#define tdsqlite3_bind_text16 tdsqlite3_api->bind_text16 +#define tdsqlite3_bind_value tdsqlite3_api->bind_value +#define tdsqlite3_busy_handler tdsqlite3_api->busy_handler +#define tdsqlite3_busy_timeout tdsqlite3_api->busy_timeout +#define tdsqlite3_changes tdsqlite3_api->changes +#define tdsqlite3_close tdsqlite3_api->close +#define tdsqlite3_collation_needed tdsqlite3_api->collation_needed +#define tdsqlite3_collation_needed16 tdsqlite3_api->collation_needed16 +#define tdsqlite3_column_blob tdsqlite3_api->column_blob +#define tdsqlite3_column_bytes tdsqlite3_api->column_bytes +#define tdsqlite3_column_bytes16 tdsqlite3_api->column_bytes16 +#define tdsqlite3_column_count tdsqlite3_api->column_count +#define tdsqlite3_column_database_name tdsqlite3_api->column_database_name +#define tdsqlite3_column_database_name16 tdsqlite3_api->column_database_name16 +#define tdsqlite3_column_decltype tdsqlite3_api->column_decltype +#define tdsqlite3_column_decltype16 tdsqlite3_api->column_decltype16 +#define tdsqlite3_column_double tdsqlite3_api->column_double +#define tdsqlite3_column_int tdsqlite3_api->column_int +#define tdsqlite3_column_int64 tdsqlite3_api->column_int64 +#define tdsqlite3_column_name tdsqlite3_api->column_name +#define tdsqlite3_column_name16 tdsqlite3_api->column_name16 +#define tdsqlite3_column_origin_name tdsqlite3_api->column_origin_name +#define tdsqlite3_column_origin_name16 tdsqlite3_api->column_origin_name16 +#define tdsqlite3_column_table_name tdsqlite3_api->column_table_name +#define tdsqlite3_column_table_name16 tdsqlite3_api->column_table_name16 +#define tdsqlite3_column_text tdsqlite3_api->column_text +#define tdsqlite3_column_text16 tdsqlite3_api->column_text16 +#define tdsqlite3_column_type tdsqlite3_api->column_type +#define tdsqlite3_column_value tdsqlite3_api->column_value +#define tdsqlite3_commit_hook tdsqlite3_api->commit_hook +#define tdsqlite3_complete tdsqlite3_api->complete +#define tdsqlite3_complete16 tdsqlite3_api->complete16 +#define tdsqlite3_create_collation tdsqlite3_api->create_collation +#define tdsqlite3_create_collation16 tdsqlite3_api->create_collation16 +#define tdsqlite3_create_function tdsqlite3_api->create_function +#define tdsqlite3_create_function16 tdsqlite3_api->create_function16 +#define tdsqlite3_create_module tdsqlite3_api->create_module +#define tdsqlite3_create_module_v2 tdsqlite3_api->create_module_v2 +#define tdsqlite3_data_count tdsqlite3_api->data_count +#define tdsqlite3_db_handle tdsqlite3_api->db_handle +#define tdsqlite3_declare_vtab tdsqlite3_api->declare_vtab +#define tdsqlite3_enable_shared_cache tdsqlite3_api->enable_shared_cache +#define tdsqlite3_errcode tdsqlite3_api->errcode +#define tdsqlite3_errmsg tdsqlite3_api->errmsg +#define tdsqlite3_errmsg16 tdsqlite3_api->errmsg16 +#define tdsqlite3_exec tdsqlite3_api->exec #ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_expired sqlite3_api->expired -#endif -#define sqlite3_finalize sqlite3_api->finalize -#define sqlite3_free sqlite3_api->free -#define sqlite3_free_table sqlite3_api->free_table -#define sqlite3_get_autocommit sqlite3_api->get_autocommit -#define sqlite3_get_auxdata sqlite3_api->get_auxdata -#define sqlite3_get_table sqlite3_api->get_table +#define tdsqlite3_expired tdsqlite3_api->expired +#endif +#define tdsqlite3_finalize tdsqlite3_api->finalize +#define tdsqlite3_free tdsqlite3_api->free +#define tdsqlite3_free_table tdsqlite3_api->free_table +#define tdsqlite3_get_autocommit tdsqlite3_api->get_autocommit +#define tdsqlite3_get_auxdata tdsqlite3_api->get_auxdata +#define tdsqlite3_get_table tdsqlite3_api->get_table #ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_global_recover sqlite3_api->global_recover -#endif -#define sqlite3_interrupt sqlite3_api->interruptx -#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid -#define sqlite3_libversion sqlite3_api->libversion -#define sqlite3_libversion_number sqlite3_api->libversion_number -#define sqlite3_malloc sqlite3_api->malloc -#define sqlite3_mprintf sqlite3_api->mprintf -#define sqlite3_open sqlite3_api->open -#define sqlite3_open16 sqlite3_api->open16 -#define sqlite3_prepare sqlite3_api->prepare -#define sqlite3_prepare16 sqlite3_api->prepare16 -#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 -#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 -#define sqlite3_profile sqlite3_api->profile -#define sqlite3_progress_handler sqlite3_api->progress_handler -#define sqlite3_realloc sqlite3_api->realloc -#define sqlite3_reset sqlite3_api->reset -#define sqlite3_result_blob sqlite3_api->result_blob -#define sqlite3_result_double sqlite3_api->result_double -#define sqlite3_result_error sqlite3_api->result_error -#define sqlite3_result_error16 sqlite3_api->result_error16 -#define sqlite3_result_int sqlite3_api->result_int -#define sqlite3_result_int64 sqlite3_api->result_int64 -#define sqlite3_result_null sqlite3_api->result_null -#define sqlite3_result_text sqlite3_api->result_text -#define sqlite3_result_text16 sqlite3_api->result_text16 -#define sqlite3_result_text16be sqlite3_api->result_text16be -#define sqlite3_result_text16le sqlite3_api->result_text16le -#define sqlite3_result_value sqlite3_api->result_value -#define sqlite3_rollback_hook sqlite3_api->rollback_hook -#define sqlite3_set_authorizer sqlite3_api->set_authorizer -#define sqlite3_set_auxdata sqlite3_api->set_auxdata -#define sqlite3_snprintf sqlite3_api->snprintf -#define sqlite3_step sqlite3_api->step -#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata -#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup -#define sqlite3_total_changes sqlite3_api->total_changes -#define sqlite3_trace sqlite3_api->trace +#define tdsqlite3_global_recover tdsqlite3_api->global_recover +#endif +#define tdsqlite3_interrupt tdsqlite3_api->interruptx +#define tdsqlite3_last_insert_rowid tdsqlite3_api->last_insert_rowid +#define tdsqlite3_libversion tdsqlite3_api->libversion +#define tdsqlite3_libversion_number tdsqlite3_api->libversion_number +#define tdsqlite3_malloc tdsqlite3_api->malloc +#define tdsqlite3_mprintf tdsqlite3_api->mprintf +#define tdsqlite3_open tdsqlite3_api->open +#define tdsqlite3_open16 tdsqlite3_api->open16 +#define tdsqlite3_prepare tdsqlite3_api->prepare +#define tdsqlite3_prepare16 tdsqlite3_api->prepare16 +#define tdsqlite3_prepare_v2 tdsqlite3_api->prepare_v2 +#define tdsqlite3_prepare16_v2 tdsqlite3_api->prepare16_v2 +#define tdsqlite3_profile tdsqlite3_api->profile +#define tdsqlite3_progress_handler tdsqlite3_api->progress_handler +#define tdsqlite3_realloc tdsqlite3_api->realloc +#define tdsqlite3_reset tdsqlite3_api->reset +#define tdsqlite3_result_blob tdsqlite3_api->result_blob +#define tdsqlite3_result_double tdsqlite3_api->result_double +#define tdsqlite3_result_error tdsqlite3_api->result_error +#define tdsqlite3_result_error16 tdsqlite3_api->result_error16 +#define tdsqlite3_result_int tdsqlite3_api->result_int +#define tdsqlite3_result_int64 tdsqlite3_api->result_int64 +#define tdsqlite3_result_null tdsqlite3_api->result_null +#define tdsqlite3_result_text tdsqlite3_api->result_text +#define tdsqlite3_result_text16 tdsqlite3_api->result_text16 +#define tdsqlite3_result_text16be tdsqlite3_api->result_text16be +#define tdsqlite3_result_text16le tdsqlite3_api->result_text16le +#define tdsqlite3_result_value tdsqlite3_api->result_value +#define tdsqlite3_rollback_hook tdsqlite3_api->rollback_hook +#define tdsqlite3_set_authorizer tdsqlite3_api->set_authorizer +#define tdsqlite3_set_auxdata tdsqlite3_api->set_auxdata +#define tdsqlite3_snprintf tdsqlite3_api->xsnprintf +#define tdsqlite3_step tdsqlite3_api->step +#define tdsqlite3_table_column_metadata tdsqlite3_api->table_column_metadata +#define tdsqlite3_thread_cleanup tdsqlite3_api->thread_cleanup +#define tdsqlite3_total_changes tdsqlite3_api->total_changes +#define tdsqlite3_trace tdsqlite3_api->trace #ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings -#endif -#define sqlite3_update_hook sqlite3_api->update_hook -#define sqlite3_user_data sqlite3_api->user_data -#define sqlite3_value_blob sqlite3_api->value_blob -#define sqlite3_value_bytes sqlite3_api->value_bytes -#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 -#define sqlite3_value_double sqlite3_api->value_double -#define sqlite3_value_int sqlite3_api->value_int -#define sqlite3_value_int64 sqlite3_api->value_int64 -#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type -#define sqlite3_value_text sqlite3_api->value_text -#define sqlite3_value_text16 sqlite3_api->value_text16 -#define sqlite3_value_text16be sqlite3_api->value_text16be -#define sqlite3_value_text16le sqlite3_api->value_text16le -#define sqlite3_value_type sqlite3_api->value_type -#define sqlite3_vmprintf sqlite3_api->vmprintf -#define sqlite3_vsnprintf sqlite3_api->vsnprintf -#define sqlite3_overload_function sqlite3_api->overload_function -#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 -#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 -#define sqlite3_clear_bindings sqlite3_api->clear_bindings -#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob -#define sqlite3_blob_bytes sqlite3_api->blob_bytes -#define sqlite3_blob_close sqlite3_api->blob_close -#define sqlite3_blob_open sqlite3_api->blob_open -#define sqlite3_blob_read sqlite3_api->blob_read -#define sqlite3_blob_write sqlite3_api->blob_write -#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 -#define sqlite3_file_control sqlite3_api->file_control -#define sqlite3_memory_highwater sqlite3_api->memory_highwater -#define sqlite3_memory_used sqlite3_api->memory_used -#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc -#define sqlite3_mutex_enter sqlite3_api->mutex_enter -#define sqlite3_mutex_free sqlite3_api->mutex_free -#define sqlite3_mutex_leave sqlite3_api->mutex_leave -#define sqlite3_mutex_try sqlite3_api->mutex_try -#define sqlite3_open_v2 sqlite3_api->open_v2 -#define sqlite3_release_memory sqlite3_api->release_memory -#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem -#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig -#define sqlite3_sleep sqlite3_api->sleep -#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit -#define sqlite3_vfs_find sqlite3_api->vfs_find -#define sqlite3_vfs_register sqlite3_api->vfs_register -#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister -#define sqlite3_threadsafe sqlite3_api->xthreadsafe -#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob -#define sqlite3_result_error_code sqlite3_api->result_error_code -#define sqlite3_test_control sqlite3_api->test_control -#define sqlite3_randomness sqlite3_api->randomness -#define sqlite3_context_db_handle sqlite3_api->context_db_handle -#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes -#define sqlite3_limit sqlite3_api->limit -#define sqlite3_next_stmt sqlite3_api->next_stmt -#define sqlite3_sql sqlite3_api->sql -#define sqlite3_status sqlite3_api->status -#define sqlite3_backup_finish sqlite3_api->backup_finish -#define sqlite3_backup_init sqlite3_api->backup_init -#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount -#define sqlite3_backup_remaining sqlite3_api->backup_remaining -#define sqlite3_backup_step sqlite3_api->backup_step -#define sqlite3_compileoption_get sqlite3_api->compileoption_get -#define sqlite3_compileoption_used sqlite3_api->compileoption_used -#define sqlite3_create_function_v2 sqlite3_api->create_function_v2 -#define sqlite3_db_config sqlite3_api->db_config -#define sqlite3_db_mutex sqlite3_api->db_mutex -#define sqlite3_db_status sqlite3_api->db_status -#define sqlite3_extended_errcode sqlite3_api->extended_errcode -#define sqlite3_log sqlite3_api->log -#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 -#define sqlite3_sourceid sqlite3_api->sourceid -#define sqlite3_stmt_status sqlite3_api->stmt_status -#define sqlite3_strnicmp sqlite3_api->strnicmp -#define sqlite3_unlock_notify sqlite3_api->unlock_notify -#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint -#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint -#define sqlite3_wal_hook sqlite3_api->wal_hook -#define sqlite3_blob_reopen sqlite3_api->blob_reopen -#define sqlite3_vtab_config sqlite3_api->vtab_config -#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict +#define tdsqlite3_transfer_bindings tdsqlite3_api->transfer_bindings +#endif +#define tdsqlite3_update_hook tdsqlite3_api->update_hook +#define tdsqlite3_user_data tdsqlite3_api->user_data +#define tdsqlite3_value_blob tdsqlite3_api->value_blob +#define tdsqlite3_value_bytes tdsqlite3_api->value_bytes +#define tdsqlite3_value_bytes16 tdsqlite3_api->value_bytes16 +#define tdsqlite3_value_double tdsqlite3_api->value_double +#define tdsqlite3_value_int tdsqlite3_api->value_int +#define tdsqlite3_value_int64 tdsqlite3_api->value_int64 +#define tdsqlite3_value_numeric_type tdsqlite3_api->value_numeric_type +#define tdsqlite3_value_text tdsqlite3_api->value_text +#define tdsqlite3_value_text16 tdsqlite3_api->value_text16 +#define tdsqlite3_value_text16be tdsqlite3_api->value_text16be +#define tdsqlite3_value_text16le tdsqlite3_api->value_text16le +#define tdsqlite3_value_type tdsqlite3_api->value_type +#define tdsqlite3_vmprintf tdsqlite3_api->vmprintf +#define tdsqlite3_vsnprintf tdsqlite3_api->xvsnprintf +#define tdsqlite3_overload_function tdsqlite3_api->overload_function +#define tdsqlite3_prepare_v2 tdsqlite3_api->prepare_v2 +#define tdsqlite3_prepare16_v2 tdsqlite3_api->prepare16_v2 +#define tdsqlite3_clear_bindings tdsqlite3_api->clear_bindings +#define tdsqlite3_bind_zeroblob tdsqlite3_api->bind_zeroblob +#define tdsqlite3_blob_bytes tdsqlite3_api->blob_bytes +#define tdsqlite3_blob_close tdsqlite3_api->blob_close +#define tdsqlite3_blob_open tdsqlite3_api->blob_open +#define tdsqlite3_blob_read tdsqlite3_api->blob_read +#define tdsqlite3_blob_write tdsqlite3_api->blob_write +#define tdsqlite3_create_collation_v2 tdsqlite3_api->create_collation_v2 +#define tdsqlite3_file_control tdsqlite3_api->file_control +#define tdsqlite3_memory_highwater tdsqlite3_api->memory_highwater +#define tdsqlite3_memory_used tdsqlite3_api->memory_used +#define tdsqlite3_mutex_alloc tdsqlite3_api->mutex_alloc +#define tdsqlite3_mutex_enter tdsqlite3_api->mutex_enter +#define tdsqlite3_mutex_free tdsqlite3_api->mutex_free +#define tdsqlite3_mutex_leave tdsqlite3_api->mutex_leave +#define tdsqlite3_mutex_try tdsqlite3_api->mutex_try +#define tdsqlite3_open_v2 tdsqlite3_api->open_v2 +#define tdsqlite3_release_memory tdsqlite3_api->release_memory +#define tdsqlite3_result_error_nomem tdsqlite3_api->result_error_nomem +#define tdsqlite3_result_error_toobig tdsqlite3_api->result_error_toobig +#define tdsqlite3_sleep tdsqlite3_api->sleep +#define tdsqlite3_soft_heap_limit tdsqlite3_api->soft_heap_limit +#define tdsqlite3_vfs_find tdsqlite3_api->vfs_find +#define tdsqlite3_vfs_register tdsqlite3_api->vfs_register +#define tdsqlite3_vfs_unregister tdsqlite3_api->vfs_unregister +#define tdsqlite3_threadsafe tdsqlite3_api->xthreadsafe +#define tdsqlite3_result_zeroblob tdsqlite3_api->result_zeroblob +#define tdsqlite3_result_error_code tdsqlite3_api->result_error_code +#define tdsqlite3_test_control tdsqlite3_api->test_control +#define tdsqlite3_randomness tdsqlite3_api->randomness +#define tdsqlite3_context_db_handle tdsqlite3_api->context_db_handle +#define tdsqlite3_extended_result_codes tdsqlite3_api->extended_result_codes +#define tdsqlite3_limit tdsqlite3_api->limit +#define tdsqlite3_next_stmt tdsqlite3_api->next_stmt +#define tdsqlite3_sql tdsqlite3_api->sql +#define tdsqlite3_status tdsqlite3_api->status +#define tdsqlite3_backup_finish tdsqlite3_api->backup_finish +#define tdsqlite3_backup_init tdsqlite3_api->backup_init +#define tdsqlite3_backup_pagecount tdsqlite3_api->backup_pagecount +#define tdsqlite3_backup_remaining tdsqlite3_api->backup_remaining +#define tdsqlite3_backup_step tdsqlite3_api->backup_step +#define tdsqlite3_compileoption_get tdsqlite3_api->compileoption_get +#define tdsqlite3_compileoption_used tdsqlite3_api->compileoption_used +#define tdsqlite3_create_function_v2 tdsqlite3_api->create_function_v2 +#define tdsqlite3_db_config tdsqlite3_api->db_config +#define tdsqlite3_db_mutex tdsqlite3_api->db_mutex +#define tdsqlite3_db_status tdsqlite3_api->db_status +#define tdsqlite3_extended_errcode tdsqlite3_api->extended_errcode +#define tdsqlite3_log tdsqlite3_api->log +#define tdsqlite3_soft_heap_limit64 tdsqlite3_api->soft_heap_limit64 +#define tdsqlite3_sourceid tdsqlite3_api->sourceid +#define tdsqlite3_stmt_status tdsqlite3_api->stmt_status +#define tdsqlite3_strnicmp tdsqlite3_api->strnicmp +#define tdsqlite3_unlock_notify tdsqlite3_api->unlock_notify +#define tdsqlite3_wal_autocheckpoint tdsqlite3_api->wal_autocheckpoint +#define tdsqlite3_wal_checkpoint tdsqlite3_api->wal_checkpoint +#define tdsqlite3_wal_hook tdsqlite3_api->wal_hook +#define tdsqlite3_blob_reopen tdsqlite3_api->blob_reopen +#define tdsqlite3_vtab_config tdsqlite3_api->vtab_config +#define tdsqlite3_vtab_on_conflict tdsqlite3_api->vtab_on_conflict /* Version 3.7.16 and later */ -#define sqlite3_close_v2 sqlite3_api->close_v2 -#define sqlite3_db_filename sqlite3_api->db_filename -#define sqlite3_db_readonly sqlite3_api->db_readonly -#define sqlite3_db_release_memory sqlite3_api->db_release_memory -#define sqlite3_errstr sqlite3_api->errstr -#define sqlite3_stmt_busy sqlite3_api->stmt_busy -#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly -#define sqlite3_stricmp sqlite3_api->stricmp -#define sqlite3_uri_boolean sqlite3_api->uri_boolean -#define sqlite3_uri_int64 sqlite3_api->uri_int64 -#define sqlite3_uri_parameter sqlite3_api->uri_parameter -#define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf -#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 +#define tdsqlite3_close_v2 tdsqlite3_api->close_v2 +#define tdsqlite3_db_filename tdsqlite3_api->db_filename +#define tdsqlite3_db_readonly tdsqlite3_api->db_readonly +#define tdsqlite3_db_release_memory tdsqlite3_api->db_release_memory +#define tdsqlite3_errstr tdsqlite3_api->errstr +#define tdsqlite3_stmt_busy tdsqlite3_api->stmt_busy +#define tdsqlite3_stmt_readonly tdsqlite3_api->stmt_readonly +#define tdsqlite3_stricmp tdsqlite3_api->stricmp +#define tdsqlite3_uri_boolean tdsqlite3_api->uri_boolean +#define tdsqlite3_uri_int64 tdsqlite3_api->uri_int64 +#define tdsqlite3_uri_parameter tdsqlite3_api->uri_parameter +#define tdsqlite3_uri_vsnprintf tdsqlite3_api->xvsnprintf +#define tdsqlite3_wal_checkpoint_v2 tdsqlite3_api->wal_checkpoint_v2 /* Version 3.8.7 and later */ -#define sqlite3_auto_extension sqlite3_api->auto_extension -#define sqlite3_bind_blob64 sqlite3_api->bind_blob64 -#define sqlite3_bind_text64 sqlite3_api->bind_text64 -#define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension -#define sqlite3_load_extension sqlite3_api->load_extension -#define sqlite3_malloc64 sqlite3_api->malloc64 -#define sqlite3_msize sqlite3_api->msize -#define sqlite3_realloc64 sqlite3_api->realloc64 -#define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension -#define sqlite3_result_blob64 sqlite3_api->result_blob64 -#define sqlite3_result_text64 sqlite3_api->result_text64 -#define sqlite3_strglob sqlite3_api->strglob +#define tdsqlite3_auto_extension tdsqlite3_api->auto_extension +#define tdsqlite3_bind_blob64 tdsqlite3_api->bind_blob64 +#define tdsqlite3_bind_text64 tdsqlite3_api->bind_text64 +#define tdsqlite3_cancel_auto_extension tdsqlite3_api->cancel_auto_extension +#define tdsqlite3_load_extension tdsqlite3_api->load_extension +#define tdsqlite3_malloc64 tdsqlite3_api->malloc64 +#define tdsqlite3_msize tdsqlite3_api->msize +#define tdsqlite3_realloc64 tdsqlite3_api->realloc64 +#define tdsqlite3_reset_auto_extension tdsqlite3_api->reset_auto_extension +#define tdsqlite3_result_blob64 tdsqlite3_api->result_blob64 +#define tdsqlite3_result_text64 tdsqlite3_api->result_text64 +#define tdsqlite3_strglob tdsqlite3_api->strglob /* Version 3.8.11 and later */ -#define sqlite3_value_dup sqlite3_api->value_dup -#define sqlite3_value_free sqlite3_api->value_free -#define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64 -#define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64 +#define tdsqlite3_value_dup tdsqlite3_api->value_dup +#define tdsqlite3_value_free tdsqlite3_api->value_free +#define tdsqlite3_result_zeroblob64 tdsqlite3_api->result_zeroblob64 +#define tdsqlite3_bind_zeroblob64 tdsqlite3_api->bind_zeroblob64 /* Version 3.9.0 and later */ -#define sqlite3_value_subtype sqlite3_api->value_subtype -#define sqlite3_result_subtype sqlite3_api->result_subtype +#define tdsqlite3_value_subtype tdsqlite3_api->value_subtype +#define tdsqlite3_result_subtype tdsqlite3_api->result_subtype /* Version 3.10.0 and later */ -#define sqlite3_status64 sqlite3_api->status64 -#define sqlite3_strlike sqlite3_api->strlike -#define sqlite3_db_cacheflush sqlite3_api->db_cacheflush +#define tdsqlite3_status64 tdsqlite3_api->status64 +#define tdsqlite3_strlike tdsqlite3_api->strlike +#define tdsqlite3_db_cacheflush tdsqlite3_api->db_cacheflush /* Version 3.12.0 and later */ -#define sqlite3_system_errno sqlite3_api->system_errno +#define tdsqlite3_system_errno tdsqlite3_api->system_errno /* Version 3.14.0 and later */ -#define sqlite3_trace_v2 sqlite3_api->trace_v2 -#define sqlite3_expanded_sql sqlite3_api->expanded_sql +#define tdsqlite3_trace_v2 tdsqlite3_api->trace_v2 +#define tdsqlite3_expanded_sql tdsqlite3_api->expanded_sql +/* Version 3.18.0 and later */ +#define tdsqlite3_set_last_insert_rowid tdsqlite3_api->set_last_insert_rowid +/* Version 3.20.0 and later */ +#define tdsqlite3_prepare_v3 tdsqlite3_api->prepare_v3 +#define tdsqlite3_prepare16_v3 tdsqlite3_api->prepare16_v3 +#define tdsqlite3_bind_pointer tdsqlite3_api->bind_pointer +#define tdsqlite3_result_pointer tdsqlite3_api->result_pointer +#define tdsqlite3_value_pointer tdsqlite3_api->value_pointer +/* Version 3.22.0 and later */ +#define tdsqlite3_vtab_nochange tdsqlite3_api->vtab_nochange +#define tdsqlite3_value_nochange tdsqlite3_api->value_nochange +#define tdsqlite3_vtab_collation tdsqlite3_api->vtab_collation +/* Version 3.24.0 and later */ +#define tdsqlite3_keyword_count tdsqlite3_api->keyword_count +#define tdsqlite3_keyword_name tdsqlite3_api->keyword_name +#define tdsqlite3_keyword_check tdsqlite3_api->keyword_check +#define tdsqlite3_str_new tdsqlite3_api->str_new +#define tdsqlite3_str_finish tdsqlite3_api->str_finish +#define tdsqlite3_str_appendf tdsqlite3_api->str_appendf +#define tdsqlite3_str_vappendf tdsqlite3_api->str_vappendf +#define tdsqlite3_str_append tdsqlite3_api->str_append +#define tdsqlite3_str_appendall tdsqlite3_api->str_appendall +#define tdsqlite3_str_appendchar tdsqlite3_api->str_appendchar +#define tdsqlite3_str_reset tdsqlite3_api->str_reset +#define tdsqlite3_str_errcode tdsqlite3_api->str_errcode +#define tdsqlite3_str_length tdsqlite3_api->str_length +#define tdsqlite3_str_value tdsqlite3_api->str_value +/* Version 3.25.0 and later */ +#define tdsqlite3_create_window_function tdsqlite3_api->create_window_function +/* Version 3.26.0 and later */ +#define tdsqlite3_normalized_sql tdsqlite3_api->normalized_sql +/* Version 3.28.0 and later */ +#define tdsqlite3_stmt_isexplain tdsqlite3_api->isexplain +#define tdsqlite3_value_frombind tdsqlite3_api->frombind +/* Version 3.30.0 and later */ +#define tdsqlite3_drop_modules tdsqlite3_api->drop_modules +/* Version 3.31.0 andn later */ +#define tdsqlite3_hard_heap_limit64 tdsqlite3_api->hard_heap_limit64 +#define tdsqlite3_uri_key tdsqlite3_api->uri_key +#define tdsqlite3_filename_database tdsqlite3_api->filename_database +#define tdsqlite3_filename_journal tdsqlite3_api->filename_journal +#define tdsqlite3_filename_wal tdsqlite3_api->filename_wal #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) /* This case when the file really is being compiled as a loadable ** extension */ -# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; -# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; +# define SQLITE_EXTENSION_INIT1 const tdsqlite3_api_routines *tdsqlite3_api=0; +# define SQLITE_EXTENSION_INIT2(v) tdsqlite3_api=v; # define SQLITE_EXTENSION_INIT3 \ - extern const sqlite3_api_routines *sqlite3_api; + extern const tdsqlite3_api_routines *tdsqlite3_api; #else /* This case when the file is being statically linked into the ** application */ @@ -113393,10 +126444,9 @@ typedef int (*sqlite3_loadext_entry)( #endif /* SQLITE3EXT_H */ -/************** End of sqlite3ext.h ******************************************/ +/************** End of tdsqlite3ext.h ******************************************/ /************** Continuing where we left off in loadext.c ********************/ /* #include "sqliteInt.h" */ -/* #include <string.h> */ #ifndef SQLITE_OMIT_LOAD_EXTENSION /* @@ -113405,91 +126455,93 @@ typedef int (*sqlite3_loadext_entry)( ** for any missing APIs. */ #ifndef SQLITE_ENABLE_COLUMN_METADATA -# define sqlite3_column_database_name 0 -# define sqlite3_column_database_name16 0 -# define sqlite3_column_table_name 0 -# define sqlite3_column_table_name16 0 -# define sqlite3_column_origin_name 0 -# define sqlite3_column_origin_name16 0 +# define tdsqlite3_column_database_name 0 +# define tdsqlite3_column_database_name16 0 +# define tdsqlite3_column_table_name 0 +# define tdsqlite3_column_table_name16 0 +# define tdsqlite3_column_origin_name 0 +# define tdsqlite3_column_origin_name16 0 #endif #ifdef SQLITE_OMIT_AUTHORIZATION -# define sqlite3_set_authorizer 0 +# define tdsqlite3_set_authorizer 0 #endif #ifdef SQLITE_OMIT_UTF16 -# define sqlite3_bind_text16 0 -# define sqlite3_collation_needed16 0 -# define sqlite3_column_decltype16 0 -# define sqlite3_column_name16 0 -# define sqlite3_column_text16 0 -# define sqlite3_complete16 0 -# define sqlite3_create_collation16 0 -# define sqlite3_create_function16 0 -# define sqlite3_errmsg16 0 -# define sqlite3_open16 0 -# define sqlite3_prepare16 0 -# define sqlite3_prepare16_v2 0 -# define sqlite3_result_error16 0 -# define sqlite3_result_text16 0 -# define sqlite3_result_text16be 0 -# define sqlite3_result_text16le 0 -# define sqlite3_value_text16 0 -# define sqlite3_value_text16be 0 -# define sqlite3_value_text16le 0 -# define sqlite3_column_database_name16 0 -# define sqlite3_column_table_name16 0 -# define sqlite3_column_origin_name16 0 +# define tdsqlite3_bind_text16 0 +# define tdsqlite3_collation_needed16 0 +# define tdsqlite3_column_decltype16 0 +# define tdsqlite3_column_name16 0 +# define tdsqlite3_column_text16 0 +# define tdsqlite3_complete16 0 +# define tdsqlite3_create_collation16 0 +# define tdsqlite3_create_function16 0 +# define tdsqlite3_errmsg16 0 +# define tdsqlite3_open16 0 +# define tdsqlite3_prepare16 0 +# define tdsqlite3_prepare16_v2 0 +# define tdsqlite3_prepare16_v3 0 +# define tdsqlite3_result_error16 0 +# define tdsqlite3_result_text16 0 +# define tdsqlite3_result_text16be 0 +# define tdsqlite3_result_text16le 0 +# define tdsqlite3_value_text16 0 +# define tdsqlite3_value_text16be 0 +# define tdsqlite3_value_text16le 0 +# define tdsqlite3_column_database_name16 0 +# define tdsqlite3_column_table_name16 0 +# define tdsqlite3_column_origin_name16 0 #endif #ifdef SQLITE_OMIT_COMPLETE -# define sqlite3_complete 0 -# define sqlite3_complete16 0 +# define tdsqlite3_complete 0 +# define tdsqlite3_complete16 0 #endif #ifdef SQLITE_OMIT_DECLTYPE -# define sqlite3_column_decltype16 0 -# define sqlite3_column_decltype 0 +# define tdsqlite3_column_decltype16 0 +# define tdsqlite3_column_decltype 0 #endif #ifdef SQLITE_OMIT_PROGRESS_CALLBACK -# define sqlite3_progress_handler 0 +# define tdsqlite3_progress_handler 0 #endif #ifdef SQLITE_OMIT_VIRTUALTABLE -# define sqlite3_create_module 0 -# define sqlite3_create_module_v2 0 -# define sqlite3_declare_vtab 0 -# define sqlite3_vtab_config 0 -# define sqlite3_vtab_on_conflict 0 +# define tdsqlite3_create_module 0 +# define tdsqlite3_create_module_v2 0 +# define tdsqlite3_declare_vtab 0 +# define tdsqlite3_vtab_config 0 +# define tdsqlite3_vtab_on_conflict 0 +# define tdsqlite3_vtab_collation 0 #endif #ifdef SQLITE_OMIT_SHARED_CACHE -# define sqlite3_enable_shared_cache 0 +# define tdsqlite3_enable_shared_cache 0 #endif #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED) -# define sqlite3_profile 0 -# define sqlite3_trace 0 +# define tdsqlite3_profile 0 +# define tdsqlite3_trace 0 #endif #ifdef SQLITE_OMIT_GET_TABLE -# define sqlite3_free_table 0 -# define sqlite3_get_table 0 +# define tdsqlite3_free_table 0 +# define tdsqlite3_get_table 0 #endif #ifdef SQLITE_OMIT_INCRBLOB -#define sqlite3_bind_zeroblob 0 -#define sqlite3_blob_bytes 0 -#define sqlite3_blob_close 0 -#define sqlite3_blob_open 0 -#define sqlite3_blob_read 0 -#define sqlite3_blob_write 0 -#define sqlite3_blob_reopen 0 +#define tdsqlite3_bind_zeroblob 0 +#define tdsqlite3_blob_bytes 0 +#define tdsqlite3_blob_close 0 +#define tdsqlite3_blob_open 0 +#define tdsqlite3_blob_read 0 +#define tdsqlite3_blob_write 0 +#define tdsqlite3_blob_reopen 0 #endif #if defined(SQLITE_OMIT_TRACE) -# define sqlite3_trace_v2 0 +# define tdsqlite3_trace_v2 0 #endif /* @@ -113502,178 +126554,178 @@ typedef int (*sqlite3_loadext_entry)( ** in order to preserve backwards compatibility. ** ** Extensions that use newer APIs should first call the -** sqlite3_libversion_number() to make sure that the API they +** tdsqlite3_libversion_number() to make sure that the API they ** intend to use is supported by the library. Extensions should ** also check to make sure that the pointer to the function is ** not NULL before calling it. */ -static const sqlite3_api_routines sqlite3Apis = { - sqlite3_aggregate_context, +static const tdsqlite3_api_routines tdsqlite3Apis = { + tdsqlite3_aggregate_context, #ifndef SQLITE_OMIT_DEPRECATED - sqlite3_aggregate_count, + tdsqlite3_aggregate_count, #else 0, #endif - sqlite3_bind_blob, - sqlite3_bind_double, - sqlite3_bind_int, - sqlite3_bind_int64, - sqlite3_bind_null, - sqlite3_bind_parameter_count, - sqlite3_bind_parameter_index, - sqlite3_bind_parameter_name, - sqlite3_bind_text, - sqlite3_bind_text16, - sqlite3_bind_value, - sqlite3_busy_handler, - sqlite3_busy_timeout, - sqlite3_changes, - sqlite3_close, - sqlite3_collation_needed, - sqlite3_collation_needed16, - sqlite3_column_blob, - sqlite3_column_bytes, - sqlite3_column_bytes16, - sqlite3_column_count, - sqlite3_column_database_name, - sqlite3_column_database_name16, - sqlite3_column_decltype, - sqlite3_column_decltype16, - sqlite3_column_double, - sqlite3_column_int, - sqlite3_column_int64, - sqlite3_column_name, - sqlite3_column_name16, - sqlite3_column_origin_name, - sqlite3_column_origin_name16, - sqlite3_column_table_name, - sqlite3_column_table_name16, - sqlite3_column_text, - sqlite3_column_text16, - sqlite3_column_type, - sqlite3_column_value, - sqlite3_commit_hook, - sqlite3_complete, - sqlite3_complete16, - sqlite3_create_collation, - sqlite3_create_collation16, - sqlite3_create_function, - sqlite3_create_function16, - sqlite3_create_module, - sqlite3_data_count, - sqlite3_db_handle, - sqlite3_declare_vtab, - sqlite3_enable_shared_cache, - sqlite3_errcode, - sqlite3_errmsg, - sqlite3_errmsg16, - sqlite3_exec, + tdsqlite3_bind_blob, + tdsqlite3_bind_double, + tdsqlite3_bind_int, + tdsqlite3_bind_int64, + tdsqlite3_bind_null, + tdsqlite3_bind_parameter_count, + tdsqlite3_bind_parameter_index, + tdsqlite3_bind_parameter_name, + tdsqlite3_bind_text, + tdsqlite3_bind_text16, + tdsqlite3_bind_value, + tdsqlite3_busy_handler, + tdsqlite3_busy_timeout, + tdsqlite3_changes, + tdsqlite3_close, + tdsqlite3_collation_needed, + tdsqlite3_collation_needed16, + tdsqlite3_column_blob, + tdsqlite3_column_bytes, + tdsqlite3_column_bytes16, + tdsqlite3_column_count, + tdsqlite3_column_database_name, + tdsqlite3_column_database_name16, + tdsqlite3_column_decltype, + tdsqlite3_column_decltype16, + tdsqlite3_column_double, + tdsqlite3_column_int, + tdsqlite3_column_int64, + tdsqlite3_column_name, + tdsqlite3_column_name16, + tdsqlite3_column_origin_name, + tdsqlite3_column_origin_name16, + tdsqlite3_column_table_name, + tdsqlite3_column_table_name16, + tdsqlite3_column_text, + tdsqlite3_column_text16, + tdsqlite3_column_type, + tdsqlite3_column_value, + tdsqlite3_commit_hook, + tdsqlite3_complete, + tdsqlite3_complete16, + tdsqlite3_create_collation, + tdsqlite3_create_collation16, + tdsqlite3_create_function, + tdsqlite3_create_function16, + tdsqlite3_create_module, + tdsqlite3_data_count, + tdsqlite3_db_handle, + tdsqlite3_declare_vtab, + tdsqlite3_enable_shared_cache, + tdsqlite3_errcode, + tdsqlite3_errmsg, + tdsqlite3_errmsg16, + tdsqlite3_exec, #ifndef SQLITE_OMIT_DEPRECATED - sqlite3_expired, + tdsqlite3_expired, #else 0, #endif - sqlite3_finalize, - sqlite3_free, - sqlite3_free_table, - sqlite3_get_autocommit, - sqlite3_get_auxdata, - sqlite3_get_table, - 0, /* Was sqlite3_global_recover(), but that function is deprecated */ - sqlite3_interrupt, - sqlite3_last_insert_rowid, - sqlite3_libversion, - sqlite3_libversion_number, - sqlite3_malloc, - sqlite3_mprintf, - sqlite3_open, - sqlite3_open16, - sqlite3_prepare, - sqlite3_prepare16, - sqlite3_profile, - sqlite3_progress_handler, - sqlite3_realloc, - sqlite3_reset, - sqlite3_result_blob, - sqlite3_result_double, - sqlite3_result_error, - sqlite3_result_error16, - sqlite3_result_int, - sqlite3_result_int64, - sqlite3_result_null, - sqlite3_result_text, - sqlite3_result_text16, - sqlite3_result_text16be, - sqlite3_result_text16le, - sqlite3_result_value, - sqlite3_rollback_hook, - sqlite3_set_authorizer, - sqlite3_set_auxdata, - sqlite3_snprintf, - sqlite3_step, - sqlite3_table_column_metadata, + tdsqlite3_finalize, + tdsqlite3_free, + tdsqlite3_free_table, + tdsqlite3_get_autocommit, + tdsqlite3_get_auxdata, + tdsqlite3_get_table, + 0, /* Was tdsqlite3_global_recover(), but that function is deprecated */ + tdsqlite3_interrupt, + tdsqlite3_last_insert_rowid, + tdsqlite3_libversion, + tdsqlite3_libversion_number, + tdsqlite3_malloc, + tdsqlite3_mprintf, + tdsqlite3_open, + tdsqlite3_open16, + tdsqlite3_prepare, + tdsqlite3_prepare16, + tdsqlite3_profile, + tdsqlite3_progress_handler, + tdsqlite3_realloc, + tdsqlite3_reset, + tdsqlite3_result_blob, + tdsqlite3_result_double, + tdsqlite3_result_error, + tdsqlite3_result_error16, + tdsqlite3_result_int, + tdsqlite3_result_int64, + tdsqlite3_result_null, + tdsqlite3_result_text, + tdsqlite3_result_text16, + tdsqlite3_result_text16be, + tdsqlite3_result_text16le, + tdsqlite3_result_value, + tdsqlite3_rollback_hook, + tdsqlite3_set_authorizer, + tdsqlite3_set_auxdata, + tdsqlite3_snprintf, + tdsqlite3_step, + tdsqlite3_table_column_metadata, #ifndef SQLITE_OMIT_DEPRECATED - sqlite3_thread_cleanup, + tdsqlite3_thread_cleanup, #else 0, #endif - sqlite3_total_changes, - sqlite3_trace, + tdsqlite3_total_changes, + tdsqlite3_trace, #ifndef SQLITE_OMIT_DEPRECATED - sqlite3_transfer_bindings, + tdsqlite3_transfer_bindings, #else 0, #endif - sqlite3_update_hook, - sqlite3_user_data, - sqlite3_value_blob, - sqlite3_value_bytes, - sqlite3_value_bytes16, - sqlite3_value_double, - sqlite3_value_int, - sqlite3_value_int64, - sqlite3_value_numeric_type, - sqlite3_value_text, - sqlite3_value_text16, - sqlite3_value_text16be, - sqlite3_value_text16le, - sqlite3_value_type, - sqlite3_vmprintf, + tdsqlite3_update_hook, + tdsqlite3_user_data, + tdsqlite3_value_blob, + tdsqlite3_value_bytes, + tdsqlite3_value_bytes16, + tdsqlite3_value_double, + tdsqlite3_value_int, + tdsqlite3_value_int64, + tdsqlite3_value_numeric_type, + tdsqlite3_value_text, + tdsqlite3_value_text16, + tdsqlite3_value_text16be, + tdsqlite3_value_text16le, + tdsqlite3_value_type, + tdsqlite3_vmprintf, /* ** The original API set ends here. All extensions can call any ** of the APIs above provided that the pointer is not NULL. But ** before calling APIs that follow, extension should check the - ** sqlite3_libversion_number() to make sure they are dealing with + ** tdsqlite3_libversion_number() to make sure they are dealing with ** a library that is new enough to support that API. ************************************************************************* */ - sqlite3_overload_function, + tdsqlite3_overload_function, /* ** Added after 3.3.13 */ - sqlite3_prepare_v2, - sqlite3_prepare16_v2, - sqlite3_clear_bindings, + tdsqlite3_prepare_v2, + tdsqlite3_prepare16_v2, + tdsqlite3_clear_bindings, /* ** Added for 3.4.1 */ - sqlite3_create_module_v2, + tdsqlite3_create_module_v2, /* ** Added for 3.5.0 */ - sqlite3_bind_zeroblob, - sqlite3_blob_bytes, - sqlite3_blob_close, - sqlite3_blob_open, - sqlite3_blob_read, - sqlite3_blob_write, - sqlite3_create_collation_v2, - sqlite3_file_control, - sqlite3_memory_highwater, - sqlite3_memory_used, + tdsqlite3_bind_zeroblob, + tdsqlite3_blob_bytes, + tdsqlite3_blob_close, + tdsqlite3_blob_open, + tdsqlite3_blob_read, + tdsqlite3_blob_write, + tdsqlite3_create_collation_v2, + tdsqlite3_file_control, + tdsqlite3_memory_highwater, + tdsqlite3_memory_used, #ifdef SQLITE_MUTEX_OMIT 0, 0, @@ -113681,154 +126733,204 @@ static const sqlite3_api_routines sqlite3Apis = { 0, 0, #else - sqlite3_mutex_alloc, - sqlite3_mutex_enter, - sqlite3_mutex_free, - sqlite3_mutex_leave, - sqlite3_mutex_try, -#endif - sqlite3_open_v2, - sqlite3_release_memory, - sqlite3_result_error_nomem, - sqlite3_result_error_toobig, - sqlite3_sleep, - sqlite3_soft_heap_limit, - sqlite3_vfs_find, - sqlite3_vfs_register, - sqlite3_vfs_unregister, + tdsqlite3_mutex_alloc, + tdsqlite3_mutex_enter, + tdsqlite3_mutex_free, + tdsqlite3_mutex_leave, + tdsqlite3_mutex_try, +#endif + tdsqlite3_open_v2, + tdsqlite3_release_memory, + tdsqlite3_result_error_nomem, + tdsqlite3_result_error_toobig, + tdsqlite3_sleep, + tdsqlite3_soft_heap_limit, + tdsqlite3_vfs_find, + tdsqlite3_vfs_register, + tdsqlite3_vfs_unregister, /* ** Added for 3.5.8 */ - sqlite3_threadsafe, - sqlite3_result_zeroblob, - sqlite3_result_error_code, - sqlite3_test_control, - sqlite3_randomness, - sqlite3_context_db_handle, + tdsqlite3_threadsafe, + tdsqlite3_result_zeroblob, + tdsqlite3_result_error_code, + tdsqlite3_test_control, + tdsqlite3_randomness, + tdsqlite3_context_db_handle, /* ** Added for 3.6.0 */ - sqlite3_extended_result_codes, - sqlite3_limit, - sqlite3_next_stmt, - sqlite3_sql, - sqlite3_status, + tdsqlite3_extended_result_codes, + tdsqlite3_limit, + tdsqlite3_next_stmt, + tdsqlite3_sql, + tdsqlite3_status, /* ** Added for 3.7.4 */ - sqlite3_backup_finish, - sqlite3_backup_init, - sqlite3_backup_pagecount, - sqlite3_backup_remaining, - sqlite3_backup_step, + tdsqlite3_backup_finish, + tdsqlite3_backup_init, + tdsqlite3_backup_pagecount, + tdsqlite3_backup_remaining, + tdsqlite3_backup_step, #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS - sqlite3_compileoption_get, - sqlite3_compileoption_used, + tdsqlite3_compileoption_get, + tdsqlite3_compileoption_used, #else 0, 0, #endif - sqlite3_create_function_v2, - sqlite3_db_config, - sqlite3_db_mutex, - sqlite3_db_status, - sqlite3_extended_errcode, - sqlite3_log, - sqlite3_soft_heap_limit64, - sqlite3_sourceid, - sqlite3_stmt_status, - sqlite3_strnicmp, + tdsqlite3_create_function_v2, + tdsqlite3_db_config, + tdsqlite3_db_mutex, + tdsqlite3_db_status, + tdsqlite3_extended_errcode, + tdsqlite3_log, + tdsqlite3_soft_heap_limit64, + tdsqlite3_sourceid, + tdsqlite3_stmt_status, + tdsqlite3_strnicmp, #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY - sqlite3_unlock_notify, + tdsqlite3_unlock_notify, #else 0, #endif #ifndef SQLITE_OMIT_WAL - sqlite3_wal_autocheckpoint, - sqlite3_wal_checkpoint, - sqlite3_wal_hook, + tdsqlite3_wal_autocheckpoint, + tdsqlite3_wal_checkpoint, + tdsqlite3_wal_hook, #else 0, 0, 0, #endif - sqlite3_blob_reopen, - sqlite3_vtab_config, - sqlite3_vtab_on_conflict, - sqlite3_close_v2, - sqlite3_db_filename, - sqlite3_db_readonly, - sqlite3_db_release_memory, - sqlite3_errstr, - sqlite3_stmt_busy, - sqlite3_stmt_readonly, - sqlite3_stricmp, - sqlite3_uri_boolean, - sqlite3_uri_int64, - sqlite3_uri_parameter, - sqlite3_vsnprintf, - sqlite3_wal_checkpoint_v2, + tdsqlite3_blob_reopen, + tdsqlite3_vtab_config, + tdsqlite3_vtab_on_conflict, + tdsqlite3_close_v2, + tdsqlite3_db_filename, + tdsqlite3_db_readonly, + tdsqlite3_db_release_memory, + tdsqlite3_errstr, + tdsqlite3_stmt_busy, + tdsqlite3_stmt_readonly, + tdsqlite3_stricmp, + tdsqlite3_uri_boolean, + tdsqlite3_uri_int64, + tdsqlite3_uri_parameter, + tdsqlite3_vsnprintf, + tdsqlite3_wal_checkpoint_v2, /* Version 3.8.7 and later */ - sqlite3_auto_extension, - sqlite3_bind_blob64, - sqlite3_bind_text64, - sqlite3_cancel_auto_extension, - sqlite3_load_extension, - sqlite3_malloc64, - sqlite3_msize, - sqlite3_realloc64, - sqlite3_reset_auto_extension, - sqlite3_result_blob64, - sqlite3_result_text64, - sqlite3_strglob, + tdsqlite3_auto_extension, + tdsqlite3_bind_blob64, + tdsqlite3_bind_text64, + tdsqlite3_cancel_auto_extension, + tdsqlite3_load_extension, + tdsqlite3_malloc64, + tdsqlite3_msize, + tdsqlite3_realloc64, + tdsqlite3_reset_auto_extension, + tdsqlite3_result_blob64, + tdsqlite3_result_text64, + tdsqlite3_strglob, /* Version 3.8.11 and later */ - (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup, - sqlite3_value_free, - sqlite3_result_zeroblob64, - sqlite3_bind_zeroblob64, + (tdsqlite3_value*(*)(const tdsqlite3_value*))tdsqlite3_value_dup, + tdsqlite3_value_free, + tdsqlite3_result_zeroblob64, + tdsqlite3_bind_zeroblob64, /* Version 3.9.0 and later */ - sqlite3_value_subtype, - sqlite3_result_subtype, + tdsqlite3_value_subtype, + tdsqlite3_result_subtype, /* Version 3.10.0 and later */ - sqlite3_status64, - sqlite3_strlike, - sqlite3_db_cacheflush, + tdsqlite3_status64, + tdsqlite3_strlike, + tdsqlite3_db_cacheflush, /* Version 3.12.0 and later */ - sqlite3_system_errno, + tdsqlite3_system_errno, /* Version 3.14.0 and later */ - sqlite3_trace_v2, - sqlite3_expanded_sql + tdsqlite3_trace_v2, + tdsqlite3_expanded_sql, + /* Version 3.18.0 and later */ + tdsqlite3_set_last_insert_rowid, + /* Version 3.20.0 and later */ + tdsqlite3_prepare_v3, + tdsqlite3_prepare16_v3, + tdsqlite3_bind_pointer, + tdsqlite3_result_pointer, + tdsqlite3_value_pointer, + /* Version 3.22.0 and later */ + tdsqlite3_vtab_nochange, + tdsqlite3_value_nochange, + tdsqlite3_vtab_collation, + /* Version 3.24.0 and later */ + tdsqlite3_keyword_count, + tdsqlite3_keyword_name, + tdsqlite3_keyword_check, + tdsqlite3_str_new, + tdsqlite3_str_finish, + tdsqlite3_str_appendf, + tdsqlite3_str_vappendf, + tdsqlite3_str_append, + tdsqlite3_str_appendall, + tdsqlite3_str_appendchar, + tdsqlite3_str_reset, + tdsqlite3_str_errcode, + tdsqlite3_str_length, + tdsqlite3_str_value, + /* Version 3.25.0 and later */ + tdsqlite3_create_window_function, + /* Version 3.26.0 and later */ +#ifdef SQLITE_ENABLE_NORMALIZE + tdsqlite3_normalized_sql, +#else + 0, +#endif + /* Version 3.28.0 and later */ + tdsqlite3_stmt_isexplain, + tdsqlite3_value_frombind, + /* Version 3.30.0 and later */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + tdsqlite3_drop_modules, +#else + 0, +#endif + /* Version 3.31.0 and later */ + tdsqlite3_hard_heap_limit64, + tdsqlite3_uri_key, + tdsqlite3_filename_database, + tdsqlite3_filename_journal, + tdsqlite3_filename_wal, }; /* ** Attempt to load an SQLite extension library contained in the file ** zFile. The entry point is zProc. zProc may be 0 in which case a -** default entry point name (sqlite3_extension_init) is used. Use +** default entry point name (tdsqlite3_extension_init) is used. Use ** of the default name is recommended. ** ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. ** ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with ** error message text. The calling function should free this memory -** by calling sqlite3DbFree(db, ). +** by calling tdsqlite3DbFree(db, ). */ -static int sqlite3LoadExtension( - sqlite3 *db, /* Load the extension into this database connection */ +static int tdsqlite3LoadExtension( + tdsqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ - const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ + const char *zProc, /* Entry point. Use "tdsqlite3_extension_init" if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ){ - sqlite3_vfs *pVfs = db->pVfs; + tdsqlite3_vfs *pVfs = db->pVfs; void *handle; - sqlite3_loadext_entry xInit; + tdsqlite3_loadext_entry xInit; char *zErrmsg = 0; const char *zEntry; char *zAltEntry = 0; void **aHandle; - u64 nMsg = 300 + sqlite3Strlen30(zFile); + u64 nMsg = 300 + tdsqlite3Strlen30(zFile); int ii; int rc; @@ -113849,124 +126951,124 @@ static int sqlite3LoadExtension( /* Ticket #1863. To avoid a creating security problems for older ** applications that relink against newer versions of SQLite, the ** ability to run load_extension is turned off by default. One - ** must call either sqlite3_enable_load_extension(db) or - ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0) + ** must call either tdsqlite3_enable_load_extension(db) or + ** tdsqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0) ** to turn on extension loading. */ if( (db->flags & SQLITE_LoadExtension)==0 ){ if( pzErrMsg ){ - *pzErrMsg = sqlite3_mprintf("not authorized"); + *pzErrMsg = tdsqlite3_mprintf("not authorized"); } return SQLITE_ERROR; } - zEntry = zProc ? zProc : "sqlite3_extension_init"; + zEntry = zProc ? zProc : "tdsqlite3_extension_init"; - handle = sqlite3OsDlOpen(pVfs, zFile); + handle = tdsqlite3OsDlOpen(pVfs, zFile); #if SQLITE_OS_UNIX || SQLITE_OS_WIN for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){ - char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]); + char *zAltFile = tdsqlite3_mprintf("%s.%s", zFile, azEndings[ii]); if( zAltFile==0 ) return SQLITE_NOMEM_BKPT; - handle = sqlite3OsDlOpen(pVfs, zAltFile); - sqlite3_free(zAltFile); + handle = tdsqlite3OsDlOpen(pVfs, zAltFile); + tdsqlite3_free(zAltFile); } #endif if( handle==0 ){ if( pzErrMsg ){ - *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg); + *pzErrMsg = zErrmsg = tdsqlite3_malloc64(nMsg); if( zErrmsg ){ - sqlite3_snprintf(nMsg, zErrmsg, + tdsqlite3_snprintf(nMsg, zErrmsg, "unable to open shared library [%s]", zFile); - sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); + tdsqlite3OsDlError(pVfs, nMsg-1, zErrmsg); } } return SQLITE_ERROR; } - xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry); + xInit = (tdsqlite3_loadext_entry)tdsqlite3OsDlSym(pVfs, handle, zEntry); /* If no entry point was specified and the default legacy - ** entry point name "sqlite3_extension_init" was not found, then - ** construct an entry point name "sqlite3_X_init" where the X is + ** entry point name "tdsqlite3_extension_init" was not found, then + ** construct an entry point name "tdsqlite3_X_init" where the X is ** replaced by the lowercase value of every ASCII alphabetic ** character in the filename after the last "/" upto the first ".", ** and eliding the first three characters if they are "lib". ** Examples: ** - ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init - ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init + ** /usr/local/lib/libExample5.4.3.so ==> tdsqlite3_example_init + ** C:/lib/mathfuncs.dll ==> tdsqlite3_mathfuncs_init */ if( xInit==0 && zProc==0 ){ int iFile, iEntry, c; - int ncFile = sqlite3Strlen30(zFile); - zAltEntry = sqlite3_malloc64(ncFile+30); + int ncFile = tdsqlite3Strlen30(zFile); + zAltEntry = tdsqlite3_malloc64(ncFile+30); if( zAltEntry==0 ){ - sqlite3OsDlClose(pVfs, handle); + tdsqlite3OsDlClose(pVfs, handle); return SQLITE_NOMEM_BKPT; } - memcpy(zAltEntry, "sqlite3_", 8); + memcpy(zAltEntry, "tdsqlite3_", 8); for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){} iFile++; - if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; + if( tdsqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){ - if( sqlite3Isalpha(c) ){ - zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c]; + if( tdsqlite3Isalpha(c) ){ + zAltEntry[iEntry++] = (char)tdsqlite3UpperToLower[(unsigned)c]; } } memcpy(zAltEntry+iEntry, "_init", 6); zEntry = zAltEntry; - xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry); + xInit = (tdsqlite3_loadext_entry)tdsqlite3OsDlSym(pVfs, handle, zEntry); } if( xInit==0 ){ if( pzErrMsg ){ - nMsg += sqlite3Strlen30(zEntry); - *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg); + nMsg += tdsqlite3Strlen30(zEntry); + *pzErrMsg = zErrmsg = tdsqlite3_malloc64(nMsg); if( zErrmsg ){ - sqlite3_snprintf(nMsg, zErrmsg, + tdsqlite3_snprintf(nMsg, zErrmsg, "no entry point [%s] in shared library [%s]", zEntry, zFile); - sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); + tdsqlite3OsDlError(pVfs, nMsg-1, zErrmsg); } } - sqlite3OsDlClose(pVfs, handle); - sqlite3_free(zAltEntry); + tdsqlite3OsDlClose(pVfs, handle); + tdsqlite3_free(zAltEntry); return SQLITE_ERROR; } - sqlite3_free(zAltEntry); - rc = xInit(db, &zErrmsg, &sqlite3Apis); + tdsqlite3_free(zAltEntry); + rc = xInit(db, &zErrmsg, &tdsqlite3Apis); if( rc ){ if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK; if( pzErrMsg ){ - *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); + *pzErrMsg = tdsqlite3_mprintf("error during initialization: %s", zErrmsg); } - sqlite3_free(zErrmsg); - sqlite3OsDlClose(pVfs, handle); + tdsqlite3_free(zErrmsg); + tdsqlite3OsDlClose(pVfs, handle); return SQLITE_ERROR; } /* Append the new shared library handle to the db->aExtension array. */ - aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1)); + aHandle = tdsqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1)); if( aHandle==0 ){ return SQLITE_NOMEM_BKPT; } if( db->nExtension>0 ){ memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension); } - sqlite3DbFree(db, db->aExtension); + tdsqlite3DbFree(db, db->aExtension); db->aExtension = aHandle; db->aExtension[db->nExtension++] = handle; return SQLITE_OK; } -SQLITE_API int sqlite3_load_extension( - sqlite3 *db, /* Load the extension into this database connection */ +SQLITE_API int tdsqlite3_load_extension( + tdsqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ - const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ + const char *zProc, /* Entry point. Use "tdsqlite3_extension_init" if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ){ int rc; - sqlite3_mutex_enter(db->mutex); - rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_enter(db->mutex); + rc = tdsqlite3LoadExtension(db, zFile, zProc, pzErrMsg); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -113974,27 +127076,27 @@ SQLITE_API int sqlite3_load_extension( ** Call this routine when the database connection is closing in order ** to clean up loaded extensions */ -SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3CloseExtensions(tdsqlite3 *db){ int i; - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nExtension; i++){ - sqlite3OsDlClose(db->pVfs, db->aExtension[i]); + tdsqlite3OsDlClose(db->pVfs, db->aExtension[i]); } - sqlite3DbFree(db, db->aExtension); + tdsqlite3DbFree(db, db->aExtension); } /* ** Enable or disable extension loading. Extension loading is disabled by ** default so as not to open security holes in older applications. */ -SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){ - sqlite3_mutex_enter(db->mutex); +SQLITE_API int tdsqlite3_enable_load_extension(tdsqlite3 *db, int onoff){ + tdsqlite3_mutex_enter(db->mutex); if( onoff ){ db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc; }else{ - db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc); + db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc); } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_OK; } @@ -114007,25 +127109,25 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){ ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER ** mutex must be held while accessing this list. */ -typedef struct sqlite3AutoExtList sqlite3AutoExtList; -static SQLITE_WSD struct sqlite3AutoExtList { +typedef struct tdsqlite3AutoExtList tdsqlite3AutoExtList; +static SQLITE_WSD struct tdsqlite3AutoExtList { u32 nExt; /* Number of entries in aExt[] */ void (**aExt)(void); /* Pointers to the extension init functions */ -} sqlite3Autoext = { 0, 0 }; +} tdsqlite3Autoext = { 0, 0 }; /* The "wsdAutoext" macro will resolve to the autoextension ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly -** to the "sqlite3Autoext" state vector declared above. +** to the "tdsqlite3Autoext" state vector declared above. */ #ifdef SQLITE_OMIT_WSD # define wsdAutoextInit \ - sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) + tdsqlite3AutoExtList *x = &GLOBAL(tdsqlite3AutoExtList,tdsqlite3Autoext) # define wsdAutoext x[0] #else # define wsdAutoextInit -# define wsdAutoext sqlite3Autoext +# define wsdAutoext tdsqlite3Autoext #endif @@ -114033,12 +127135,12 @@ static SQLITE_WSD struct sqlite3AutoExtList { ** Register a statically linked extension that is automatically ** loaded by every new database connection. */ -SQLITE_API int sqlite3_auto_extension( +SQLITE_API int tdsqlite3_auto_extension( void (*xInit)(void) ){ int rc = SQLITE_OK; #ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); + rc = tdsqlite3_initialize(); if( rc ){ return rc; }else @@ -114046,17 +127148,17 @@ SQLITE_API int sqlite3_auto_extension( { u32 i; #if SQLITE_THREADSAFE - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); + tdsqlite3_mutex *mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif wsdAutoextInit; - sqlite3_mutex_enter(mutex); + tdsqlite3_mutex_enter(mutex); for(i=0; i<wsdAutoext.nExt; i++){ if( wsdAutoext.aExt[i]==xInit ) break; } if( i==wsdAutoext.nExt ){ u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]); void (**aNew)(void); - aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte); + aNew = tdsqlite3_realloc64(wsdAutoext.aExt, nByte); if( aNew==0 ){ rc = SQLITE_NOMEM_BKPT; }else{ @@ -114065,14 +127167,14 @@ SQLITE_API int sqlite3_auto_extension( wsdAutoext.nExt++; } } - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); assert( (rc&0xff)==rc ); return rc; } } /* -** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the +** Cancel a prior call to tdsqlite3_auto_extension. Remove xInit from the ** set of routines that is invoked for each new database connection, if it ** is currently on the list. If xInit is not on the list, then this ** routine is a no-op. @@ -114080,16 +127182,16 @@ SQLITE_API int sqlite3_auto_extension( ** Return 1 if xInit was found on the list and removed. Return 0 if xInit ** was not on the list. */ -SQLITE_API int sqlite3_cancel_auto_extension( +SQLITE_API int tdsqlite3_cancel_auto_extension( void (*xInit)(void) ){ #if SQLITE_THREADSAFE - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); + tdsqlite3_mutex *mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif int i; int n = 0; wsdAutoextInit; - sqlite3_mutex_enter(mutex); + tdsqlite3_mutex_enter(mutex); for(i=(int)wsdAutoext.nExt-1; i>=0; i--){ if( wsdAutoext.aExt[i]==xInit ){ wsdAutoext.nExt--; @@ -114098,27 +127200,27 @@ SQLITE_API int sqlite3_cancel_auto_extension( break; } } - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); return n; } /* ** Reset the automatic extension loading mechanism. */ -SQLITE_API void sqlite3_reset_auto_extension(void){ +SQLITE_API void tdsqlite3_reset_auto_extension(void){ #ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize()==SQLITE_OK ) + if( tdsqlite3_initialize()==SQLITE_OK ) #endif { #if SQLITE_THREADSAFE - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); + tdsqlite3_mutex *mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif wsdAutoextInit; - sqlite3_mutex_enter(mutex); - sqlite3_free(wsdAutoext.aExt); + tdsqlite3_mutex_enter(mutex); + tdsqlite3_free(wsdAutoext.aExt); wsdAutoext.aExt = 0; wsdAutoext.nExt = 0; - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); } } @@ -114127,11 +127229,11 @@ SQLITE_API void sqlite3_reset_auto_extension(void){ ** ** If anything goes wrong, set an error in the database connection. */ -SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3AutoLoadExtensions(tdsqlite3 *db){ u32 i; int go = 1; int rc; - sqlite3_loadext_entry xInit; + tdsqlite3_loadext_entry xInit; wsdAutoextInit; if( wsdAutoext.nExt==0 ){ @@ -114141,28 +127243,28 @@ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){ for(i=0; go; i++){ char *zErrmsg; #if SQLITE_THREADSAFE - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); + tdsqlite3_mutex *mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif #ifdef SQLITE_OMIT_LOAD_EXTENSION - const sqlite3_api_routines *pThunk = 0; + const tdsqlite3_api_routines *pThunk = 0; #else - const sqlite3_api_routines *pThunk = &sqlite3Apis; + const tdsqlite3_api_routines *pThunk = &tdsqlite3Apis; #endif - sqlite3_mutex_enter(mutex); + tdsqlite3_mutex_enter(mutex); if( i>=wsdAutoext.nExt ){ xInit = 0; go = 0; }else{ - xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i]; + xInit = (tdsqlite3_loadext_entry)wsdAutoext.aExt[i]; } - sqlite3_mutex_leave(mutex); + tdsqlite3_mutex_leave(mutex); zErrmsg = 0; if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){ - sqlite3ErrorWithMsg(db, rc, + tdsqlite3ErrorWithMsg(db, rc, "automatic extension loading failed: %s", zErrmsg); go = 0; } - sqlite3_free(zErrmsg); + tdsqlite3_free(zErrmsg); } } @@ -114205,6 +127307,8 @@ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){ ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit ** that script and rerun it. */ + +/* The various pragma types */ #define PragTyp_HEADER_VALUE 0 #define PragTyp_AUTO_VACUUM 1 #define PragTyp_FLAG 2 @@ -114220,450 +127324,667 @@ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){ #define PragTyp_ENCODING 12 #define PragTyp_FOREIGN_KEY_CHECK 13 #define PragTyp_FOREIGN_KEY_LIST 14 -#define PragTyp_INCREMENTAL_VACUUM 15 -#define PragTyp_INDEX_INFO 16 -#define PragTyp_INDEX_LIST 17 -#define PragTyp_INTEGRITY_CHECK 18 -#define PragTyp_JOURNAL_MODE 19 -#define PragTyp_JOURNAL_SIZE_LIMIT 20 -#define PragTyp_LOCK_PROXY_FILE 21 -#define PragTyp_LOCKING_MODE 22 -#define PragTyp_PAGE_COUNT 23 -#define PragTyp_MMAP_SIZE 24 -#define PragTyp_PAGE_SIZE 25 -#define PragTyp_SECURE_DELETE 26 -#define PragTyp_SHRINK_MEMORY 27 -#define PragTyp_SOFT_HEAP_LIMIT 28 -#define PragTyp_STATS 29 -#define PragTyp_SYNCHRONOUS 30 -#define PragTyp_TABLE_INFO 31 -#define PragTyp_TEMP_STORE 32 -#define PragTyp_TEMP_STORE_DIRECTORY 33 -#define PragTyp_THREADS 34 -#define PragTyp_WAL_AUTOCHECKPOINT 35 -#define PragTyp_WAL_CHECKPOINT 36 -#define PragTyp_ACTIVATE_EXTENSIONS 37 -#define PragTyp_HEXKEY 38 -#define PragTyp_KEY 39 -#define PragTyp_REKEY 40 -#define PragTyp_LOCK_STATUS 41 -#define PragTyp_PARSER_TRACE 42 -#define PragFlag_NeedSchema 0x01 -#define PragFlag_ReadOnly 0x02 -static const struct sPragmaNames { - const char *const zName; /* Name of pragma */ - u8 ePragTyp; /* PragTyp_XXX value */ - u8 mPragFlag; /* Zero or more PragFlag_XXX values */ - u32 iArg; /* Extra argument */ -} aPragmaNames[] = { +#define PragTyp_FUNCTION_LIST 15 +#define PragTyp_HARD_HEAP_LIMIT 16 +#define PragTyp_INCREMENTAL_VACUUM 17 +#define PragTyp_INDEX_INFO 18 +#define PragTyp_INDEX_LIST 19 +#define PragTyp_INTEGRITY_CHECK 20 +#define PragTyp_JOURNAL_MODE 21 +#define PragTyp_JOURNAL_SIZE_LIMIT 22 +#define PragTyp_LOCK_PROXY_FILE 23 +#define PragTyp_LOCKING_MODE 24 +#define PragTyp_PAGE_COUNT 25 +#define PragTyp_MMAP_SIZE 26 +#define PragTyp_MODULE_LIST 27 +#define PragTyp_OPTIMIZE 28 +#define PragTyp_PAGE_SIZE 29 +#define PragTyp_PRAGMA_LIST 30 +#define PragTyp_SECURE_DELETE 31 +#define PragTyp_SHRINK_MEMORY 32 +#define PragTyp_SOFT_HEAP_LIMIT 33 +#define PragTyp_SYNCHRONOUS 34 +#define PragTyp_TABLE_INFO 35 +#define PragTyp_TEMP_STORE 36 +#define PragTyp_TEMP_STORE_DIRECTORY 37 +#define PragTyp_THREADS 38 +#define PragTyp_WAL_AUTOCHECKPOINT 39 +#define PragTyp_WAL_CHECKPOINT 40 +#define PragTyp_ACTIVATE_EXTENSIONS 41 +#define PragTyp_KEY 42 +#define PragTyp_LOCK_STATUS 43 +#define PragTyp_STATS 44 + +/* Property flags associated with various pragma. */ +#define PragFlg_NeedSchema 0x01 /* Force schema load before running */ +#define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */ +#define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */ +#define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */ +#define PragFlg_Result0 0x10 /* Acts as query when no argument */ +#define PragFlg_Result1 0x20 /* Acts as query when has one argument */ +#define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */ +#define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */ + +/* Names of columns for pragmas that return multi-column result +** or that return single-column results where the name of the +** result column is different from the name of the pragma +*/ +static const char *const pragCName[] = { + /* 0 */ "id", /* Used by: foreign_key_list */ + /* 1 */ "seq", + /* 2 */ "table", + /* 3 */ "from", + /* 4 */ "to", + /* 5 */ "on_update", + /* 6 */ "on_delete", + /* 7 */ "match", + /* 8 */ "cid", /* Used by: table_xinfo */ + /* 9 */ "name", + /* 10 */ "type", + /* 11 */ "notnull", + /* 12 */ "dflt_value", + /* 13 */ "pk", + /* 14 */ "hidden", + /* table_info reuses 8 */ + /* 15 */ "seqno", /* Used by: index_xinfo */ + /* 16 */ "cid", + /* 17 */ "name", + /* 18 */ "desc", + /* 19 */ "coll", + /* 20 */ "key", + /* 21 */ "name", /* Used by: function_list */ + /* 22 */ "builtin", + /* 23 */ "type", + /* 24 */ "enc", + /* 25 */ "narg", + /* 26 */ "flags", + /* 27 */ "tbl", /* Used by: stats */ + /* 28 */ "idx", + /* 29 */ "wdth", + /* 30 */ "hght", + /* 31 */ "flgs", + /* 32 */ "seq", /* Used by: index_list */ + /* 33 */ "name", + /* 34 */ "unique", + /* 35 */ "origin", + /* 36 */ "partial", + /* 37 */ "table", /* Used by: foreign_key_check */ + /* 38 */ "rowid", + /* 39 */ "parent", + /* 40 */ "fkid", + /* index_info reuses 15 */ + /* 41 */ "seq", /* Used by: database_list */ + /* 42 */ "name", + /* 43 */ "file", + /* 44 */ "busy", /* Used by: wal_checkpoint */ + /* 45 */ "log", + /* 46 */ "checkpointed", + /* collation_list reuses 32 */ + /* 47 */ "database", /* Used by: lock_status */ + /* 48 */ "status", + /* 49 */ "cache_size", /* Used by: default_cache_size */ + /* module_list pragma_list reuses 9 */ + /* 50 */ "timeout", /* Used by: busy_timeout */ +}; + +/* Definitions of all built-in pragmas */ +typedef struct PragmaName { + const char *const zName; /* Name of pragma */ + u8 ePragTyp; /* PragTyp_XXX value */ + u8 mPragFlg; /* Zero or more PragFlg_XXX values */ + u8 iPragCName; /* Start of column names in pragCName[] */ + u8 nPragCName; /* Num of col names. 0 means use pragma name */ + u64 iArg; /* Extra argument */ +} PragmaName; +static const PragmaName aPragmaName[] = { #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) - { /* zName: */ "activate_extensions", - /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "activate_extensions", + /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS, + /* ePragFlg: */ 0, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - { /* zName: */ "application_id", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlag: */ 0, - /* iArg: */ BTREE_APPLICATION_ID }, + {/* zName: */ "application_id", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ BTREE_APPLICATION_ID }, #endif #if !defined(SQLITE_OMIT_AUTOVACUUM) - { /* zName: */ "auto_vacuum", - /* ePragTyp: */ PragTyp_AUTO_VACUUM, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "auto_vacuum", + /* ePragTyp: */ PragTyp_AUTO_VACUUM, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX) - { /* zName: */ "automatic_index", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_AutoIndex }, -#endif -#endif - { /* zName: */ "busy_timeout", - /* ePragTyp: */ PragTyp_BUSY_TIMEOUT, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "automatic_index", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_AutoIndex }, +#endif +#endif + {/* zName: */ "busy_timeout", + /* ePragTyp: */ PragTyp_BUSY_TIMEOUT, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 50, 1, + /* iArg: */ 0 }, #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - { /* zName: */ "cache_size", - /* ePragTyp: */ PragTyp_CACHE_SIZE, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "cache_size", + /* ePragTyp: */ PragTyp_CACHE_SIZE, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "cache_spill", - /* ePragTyp: */ PragTyp_CACHE_SPILL, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, -#endif - { /* zName: */ "case_sensitive_like", - /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, - { /* zName: */ "cell_size_check", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_CellSizeCk }, + {/* zName: */ "cache_spill", + /* ePragTyp: */ PragTyp_CACHE_SPILL, + /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA) + {/* zName: */ "case_sensitive_like", + /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE, + /* ePragFlg: */ PragFlg_NoColumns, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, +#endif + {/* zName: */ "cell_size_check", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_CellSizeCk }, #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "checkpoint_fullfsync", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_CkptFullFSync }, + {/* zName: */ "checkpoint_fullfsync", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_CkptFullFSync }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - { /* zName: */ "collation_list", - /* ePragTyp: */ PragTyp_COLLATION_LIST, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "collation_list", + /* ePragTyp: */ PragTyp_COLLATION_LIST, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 32, 2, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS) - { /* zName: */ "compile_options", - /* ePragTyp: */ PragTyp_COMPILE_OPTIONS, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "compile_options", + /* ePragTyp: */ PragTyp_COMPILE_OPTIONS, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "count_changes", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_CountRows }, + {/* zName: */ "count_changes", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_CountRows }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN - { /* zName: */ "data_store_directory", - /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "data_store_directory", + /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY, + /* ePragFlg: */ PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - { /* zName: */ "data_version", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlag: */ PragFlag_ReadOnly, - /* iArg: */ BTREE_DATA_VERSION }, + {/* zName: */ "data_version", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ BTREE_DATA_VERSION }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - { /* zName: */ "database_list", - /* ePragTyp: */ PragTyp_DATABASE_LIST, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "database_list", + /* ePragTyp: */ PragTyp_DATABASE_LIST, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0, + /* ColNames: */ 41, 3, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) - { /* zName: */ "default_cache_size", - /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "default_cache_size", + /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, + /* ColNames: */ 49, 1, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - { /* zName: */ "defer_foreign_keys", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_DeferFKs }, + {/* zName: */ "defer_foreign_keys", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_DeferFKs }, #endif #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "empty_result_callbacks", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_NullCallback }, + {/* zName: */ "empty_result_callbacks", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_NullCallback }, #endif #if !defined(SQLITE_OMIT_UTF16) - { /* zName: */ "encoding", - /* ePragTyp: */ PragTyp_ENCODING, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "encoding", + /* ePragTyp: */ PragTyp_ENCODING, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - { /* zName: */ "foreign_key_check", - /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "foreign_key_check", + /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0, + /* ColNames: */ 37, 4, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FOREIGN_KEY) - { /* zName: */ "foreign_key_list", - /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "foreign_key_list", + /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, + /* ColNames: */ 0, 8, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - { /* zName: */ "foreign_keys", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_ForeignKeys }, + {/* zName: */ "foreign_keys", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_ForeignKeys }, #endif #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - { /* zName: */ "freelist_count", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlag: */ PragFlag_ReadOnly, - /* iArg: */ BTREE_FREE_PAGE_COUNT }, + {/* zName: */ "freelist_count", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ BTREE_FREE_PAGE_COUNT }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "full_column_names", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_FullColNames }, - { /* zName: */ "fullfsync", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_FullFSync }, + {/* zName: */ "full_column_names", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_FullColNames }, + {/* zName: */ "fullfsync", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_FullFSync }, #endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) +#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) + {/* zName: */ "function_list", + /* ePragTyp: */ PragTyp_FUNCTION_LIST, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 21, 6, + /* iArg: */ 0 }, +#endif +#endif + {/* zName: */ "hard_heap_limit", + /* ePragTyp: */ PragTyp_HARD_HEAP_LIMIT, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #if defined(SQLITE_HAS_CODEC) - { /* zName: */ "hexkey", - /* ePragTyp: */ PragTyp_HEXKEY, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, - { /* zName: */ "hexrekey", - /* ePragTyp: */ PragTyp_HEXKEY, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "hexkey", + /* ePragTyp: */ PragTyp_KEY, + /* ePragFlg: */ 0, + /* ColNames: */ 0, 0, + /* iArg: */ 2 }, + {/* zName: */ "hexrekey", + /* ePragTyp: */ PragTyp_KEY, + /* ePragFlg: */ 0, + /* ColNames: */ 0, 0, + /* iArg: */ 3 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if !defined(SQLITE_OMIT_CHECK) - { /* zName: */ "ignore_check_constraints", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_IgnoreChecks }, + {/* zName: */ "ignore_check_constraints", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_IgnoreChecks }, #endif #endif #if !defined(SQLITE_OMIT_AUTOVACUUM) - { /* zName: */ "incremental_vacuum", - /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "incremental_vacuum", + /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - { /* zName: */ "index_info", - /* ePragTyp: */ PragTyp_INDEX_INFO, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, - { /* zName: */ "index_list", - /* ePragTyp: */ PragTyp_INDEX_LIST, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, - { /* zName: */ "index_xinfo", - /* ePragTyp: */ PragTyp_INDEX_INFO, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 1 }, + {/* zName: */ "index_info", + /* ePragTyp: */ PragTyp_INDEX_INFO, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, + /* ColNames: */ 15, 3, + /* iArg: */ 0 }, + {/* zName: */ "index_list", + /* ePragTyp: */ PragTyp_INDEX_LIST, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, + /* ColNames: */ 32, 5, + /* iArg: */ 0 }, + {/* zName: */ "index_xinfo", + /* ePragTyp: */ PragTyp_INDEX_INFO, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, + /* ColNames: */ 15, 6, + /* iArg: */ 1 }, #endif #if !defined(SQLITE_OMIT_INTEGRITY_CHECK) - { /* zName: */ "integrity_check", - /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "integrity_check", + /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - { /* zName: */ "journal_mode", - /* ePragTyp: */ PragTyp_JOURNAL_MODE, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, - { /* zName: */ "journal_size_limit", - /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "journal_mode", + /* ePragTyp: */ PragTyp_JOURNAL_MODE, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, + {/* zName: */ "journal_size_limit", + /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT, + /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if defined(SQLITE_HAS_CODEC) - { /* zName: */ "key", - /* ePragTyp: */ PragTyp_KEY, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "key", + /* ePragTyp: */ PragTyp_KEY, + /* ePragFlg: */ 0, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "legacy_file_format", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_LegacyFileFmt }, + {/* zName: */ "legacy_alter_table", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_LegacyAlter }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE - { /* zName: */ "lock_proxy_file", - /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "lock_proxy_file", + /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE, + /* ePragFlg: */ PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - { /* zName: */ "lock_status", - /* ePragTyp: */ PragTyp_LOCK_STATUS, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "lock_status", + /* ePragTyp: */ PragTyp_LOCK_STATUS, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 47, 2, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) + {/* zName: */ "locking_mode", + /* ePragTyp: */ PragTyp_LOCKING_MODE, + /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, + {/* zName: */ "max_page_count", + /* ePragTyp: */ PragTyp_PAGE_COUNT, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, + {/* zName: */ "mmap_size", + /* ePragTyp: */ PragTyp_MMAP_SIZE, + /* ePragFlg: */ 0, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) +#if !defined(SQLITE_OMIT_VIRTUALTABLE) +#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) + {/* zName: */ "module_list", + /* ePragTyp: */ PragTyp_MODULE_LIST, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 9, 1, + /* iArg: */ 0 }, +#endif +#endif +#endif + {/* zName: */ "optimize", + /* ePragTyp: */ PragTyp_OPTIMIZE, + /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - { /* zName: */ "locking_mode", - /* ePragTyp: */ PragTyp_LOCKING_MODE, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, - { /* zName: */ "max_page_count", - /* ePragTyp: */ PragTyp_PAGE_COUNT, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, - { /* zName: */ "mmap_size", - /* ePragTyp: */ PragTyp_MMAP_SIZE, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, - { /* zName: */ "page_count", - /* ePragTyp: */ PragTyp_PAGE_COUNT, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, - { /* zName: */ "page_size", - /* ePragTyp: */ PragTyp_PAGE_SIZE, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, -#endif -#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE) - { /* zName: */ "parser_trace", - /* ePragTyp: */ PragTyp_PARSER_TRACE, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "page_count", + /* ePragTyp: */ PragTyp_PAGE_COUNT, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, + {/* zName: */ "page_size", + /* ePragTyp: */ PragTyp_PAGE_SIZE, + /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "query_only", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_QueryOnly }, +#if defined(SQLITE_DEBUG) + {/* zName: */ "parser_trace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_ParserTrace }, +#endif +#endif +#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) + {/* zName: */ "pragma_list", + /* ePragTyp: */ PragTyp_PRAGMA_LIST, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 9, 1, + /* iArg: */ 0 }, +#endif +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) + {/* zName: */ "query_only", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_QueryOnly }, #endif #if !defined(SQLITE_OMIT_INTEGRITY_CHECK) - { /* zName: */ "quick_check", - /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "quick_check", + /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "read_uncommitted", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_ReadUncommitted }, - { /* zName: */ "recursive_triggers", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_RecTriggers }, + {/* zName: */ "read_uncommitted", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_ReadUncommit }, + {/* zName: */ "recursive_triggers", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_RecTriggers }, #endif #if defined(SQLITE_HAS_CODEC) - { /* zName: */ "rekey", - /* ePragTyp: */ PragTyp_REKEY, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "rekey", + /* ePragTyp: */ PragTyp_KEY, + /* ePragFlg: */ 0, + /* ColNames: */ 0, 0, + /* iArg: */ 1 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "reverse_unordered_selects", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_ReverseOrder }, + {/* zName: */ "reverse_unordered_selects", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_ReverseOrder }, #endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - { /* zName: */ "schema_version", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlag: */ 0, - /* iArg: */ BTREE_SCHEMA_VERSION }, + {/* zName: */ "schema_version", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ BTREE_SCHEMA_VERSION }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - { /* zName: */ "secure_delete", - /* ePragTyp: */ PragTyp_SECURE_DELETE, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "secure_delete", + /* ePragTyp: */ PragTyp_SECURE_DELETE, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "short_column_names", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_ShortColNames }, -#endif - { /* zName: */ "shrink_memory", - /* ePragTyp: */ PragTyp_SHRINK_MEMORY, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, - { /* zName: */ "soft_heap_limit", - /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "short_column_names", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_ShortColNames }, +#endif + {/* zName: */ "shrink_memory", + /* ePragTyp: */ PragTyp_SHRINK_MEMORY, + /* ePragFlg: */ PragFlg_NoColumns, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, + {/* zName: */ "soft_heap_limit", + /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if defined(SQLITE_DEBUG) - { /* zName: */ "sql_trace", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_SqlTrace }, + {/* zName: */ "sql_trace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_SqlTrace }, #endif #endif -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - { /* zName: */ "stats", - /* ePragTyp: */ PragTyp_STATS, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG) + {/* zName: */ "stats", + /* ePragTyp: */ PragTyp_STATS, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, + /* ColNames: */ 27, 5, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - { /* zName: */ "synchronous", - /* ePragTyp: */ PragTyp_SYNCHRONOUS, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "synchronous", + /* ePragTyp: */ PragTyp_SYNCHRONOUS, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - { /* zName: */ "table_info", - /* ePragTyp: */ PragTyp_TABLE_INFO, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "table_info", + /* ePragTyp: */ PragTyp_TABLE_INFO, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, + /* ColNames: */ 8, 6, + /* iArg: */ 0 }, + {/* zName: */ "table_xinfo", + /* ePragTyp: */ PragTyp_TABLE_INFO, + /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, + /* ColNames: */ 8, 7, + /* iArg: */ 1 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - { /* zName: */ "temp_store", - /* ePragTyp: */ PragTyp_TEMP_STORE, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, - { /* zName: */ "temp_store_directory", - /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, -#endif - { /* zName: */ "threads", - /* ePragTyp: */ PragTyp_THREADS, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, + {/* zName: */ "temp_store", + /* ePragTyp: */ PragTyp_TEMP_STORE, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, + {/* zName: */ "temp_store_directory", + /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY, + /* ePragFlg: */ PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, +#endif +#if defined(SQLITE_HAS_CODEC) + {/* zName: */ "textkey", + /* ePragTyp: */ PragTyp_KEY, + /* ePragFlg: */ 0, + /* ColNames: */ 0, 0, + /* iArg: */ 4 }, + {/* zName: */ "textrekey", + /* ePragTyp: */ PragTyp_KEY, + /* ePragFlg: */ 0, + /* ColNames: */ 0, 0, + /* iArg: */ 5 }, +#endif + {/* zName: */ "threads", + /* ePragTyp: */ PragTyp_THREADS, + /* ePragFlg: */ PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, +#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) + {/* zName: */ "trusted_schema", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_TrustedSchema }, +#endif #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - { /* zName: */ "user_version", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlag: */ 0, - /* iArg: */ BTREE_USER_VERSION }, + {/* zName: */ "user_version", + /* ePragTyp: */ PragTyp_HEADER_VALUE, + /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0, + /* ColNames: */ 0, 0, + /* iArg: */ BTREE_USER_VERSION }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) #if defined(SQLITE_DEBUG) - { /* zName: */ "vdbe_addoptrace", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_VdbeAddopTrace }, - { /* zName: */ "vdbe_debug", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace }, - { /* zName: */ "vdbe_eqp", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_VdbeEQP }, - { /* zName: */ "vdbe_listing", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_VdbeListing }, - { /* zName: */ "vdbe_trace", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_VdbeTrace }, + {/* zName: */ "vdbe_addoptrace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_VdbeAddopTrace }, + {/* zName: */ "vdbe_debug", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace }, + {/* zName: */ "vdbe_eqp", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_VdbeEQP }, + {/* zName: */ "vdbe_listing", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_VdbeListing }, + {/* zName: */ "vdbe_trace", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_VdbeTrace }, #endif #endif #if !defined(SQLITE_OMIT_WAL) - { /* zName: */ "wal_autocheckpoint", - /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT, - /* ePragFlag: */ 0, - /* iArg: */ 0 }, - { /* zName: */ "wal_checkpoint", - /* ePragTyp: */ PragTyp_WAL_CHECKPOINT, - /* ePragFlag: */ PragFlag_NeedSchema, - /* iArg: */ 0 }, + {/* zName: */ "wal_autocheckpoint", + /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT, + /* ePragFlg: */ 0, + /* ColNames: */ 0, 0, + /* iArg: */ 0 }, + {/* zName: */ "wal_checkpoint", + /* ePragTyp: */ PragTyp_WAL_CHECKPOINT, + /* ePragFlg: */ PragFlg_NeedSchema, + /* ColNames: */ 44, 3, + /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - { /* zName: */ "writable_schema", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlag: */ 0, - /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode }, + {/* zName: */ "writable_schema", + /* ePragTyp: */ PragTyp_FLAG, + /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, + /* ColNames: */ 0, 0, + /* iArg: */ SQLITE_WriteSchema|SQLITE_NoSchemaError }, #endif }; -/* Number of pragmas: 60 on by default, 73 total. */ +/* Number of pragmas: 66 on by default, 82 total. */ /************** End of pragma.h **********************************************/ /************** Continuing where we left off in pragma.c *********************/ @@ -114675,7 +127996,7 @@ static const struct sPragmaNames { ** if the omitFull parameter it 1. ** ** Note that the values returned are one less that the values that -** should be passed into sqlite3BtreeSetSafetyLevel(). The is done +** should be passed into tdsqlite3BtreeSetSafetyLevel(). The is done ** to support legacy SQL code. The safety level used to be boolean ** and older scripts may have used numbers 0 for OFF and 1 for ON. */ @@ -114687,12 +128008,12 @@ static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){ static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2}; /* on no off false yes true extra full */ int i, n; - if( sqlite3Isdigit(*z) ){ - return (u8)sqlite3Atoi(z); + if( tdsqlite3Isdigit(*z) ){ + return (u8)tdsqlite3Atoi(z); } - n = sqlite3Strlen30(z); + n = tdsqlite3Strlen30(z); for(i=0; i<ArraySize(iLength); i++){ - if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 + if( iLength[i]==n && tdsqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 && (!omitFull || iValue[i]<=1) ){ return iValue[i]; @@ -114704,11 +128025,11 @@ static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){ /* ** Interpret the given string as a boolean value. */ -SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){ +SQLITE_PRIVATE u8 tdsqlite3GetBoolean(const char *z, u8 dflt){ return getSafetyLevel(z,1,dflt)!=0; } -/* The sqlite3GetBoolean() function is used by other modules but the +/* The tdsqlite3GetBoolean() function is used by other modules but the ** remainder of this file is specific to PRAGMA processing. So omit ** the rest of the file if PRAGMAs are omitted from the build. */ @@ -114719,8 +128040,8 @@ SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){ */ static int getLockingMode(const char *z){ if( z ){ - if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE; - if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL; + if( 0==tdsqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE; + if( 0==tdsqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL; } return PAGER_LOCKINGMODE_QUERY; } @@ -114734,10 +128055,10 @@ static int getLockingMode(const char *z){ */ static int getAutoVacuum(const char *z){ int i; - if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE; - if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL; - if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR; - i = sqlite3Atoi(z); + if( 0==tdsqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE; + if( 0==tdsqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL; + if( 0==tdsqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR; + i = tdsqlite3Atoi(z); return (u8)((i>=0&&i<=2)?i:0); } #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */ @@ -114751,9 +128072,9 @@ static int getAutoVacuum(const char *z){ static int getTempStore(const char *z){ if( z[0]>='0' && z[0]<='2' ){ return z[0] - '0'; - }else if( sqlite3StrICmp(z, "file")==0 ){ + }else if( tdsqlite3StrICmp(z, "file")==0 ){ return 1; - }else if( sqlite3StrICmp(z, "memory")==0 ){ + }else if( tdsqlite3StrICmp(z, "memory")==0 ){ return 2; }else{ return 0; @@ -114767,16 +128088,16 @@ static int getTempStore(const char *z){ ** from default, or when 'file' and the temp_store_directory has changed */ static int invalidateTempStorage(Parse *pParse){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; if( db->aDb[1].pBt!=0 ){ - if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){ - sqlite3ErrorMsg(pParse, "temporary storage cannot be changed " + if( !db->autoCommit || tdsqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){ + tdsqlite3ErrorMsg(pParse, "temporary storage cannot be changed " "from within a transaction"); return SQLITE_ERROR; } - sqlite3BtreeClose(db->aDb[1].pBt); + tdsqlite3BtreeClose(db->aDb[1].pBt); db->aDb[1].pBt = 0; - sqlite3ResetAllSchemasOfConnection(db); + tdsqlite3ResetAllSchemasOfConnection(db); } return SQLITE_OK; } @@ -114790,7 +128111,7 @@ static int invalidateTempStorage(Parse *pParse){ */ static int changeTempStorage(Parse *pParse, const char *zStorageType){ int ts = getTempStore(zStorageType); - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; if( db->temp_store==ts ) return SQLITE_OK; if( invalidateTempStorage( pParse ) != SQLITE_OK ){ return SQLITE_ERROR; @@ -114801,30 +128122,30 @@ static int changeTempStorage(Parse *pParse, const char *zStorageType){ #endif /* SQLITE_PAGER_PRAGMAS */ /* -** Set the names of the first N columns to the values in azCol[] +** Set result column names for a pragma. */ -static void setAllColumnNames( - Vdbe *v, /* The query under construction */ - int N, /* Number of columns */ - const char **azCol /* Names of columns */ +static void setPragmaResultColumnNames( + Vdbe *v, /* The query under construction */ + const PragmaName *pPragma /* The pragma */ ){ - int i; - sqlite3VdbeSetNumCols(v, N); - for(i=0; i<N; i++){ - sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC); + u8 n = pPragma->nPragCName; + tdsqlite3VdbeSetNumCols(v, n==0 ? 1 : n); + if( n==0 ){ + tdsqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC); + }else{ + int i, j; + for(i=0, j=pPragma->iPragCName; i<n; i++, j++){ + tdsqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC); + } } } -static void setOneColumnName(Vdbe *v, const char *z){ - setAllColumnNames(v, 1, &z); -} /* ** Generate code to return a single integer value. */ -static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){ - sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64); - setOneColumnName(v, zLabel); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); +static void returnSingleInt(Vdbe *v, i64 value){ + tdsqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } /* @@ -114832,13 +128153,11 @@ static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){ */ static void returnSingleText( Vdbe *v, /* Prepared statement under construction */ - const char *zLabel, /* Name of the result column */ const char *zValue /* Value to be returned */ ){ if( zValue ){ - sqlite3VdbeLoadString(v, 1, (const char*)zValue); - setOneColumnName(v, zLabel); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + tdsqlite3VdbeLoadString(v, 1, (const char*)zValue); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } } @@ -114848,7 +128167,7 @@ static void returnSingleText( ** set these values for all pagers. */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS -static void setAllPagerFlags(sqlite3 *db){ +static void setAllPagerFlags(tdsqlite3 *db){ if( db->autoCommit ){ Db *pDb = db->aDb; int n = db->nDb; @@ -114860,7 +128179,7 @@ static void setAllPagerFlags(sqlite3 *db){ assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level ); while( (n--) > 0 ){ if( pDb->pBt ){ - sqlite3BtreeSetPagerFlags(pDb->pBt, + tdsqlite3BtreeSetPagerFlags(pDb->pBt, pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) ); } pDb++; @@ -114896,7 +128215,7 @@ static const char *actionName(u8 action){ ** defined in pager.h. This function returns the associated lowercase ** journal-mode name. */ -SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){ +SQLITE_PRIVATE const char *tdsqlite3JournalModename(int eMode){ static char * const azModeName[] = { "delete", "persist", "off", "truncate", "memory" #ifndef SQLITE_OMIT_WAL @@ -114916,6 +128235,91 @@ SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){ } /* +** Locate a pragma in the aPragmaName[] array. +*/ +static const PragmaName *pragmaLocate(const char *zName){ + int upr, lwr, mid = 0, rc; + lwr = 0; + upr = ArraySize(aPragmaName)-1; + while( lwr<=upr ){ + mid = (lwr+upr)/2; + rc = tdsqlite3_stricmp(zName, aPragmaName[mid].zName); + if( rc==0 ) break; + if( rc<0 ){ + upr = mid - 1; + }else{ + lwr = mid + 1; + } + } + return lwr>upr ? 0 : &aPragmaName[mid]; +} + +/* +** Create zero or more entries in the output for the SQL functions +** defined by FuncDef p. +*/ +static void pragmaFunclistLine( + Vdbe *v, /* The prepared statement being created */ + FuncDef *p, /* A particular function definition */ + int isBuiltin, /* True if this is a built-in function */ + int showInternFuncs /* True if showing internal functions */ +){ + for(; p; p=p->pNext){ + const char *zType; + static const u32 mask = + SQLITE_DETERMINISTIC | + SQLITE_DIRECTONLY | + SQLITE_SUBTYPE | + SQLITE_INNOCUOUS | + SQLITE_FUNC_INTERNAL + ; + static const char *azEnc[] = { 0, "utf8", "utf16le", "utf16be" }; + + assert( SQLITE_FUNC_ENCMASK==0x3 ); + assert( strcmp(azEnc[SQLITE_UTF8],"utf8")==0 ); + assert( strcmp(azEnc[SQLITE_UTF16LE],"utf16le")==0 ); + assert( strcmp(azEnc[SQLITE_UTF16BE],"utf16be")==0 ); + + if( p->xSFunc==0 ) continue; + if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0 + && showInternFuncs==0 + ){ + continue; + } + if( p->xValue!=0 ){ + zType = "w"; + }else if( p->xFinalize!=0 ){ + zType = "a"; + }else{ + zType = "s"; + } + tdsqlite3VdbeMultiLoad(v, 1, "sissii", + p->zName, isBuiltin, + zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK], + p->nArg, + (p->funcFlags & mask) ^ SQLITE_INNOCUOUS + ); + } +} + + +/* +** Helper subroutine for PRAGMA integrity_check: +** +** Generate code to output a single-column result row with a value of the +** string held in register 3. Decrement the result count in register 1 +** and halt if the maximum number of result rows have been issued. +*/ +static int integrityCheckResultRow(Vdbe *v){ + int addr; + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); + addr = tdsqlite3VdbeAddOp3(v, OP_IfPos, 1, tdsqlite3VdbeCurrentAddr(v)+2, 1); + VdbeCoverage(v); + tdsqlite3VdbeAddOp0(v, OP_Halt); + return addr; +} + +/* ** Process a pragma statement. ** ** Pragmas are of this form: @@ -114930,7 +128334,7 @@ SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){ ** and pId2 is the id. If the left side is just "id" then pId1 is the ** id and pId2 is any empty string. */ -SQLITE_PRIVATE void sqlite3Pragma( +SQLITE_PRIVATE void tdsqlite3Pragma( Parse *pParse, Token *pId1, /* First part of [schema.]id field */ Token *pId2, /* Second part of [schema.]id field, or NULL */ @@ -114943,46 +128347,40 @@ SQLITE_PRIVATE void sqlite3Pragma( Token *pId; /* Pointer to <id> token */ char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */ int iDb; /* Database index for <database> */ - int lwr, upr, mid = 0; /* Binary search bounds */ int rc; /* return value form SQLITE_FCNTL_PRAGMA */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ Db *pDb; /* The specific database being pragmaed */ - Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */ - const struct sPragmaNames *pPragma; -/* BEGIN SQLCIPHER */ -#ifdef SQLITE_HAS_CODEC - extern int sqlcipher_codec_pragma(sqlite3*, int, Parse *, const char *, const char *); -#endif -/* END SQLCIPHER */ + Vdbe *v = tdsqlite3GetVdbe(pParse); /* Prepared statement */ + const PragmaName *pPragma; /* The pragma */ if( v==0 ) return; - sqlite3VdbeRunOnlyOnce(v); + tdsqlite3VdbeRunOnlyOnce(v); pParse->nMem = 2; /* Interpret the [schema.] part of the pragma statement. iDb is the ** index of the database this pragma is being applied to in db.aDb[]. */ - iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); + iDb = tdsqlite3TwoPartName(pParse, pId1, pId2, &pId); if( iDb<0 ) return; pDb = &db->aDb[iDb]; /* If the temp database has been explicitly named as part of the ** pragma, make sure it is open. */ - if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ + if( iDb==1 && tdsqlite3OpenTempDatabase(pParse) ){ return; } - zLeft = sqlite3NameFromToken(db, pId); + zLeft = tdsqlite3NameFromToken(db, pId); if( !zLeft ) return; if( minusFlag ){ - zRight = sqlite3MPrintf(db, "-%T", pValue); + zRight = tdsqlite3MPrintf(db, "-%T", pValue); }else{ - zRight = sqlite3NameFromToken(db, pValue); + zRight = tdsqlite3NameFromToken(db, pValue); } assert( pId2 ); zDb = pId2->n>0 ? pDb->zDbSName : 0; - if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ + if( tdsqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ goto pragma_out; } @@ -114991,7 +128389,7 @@ SQLITE_PRIVATE void sqlite3Pragma( ** handled the pragma and generate a no-op prepared statement. ** ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed, - ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file + ** an SQLITE_FCNTL_PRAGMA file control is sent to the open tdsqlite3_file ** object corresponding to the database file to which the pragma ** statement refers. ** @@ -115006,16 +128404,18 @@ SQLITE_PRIVATE void sqlite3Pragma( aFcntl[2] = zRight; aFcntl[3] = 0; db->busyHandler.nBusy = 0; - rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); + rc = tdsqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); if( rc==SQLITE_OK ){ - returnSingleText(v, "result", aFcntl[0]); - sqlite3_free(aFcntl[0]); + tdsqlite3VdbeSetNumCols(v, 1); + tdsqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT); + returnSingleText(v, aFcntl[0]); + tdsqlite3_free(aFcntl[0]); goto pragma_out; } if( rc!=SQLITE_NOTFOUND ){ if( aFcntl[0] ){ - sqlite3ErrorMsg(pParse, "%s", aFcntl[0]); - sqlite3_free(aFcntl[0]); + tdsqlite3ErrorMsg(pParse, "%s", aFcntl[0]); + tdsqlite3_free(aFcntl[0]); } pParse->nErr++; pParse->rc = rc; @@ -115033,24 +128433,19 @@ SQLITE_PRIVATE void sqlite3Pragma( /* END SQLCIPHER */ /* Locate the pragma in the lookup table */ - lwr = 0; - upr = ArraySize(aPragmaNames)-1; - while( lwr<=upr ){ - mid = (lwr+upr)/2; - rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName); - if( rc==0 ) break; - if( rc<0 ){ - upr = mid - 1; - }else{ - lwr = mid + 1; - } - } - if( lwr>upr ) goto pragma_out; - pPragma = &aPragmaNames[mid]; + pPragma = pragmaLocate(zLeft); + if( pPragma==0 ) goto pragma_out; /* Make sure the database schema is loaded if the pragma requires that */ - if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){ - if( sqlite3ReadSchema(pParse) ) goto pragma_out; + if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){ + if( tdsqlite3ReadSchema(pParse) ) goto pragma_out; + } + + /* Register the result column names for pragmas that return results */ + if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 + && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0) + ){ + setPragmaResultColumnNames(v, pPragma); } /* Jump to the appropriate pragma handler */ @@ -115087,23 +128482,22 @@ SQLITE_PRIVATE void sqlite3Pragma( { OP_ResultRow, 1, 1, 0}, }; VdbeOp *aOp; - sqlite3VdbeUsesBtree(v, iDb); + tdsqlite3VdbeUsesBtree(v, iDb); if( !zRight ){ - setOneColumnName(v, "cache_size"); pParse->nMem += 2; - sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize)); - aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn); + tdsqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize)); + aOp = tdsqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE; }else{ - int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + int size = tdsqlite3AbsInt32(tdsqlite3Atoi(zRight)); + tdsqlite3BeginWriteOperation(pParse, 0, iDb); + tdsqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); pDb->pSchema->cache_size = size; - sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); + tdsqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } @@ -115123,15 +128517,15 @@ SQLITE_PRIVATE void sqlite3Pragma( Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ - int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; - returnSingleInt(v, "page_size", size); + int size = ALWAYS(pBt) ? tdsqlite3BtreeGetPageSize(pBt) : 0; + returnSingleInt(v, size); }else{ /* Malloc may fail when setting the page-size, as there is an internal - ** buffer that the pager module resizes using sqlite3_realloc(). + ** buffer that the pager module resizes using tdsqlite3_realloc(). */ - db->nextPagesize = sqlite3Atoi(zRight); - if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ - sqlite3OomFault(db); + db->nextPagesize = tdsqlite3Atoi(zRight); + if( SQLITE_NOMEM==tdsqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ + tdsqlite3OomFault(db); } } break; @@ -115139,27 +128533,31 @@ SQLITE_PRIVATE void sqlite3Pragma( /* ** PRAGMA [schema.]secure_delete - ** PRAGMA [schema.]secure_delete=ON/OFF + ** PRAGMA [schema.]secure_delete=ON/OFF/FAST ** ** The first form reports the current setting for the ** secure_delete flag. The second form changes the secure_delete - ** flag setting and reports thenew value. + ** flag setting and reports the new value. */ case PragTyp_SECURE_DELETE: { Btree *pBt = pDb->pBt; int b = -1; assert( pBt!=0 ); if( zRight ){ - b = sqlite3GetBoolean(zRight, 0); + if( tdsqlite3_stricmp(zRight, "fast")==0 ){ + b = 2; + }else{ + b = tdsqlite3GetBoolean(zRight, 0); + } } if( pId2->n==0 && b>=0 ){ int ii; for(ii=0; ii<db->nDb; ii++){ - sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); + tdsqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); } } - b = sqlite3BtreeSecureDelete(pBt, b); - returnSingleInt(v, "secure_delete", b); + b = tdsqlite3BtreeSecureDelete(pBt, b); + returnSingleInt(v, b); break; } @@ -115174,7 +128572,7 @@ SQLITE_PRIVATE void sqlite3Pragma( ** ** The absolute value of N is used. This is undocumented and might ** change. The only purpose is to provide an easy way to test - ** the sqlite3AbsInt32() function. + ** the tdsqlite3AbsInt32() function. ** ** PRAGMA [schema.]page_count ** @@ -115182,17 +128580,15 @@ SQLITE_PRIVATE void sqlite3Pragma( */ case PragTyp_PAGE_COUNT: { int iReg; - sqlite3CodeVerifySchema(pParse, iDb); + tdsqlite3CodeVerifySchema(pParse, iDb); iReg = ++pParse->nMem; - if( sqlite3Tolower(zLeft[0])=='p' ){ - sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); + if( tdsqlite3Tolower(zLeft[0])=='p' ){ + tdsqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); }else{ - sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, - sqlite3AbsInt32(sqlite3Atoi(zRight))); + tdsqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, + tdsqlite3AbsInt32(tdsqlite3Atoi(zRight))); } - sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); break; } @@ -115224,13 +128620,13 @@ SQLITE_PRIVATE void sqlite3Pragma( int ii; assert(pDb==&db->aDb[0]); for(ii=2; ii<db->nDb; ii++){ - pPager = sqlite3BtreePager(db->aDb[ii].pBt); - sqlite3PagerLockingMode(pPager, eMode); + pPager = tdsqlite3BtreePager(db->aDb[ii].pBt); + tdsqlite3PagerLockingMode(pPager, eMode); } db->dfltLockMode = (u8)eMode; } - pPager = sqlite3BtreePager(pDb->pBt); - eMode = sqlite3PagerLockingMode(pPager, eMode); + pPager = tdsqlite3BtreePager(pDb->pBt); + eMode = tdsqlite3PagerLockingMode(pPager, eMode); } assert( eMode==PAGER_LOCKINGMODE_NORMAL @@ -115238,7 +128634,7 @@ SQLITE_PRIVATE void sqlite3Pragma( if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ zRet = "exclusive"; } - returnSingleText(v, "locking_mode", zRet); + returnSingleText(v, zRet); break; } @@ -115251,22 +128647,26 @@ SQLITE_PRIVATE void sqlite3Pragma( int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */ int ii; /* Loop counter */ - setOneColumnName(v, "journal_mode"); if( zRight==0 ){ /* If there is no "=MODE" part of the pragma, do a query for the ** current mode */ eMode = PAGER_JOURNALMODE_QUERY; }else{ const char *zMode; - int n = sqlite3Strlen30(zRight); - for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ - if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; + int n = tdsqlite3Strlen30(zRight); + for(eMode=0; (zMode = tdsqlite3JournalModename(eMode))!=0; eMode++){ + if( tdsqlite3StrNICmp(zRight, zMode, n)==0 ) break; } if( !zMode ){ /* If the "=MODE" part does not match any known journal mode, ** then do a query */ eMode = PAGER_JOURNALMODE_QUERY; } + if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){ + /* Do not allow journal-mode "OFF" in defensive since the database + ** can become corrupted using ordinary SQL when the journal is off */ + eMode = PAGER_JOURNALMODE_QUERY; + } } if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */ @@ -115275,11 +128675,11 @@ SQLITE_PRIVATE void sqlite3Pragma( } for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ - sqlite3VdbeUsesBtree(v, ii); - sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); + tdsqlite3VdbeUsesBtree(v, ii); + tdsqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); } } - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); break; } @@ -115290,14 +128690,14 @@ SQLITE_PRIVATE void sqlite3Pragma( ** Get or set the size limit on rollback journal files. */ case PragTyp_JOURNAL_SIZE_LIMIT: { - Pager *pPager = sqlite3BtreePager(pDb->pBt); + Pager *pPager = tdsqlite3BtreePager(pDb->pBt); i64 iLimit = -2; if( zRight ){ - sqlite3DecOrHexToI64(zRight, &iLimit); + tdsqlite3DecOrHexToI64(zRight, &iLimit); if( iLimit<-1 ) iLimit = -1; } - iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); - returnSingleInt(v, "journal_size_limit", iLimit); + iLimit = tdsqlite3PagerJournalSizeLimit(pPager, iLimit); + returnSingleInt(v, iLimit); break; } @@ -115315,7 +128715,7 @@ SQLITE_PRIVATE void sqlite3Pragma( Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ - returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt)); + returnSingleInt(v, tdsqlite3BtreeGetAutoVacuum(pBt)); }else{ int eAuto = getAutoVacuum(zRight); assert( eAuto>=0 && eAuto<=2 ); @@ -115325,7 +128725,7 @@ SQLITE_PRIVATE void sqlite3Pragma( ** creates the database file. It is important that it is created ** as an auto-vacuum capable db. */ - rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); + rc = tdsqlite3BtreeSetAutoVacuum(pBt, eAuto); if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ /* When setting the auto_vacuum mode to either "full" or ** "incremental", write the value of meta[6] in the database @@ -115341,16 +128741,16 @@ SQLITE_PRIVATE void sqlite3Pragma( { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */ }; VdbeOp *aOp; - int iAddr = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6)); - aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn); + int iAddr = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6)); + aOp = tdsqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[2].p2 = iAddr+4; aOp[4].p1 = iDb; aOp[4].p3 = eAuto - 1; - sqlite3VdbeUsesBtree(v, iDb); + tdsqlite3VdbeUsesBtree(v, iDb); } } break; @@ -115365,16 +128765,16 @@ SQLITE_PRIVATE void sqlite3Pragma( #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_INCREMENTAL_VACUUM: { int iLimit, addr; - if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ + if( zRight==0 || !tdsqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ iLimit = 0x7fffffff; } - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); - addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v); - sqlite3VdbeAddOp1(v, OP_ResultRow, 1); - sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); - sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr); + tdsqlite3BeginWriteOperation(pParse, 0, iDb); + tdsqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); + addr = tdsqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v); + tdsqlite3VdbeAddOp1(v, OP_ResultRow, 1); + tdsqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); + tdsqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addr); break; } #endif @@ -115392,13 +128792,13 @@ SQLITE_PRIVATE void sqlite3Pragma( ** of memory. */ case PragTyp_CACHE_SIZE: { - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ - returnSingleInt(v, "cache_size", pDb->pSchema->cache_size); + returnSingleInt(v, pDb->pSchema->cache_size); }else{ - int size = sqlite3Atoi(zRight); + int size = tdsqlite3Atoi(zRight); pDb->pSchema->cache_size = size; - sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); + tdsqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } @@ -115426,20 +128826,20 @@ SQLITE_PRIVATE void sqlite3Pragma( ** not just the schema specified. */ case PragTyp_CACHE_SPILL: { - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ - returnSingleInt(v, "cache_spill", + returnSingleInt(v, (db->flags & SQLITE_CacheSpill)==0 ? 0 : - sqlite3BtreeSetSpillSize(pDb->pBt,0)); + tdsqlite3BtreeSetSpillSize(pDb->pBt,0)); }else{ int size = 1; - if( sqlite3GetInt32(zRight, &size) ){ - sqlite3BtreeSetSpillSize(pDb->pBt, size); + if( tdsqlite3GetInt32(zRight, &size) ){ + tdsqlite3BtreeSetSpillSize(pDb->pBt, size); } - if( sqlite3GetBoolean(zRight, size!=0) ){ + if( tdsqlite3GetBoolean(zRight, size!=0) ){ db->flags |= SQLITE_CacheSpill; }else{ - db->flags &= ~SQLITE_CacheSpill; + db->flags &= ~(u64)SQLITE_CacheSpill; } setAllPagerFlags(db); } @@ -115453,7 +128853,7 @@ SQLITE_PRIVATE void sqlite3Pragma( ** used to limit the aggregate size of all memory mapped regions of the ** database file. If this parameter is set to zero, then memory mapping ** is not used at all. If N is negative, then the default memory map - ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. + ** limit determined by tdsqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. ** The parameter N is measured in bytes. ** ** This value is advisory. The underlying VFS is free to memory map @@ -115461,28 +128861,28 @@ SQLITE_PRIVATE void sqlite3Pragma( ** upper layers will never invoke the xFetch interfaces to the VFS. */ case PragTyp_MMAP_SIZE: { - sqlite3_int64 sz; + tdsqlite3_int64 sz; #if SQLITE_MAX_MMAP_SIZE>0 - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); if( zRight ){ int ii; - sqlite3DecOrHexToI64(zRight, &sz); - if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; + tdsqlite3DecOrHexToI64(zRight, &sz); + if( sz<0 ) sz = tdsqlite3GlobalConfig.szMmap; if( pId2->n==0 ) db->szMmap = sz; for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ - sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); + tdsqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); } } } sz = -1; - rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); + rc = tdsqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); #else sz = 0; rc = SQLITE_OK; #endif if( rc==SQLITE_OK ){ - returnSingleInt(v, "mmap_size", sz); + returnSingleInt(v, sz); }else if( rc!=SQLITE_NOTFOUND ){ pParse->nErr++; pParse->rc = rc; @@ -115503,7 +128903,7 @@ SQLITE_PRIVATE void sqlite3Pragma( */ case PragTyp_TEMP_STORE: { if( !zRight ){ - returnSingleInt(v, "temp_store", db->temp_store); + returnSingleInt(v, db->temp_store); }else{ changeTempStorage(pParse, zRight); } @@ -115522,14 +128922,14 @@ SQLITE_PRIVATE void sqlite3Pragma( */ case PragTyp_TEMP_STORE_DIRECTORY: { if( !zRight ){ - returnSingleText(v, "temp_store_directory", sqlite3_temp_directory); + returnSingleText(v, tdsqlite3_temp_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; - rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); + rc = tdsqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ - sqlite3ErrorMsg(pParse, "not a writable directory"); + tdsqlite3ErrorMsg(pParse, "not a writable directory"); goto pragma_out; } } @@ -115539,11 +128939,11 @@ SQLITE_PRIVATE void sqlite3Pragma( ){ invalidateTempStorage(pParse); } - sqlite3_free(sqlite3_temp_directory); + tdsqlite3_free(tdsqlite3_temp_directory); if( zRight[0] ){ - sqlite3_temp_directory = sqlite3_mprintf("%s", zRight); + tdsqlite3_temp_directory = tdsqlite3_mprintf("%s", zRight); }else{ - sqlite3_temp_directory = 0; + tdsqlite3_temp_directory = 0; } #endif /* SQLITE_OMIT_WSD */ } @@ -115566,22 +128966,22 @@ SQLITE_PRIVATE void sqlite3Pragma( */ case PragTyp_DATA_STORE_DIRECTORY: { if( !zRight ){ - returnSingleText(v, "data_store_directory", sqlite3_data_directory); + returnSingleText(v, tdsqlite3_data_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; - rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); + rc = tdsqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ - sqlite3ErrorMsg(pParse, "not a writable directory"); + tdsqlite3ErrorMsg(pParse, "not a writable directory"); goto pragma_out; } } - sqlite3_free(sqlite3_data_directory); + tdsqlite3_free(tdsqlite3_data_directory); if( zRight[0] ){ - sqlite3_data_directory = sqlite3_mprintf("%s", zRight); + tdsqlite3_data_directory = tdsqlite3_mprintf("%s", zRight); }else{ - sqlite3_data_directory = 0; + tdsqlite3_data_directory = 0; } #endif /* SQLITE_OMIT_WSD */ } @@ -115600,25 +129000,25 @@ SQLITE_PRIVATE void sqlite3Pragma( */ case PragTyp_LOCK_PROXY_FILE: { if( !zRight ){ - Pager *pPager = sqlite3BtreePager(pDb->pBt); + Pager *pPager = tdsqlite3BtreePager(pDb->pBt); char *proxy_file_path = NULL; - sqlite3_file *pFile = sqlite3PagerFile(pPager); - sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, + tdsqlite3_file *pFile = tdsqlite3PagerFile(pPager); + tdsqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, &proxy_file_path); - returnSingleText(v, "lock_proxy_file", proxy_file_path); + returnSingleText(v, proxy_file_path); }else{ - Pager *pPager = sqlite3BtreePager(pDb->pBt); - sqlite3_file *pFile = sqlite3PagerFile(pPager); + Pager *pPager = tdsqlite3BtreePager(pDb->pBt); + tdsqlite3_file *pFile = tdsqlite3PagerFile(pPager); int res; if( zRight[0] ){ - res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, + res=tdsqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, zRight); } else { - res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, + res=tdsqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, NULL); } if( res!=SQLITE_OK ){ - sqlite3ErrorMsg(pParse, "failed to set lock proxy file"); + tdsqlite3ErrorMsg(pParse, "failed to set lock proxy file"); goto pragma_out; } } @@ -115637,12 +129037,12 @@ SQLITE_PRIVATE void sqlite3Pragma( */ case PragTyp_SYNCHRONOUS: { if( !zRight ){ - returnSingleInt(v, "synchronous", pDb->safety_level-1); + returnSingleInt(v, pDb->safety_level-1); }else{ if( !db->autoCommit ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "Safety level may not be changed inside a transaction"); - }else{ + }else if( iDb!=1 ){ int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK; if( iLevel==0 ) iLevel = 1; pDb->safety_level = iLevel; @@ -115657,9 +129057,10 @@ SQLITE_PRIVATE void sqlite3Pragma( #ifndef SQLITE_OMIT_FLAG_PRAGMAS case PragTyp_FLAG: { if( zRight==0 ){ - returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 ); + setPragmaResultColumnNames(v, pPragma); + returnSingleInt(v, (db->flags & pPragma->iArg)!=0 ); }else{ - int mask = pPragma->iArg; /* Mask of bits to set or clear. */ + u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */ if( db->autoCommit==0 ){ /* Foreign key support may not be enabled or disabled while not ** in auto-commit mode. */ @@ -115672,7 +129073,7 @@ SQLITE_PRIVATE void sqlite3Pragma( } #endif - if( sqlite3GetBoolean(zRight, 0) ){ + if( tdsqlite3GetBoolean(zRight, 0) ){ db->flags |= mask; }else{ db->flags &= ~mask; @@ -115683,7 +129084,7 @@ SQLITE_PRIVATE void sqlite3Pragma( ** compiler (eg. count_changes). So add an opcode to expire all ** compiled SQL statements after modifying a pragma value. */ - sqlite3VdbeAddOp0(v, OP_Expire); + tdsqlite3VdbeAddOp0(v, OP_Expire); setAllPagerFlags(db); } break; @@ -115702,26 +129103,34 @@ SQLITE_PRIVATE void sqlite3Pragma( ** type: Column declaration type. ** notnull: True if 'NOT NULL' is part of column declaration ** dflt_value: The default value for the column, if any. + ** pk: Non-zero for PK fields. */ case PragTyp_TABLE_INFO: if( zRight ){ Table *pTab; - pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); + pTab = tdsqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); if( pTab ){ - static const char *azCol[] = { - "cid", "name", "type", "notnull", "dflt_value", "pk" - }; + int iTabDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); int i, k; int nHidden = 0; Column *pCol; - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - pParse->nMem = 6; - sqlite3CodeVerifySchema(pParse, iDb); - setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) ); - sqlite3ViewGetColumnNames(pParse, pTab); + Index *pPk = tdsqlite3PrimaryKeyIndex(pTab); + pParse->nMem = 7; + tdsqlite3CodeVerifySchema(pParse, iTabDb); + tdsqlite3ViewGetColumnNames(pParse, pTab); for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ - if( IsHiddenColumn(pCol) ){ - nHidden++; - continue; + int isHidden = 0; + if( pCol->colFlags & COLFLAG_NOINSERT ){ + if( pPragma->iArg==0 ){ + nHidden++; + continue; + } + if( pCol->colFlags & COLFLAG_VIRTUAL ){ + isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */ + }else if( pCol->colFlags & COLFLAG_STORED ){ + isHidden = 3; /* GENERATED ALWAYS AS ... STORED */ + }else{ assert( pCol->colFlags & COLFLAG_HIDDEN ); + isHidden = 1; /* HIDDEN */ + } } if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ k = 0; @@ -115730,55 +129139,62 @@ SQLITE_PRIVATE void sqlite3Pragma( }else{ for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){} } - assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN ); - sqlite3VdbeMultiLoad(v, 1, "issisi", + assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 ); + tdsqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi", i-nHidden, pCol->zName, - sqlite3ColumnType(pCol,""), + tdsqlite3ColumnType(pCol,""), pCol->notNull ? 1 : 0, - pCol->pDflt ? pCol->pDflt->u.zToken : 0, - k); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6); + pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0, + k, + isHidden); } } } break; +#ifdef SQLITE_DEBUG case PragTyp_STATS: { - static const char *azCol[] = { "table", "index", "width", "height" }; Index *pIdx; HashElem *i; - v = sqlite3GetVdbe(pParse); - pParse->nMem = 4; - sqlite3CodeVerifySchema(pParse, iDb); - setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) ); + pParse->nMem = 5; + tdsqlite3CodeVerifySchema(pParse, iDb); for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ Table *pTab = sqliteHashData(i); - sqlite3VdbeMultiLoad(v, 1, "ssii", + tdsqlite3VdbeMultiLoad(v, 1, "ssiii", pTab->zName, 0, pTab->szTabRow, - pTab->nRowLogEst); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); + pTab->nRowLogEst, + pTab->tabFlags); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - sqlite3VdbeMultiLoad(v, 2, "sii", + tdsqlite3VdbeMultiLoad(v, 2, "siiiX", pIdx->zName, pIdx->szIdxRow, - pIdx->aiRowLogEst[0]); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4); + pIdx->aiRowLogEst[0], + pIdx->hasStat1); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); } } } break; +#endif case PragTyp_INDEX_INFO: if( zRight ){ Index *pIdx; Table *pTab; - pIdx = sqlite3FindIndex(db, zRight, zDb); + pIdx = tdsqlite3FindIndex(db, zRight, zDb); + if( pIdx==0 ){ + /* If there is no index named zRight, check to see if there is a + ** WITHOUT ROWID table named zRight, and if there is, show the + ** structure of the PRIMARY KEY index for that table. */ + pTab = tdsqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); + if( pTab && !HasRowid(pTab) ){ + pIdx = tdsqlite3PrimaryKeyIndex(pTab); + } + } if( pIdx ){ - static const char *azCol[] = { - "seqno", "cid", "name", "desc", "coll", "key" - }; + int iIdxDb = tdsqlite3SchemaToIndex(db, pIdx->pSchema); int i; int mx; if( pPragma->iArg ){ @@ -115791,20 +129207,19 @@ SQLITE_PRIVATE void sqlite3Pragma( pParse->nMem = 3; } pTab = pIdx->pTable; - sqlite3CodeVerifySchema(pParse, iDb); - assert( pParse->nMem<=ArraySize(azCol) ); - setAllColumnNames(v, pParse->nMem, azCol); + tdsqlite3CodeVerifySchema(pParse, iIdxDb); + assert( pParse->nMem<=pPragma->nPragCName ); for(i=0; i<mx; i++){ i16 cnum = pIdx->aiColumn[i]; - sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum, + tdsqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum, cnum<0 ? 0 : pTab->aCol[cnum].zName); if( pPragma->iArg ){ - sqlite3VdbeMultiLoad(v, 4, "isi", + tdsqlite3VdbeMultiLoad(v, 4, "isiX", pIdx->aSortOrder[i], pIdx->azColl[i], i<pIdx->nKeyCol); } - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem); } } } @@ -115814,82 +129229,107 @@ SQLITE_PRIVATE void sqlite3Pragma( Index *pIdx; Table *pTab; int i; - pTab = sqlite3FindTable(db, zRight, zDb); + pTab = tdsqlite3FindTable(db, zRight, zDb); if( pTab ){ - static const char *azCol[] = { - "seq", "name", "unique", "origin", "partial" - }; - v = sqlite3GetVdbe(pParse); + int iTabDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); pParse->nMem = 5; - sqlite3CodeVerifySchema(pParse, iDb); - setAllColumnNames(v, 5, azCol); assert( 5==ArraySize(azCol) ); + tdsqlite3CodeVerifySchema(pParse, iTabDb); for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ const char *azOrigin[] = { "c", "u", "pk" }; - sqlite3VdbeMultiLoad(v, 1, "isisi", + tdsqlite3VdbeMultiLoad(v, 1, "isisi", i, pIdx->zName, IsUniqueIndex(pIdx), azOrigin[pIdx->idxType], pIdx->pPartIdxWhere!=0); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); } } } break; case PragTyp_DATABASE_LIST: { - static const char *azCol[] = { "seq", "name", "file" }; int i; pParse->nMem = 3; - setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) ); for(i=0; i<db->nDb; i++){ if( db->aDb[i].pBt==0 ) continue; assert( db->aDb[i].zDbSName!=0 ); - sqlite3VdbeMultiLoad(v, 1, "iss", + tdsqlite3VdbeMultiLoad(v, 1, "iss", i, db->aDb[i].zDbSName, - sqlite3BtreeGetFilename(db->aDb[i].pBt)); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + tdsqlite3BtreeGetFilename(db->aDb[i].pBt)); } } break; case PragTyp_COLLATION_LIST: { - static const char *azCol[] = { "seq", "name" }; int i = 0; HashElem *p; pParse->nMem = 2; - setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) ); for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ CollSeq *pColl = (CollSeq *)sqliteHashData(p); - sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); + tdsqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName); } } break; + +#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS + case PragTyp_FUNCTION_LIST: { + int i; + HashElem *j; + FuncDef *p; + int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0; + pParse->nMem = 6; + for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){ + for(p=tdsqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){ + pragmaFunclistLine(v, p, 1, showInternFunc); + } + } + for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){ + p = (FuncDef*)sqliteHashData(j); + pragmaFunclistLine(v, p, 0, showInternFunc); + } + } + break; + +#ifndef SQLITE_OMIT_VIRTUALTABLE + case PragTyp_MODULE_LIST: { + HashElem *j; + pParse->nMem = 1; + for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){ + Module *pMod = (Module*)sqliteHashData(j); + tdsqlite3VdbeMultiLoad(v, 1, "s", pMod->zName); + } + } + break; +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + + case PragTyp_PRAGMA_LIST: { + int i; + for(i=0; i<ArraySize(aPragmaName); i++){ + tdsqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName); + } + } + break; +#endif /* SQLITE_INTROSPECTION_PRAGMAS */ + #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */ #ifndef SQLITE_OMIT_FOREIGN_KEY case PragTyp_FOREIGN_KEY_LIST: if( zRight ){ FKey *pFK; Table *pTab; - pTab = sqlite3FindTable(db, zRight, zDb); + pTab = tdsqlite3FindTable(db, zRight, zDb); if( pTab ){ - v = sqlite3GetVdbe(pParse); pFK = pTab->pFKey; if( pFK ){ - static const char *azCol[] = { - "id", "seq", "table", "from", "to", "on_update", "on_delete", - "match" - }; + int iTabDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); int i = 0; pParse->nMem = 8; - sqlite3CodeVerifySchema(pParse, iDb); - setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) ); + tdsqlite3CodeVerifySchema(pParse, iTabDb); while(pFK){ int j; for(j=0; j<pFK->nCol; j++){ - sqlite3VdbeMultiLoad(v, 1, "iissssss", + tdsqlite3VdbeMultiLoad(v, 1, "iissssss", i, j, pFK->zTo, @@ -115898,7 +129338,6 @@ SQLITE_PRIVATE void sqlite3Pragma( actionName(pFK->aAction[1]), /* ON UPDATE */ actionName(pFK->aAction[0]), /* ON DELETE */ "NONE"); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8); } ++i; pFK = pFK->pNextFrom; @@ -115926,41 +129365,40 @@ SQLITE_PRIVATE void sqlite3Pragma( int addrTop; /* Top of a loop checking foreign keys */ int addrOk; /* Jump here if the key is OK */ int *aiCols; /* child to parent column mapping */ - static const char *azCol[] = { "table", "rowid", "parent", "fkid" }; regResult = pParse->nMem+1; pParse->nMem += 4; regKey = ++pParse->nMem; regRow = ++pParse->nMem; - v = sqlite3GetVdbe(pParse); - setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) ); - sqlite3CodeVerifySchema(pParse, iDb); k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); while( k ){ + int iTabDb; if( zRight ){ - pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); + pTab = tdsqlite3LocateTable(pParse, 0, zRight, zDb); k = 0; }else{ pTab = (Table*)sqliteHashData(k); k = sqliteHashNext(k); } if( pTab==0 || pTab->pFKey==0 ) continue; - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + iTabDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); + tdsqlite3CodeVerifySchema(pParse, iTabDb); + tdsqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName); if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; - sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead); - sqlite3VdbeLoadString(v, regResult, pTab->zName); + tdsqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead); + tdsqlite3VdbeLoadString(v, regResult, pTab->zName); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ - pParent = sqlite3FindTable(db, pFK->zTo, zDb); + pParent = tdsqlite3FindTable(db, pFK->zTo, zDb); if( pParent==0 ) continue; pIdx = 0; - sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName); - x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); + tdsqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName); + x = tdsqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); if( x==0 ){ if( pIdx==0 ){ - sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead); + tdsqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead); }else{ - sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); + tdsqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb); + tdsqlite3VdbeSetP4KeyInfo(pParse, pIdx); } }else{ k = 0; @@ -115970,92 +129408,93 @@ SQLITE_PRIVATE void sqlite3Pragma( assert( pParse->nErr>0 || pFK==0 ); if( pFK ) break; if( pParse->nTab<i ) pParse->nTab = i; - addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v); + addrTop = tdsqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ - pParent = sqlite3FindTable(db, pFK->zTo, zDb); + pParent = tdsqlite3FindTable(db, pFK->zTo, zDb); pIdx = 0; aiCols = 0; if( pParent ){ - x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); + x = tdsqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); assert( x==0 ); } - addrOk = sqlite3VdbeMakeLabel(v); - if( pParent && pIdx==0 ){ - int iKey = pFK->aCol[0].iFrom; - assert( iKey>=0 && iKey<pTab->nCol ); - if( iKey!=pTab->iPKey ){ - sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow); - sqlite3ColumnDefault(v, pTab, iKey, regRow); - sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v); - }else{ - sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow); - } - sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v); - sqlite3VdbeGoto(v, addrOk); - sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); + addrOk = tdsqlite3VdbeMakeLabel(pParse); + + /* Generate code to read the child key values into registers + ** regRow..regRow+n. If any of the child key values are NULL, this + ** row cannot cause an FK violation. Jump directly to addrOk in + ** this case. */ + for(j=0; j<pFK->nCol; j++){ + int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom; + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j); + tdsqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v); + } + + /* Generate code to query the parent index for a matching parent + ** key. If a match is found, jump to addrOk. */ + if( pIdx ){ + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey, + tdsqlite3IndexAffinityStr(db,pIdx), pFK->nCol); + tdsqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); + VdbeCoverage(v); + }else if( pParent ){ + int jmp = tdsqlite3VdbeCurrentAddr(v)+2; + tdsqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v); + tdsqlite3VdbeGoto(v, addrOk); + assert( pFK->nCol==1 ); + } + + /* Generate code to report an FK violation to the caller. */ + if( HasRowid(pTab) ){ + tdsqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); }else{ - for(j=0; j<pFK->nCol; j++){ - sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, - aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j); - sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v); - } - if( pParent ){ - sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey, - sqlite3IndexAffinityStr(db,pIdx), pFK->nCol); - sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); - VdbeCoverage(v); - } + tdsqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1); } - sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); - sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1); - sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); - sqlite3VdbeResolveLabel(v, addrOk); - sqlite3DbFree(db, aiCols); + tdsqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); + tdsqlite3VdbeResolveLabel(v, addrOk); + tdsqlite3DbFree(db, aiCols); } - sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addrTop); + tdsqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addrTop); } } break; #endif /* !defined(SQLITE_OMIT_TRIGGER) */ #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ -#ifndef NDEBUG - case PragTyp_PARSER_TRACE: { - if( zRight ){ - if( sqlite3GetBoolean(zRight, 0) ){ - sqlite3ParserTrace(stdout, "parser: "); - }else{ - sqlite3ParserTrace(0, 0); - } - } - } - break; -#endif - +#ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA /* Reinstall the LIKE and GLOB functions. The variant of LIKE ** used will be case sensitive or not depending on the RHS. */ case PragTyp_CASE_SENSITIVE_LIKE: { if( zRight ){ - sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); + tdsqlite3RegisterLikeFunctions(db, tdsqlite3GetBoolean(zRight, 0)); } } break; +#endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */ #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 #endif #ifndef SQLITE_OMIT_INTEGRITY_CHECK - /* Pragma "quick_check" is reduced version of + /* PRAGMA integrity_check + ** PRAGMA integrity_check(N) + ** PRAGMA quick_check + ** PRAGMA quick_check(N) + ** + ** Verify the integrity of the database. + ** + ** The "quick_check" is reduced version of ** integrity_check designed to detect most database corruption - ** without most of the overhead of a full integrity-check. + ** without the overhead of cross-checking indexes. Quick_check + ** is linear time wherease integrity_check is O(NlogN). */ case PragTyp_INTEGRITY_CHECK: { int i, j, addr, mxErr; - int isQuick = (sqlite3Tolower(zLeft[0])=='q'); + int isQuick = (tdsqlite3Tolower(zLeft[0])=='q'); /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check", ** then iDb is set to the index of the database identified by <db>. @@ -116072,80 +129511,75 @@ SQLITE_PRIVATE void sqlite3Pragma( /* Initialize the VDBE program */ pParse->nMem = 6; - setOneColumnName(v, "integrity_check"); /* Set the maximum error count */ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; if( zRight ){ - sqlite3GetInt32(zRight, &mxErr); + tdsqlite3GetInt32(zRight, &mxErr); if( mxErr<=0 ){ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; } } - sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */ + tdsqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */ /* Do an integrity check on each database file */ for(i=0; i<db->nDb; i++){ - HashElem *x; - Hash *pTbls; - int *aRoot; - int cnt = 0; - int mxIdx = 0; - int nIdx; + HashElem *x; /* For looping over tables in the schema */ + Hash *pTbls; /* Set of all tables in the schema */ + int *aRoot; /* Array of root page numbers of all btrees */ + int cnt = 0; /* Number of entries in aRoot[] */ + int mxIdx = 0; /* Maximum number of indexes for any table */ if( OMIT_TEMPDB && i==1 ) continue; if( iDb>=0 && i!=iDb ) continue; - sqlite3CodeVerifySchema(pParse, i); - addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */ - VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); - sqlite3VdbeJumpHere(v, addr); + tdsqlite3CodeVerifySchema(pParse, i); /* Do an integrity check of the B-Tree ** ** Begin by finding the root pages numbers ** for all tables and indices in the database. */ - assert( sqlite3SchemaMutexHeld(db, i, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, i, 0) ); pTbls = &db->aDb[i].pSchema->tblHash; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ - Table *pTab = sqliteHashData(x); - Index *pIdx; + Table *pTab = sqliteHashData(x); /* Current table */ + Index *pIdx; /* An index on pTab */ + int nIdx; /* Number of indexes on pTab */ if( HasRowid(pTab) ) cnt++; for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } if( nIdx>mxIdx ) mxIdx = nIdx; } - aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); + aRoot = tdsqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); if( aRoot==0 ) break; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; - if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum; + if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - aRoot[cnt++] = pIdx->tnum; + aRoot[++cnt] = pIdx->tnum; } } - aRoot[cnt] = 0; + aRoot[0] = cnt; /* Make sure sufficient number of registers have been allocated */ pParse->nMem = MAX( pParse->nMem, 8+mxIdx ); + tdsqlite3ClearTempRegCache(pParse); /* Do the b-tree integrity checks */ - sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY); - sqlite3VdbeChangeP5(v, (u8)i); - addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, - sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName), + tdsqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY); + tdsqlite3VdbeChangeP5(v, (u8)i); + addr = tdsqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + tdsqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName), P4_DYNAMIC); - sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1); - sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2); - sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1); - sqlite3VdbeJumpHere(v, addr); + tdsqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3); + integrityCheckResultRow(v); + tdsqlite3VdbeJumpHere(v, addr); /* Make sure all the indices are constructed correctly. */ - for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){ + for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx, *pPk; Index *pPrior = 0; @@ -116153,108 +129587,130 @@ SQLITE_PRIVATE void sqlite3Pragma( int iDataCur, iIdxCur; int r1 = -1; - if( pTab->pIndex==0 ) continue; - pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); - addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */ - VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); - sqlite3VdbeJumpHere(v, addr); - sqlite3ExprCacheClear(pParse); - sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0, + if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */ + pPk = HasRowid(pTab) ? 0 : tdsqlite3PrimaryKeyIndex(pTab); + tdsqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0, 1, 0, &iDataCur, &iIdxCur); - sqlite3VdbeAddOp2(v, OP_Integer, 0, 7); + /* reg[7] counts the number of entries in the table. + ** reg[8+i] counts the number of entries in the i-th index + */ + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, 7); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */ + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */ } assert( pParse->nMem>=8+j ); - assert( sqlite3NoTempsInRange(pParse,1,7+j) ); - sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v); - loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); + assert( tdsqlite3NoTempsInRange(pParse,1,7+j) ); + tdsqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v); + loopTop = tdsqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); + if( !isQuick ){ + /* Sanity check on record header decoding */ + tdsqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3); + tdsqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); + } /* Verify that all NOT NULL columns really are NOT NULL */ for(j=0; j<pTab->nCol; j++){ char *zErr; - int jmp2, jmp3; + int jmp2; if( j==pTab->iPKey ) continue; if( pTab->aCol[j].notNull==0 ) continue; - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3); - sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); - jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ - zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName, + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3); + if( tdsqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){ + tdsqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); + } + jmp2 = tdsqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v); + zErr = tdsqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName, pTab->aCol[j].zName); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); - sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); - jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v); - sqlite3VdbeAddOp0(v, OP_Halt); - sqlite3VdbeJumpHere(v, jmp2); - sqlite3VdbeJumpHere(v, jmp3); - } - /* Validate index entries for the current row */ - for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - int jmp2, jmp3, jmp4, jmp5; - int ckUniq = sqlite3VdbeMakeLabel(v); - if( pPk==pIdx ) continue; - r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3, - pPrior, r1); - pPrior = pIdx; - sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */ - /* Verify that an index entry exists for the current table row */ - jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, - pIdx->nColumn); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ - sqlite3VdbeLoadString(v, 3, "row "); - sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); - sqlite3VdbeLoadString(v, 4, " missing from index "); - sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); - jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName); - sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); - sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); - jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v); - sqlite3VdbeAddOp0(v, OP_Halt); - sqlite3VdbeJumpHere(v, jmp2); - /* For UNIQUE indexes, verify that only one entry exists with the - ** current key. The entry is unique if (1) any column is NULL - ** or (2) the next entry has a different key */ - if( IsUniqueIndex(pIdx) ){ - int uniqOk = sqlite3VdbeMakeLabel(v); - int jmp6; - int kk; - for(kk=0; kk<pIdx->nKeyCol; kk++){ - int iCol = pIdx->aiColumn[kk]; - assert( iCol!=XN_ROWID && iCol<pTab->nCol ); - if( iCol>=0 && pTab->aCol[iCol].notNull ) continue; - sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk); - VdbeCoverage(v); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); + integrityCheckResultRow(v); + tdsqlite3VdbeJumpHere(v, jmp2); + } + /* Verify CHECK constraints */ + if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ + ExprList *pCheck = tdsqlite3ExprListDup(db, pTab->pCheck, 0); + if( db->mallocFailed==0 ){ + int addrCkFault = tdsqlite3VdbeMakeLabel(pParse); + int addrCkOk = tdsqlite3VdbeMakeLabel(pParse); + char *zErr; + int k; + pParse->iSelfTab = iDataCur + 1; + for(k=pCheck->nExpr-1; k>0; k--){ + tdsqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0); + } + tdsqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, + SQLITE_JUMPIFNULL); + tdsqlite3VdbeResolveLabel(v, addrCkFault); + pParse->iSelfTab = 0; + zErr = tdsqlite3MPrintf(db, "CHECK constraint failed in %s", + pTab->zName); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); + integrityCheckResultRow(v); + tdsqlite3VdbeResolveLabel(v, addrCkOk); + } + tdsqlite3ExprListDelete(db, pCheck); + } + if( !isQuick ){ /* Omit the remaining tests for quick_check */ + /* Validate index entries for the current row */ + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + int jmp2, jmp3, jmp4, jmp5; + int ckUniq = tdsqlite3VdbeMakeLabel(pParse); + if( pPk==pIdx ) continue; + r1 = tdsqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3, + pPrior, r1); + pPrior = pIdx; + tdsqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */ + /* Verify that an index entry exists for the current table row */ + jmp2 = tdsqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, + pIdx->nColumn); VdbeCoverage(v); + tdsqlite3VdbeLoadString(v, 3, "row "); + tdsqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); + tdsqlite3VdbeLoadString(v, 4, " missing from index "); + tdsqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); + jmp5 = tdsqlite3VdbeLoadString(v, 4, pIdx->zName); + tdsqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); + jmp4 = integrityCheckResultRow(v); + tdsqlite3VdbeJumpHere(v, jmp2); + /* For UNIQUE indexes, verify that only one entry exists with the + ** current key. The entry is unique if (1) any column is NULL + ** or (2) the next entry has a different key */ + if( IsUniqueIndex(pIdx) ){ + int uniqOk = tdsqlite3VdbeMakeLabel(pParse); + int jmp6; + int kk; + for(kk=0; kk<pIdx->nKeyCol; kk++){ + int iCol = pIdx->aiColumn[kk]; + assert( iCol!=XN_ROWID && iCol<pTab->nCol ); + if( iCol>=0 && pTab->aCol[iCol].notNull ) continue; + tdsqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk); + VdbeCoverage(v); + } + jmp6 = tdsqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v); + tdsqlite3VdbeGoto(v, uniqOk); + tdsqlite3VdbeJumpHere(v, jmp6); + tdsqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1, + pIdx->nKeyCol); VdbeCoverage(v); + tdsqlite3VdbeLoadString(v, 3, "non-unique entry in index "); + tdsqlite3VdbeGoto(v, jmp5); + tdsqlite3VdbeResolveLabel(v, uniqOk); } - jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v); - sqlite3VdbeGoto(v, uniqOk); - sqlite3VdbeJumpHere(v, jmp6); - sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1, - pIdx->nKeyCol); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */ - sqlite3VdbeLoadString(v, 3, "non-unique entry in index "); - sqlite3VdbeGoto(v, jmp5); - sqlite3VdbeResolveLabel(v, uniqOk); + tdsqlite3VdbeJumpHere(v, jmp4); + tdsqlite3ResolvePartIdxLabel(pParse, jmp3); } - sqlite3VdbeJumpHere(v, jmp4); - sqlite3ResolvePartIdxLabel(pParse, jmp3); } - sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, loopTop-1); + tdsqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, loopTop-1); #ifndef SQLITE_OMIT_BTREECOUNT - sqlite3VdbeLoadString(v, 2, "wrong # of entries in index "); - for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - if( pPk==pIdx ) continue; - addr = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); - sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); - sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); - sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); - sqlite3VdbeLoadString(v, 3, pIdx->zName); - sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7); - sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1); + if( !isQuick ){ + tdsqlite3VdbeLoadString(v, 2, "wrong # of entries in index "); + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + if( pPk==pIdx ) continue; + tdsqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); + addr = tdsqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v); + tdsqlite3VdbeChangeP5(v, SQLITE_NOTNULL); + tdsqlite3VdbeLoadString(v, 4, pIdx->zName); + tdsqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3); + integrityCheckResultRow(v); + tdsqlite3VdbeJumpHere(v, addr); + } } #endif /* SQLITE_OMIT_BTREECOUNT */ } @@ -116263,18 +129719,24 @@ SQLITE_PRIVATE void sqlite3Pragma( static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList endCode[] = { { OP_AddImm, 1, 0, 0}, /* 0 */ - { OP_If, 1, 4, 0}, /* 1 */ + { OP_IfNotZero, 1, 4, 0}, /* 1 */ { OP_String8, 0, 3, 0}, /* 2 */ { OP_ResultRow, 3, 1, 0}, /* 3 */ + { OP_Halt, 0, 0, 0}, /* 4 */ + { OP_String8, 0, 3, 0}, /* 5 */ + { OP_Goto, 0, 3, 0}, /* 6 */ }; VdbeOp *aOp; - aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn); + aOp = tdsqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn); if( aOp ){ - aOp[0].p2 = -mxErr; + aOp[0].p2 = 1-mxErr; aOp[2].p4type = P4_STATIC; aOp[2].p4.z = "ok"; + aOp[5].p4type = P4_STATIC; + aOp[5].p4.z = (char*)tdsqlite3ErrStr(SQLITE_CORRUPT); } + tdsqlite3VdbeChangeP3(v, 0, tdsqlite3VdbeCurrentAddr(v)-2); } } break; @@ -116320,30 +129782,37 @@ SQLITE_PRIVATE void sqlite3Pragma( }; const struct EncName *pEnc; if( !zRight ){ /* "PRAGMA encoding" */ - if( sqlite3ReadSchema(pParse) ) goto pragma_out; + if( tdsqlite3ReadSchema(pParse) ) goto pragma_out; assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); - returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName); + returnSingleText(v, encnames[ENC(pParse->db)].zName); }else{ /* "PRAGMA encoding = XXX" */ /* Only change the value of sqlite.enc if the database handle is not ** initialized. If the main database exists, the new sqlite.enc value ** will be overwritten when the schema is next loaded. If it does not ** already exists, it will be created to use the new encoding value. */ - if( - !(DbHasProperty(db, 0, DB_SchemaLoaded)) || - DbHasProperty(db, 0, DB_Empty) - ){ + int canChangeEnc = 1; /* True if allowed to change the encoding */ + int i; /* For looping over all attached databases */ + for(i=0; i<db->nDb; i++){ + if( db->aDb[i].pBt!=0 + && DbHasProperty(db,i,DB_SchemaLoaded) + && !DbHasProperty(db,i,DB_Empty) + ){ + canChangeEnc = 0; + } + } + if( canChangeEnc ){ for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ - if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ + if( 0==tdsqlite3StrICmp(zRight, pEnc->zName) ){ SCHEMA_ENC(db) = ENC(db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; break; } } if( !pEnc->zName ){ - sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight); + tdsqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight); } } } @@ -116386,21 +129855,21 @@ SQLITE_PRIVATE void sqlite3Pragma( */ case PragTyp_HEADER_VALUE: { int iCookie = pPragma->iArg; /* Which cookie to read or write */ - sqlite3VdbeUsesBtree(v, iDb); - if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){ + tdsqlite3VdbeUsesBtree(v, iDb); + if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){ /* Write the specified cookie value */ static const VdbeOpList setCookie[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ { OP_SetCookie, 0, 0, 0}, /* 1 */ }; VdbeOp *aOp; - sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie)); - aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0); + tdsqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie)); + aOp = tdsqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p2 = iCookie; - aOp[1].p3 = sqlite3Atoi(zRight); + aOp[1].p3 = tdsqlite3Atoi(zRight); }else{ /* Read the specified cookie value */ static const VdbeOpList readCookie[] = { @@ -116409,15 +129878,13 @@ SQLITE_PRIVATE void sqlite3Pragma( { OP_ResultRow, 1, 1, 0} }; VdbeOp *aOp; - sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie)); - aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0); + tdsqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie)); + aOp = tdsqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p3 = iCookie; - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT); - sqlite3VdbeReusable(v); + tdsqlite3VdbeReusable(v); } } break; @@ -116434,12 +129901,11 @@ SQLITE_PRIVATE void sqlite3Pragma( int i = 0; const char *zOpt; pParse->nMem = 1; - setOneColumnName(v, "compile_option"); - while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ - sqlite3VdbeLoadString(v, 1, zOpt); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + while( (zOpt = tdsqlite3_compileoption_get(i++))!=0 ){ + tdsqlite3VdbeLoadString(v, 1, zOpt); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } - sqlite3VdbeReusable(v); + tdsqlite3VdbeReusable(v); } break; #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ @@ -116451,22 +129917,20 @@ SQLITE_PRIVATE void sqlite3Pragma( ** Checkpoint the database. */ case PragTyp_WAL_CHECKPOINT: { - static const char *azCol[] = { "busy", "log", "checkpointed" }; int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); int eMode = SQLITE_CHECKPOINT_PASSIVE; if( zRight ){ - if( sqlite3StrICmp(zRight, "full")==0 ){ + if( tdsqlite3StrICmp(zRight, "full")==0 ){ eMode = SQLITE_CHECKPOINT_FULL; - }else if( sqlite3StrICmp(zRight, "restart")==0 ){ + }else if( tdsqlite3StrICmp(zRight, "restart")==0 ){ eMode = SQLITE_CHECKPOINT_RESTART; - }else if( sqlite3StrICmp(zRight, "truncate")==0 ){ + }else if( tdsqlite3StrICmp(zRight, "truncate")==0 ){ eMode = SQLITE_CHECKPOINT_TRUNCATE; } } - setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) ); pParse->nMem = 3; - sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + tdsqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } break; @@ -116480,10 +129944,10 @@ SQLITE_PRIVATE void sqlite3Pragma( */ case PragTyp_WAL_AUTOCHECKPOINT: { if( zRight ){ - sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); + tdsqlite3_wal_autocheckpoint(db, tdsqlite3Atoi(zRight)); } - returnSingleInt(v, "wal_autocheckpoint", - db->xWalCallback==sqlite3WalDefaultHook ? + returnSingleInt(v, + db->xWalCallback==tdsqlite3WalDefaultHook ? SQLITE_PTR_TO_INT(db->pWalArg) : 0); } break; @@ -116494,10 +129958,123 @@ SQLITE_PRIVATE void sqlite3Pragma( ** ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database ** connection on which it is invoked to free up as much memory as it - ** can, by calling sqlite3_db_release_memory(). + ** can, by calling tdsqlite3_db_release_memory(). */ case PragTyp_SHRINK_MEMORY: { - sqlite3_db_release_memory(db); + tdsqlite3_db_release_memory(db); + break; + } + + /* + ** PRAGMA optimize + ** PRAGMA optimize(MASK) + ** PRAGMA schema.optimize + ** PRAGMA schema.optimize(MASK) + ** + ** Attempt to optimize the database. All schemas are optimized in the first + ** two forms, and only the specified schema is optimized in the latter two. + ** + ** The details of optimizations performed by this pragma are expected + ** to change and improve over time. Applications should anticipate that + ** this pragma will perform new optimizations in future releases. + ** + ** The optional argument is a bitmask of optimizations to perform: + ** + ** 0x0001 Debugging mode. Do not actually perform any optimizations + ** but instead return one line of text for each optimization + ** that would have been done. Off by default. + ** + ** 0x0002 Run ANALYZE on tables that might benefit. On by default. + ** See below for additional information. + ** + ** 0x0004 (Not yet implemented) Record usage and performance + ** information from the current session in the + ** database file so that it will be available to "optimize" + ** pragmas run by future database connections. + ** + ** 0x0008 (Not yet implemented) Create indexes that might have + ** been helpful to recent queries + ** + ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all + ** of the optimizations listed above except Debug Mode, including new + ** optimizations that have not yet been invented. If new optimizations are + ** ever added that should be off by default, those off-by-default + ** optimizations will have bitmasks of 0x10000 or larger. + ** + ** DETERMINATION OF WHEN TO RUN ANALYZE + ** + ** In the current implementation, a table is analyzed if only if all of + ** the following are true: + ** + ** (1) MASK bit 0x02 is set. + ** + ** (2) The query planner used sqlite_stat1-style statistics for one or + ** more indexes of the table at some point during the lifetime of + ** the current connection. + ** + ** (3) One or more indexes of the table are currently unanalyzed OR + ** the number of rows in the table has increased by 25 times or more + ** since the last time ANALYZE was run. + ** + ** The rules for when tables are analyzed are likely to change in + ** future releases. + */ + case PragTyp_OPTIMIZE: { + int iDbLast; /* Loop termination point for the schema loop */ + int iTabCur; /* Cursor for a table whose size needs checking */ + HashElem *k; /* Loop over tables of a schema */ + Schema *pSchema; /* The current schema */ + Table *pTab; /* A table in the schema */ + Index *pIdx; /* An index of the table */ + LogEst szThreshold; /* Size threshold above which reanalysis is needd */ + char *zSubSql; /* SQL statement for the OP_SqlExec opcode */ + u32 opMask; /* Mask of operations to perform */ + + if( zRight ){ + opMask = (u32)tdsqlite3Atoi(zRight); + if( (opMask & 0x02)==0 ) break; + }else{ + opMask = 0xfffe; + } + iTabCur = pParse->nTab++; + for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){ + if( iDb==1 ) continue; + tdsqlite3CodeVerifySchema(pParse, iDb); + pSchema = db->aDb[iDb].pSchema; + for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ + pTab = (Table*)sqliteHashData(k); + + /* If table pTab has not been used in a way that would benefit from + ** having analysis statistics during the current session, then skip it. + ** This also has the effect of skipping virtual tables and views */ + if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue; + + /* Reanalyze if the table is 25 times larger than the last analysis */ + szThreshold = pTab->nRowLogEst + 46; assert( tdsqlite3LogEst(25)==46 ); + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( !pIdx->hasStat1 ){ + szThreshold = 0; /* Always analyze if any index lacks statistics */ + break; + } + } + if( szThreshold ){ + tdsqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); + tdsqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, + tdsqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold); + VdbeCoverage(v); + } + zSubSql = tdsqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"", + db->aDb[iDb].zDbSName, pTab->zName); + if( opMask & 0x01 ){ + int r1 = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1); + }else{ + tdsqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC); + } + } + } + tdsqlite3VdbeAddOp0(v, OP_Expire); break; } @@ -116505,7 +130082,7 @@ SQLITE_PRIVATE void sqlite3Pragma( ** PRAGMA busy_timeout ** PRAGMA busy_timeout = N ** - ** Call sqlite3_busy_timeout(db, N). Return the current timeout value + ** Call tdsqlite3_busy_timeout(db, N). Return the current timeout value ** if one is set. If no busy handler or a different busy handler is set ** then 0 is returned. Setting the busy_timeout to 0 or negative ** disables the timeout. @@ -116513,9 +130090,9 @@ SQLITE_PRIVATE void sqlite3Pragma( /*case PragTyp_BUSY_TIMEOUT*/ default: { assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT ); if( zRight ){ - sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); + tdsqlite3_busy_timeout(db, tdsqlite3Atoi(zRight)); } - returnSingleInt(v, "timeout", db->busyTimeout); + returnSingleInt(v, db->busyTimeout); break; } @@ -116524,18 +130101,39 @@ SQLITE_PRIVATE void sqlite3Pragma( ** PRAGMA soft_heap_limit = N ** ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the - ** sqlite3_soft_heap_limit64() interface with the argument N, if N is + ** tdsqlite3_soft_heap_limit64() interface with the argument N, if N is ** specified and is a non-negative integer. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always ** returns the same integer that would be returned by the - ** sqlite3_soft_heap_limit64(-1) C-language function. + ** tdsqlite3_soft_heap_limit64(-1) C-language function. */ case PragTyp_SOFT_HEAP_LIMIT: { - sqlite3_int64 N; - if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ - sqlite3_soft_heap_limit64(N); + tdsqlite3_int64 N; + if( zRight && tdsqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ + tdsqlite3_soft_heap_limit64(N); } - returnSingleInt(v, "soft_heap_limit", sqlite3_soft_heap_limit64(-1)); + returnSingleInt(v, tdsqlite3_soft_heap_limit64(-1)); + break; + } + + /* + ** PRAGMA hard_heap_limit + ** PRAGMA hard_heap_limit = N + ** + ** Invoke tdsqlite3_hard_heap_limit64() to query or set the hard heap + ** limit. The hard heap limit can be activated or lowered by this + ** pragma, but not raised or deactivated. Only the + ** tdsqlite3_hard_heap_limit64() C-language API can raise or deactivate + ** the hard heap limit. This allows an application to set a heap limit + ** constraint that cannot be relaxed by an untrusted SQL script. + */ + case PragTyp_HARD_HEAP_LIMIT: { + tdsqlite3_int64 N; + if( zRight && tdsqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ + tdsqlite3_int64 iPrior = tdsqlite3_hard_heap_limit64(-1); + if( N>0 && (iPrior==0 || iPrior>N) ) tdsqlite3_hard_heap_limit64(N); + } + returnSingleInt(v, tdsqlite3_hard_heap_limit64(-1)); break; } @@ -116547,15 +130145,14 @@ SQLITE_PRIVATE void sqlite3Pragma( ** maximum, which might be less than requested. */ case PragTyp_THREADS: { - sqlite3_int64 N; + tdsqlite3_int64 N; if( zRight - && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK + && tdsqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK && N>=0 ){ - sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff)); + tdsqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff)); } - returnSingleInt(v, "threads", - sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1)); + returnSingleInt(v, tdsqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1)); break; } @@ -116567,9 +130164,7 @@ SQLITE_PRIVATE void sqlite3Pragma( static const char *const azLockName[] = { "unlocked", "shared", "reserved", "pending", "exclusive" }; - static const char *azCol[] = { "database", "status" }; int i; - setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) ); pParse->nMem = 2; for(i=0; i<db->nDb; i++){ Btree *pBt; @@ -116577,41 +130172,54 @@ SQLITE_PRIVATE void sqlite3Pragma( int j; if( db->aDb[i].zDbSName==0 ) continue; pBt = db->aDb[i].pBt; - if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ + if( pBt==0 || tdsqlite3BtreePager(pBt)==0 ){ zState = "closed"; - }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, + }else if( tdsqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ zState = azLockName[j]; } - sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); + tdsqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState); } break; } #endif #ifdef SQLITE_HAS_CODEC + /* Pragma iArg + ** ---------- ------ + ** key 0 + ** rekey 1 + ** hexkey 2 + ** hexrekey 3 + ** textkey 4 + ** textrekey 5 + */ case PragTyp_KEY: { - if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); - break; - } - case PragTyp_REKEY: { - if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); - break; - } - case PragTyp_HEXKEY: { if( zRight ){ - u8 iByte; - int i; - char zKey[40]; - for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){ - iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]); - if( (i&1)!=0 ) zKey[i/2] = iByte; + char zBuf[40]; + const char *zKey = zRight; + int n; + if( pPragma->iArg==2 || pPragma->iArg==3 ){ + u8 iByte; + int i; + for(i=0, iByte=0; i<sizeof(zBuf)*2 && tdsqlite3Isxdigit(zRight[i]); i++){ + iByte = (iByte<<4) + tdsqlite3HexToInt(zRight[i]); + if( (i&1)!=0 ) zBuf[i/2] = iByte; + } + zKey = zBuf; + n = i/2; + }else{ + n = pPragma->iArg<4 ? tdsqlite3Strlen30(zRight) : -1; } - if( (zLeft[3] & 0xf)==0xb ){ - sqlite3_key_v2(db, zDb, zKey, i/2); + if( (pPragma->iArg & 1)==0 ){ + rc = tdsqlite3_key_v2(db, zDb, zKey, n); }else{ - sqlite3_rekey_v2(db, zDb, zKey, i/2); + rc = tdsqlite3_rekey_v2(db, zDb, zKey, n); + } + if( rc==SQLITE_OK && n!=0 ){ + tdsqlite3VdbeSetNumCols(v, 1); + tdsqlite3VdbeSetColName(v, 0, COLNAME_NAME, "ok", SQLITE_STATIC); + returnSingleText(v, "ok"); } } break; @@ -116620,13 +130228,13 @@ SQLITE_PRIVATE void sqlite3Pragma( #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){ #ifdef SQLITE_HAS_CODEC - if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){ - sqlite3_activate_see(&zRight[4]); + if( tdsqlite3StrNICmp(zRight, "see-", 4)==0 ){ + tdsqlite3_activate_see(&zRight[4]); } #endif #ifdef SQLITE_ENABLE_CEROD - if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){ - sqlite3_activate_cerod(&zRight[6]); + if( tdsqlite3StrNICmp(zRight, "cerod-", 6)==0 ){ + tdsqlite3_activate_cerod(&zRight[6]); } #endif } @@ -116635,11 +130243,330 @@ SQLITE_PRIVATE void sqlite3Pragma( } /* End of the PRAGMA switch */ + /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only + ** purpose is to execute assert() statements to verify that if the + ** PragFlg_NoColumns1 flag is set and the caller specified an argument + ** to the PRAGMA, the implementation has not added any OP_ResultRow + ** instructions to the VM. */ + if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){ + tdsqlite3VdbeVerifyNoResultRow(v); + } + pragma_out: - sqlite3DbFree(db, zLeft); - sqlite3DbFree(db, zRight); + tdsqlite3DbFree(db, zLeft); + tdsqlite3DbFree(db, zRight); +} +#ifndef SQLITE_OMIT_VIRTUALTABLE +/***************************************************************************** +** Implementation of an eponymous virtual table that runs a pragma. +** +*/ +typedef struct PragmaVtab PragmaVtab; +typedef struct PragmaVtabCursor PragmaVtabCursor; +struct PragmaVtab { + tdsqlite3_vtab base; /* Base class. Must be first */ + tdsqlite3 *db; /* The database connection to which it belongs */ + const PragmaName *pName; /* Name of the pragma */ + u8 nHidden; /* Number of hidden columns */ + u8 iHidden; /* Index of the first hidden column */ +}; +struct PragmaVtabCursor { + tdsqlite3_vtab_cursor base; /* Base class. Must be first */ + tdsqlite3_stmt *pPragma; /* The pragma statement to run */ + sqlite_int64 iRowid; /* Current rowid */ + char *azArg[2]; /* Value of the argument and schema */ +}; + +/* +** Pragma virtual table module xConnect method. +*/ +static int pragmaVtabConnect( + tdsqlite3 *db, + void *pAux, + int argc, const char *const*argv, + tdsqlite3_vtab **ppVtab, + char **pzErr +){ + const PragmaName *pPragma = (const PragmaName*)pAux; + PragmaVtab *pTab = 0; + int rc; + int i, j; + char cSep = '('; + StrAccum acc; + char zBuf[200]; + + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); + tdsqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); + tdsqlite3_str_appendall(&acc, "CREATE TABLE x"); + for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){ + tdsqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]); + cSep = ','; + } + if( i==0 ){ + tdsqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName); + i++; + } + j = 0; + if( pPragma->mPragFlg & PragFlg_Result1 ){ + tdsqlite3_str_appendall(&acc, ",arg HIDDEN"); + j++; + } + if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){ + tdsqlite3_str_appendall(&acc, ",schema HIDDEN"); + j++; + } + tdsqlite3_str_append(&acc, ")", 1); + tdsqlite3StrAccumFinish(&acc); + assert( strlen(zBuf) < sizeof(zBuf)-1 ); + rc = tdsqlite3_declare_vtab(db, zBuf); + if( rc==SQLITE_OK ){ + pTab = (PragmaVtab*)tdsqlite3_malloc(sizeof(PragmaVtab)); + if( pTab==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pTab, 0, sizeof(PragmaVtab)); + pTab->pName = pPragma; + pTab->db = db; + pTab->iHidden = i; + pTab->nHidden = j; + } + }else{ + *pzErr = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); + } + + *ppVtab = (tdsqlite3_vtab*)pTab; + return rc; +} + +/* +** Pragma virtual table module xDisconnect method. +*/ +static int pragmaVtabDisconnect(tdsqlite3_vtab *pVtab){ + PragmaVtab *pTab = (PragmaVtab*)pVtab; + tdsqlite3_free(pTab); + return SQLITE_OK; } +/* Figure out the best index to use to search a pragma virtual table. +** +** There are not really any index choices. But we want to encourage the +** query planner to give == constraints on as many hidden parameters as +** possible, and especially on the first hidden parameter. So return a +** high cost if hidden parameters are unconstrained. +*/ +static int pragmaVtabBestIndex(tdsqlite3_vtab *tab, tdsqlite3_index_info *pIdxInfo){ + PragmaVtab *pTab = (PragmaVtab*)tab; + const struct tdsqlite3_index_constraint *pConstraint; + int i, j; + int seen[2]; + + pIdxInfo->estimatedCost = (double)1; + if( pTab->nHidden==0 ){ return SQLITE_OK; } + pConstraint = pIdxInfo->aConstraint; + seen[0] = 0; + seen[1] = 0; + for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ + if( pConstraint->usable==0 ) continue; + if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; + if( pConstraint->iColumn < pTab->iHidden ) continue; + j = pConstraint->iColumn - pTab->iHidden; + assert( j < 2 ); + seen[j] = i+1; + } + if( seen[0]==0 ){ + pIdxInfo->estimatedCost = (double)2147483647; + pIdxInfo->estimatedRows = 2147483647; + return SQLITE_OK; + } + j = seen[0]-1; + pIdxInfo->aConstraintUsage[j].argvIndex = 1; + pIdxInfo->aConstraintUsage[j].omit = 1; + if( seen[1]==0 ) return SQLITE_OK; + pIdxInfo->estimatedCost = (double)20; + pIdxInfo->estimatedRows = 20; + j = seen[1]-1; + pIdxInfo->aConstraintUsage[j].argvIndex = 2; + pIdxInfo->aConstraintUsage[j].omit = 1; + return SQLITE_OK; +} + +/* Create a new cursor for the pragma virtual table */ +static int pragmaVtabOpen(tdsqlite3_vtab *pVtab, tdsqlite3_vtab_cursor **ppCursor){ + PragmaVtabCursor *pCsr; + pCsr = (PragmaVtabCursor*)tdsqlite3_malloc(sizeof(*pCsr)); + if( pCsr==0 ) return SQLITE_NOMEM; + memset(pCsr, 0, sizeof(PragmaVtabCursor)); + pCsr->base.pVtab = pVtab; + *ppCursor = &pCsr->base; + return SQLITE_OK; +} + +/* Clear all content from pragma virtual table cursor. */ +static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){ + int i; + tdsqlite3_finalize(pCsr->pPragma); + pCsr->pPragma = 0; + for(i=0; i<ArraySize(pCsr->azArg); i++){ + tdsqlite3_free(pCsr->azArg[i]); + pCsr->azArg[i] = 0; + } +} + +/* Close a pragma virtual table cursor */ +static int pragmaVtabClose(tdsqlite3_vtab_cursor *cur){ + PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur; + pragmaVtabCursorClear(pCsr); + tdsqlite3_free(pCsr); + return SQLITE_OK; +} + +/* Advance the pragma virtual table cursor to the next row */ +static int pragmaVtabNext(tdsqlite3_vtab_cursor *pVtabCursor){ + PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; + int rc = SQLITE_OK; + + /* Increment the xRowid value */ + pCsr->iRowid++; + assert( pCsr->pPragma ); + if( SQLITE_ROW!=tdsqlite3_step(pCsr->pPragma) ){ + rc = tdsqlite3_finalize(pCsr->pPragma); + pCsr->pPragma = 0; + pragmaVtabCursorClear(pCsr); + } + return rc; +} + +/* +** Pragma virtual table module xFilter method. +*/ +static int pragmaVtabFilter( + tdsqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, tdsqlite3_value **argv +){ + PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; + PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab); + int rc; + int i, j; + StrAccum acc; + char *zSql; + + UNUSED_PARAMETER(idxNum); + UNUSED_PARAMETER(idxStr); + pragmaVtabCursorClear(pCsr); + j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1; + for(i=0; i<argc; i++, j++){ + const char *zText = (const char*)tdsqlite3_value_text(argv[i]); + assert( j<ArraySize(pCsr->azArg) ); + assert( pCsr->azArg[j]==0 ); + if( zText ){ + pCsr->azArg[j] = tdsqlite3_mprintf("%s", zText); + if( pCsr->azArg[j]==0 ){ + return SQLITE_NOMEM; + } + } + } + tdsqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]); + tdsqlite3_str_appendall(&acc, "PRAGMA "); + if( pCsr->azArg[1] ){ + tdsqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]); + } + tdsqlite3_str_appendall(&acc, pTab->pName->zName); + if( pCsr->azArg[0] ){ + tdsqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]); + } + zSql = tdsqlite3StrAccumFinish(&acc); + if( zSql==0 ) return SQLITE_NOMEM; + rc = tdsqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0); + tdsqlite3_free(zSql); + if( rc!=SQLITE_OK ){ + pTab->base.zErrMsg = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(pTab->db)); + return rc; + } + return pragmaVtabNext(pVtabCursor); +} + +/* +** Pragma virtual table module xEof method. +*/ +static int pragmaVtabEof(tdsqlite3_vtab_cursor *pVtabCursor){ + PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; + return (pCsr->pPragma==0); +} + +/* The xColumn method simply returns the corresponding column from +** the PRAGMA. +*/ +static int pragmaVtabColumn( + tdsqlite3_vtab_cursor *pVtabCursor, + tdsqlite3_context *ctx, + int i +){ + PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; + PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab); + if( i<pTab->iHidden ){ + tdsqlite3_result_value(ctx, tdsqlite3_column_value(pCsr->pPragma, i)); + }else{ + tdsqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT); + } + return SQLITE_OK; +} + +/* +** Pragma virtual table module xRowid method. +*/ +static int pragmaVtabRowid(tdsqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){ + PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; + *p = pCsr->iRowid; + return SQLITE_OK; +} + +/* The pragma virtual table object */ +static const tdsqlite3_module pragmaVtabModule = { + 0, /* iVersion */ + 0, /* xCreate - create a table */ + pragmaVtabConnect, /* xConnect - connect to an existing table */ + pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */ + pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */ + 0, /* xDestroy - Drop a table */ + pragmaVtabOpen, /* xOpen - open a cursor */ + pragmaVtabClose, /* xClose - close a cursor */ + pragmaVtabFilter, /* xFilter - configure scan constraints */ + pragmaVtabNext, /* xNext - advance a cursor */ + pragmaVtabEof, /* xEof */ + pragmaVtabColumn, /* xColumn - read data */ + pragmaVtabRowid, /* xRowid - read data */ + 0, /* xUpdate - write data */ + 0, /* xBegin - begin transaction */ + 0, /* xSync - sync transaction */ + 0, /* xCommit - commit transaction */ + 0, /* xRollback - rollback transaction */ + 0, /* xFindFunction - function overloading */ + 0, /* xRename - rename the table */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0 /* xShadowName */ +}; + +/* +** Check to see if zTabName is really the name of a pragma. If it is, +** then register an eponymous virtual table for that pragma and return +** a pointer to the Module object for the new virtual table. +*/ +SQLITE_PRIVATE Module *tdsqlite3PragmaVtabRegister(tdsqlite3 *db, const char *zName){ + const PragmaName *pName; + assert( tdsqlite3_strnicmp(zName, "pragma_", 7)==0 ); + pName = pragmaLocate(zName+7); + if( pName==0 ) return 0; + if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0; + assert( tdsqlite3HashFind(&db->aModule, zName)==0 ); + return tdsqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0); +} + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + #endif /* SQLITE_OMIT_PRAGMA */ /************** End of pragma.c **********************************************/ @@ -116655,7 +130582,7 @@ pragma_out: ** May you share freely, never taking more than you give. ** ************************************************************************* -** This file contains the implementation of the sqlite3_prepare() +** This file contains the implementation of the tdsqlite3_prepare() ** interface, and routines that contribute to loading the database schema ** from disk. */ @@ -116670,49 +130597,85 @@ static void corruptSchema( const char *zObj, /* Object being parsed at the point of error */ const char *zExtra /* Error information */ ){ - sqlite3 *db = pData->db; - if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){ + tdsqlite3 *db = pData->db; + if( db->mallocFailed ){ + pData->rc = SQLITE_NOMEM_BKPT; + }else if( pData->pzErrMsg[0]!=0 ){ + /* A error message has already been generated. Do not overwrite it */ + }else if( pData->mInitFlags & INITFLAG_AlterTable ){ + *pData->pzErrMsg = tdsqlite3DbStrDup(db, zExtra); + pData->rc = SQLITE_ERROR; + }else if( db->flags & SQLITE_WriteSchema ){ + pData->rc = SQLITE_CORRUPT_BKPT; + }else{ char *z; if( zObj==0 ) zObj = "?"; - z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj); - if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra); - sqlite3DbFree(db, *pData->pzErrMsg); + z = tdsqlite3MPrintf(db, "malformed database schema (%s)", zObj); + if( zExtra && zExtra[0] ) z = tdsqlite3MPrintf(db, "%z - %s", z, zExtra); *pData->pzErrMsg = z; + pData->rc = SQLITE_CORRUPT_BKPT; + } +} + +/* +** Check to see if any sibling index (another index on the same table) +** of pIndex has the same root page number, and if it does, return true. +** This would indicate a corrupt schema. +*/ +SQLITE_PRIVATE int tdsqlite3IndexHasDuplicateRootPage(Index *pIndex){ + Index *p; + for(p=pIndex->pTable->pIndex; p; p=p->pNext){ + if( p->tnum==pIndex->tnum && p!=pIndex ) return 1; } - pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT; + return 0; } +/* forward declaration */ +static int tdsqlite3Prepare( + tdsqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ + Vdbe *pReprepare, /* VM being reprepared */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +); + + /* ** This is the callback routine for the code that initializes the -** database. See sqlite3Init() below for additional information. +** database. See tdsqlite3Init() below for additional information. ** This routine is also called from the OP_ParseSchema opcode of the VDBE. ** ** Each callback contains the following information: ** -** argv[0] = name of thing being created -** argv[1] = root page number for table or index. 0 for trigger or view. -** argv[2] = SQL text for the CREATE statement. +** argv[0] = type of object: "table", "index", "trigger", or "view". +** argv[1] = name of thing being created +** argv[2] = associated table if an index or trigger +** argv[3] = root page number for table or index. 0 for trigger or view. +** argv[4] = SQL text for the CREATE statement. ** */ -SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){ +SQLITE_PRIVATE int tdsqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){ InitData *pData = (InitData*)pInit; - sqlite3 *db = pData->db; + tdsqlite3 *db = pData->db; int iDb = pData->iDb; - assert( argc==3 ); + assert( argc==5 ); UNUSED_PARAMETER2(NotUsed, argc); - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); DbClearProperty(db, iDb, DB_Empty); + pData->nInitRow++; if( db->mallocFailed ){ - corruptSchema(pData, argv[0], 0); + corruptSchema(pData, argv[1], 0); return 1; } assert( iDb>=0 && iDb<db->nDb ); if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ - if( argv[1]==0 ){ - corruptSchema(pData, argv[0], 0); - }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){ + if( argv[3]==0 ){ + corruptSchema(pData, argv[1], 0); + }else if( tdsqlite3_strnicmp(argv[4],"create ",7)==0 ){ /* Call the parser to process a CREATE TABLE, INDEX or VIEW. ** But because db->init.busy is set to 1, no VDBE code is generated ** or executed. All the parser does is build the internal data @@ -116720,33 +130683,35 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char */ int rc; u8 saved_iDb = db->init.iDb; - sqlite3_stmt *pStmt; - TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ + tdsqlite3_stmt *pStmt; + TESTONLY(int rcp); /* Return code from tdsqlite3_prepare() */ assert( db->init.busy ); db->init.iDb = iDb; - db->init.newTnum = sqlite3Atoi(argv[1]); + db->init.newTnum = tdsqlite3Atoi(argv[3]); db->init.orphanTrigger = 0; - TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0); + db->init.azInit = argv; + pStmt = 0; + TESTONLY(rcp = ) tdsqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0); rc = db->errCode; assert( (rc&0xFF)==(rcp&0xFF) ); db->init.iDb = saved_iDb; - assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 ); + /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */ if( SQLITE_OK!=rc ){ if( db->init.orphanTrigger ){ assert( iDb==1 ); }else{ - pData->rc = rc; + if( rc > pData->rc ) pData->rc = rc; if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){ - corruptSchema(pData, argv[0], sqlite3_errmsg(db)); + corruptSchema(pData, argv[1], tdsqlite3_errmsg(db)); } } } - sqlite3_finalize(pStmt); - }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){ - corruptSchema(pData, argv[0], 0); + tdsqlite3_finalize(pStmt); + }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){ + corruptSchema(pData, argv[1], 0); }else{ /* If the SQL column is blank it means this is an index that ** was created to be the PRIMARY KEY or to fulfill a UNIQUE @@ -116755,16 +130720,13 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char ** to do here is record the root page number for that index. */ Index *pIndex; - pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName); - if( pIndex==0 ){ - /* This can occur if there exists an index on a TEMP table which - ** has the same name as another index on a permanent index. Since - ** the permanent table is hidden by the TEMP table, we can also - ** safely ignore the index on the permanent table. - */ - /* Do Nothing */; - }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){ - corruptSchema(pData, argv[0], "invalid rootpage"); + pIndex = tdsqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName); + if( pIndex==0 + || tdsqlite3GetInt32(argv[3],&pIndex->tnum)==0 + || pIndex->tnum<2 + || tdsqlite3IndexHasDuplicateRootPage(pIndex) + ){ + corruptSchema(pData, argv[1], pIndex?"invalid rootpage":"orphan index"); } } return 0; @@ -116778,39 +130740,46 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char ** auxiliary databases. Return one of the SQLITE_ error codes to ** indicate success or failure. */ -static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ +SQLITE_PRIVATE int tdsqlite3InitOne(tdsqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){ int rc; int i; #ifndef SQLITE_OMIT_DEPRECATED int size; #endif Db *pDb; - char const *azArg[4]; + char const *azArg[6]; int meta[5]; InitData initData; const char *zMasterName; int openedTransaction = 0; + assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ); assert( iDb>=0 && iDb<db->nDb ); assert( db->aDb[iDb].pSchema ); - assert( sqlite3_mutex_held(db->mutex) ); - assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); + assert( tdsqlite3_mutex_held(db->mutex) ); + assert( iDb==1 || tdsqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); + + db->init.busy = 1; /* Construct the in-memory representation schema tables (sqlite_master or ** sqlite_temp_master) by invoking the parser directly. The appropriate ** table name will be inserted automatically by the parser so we can just ** use the abbreviation "x" here. The parser will also automatically tag ** the schema table as read-only. */ - azArg[0] = zMasterName = SCHEMA_TABLE(iDb); - azArg[1] = "1"; - azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text," - "rootpage integer,sql text)"; - azArg[3] = 0; + azArg[0] = "table"; + azArg[1] = zMasterName = SCHEMA_TABLE(iDb); + azArg[2] = azArg[1]; + azArg[3] = "1"; + azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text," + "rootpage int,sql text)"; + azArg[5] = 0; initData.db = db; initData.iDb = iDb; initData.rc = SQLITE_OK; initData.pzErrMsg = pzErrMsg; - sqlite3InitCallback(&initData, 3, (char **)azArg, 0); + initData.mInitFlags = mFlags; + initData.nInitRow = 0; + tdsqlite3InitCallback(&initData, 5, (char **)azArg, 0); if( initData.rc ){ rc = initData.rc; goto error_out; @@ -116820,20 +130789,20 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ */ pDb = &db->aDb[iDb]; if( pDb->pBt==0 ){ - if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){ - DbSetProperty(db, 1, DB_SchemaLoaded); - } - return SQLITE_OK; + assert( iDb==1 ); + DbSetProperty(db, 1, DB_SchemaLoaded); + rc = SQLITE_OK; + goto error_out; } /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed before this function returns. */ - sqlite3BtreeEnter(pDb->pBt); - if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){ - rc = sqlite3BtreeBeginTrans(pDb->pBt, 0); + tdsqlite3BtreeEnter(pDb->pBt); + if( !tdsqlite3BtreeIsInReadTrans(pDb->pBt) ){ + rc = tdsqlite3BtreeBeginTrans(pDb->pBt, 0, 0); if( rc!=SQLITE_OK ){ - sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc)); + tdsqlite3SetString(pzErrMsg, db, tdsqlite3ErrStr(rc)); goto initone_error_out; } openedTransaction = 1; @@ -116857,7 +130826,10 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ ** the possible values of meta[4]. */ for(i=0; i<ArraySize(meta); i++){ - sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]); + tdsqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]); + } + if( (db->flags & SQLITE_ResetDatabase)!=0 ){ + memset(meta, 0, sizeof(meta)); } pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1]; @@ -116880,7 +130852,7 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ }else{ /* If opening an attached database, the encoding much match ENC(db) */ if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){ - sqlite3SetString(pzErrMsg, db, "attached databases must use the same" + tdsqlite3SetString(pzErrMsg, db, "attached databases must use the same" " text encoding as main database"); rc = SQLITE_ERROR; goto initone_error_out; @@ -116893,13 +130865,13 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ if( pDb->pSchema->cache_size==0 ){ #ifndef SQLITE_OMIT_DEPRECATED - size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]); + size = tdsqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]); if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; } pDb->pSchema->cache_size = size; #else pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE; #endif - sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); + tdsqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } /* @@ -116913,7 +130885,7 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ pDb->pSchema->file_format = 1; } if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){ - sqlite3SetString(pzErrMsg, db, "unsupported file format"); + tdsqlite3SetString(pzErrMsg, db, "unsupported file format"); rc = SQLITE_ERROR; goto initone_error_out; } @@ -116924,7 +130896,7 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ ** indices that the user might have created. */ if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){ - db->flags &= ~SQLITE_LegacyFileFmt; + db->flags &= ~(u64)SQLITE_LegacyFileFmt; } /* Read the schema information out of the schema tables @@ -116932,36 +130904,36 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ assert( db->init.busy ); { char *zSql; - zSql = sqlite3MPrintf(db, - "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid", + zSql = tdsqlite3MPrintf(db, + "SELECT*FROM\"%w\".%s ORDER BY rowid", db->aDb[iDb].zDbSName, zMasterName); #ifndef SQLITE_OMIT_AUTHORIZATION { - sqlite3_xauth xAuth; + tdsqlite3_xauth xAuth; xAuth = db->xAuth; db->xAuth = 0; #endif - rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); + rc = tdsqlite3_exec(db, zSql, tdsqlite3InitCallback, &initData, 0); #ifndef SQLITE_OMIT_AUTHORIZATION db->xAuth = xAuth; } #endif if( rc==SQLITE_OK ) rc = initData.rc; - sqlite3DbFree(db, zSql); + tdsqlite3DbFree(db, zSql); #ifndef SQLITE_OMIT_ANALYZE if( rc==SQLITE_OK ){ - sqlite3AnalysisLoad(db, iDb); + tdsqlite3AnalysisLoad(db, iDb); } #endif } if( db->mallocFailed ){ rc = SQLITE_NOMEM_BKPT; - sqlite3ResetAllSchemasOfConnection(db); + tdsqlite3ResetAllSchemasOfConnection(db); } - if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){ - /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider + if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){ + /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider ** the schema loaded, even if errors occurred. In this situation the - ** current sqlite3_prepare() operation will fail, but the following one + ** current tdsqlite3_prepare() operation will fail, but the following one ** will attempt to compile the supplied statement against whatever subset ** of the schema was loaded before the error occurred. The primary ** purpose of this is to allow access to the sqlite_master table @@ -116972,19 +130944,23 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ } /* Jump here for an error that occurs after successfully allocating - ** curMain and calling sqlite3BtreeEnter(). For an error that occurs + ** curMain and calling tdsqlite3BtreeEnter(). For an error that occurs ** before that point, jump to error_out. */ initone_error_out: if( openedTransaction ){ - sqlite3BtreeCommit(pDb->pBt); + tdsqlite3BtreeCommit(pDb->pBt); } - sqlite3BtreeLeave(pDb->pBt); + tdsqlite3BtreeLeave(pDb->pBt); error_out: - if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ - sqlite3OomFault(db); + if( rc ){ + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ + tdsqlite3OomFault(db); + } + tdsqlite3ResetOneSchema(db, iDb); } + db->init.busy = 0; return rc; } @@ -116998,60 +130974,50 @@ error_out: ** bit is set in the flags field of the Db structure. If the database ** file was of zero-length, then the DB_Empty flag is also set. */ -SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){ +SQLITE_PRIVATE int tdsqlite3Init(tdsqlite3 *db, char **pzErrMsg){ int i, rc; - int commit_internal = !(db->flags&SQLITE_InternChanges); + int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange); - assert( sqlite3_mutex_held(db->mutex) ); - assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) ); + assert( tdsqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3BtreeHoldsMutex(db->aDb[0].pBt) ); assert( db->init.busy==0 ); - rc = SQLITE_OK; - db->init.busy = 1; ENC(db) = SCHEMA_ENC(db); - for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ - if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue; - rc = sqlite3InitOne(db, i, pzErrMsg); - if( rc ){ - sqlite3ResetOneSchema(db, i); - } + assert( db->nDb>0 ); + /* Do the main schema first */ + if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){ + rc = tdsqlite3InitOne(db, 0, pzErrMsg, 0); + if( rc ) return rc; } - - /* Once all the other databases have been initialized, load the schema - ** for the TEMP database. This is loaded last, as the TEMP database - ** schema may contain references to objects in other databases. - */ -#ifndef SQLITE_OMIT_TEMPDB - assert( db->nDb>1 ); - if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){ - rc = sqlite3InitOne(db, 1, pzErrMsg); - if( rc ){ - sqlite3ResetOneSchema(db, 1); + /* All other schemas after the main schema. The "temp" schema must be last */ + for(i=db->nDb-1; i>0; i--){ + assert( i==1 || tdsqlite3BtreeHoldsMutex(db->aDb[i].pBt) ); + if( !DbHasProperty(db, i, DB_SchemaLoaded) ){ + rc = tdsqlite3InitOne(db, i, pzErrMsg, 0); + if( rc ) return rc; } } -#endif - - db->init.busy = 0; - if( rc==SQLITE_OK && commit_internal ){ - sqlite3CommitInternalChanges(db); + if( commit_internal ){ + tdsqlite3CommitInternalChanges(db); } - - return rc; + return SQLITE_OK; } /* ** This routine is a no-op if the database schema is already initialized. ** Otherwise, the schema is loaded. An error code is returned. */ -SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){ +SQLITE_PRIVATE int tdsqlite3ReadSchema(Parse *pParse){ int rc = SQLITE_OK; - sqlite3 *db = pParse->db; - assert( sqlite3_mutex_held(db->mutex) ); + tdsqlite3 *db = pParse->db; + assert( tdsqlite3_mutex_held(db->mutex) ); if( !db->init.busy ){ - rc = sqlite3Init(db, &pParse->zErrMsg); - } - if( rc!=SQLITE_OK ){ - pParse->rc = rc; - pParse->nErr++; + rc = tdsqlite3Init(db, &pParse->zErrMsg); + if( rc!=SQLITE_OK ){ + pParse->rc = rc; + pParse->nErr++; + }else if( db->noSharedCache ){ + db->mDbFlags |= DBFLAG_SchemaKnownOk; + } } return rc; } @@ -117063,13 +131029,13 @@ SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){ ** make no changes to pParse->rc. */ static void schemaIsValid(Parse *pParse){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; int iDb; int rc; int cookie; assert( pParse->checkSchema ); - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); for(iDb=0; iDb<db->nDb; iDb++){ int openedTransaction = 0; /* True if a transaction is opened */ Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */ @@ -117078,10 +131044,10 @@ static void schemaIsValid(Parse *pParse){ /* If there is not already a read-only (or read-write) transaction opened ** on the b-tree database, open one now. If a transaction is opened, it ** will be closed immediately after reading the meta-value. */ - if( !sqlite3BtreeIsInReadTrans(pBt) ){ - rc = sqlite3BtreeBeginTrans(pBt, 0); + if( !tdsqlite3BtreeIsInReadTrans(pBt) ){ + rc = tdsqlite3BtreeBeginTrans(pBt, 0, 0); if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); } if( rc!=SQLITE_OK ) return; openedTransaction = 1; @@ -117090,16 +131056,16 @@ static void schemaIsValid(Parse *pParse){ /* Read the schema cookie from the database. If it does not match the ** value stored as part of the in-memory schema representation, ** set Parse.rc to SQLITE_SCHEMA. */ - sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + tdsqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){ - sqlite3ResetOneSchema(db, iDb); + tdsqlite3ResetOneSchema(db, iDb); pParse->rc = SQLITE_SCHEMA; } /* Close the transaction, if one was opened. */ if( openedTransaction ){ - sqlite3BtreeCommit(pBt); + tdsqlite3BtreeCommit(pBt); } } } @@ -117111,7 +131077,7 @@ static void schemaIsValid(Parse *pParse){ ** If the same database is attached more than once, the first ** attached database is returned. */ -SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ +SQLITE_PRIVATE int tdsqlite3SchemaToIndex(tdsqlite3 *db, Schema *pSchema){ int i = -1000000; /* If pSchema is NULL, then return -1000000. This happens when code in @@ -117124,9 +131090,10 @@ SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ ** more likely to cause a segfault than -1 (of course there are assert() ** statements too, but it never hurts to play the odds). */ - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); if( pSchema ){ - for(i=0; ALWAYS(i<db->nDb); i++){ + for(i=0; 1; i++){ + assert( i<db->nDb ); if( db->aDb[i].pSchema==pSchema ){ break; } @@ -117139,29 +131106,28 @@ SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ /* ** Free all memory allocations in the pParse object */ -SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){ - if( pParse ){ - sqlite3 *db = pParse->db; - sqlite3DbFree(db, pParse->aLabel); - sqlite3ExprListDelete(db, pParse->pConstExpr); - if( db ){ - assert( db->lookaside.bDisable >= pParse->disableLookaside ); - db->lookaside.bDisable -= pParse->disableLookaside; - } - pParse->disableLookaside = 0; +SQLITE_PRIVATE void tdsqlite3ParserReset(Parse *pParse){ + tdsqlite3 *db = pParse->db; + tdsqlite3DbFree(db, pParse->aLabel); + tdsqlite3ExprListDelete(db, pParse->pConstExpr); + if( db ){ + assert( db->lookaside.bDisable >= pParse->disableLookaside ); + db->lookaside.bDisable -= pParse->disableLookaside; + db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue; } + pParse->disableLookaside = 0; } /* ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. */ -static int sqlite3Prepare( - sqlite3 *db, /* Database handle. */ +static int tdsqlite3Prepare( + tdsqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ - int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ + u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ Vdbe *pReprepare, /* VM being reprepared */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ char *zErrMsg = 0; /* Error message */ @@ -117174,7 +131140,16 @@ static int sqlite3Prepare( sParse.pReprepare = pReprepare; assert( ppStmt && *ppStmt==0 ); /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */ - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); + + /* For a long-term use prepared statement avoid the use of + ** lookaside memory. + */ + if( prepFlags & SQLITE_PREPARE_PERSISTENT ){ + sParse.disableLookaside++; + DisableLookaside; + } + sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0; /* Check to verify that it is possible to get a read lock on all ** database schemas. The inability to get a read lock indicates that @@ -117189,7 +131164,7 @@ static int sqlite3Prepare( ** the schema change. Disaster would follow. ** ** This thread is currently holding mutexes on all Btrees (because - ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it + ** of the tdsqlite3BtreeEnterAll() in tdsqlite3LockAndPrepare()) so it ** is not possible for another thread to start a new schema change ** while this routine is running. Hence, we do not need to hold ** locks on the schema, we just need to make sure nobody else is @@ -117199,21 +131174,23 @@ static int sqlite3Prepare( ** but it does *not* override schema lock detection, so this all still ** works even if READ_UNCOMMITTED is set. */ - for(i=0; i<db->nDb; i++) { - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - assert( sqlite3BtreeHoldsMutex(pBt) ); - rc = sqlite3BtreeSchemaLocked(pBt); - if( rc ){ - const char *zDb = db->aDb[i].zDbSName; - sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb); - testcase( db->flags & SQLITE_ReadUncommitted ); - goto end_prepare; + if( !db->noSharedCache ){ + for(i=0; i<db->nDb; i++) { + Btree *pBt = db->aDb[i].pBt; + if( pBt ){ + assert( tdsqlite3BtreeHoldsMutex(pBt) ); + rc = tdsqlite3BtreeSchemaLocked(pBt); + if( rc ){ + const char *zDb = db->aDb[i].zDbSName; + tdsqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb); + testcase( db->flags & SQLITE_ReadUncommit ); + goto end_prepare; + } } } } - sqlite3VtabUnlockList(db); + tdsqlite3VtabUnlockList(db); sParse.db = db; if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){ @@ -117222,154 +131199,138 @@ static int sqlite3Prepare( testcase( nBytes==mxLen ); testcase( nBytes==mxLen+1 ); if( nBytes>mxLen ){ - sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long"); - rc = sqlite3ApiExit(db, SQLITE_TOOBIG); + tdsqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long"); + rc = tdsqlite3ApiExit(db, SQLITE_TOOBIG); goto end_prepare; } - zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes); + zSqlCopy = tdsqlite3DbStrNDup(db, zSql, nBytes); if( zSqlCopy ){ - sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg); + tdsqlite3RunParser(&sParse, zSqlCopy, &zErrMsg); sParse.zTail = &zSql[sParse.zTail-zSqlCopy]; - sqlite3DbFree(db, zSqlCopy); + tdsqlite3DbFree(db, zSqlCopy); }else{ sParse.zTail = &zSql[nBytes]; } }else{ - sqlite3RunParser(&sParse, zSql, &zErrMsg); + tdsqlite3RunParser(&sParse, zSql, &zErrMsg); } assert( 0==sParse.nQueryLoop ); - if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK; + if( sParse.rc==SQLITE_DONE ){ + sParse.rc = SQLITE_OK; + } if( sParse.checkSchema ){ schemaIsValid(&sParse); } - if( db->mallocFailed ){ - sParse.rc = SQLITE_NOMEM_BKPT; - } if( pzTail ){ *pzTail = sParse.zTail; } - rc = sParse.rc; - -#ifndef SQLITE_OMIT_EXPLAIN - if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){ - static const char * const azColName[] = { - "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", - "selectid", "order", "from", "detail" - }; - int iFirst, mx; - if( sParse.explain==2 ){ - sqlite3VdbeSetNumCols(sParse.pVdbe, 4); - iFirst = 8; - mx = 12; - }else{ - sqlite3VdbeSetNumCols(sParse.pVdbe, 8); - iFirst = 0; - mx = 8; - } - for(i=iFirst; i<mx; i++){ - sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME, - azColName[i], SQLITE_STATIC); - } - } -#endif if( db->init.busy==0 ){ - Vdbe *pVdbe = sParse.pVdbe; - sqlite3VdbeSetSql(pVdbe, zSql, (int)(sParse.zTail-zSql), saveSqlFlag); + tdsqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags); } - if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){ - sqlite3VdbeFinalize(sParse.pVdbe); + if( db->mallocFailed ){ + sParse.rc = SQLITE_NOMEM_BKPT; + } + rc = sParse.rc; + if( rc!=SQLITE_OK ){ + if( sParse.pVdbe ) tdsqlite3VdbeFinalize(sParse.pVdbe); assert(!(*ppStmt)); }else{ - *ppStmt = (sqlite3_stmt*)sParse.pVdbe; + *ppStmt = (tdsqlite3_stmt*)sParse.pVdbe; } if( zErrMsg ){ - sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg); - sqlite3DbFree(db, zErrMsg); + tdsqlite3ErrorWithMsg(db, rc, "%s", zErrMsg); + tdsqlite3DbFree(db, zErrMsg); }else{ - sqlite3Error(db, rc); + tdsqlite3Error(db, rc); } /* Delete any TriggerPrg structures allocated while parsing this statement. */ while( sParse.pTriggerPrg ){ TriggerPrg *pT = sParse.pTriggerPrg; sParse.pTriggerPrg = pT->pNext; - sqlite3DbFree(db, pT); + tdsqlite3DbFree(db, pT); } end_prepare: - sqlite3ParserReset(&sParse); - rc = sqlite3ApiExit(db, rc); - assert( (rc&db->errMask)==rc ); + tdsqlite3ParserReset(&sParse); return rc; } -static int sqlite3LockAndPrepare( - sqlite3 *db, /* Database handle. */ +static int tdsqlite3LockAndPrepare( + tdsqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ - int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ + u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ Vdbe *pOld, /* VM being reprepared */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; + int cnt = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; #endif *ppStmt = 0; - if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ + if( !tdsqlite3SafetyCheckOk(db)||zSql==0 ){ return SQLITE_MISUSE_BKPT; } - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeEnterAll(db); - rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); - if( rc==SQLITE_SCHEMA ){ - sqlite3_finalize(*ppStmt); - rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail); - } - sqlite3BtreeLeaveAll(db); - sqlite3_mutex_leave(db->mutex); - assert( rc==SQLITE_OK || *ppStmt==0 ); + tdsqlite3_mutex_enter(db->mutex); + tdsqlite3BtreeEnterAll(db); + do{ + /* Make multiple attempts to compile the SQL, until it either succeeds + ** or encounters a permanent error. A schema problem after one schema + ** reset is considered a permanent error. */ + rc = tdsqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail); + assert( rc==SQLITE_OK || *ppStmt==0 ); + }while( rc==SQLITE_ERROR_RETRY + || (rc==SQLITE_SCHEMA && (tdsqlite3ResetOneSchema(db,-1), cnt++)==0) ); + tdsqlite3BtreeLeaveAll(db); + rc = tdsqlite3ApiExit(db, rc); + assert( (rc&db->errMask)==rc ); + tdsqlite3_mutex_leave(db->mutex); return rc; } + /* ** Rerun the compilation of a statement after a schema change. ** ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, ** if the statement cannot be recompiled because another connection has -** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error +** locked the tdsqlite3_master table, return SQLITE_LOCKED. If any other error ** occurs, return SQLITE_SCHEMA. */ -SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){ +SQLITE_PRIVATE int tdsqlite3Reprepare(Vdbe *p){ int rc; - sqlite3_stmt *pNew; + tdsqlite3_stmt *pNew; const char *zSql; - sqlite3 *db; + tdsqlite3 *db; + u8 prepFlags; - assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) ); - zSql = sqlite3_sql((sqlite3_stmt *)p); + assert( tdsqlite3_mutex_held(tdsqlite3VdbeDb(p)->mutex) ); + zSql = tdsqlite3_sql((tdsqlite3_stmt *)p); assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */ - db = sqlite3VdbeDb(p); - assert( sqlite3_mutex_held(db->mutex) ); - rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0); + db = tdsqlite3VdbeDb(p); + assert( tdsqlite3_mutex_held(db->mutex) ); + prepFlags = tdsqlite3VdbePrepareFlags(p); + rc = tdsqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0); if( rc ){ if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); } assert( pNew==0 ); return rc; }else{ assert( pNew!=0 ); } - sqlite3VdbeSwap((Vdbe*)pNew, p); - sqlite3TransferBindings(pNew, (sqlite3_stmt*)p); - sqlite3VdbeResetStepResult((Vdbe*)pNew); - sqlite3VdbeFinalize((Vdbe*)pNew); + tdsqlite3VdbeSwap((Vdbe*)pNew, p); + tdsqlite3TransferBindings(pNew, (tdsqlite3_stmt*)p); + tdsqlite3VdbeResetStepResult((Vdbe*)pNew); + tdsqlite3VdbeFinalize((Vdbe*)pNew); return SQLITE_OK; } @@ -117378,32 +131339,60 @@ SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){ ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by -** sqlite3_step(). In the new version, the original SQL text is retained +** tdsqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ -SQLITE_API int sqlite3_prepare( - sqlite3 *db, /* Database handle. */ +SQLITE_API int tdsqlite3_prepare( + tdsqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; - rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail); + rc = tdsqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } -SQLITE_API int sqlite3_prepare_v2( - sqlite3 *db, /* Database handle. */ +SQLITE_API int tdsqlite3_prepare_v2( + tdsqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; - rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + /* EVIDENCE-OF: R-37923-12173 The tdsqlite3_prepare_v2() interface works + ** exactly the same as tdsqlite3_prepare_v3() with a zero prepFlags + ** parameter. + ** + ** Proof in that the 5th parameter to tdsqlite3LockAndPrepare is 0 */ + rc = tdsqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0, + ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); + return rc; +} +SQLITE_API int tdsqlite3_prepare_v3( + tdsqlite3 *db, /* Database handle. */ + const char *zSql, /* UTF-8 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const char **pzTail /* OUT: End of parsed string */ +){ + int rc; + /* EVIDENCE-OF: R-56861-42673 tdsqlite3_prepare_v3() differs from + ** tdsqlite3_prepare_v2() only in having the extra prepFlags parameter, + ** which is a bit array consisting of zero or more of the + ** SQLITE_PREPARE_* flags. + ** + ** Proof by comparison to the implementation of tdsqlite3_prepare_v2() + ** directly above. */ + rc = tdsqlite3LockAndPrepare(db,zSql,nBytes, + SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK), + 0,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); return rc; } @@ -117412,16 +131401,16 @@ SQLITE_API int sqlite3_prepare_v2( /* ** Compile the UTF-16 encoded SQL statement zSql into a statement handle. */ -static int sqlite3Prepare16( - sqlite3 *db, /* Database handle. */ +static int tdsqlite3Prepare16( + tdsqlite3 *db, /* Database handle. */ const void *zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ - int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ /* This function currently works by first transforming the UTF-16 - ** encoded string to UTF-8, then invoking sqlite3_prepare(). The + ** encoded string to UTF-8, then invoking tdsqlite3_prepare(). The ** tricky bit is figuring out the pointer to return in *pzTail. */ char *zSql8; @@ -117432,7 +131421,7 @@ static int sqlite3Prepare16( if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; #endif *ppStmt = 0; - if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ + if( !tdsqlite3SafetyCheckOk(db)||zSql==0 ){ return SQLITE_MISUSE_BKPT; } if( nBytes>=0 ){ @@ -117441,24 +131430,24 @@ static int sqlite3Prepare16( for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){} nBytes = sz; } - sqlite3_mutex_enter(db->mutex); - zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); + tdsqlite3_mutex_enter(db->mutex); + zSql8 = tdsqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); if( zSql8 ){ - rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8); + rc = tdsqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8); } if( zTail8 && pzTail ){ - /* If sqlite3_prepare returns a tail pointer, we calculate the + /* If tdsqlite3_prepare returns a tail pointer, we calculate the ** equivalent pointer into the UTF-16 string by counting the unicode ** characters between zSql8 and zTail8, and then returning a pointer ** the same number of characters into the UTF-16 string. */ - int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); - *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); + int chars_parsed = tdsqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); + *pzTail = (u8 *)zSql + tdsqlite3Utf16ByteLen(zSql, chars_parsed); } - sqlite3DbFree(db, zSql8); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + tdsqlite3DbFree(db, zSql8); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -117466,31 +131455,46 @@ static int sqlite3Prepare16( ** Two versions of the official API. Legacy and new use. In the legacy ** version, the original SQL text is not saved in the prepared statement ** and so if a schema change occurs, SQLITE_SCHEMA is returned by -** sqlite3_step(). In the new version, the original SQL text is retained +** tdsqlite3_step(). In the new version, the original SQL text is retained ** and the statement is automatically recompiled if an schema change ** occurs. */ -SQLITE_API int sqlite3_prepare16( - sqlite3 *db, /* Database handle. */ +SQLITE_API int tdsqlite3_prepare16( + tdsqlite3 *db, /* Database handle. */ const void *zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ int rc; - rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); + rc = tdsqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } -SQLITE_API int sqlite3_prepare16_v2( - sqlite3 *db, /* Database handle. */ +SQLITE_API int tdsqlite3_prepare16_v2( + tdsqlite3 *db, /* Database handle. */ const void *zSql, /* UTF-16 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ int rc; - rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail); + rc = tdsqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail); + assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ + return rc; +} +SQLITE_API int tdsqlite3_prepare16_v3( + tdsqlite3 *db, /* Database handle. */ + const void *zSql, /* UTF-16 encoded SQL statement. */ + int nBytes, /* Length of zSql in bytes. */ + unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ + tdsqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ + const void **pzTail /* OUT: End of parsed string */ +){ + int rc; + rc = tdsqlite3Prepare16(db,zSql,nBytes, + SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK), + ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } @@ -117519,12 +131523,11 @@ SQLITE_API int sqlite3_prepare16_v2( ** Trace output macros */ #if SELECTTRACE_ENABLED -/***/ int sqlite3SelectTrace = 0; +/***/ int tdsqlite3SelectTrace = 0; # define SELECTTRACE(K,P,S,X) \ - if(sqlite3SelectTrace&(K)) \ - sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\ - (S)->zSelName,(S)),\ - sqlite3DebugPrintf X + if(tdsqlite3SelectTrace&(K)) \ + tdsqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\ + tdsqlite3DebugPrintf X #else # define SELECTTRACE(K,P,S,X) #endif @@ -117546,6 +131549,20 @@ struct DistinctCtx { /* ** An instance of the following object is used to record information about ** the ORDER BY (or GROUP BY) clause of query is being coded. +** +** The aDefer[] array is used by the sorter-references optimization. For +** example, assuming there is no index that can be used for the ORDER BY, +** for the query: +** +** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10; +** +** it may be more efficient to add just the "a" values to the sorter, and +** retrieve the associated "bigblob" values directly from table t1 as the +** 10 smallest "a" values are extracted from the sorter. +** +** When the sorter-reference optimization is used, there is one entry in the +** aDefer[] array for each database table that may be read as values are +** extracted from the sorter. */ typedef struct SortCtx SortCtx; struct SortCtx { @@ -117556,28 +131573,45 @@ struct SortCtx { int labelBkOut; /* Start label for the block-output subroutine */ int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ int labelDone; /* Jump here when done, ex: LIMIT reached */ + int labelOBLopt; /* Jump here when sorter is full */ u8 sortFlags; /* Zero or more SORTFLAG_* bits */ - u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */ +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + u8 nDefer; /* Number of valid entries in aDefer[] */ + struct DeferredCsr { + Table *pTab; /* Table definition */ + int iCsr; /* Cursor number for table */ + int nKey; /* Number of PK columns for table pTab (>=1) */ + } aDefer[4]; +#endif + struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */ }; #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ /* ** Delete all the content of a Select structure. Deallocate the structure -** itself only if bFree is true. +** itself depending on the value of bFree +** +** If bFree==1, call tdsqlite3DbFree() on the p object. +** If bFree==0, Leave the first Select object unfreed */ -static void clearSelect(sqlite3 *db, Select *p, int bFree){ +static void clearSelect(tdsqlite3 *db, Select *p, int bFree){ while( p ){ Select *pPrior = p->pPrior; - sqlite3ExprListDelete(db, p->pEList); - sqlite3SrcListDelete(db, p->pSrc); - sqlite3ExprDelete(db, p->pWhere); - sqlite3ExprListDelete(db, p->pGroupBy); - sqlite3ExprDelete(db, p->pHaving); - sqlite3ExprListDelete(db, p->pOrderBy); - sqlite3ExprDelete(db, p->pLimit); - sqlite3ExprDelete(db, p->pOffset); - if( p->pWith ) sqlite3WithDelete(db, p->pWith); - if( bFree ) sqlite3DbFree(db, p); + tdsqlite3ExprListDelete(db, p->pEList); + tdsqlite3SrcListDelete(db, p->pSrc); + tdsqlite3ExprDelete(db, p->pWhere); + tdsqlite3ExprListDelete(db, p->pGroupBy); + tdsqlite3ExprDelete(db, p->pHaving); + tdsqlite3ExprListDelete(db, p->pOrderBy); + tdsqlite3ExprDelete(db, p->pLimit); +#ifndef SQLITE_OMIT_WINDOWFUNC + if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){ + tdsqlite3WindowListDelete(db, p->pWinDefn); + } + assert( p->pWin==0 ); +#endif + if( OK_IF_ALWAYS_TRUE(p->pWith) ) tdsqlite3WithDelete(db, p->pWith); + if( bFree ) tdsqlite3DbFreeNN(db, p); p = pPrior; bFree = 1; } @@ -117586,7 +131620,7 @@ static void clearSelect(sqlite3 *db, Select *p, int bFree){ /* ** Initialize a SelectDest structure. */ -SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ +SQLITE_PRIVATE void tdsqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ pDest->eDest = (u8)eDest; pDest->iSDParm = iParm; pDest->zAffSdst = 0; @@ -117599,7 +131633,7 @@ SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iPar ** Allocate a new Select structure and return a pointer to that ** structure. */ -SQLITE_PRIVATE Select *sqlite3SelectNew( +SQLITE_PRIVATE Select *tdsqlite3SelectNew( Parse *pParse, /* Parsing context */ ExprList *pEList, /* which columns to include in the result */ SrcList *pSrc, /* the FROM clause -- which tables to scan */ @@ -117608,32 +131642,29 @@ SQLITE_PRIVATE Select *sqlite3SelectNew( Expr *pHaving, /* the HAVING clause */ ExprList *pOrderBy, /* the ORDER BY clause */ u32 selFlags, /* Flag parameters, such as SF_Distinct */ - Expr *pLimit, /* LIMIT value. NULL means not used */ - Expr *pOffset /* OFFSET value. NULL means no offset */ + Expr *pLimit /* LIMIT value. NULL means not used */ ){ Select *pNew; Select standin; - sqlite3 *db = pParse->db; - pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); + pNew = tdsqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) ); if( pNew==0 ){ - assert( db->mallocFailed ); + assert( pParse->db->mallocFailed ); pNew = &standin; } if( pEList==0 ){ - pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0)); + pEList = tdsqlite3ExprListAppend(pParse, 0, + tdsqlite3Expr(pParse->db,TK_ASTERISK,0)); } pNew->pEList = pEList; pNew->op = TK_SELECT; pNew->selFlags = selFlags; pNew->iLimit = 0; pNew->iOffset = 0; -#if SELECTTRACE_ENABLED - pNew->zSelName[0] = 0; -#endif + pNew->selId = ++pParse->nSelect; pNew->addrOpenEphm[0] = -1; pNew->addrOpenEphm[1] = -1; pNew->nSelectRow = 0; - if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc)); + if( pSrc==0 ) pSrc = tdsqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); pNew->pSrc = pSrc; pNew->pWhere = pWhere; pNew->pGroupBy = pGroupBy; @@ -117642,11 +131673,13 @@ SQLITE_PRIVATE Select *sqlite3SelectNew( pNew->pPrior = 0; pNew->pNext = 0; pNew->pLimit = pLimit; - pNew->pOffset = pOffset; pNew->pWith = 0; - assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 ); - if( db->mallocFailed ) { - clearSelect(db, pNew, pNew!=&standin); +#ifndef SQLITE_OMIT_WINDOWFUNC + pNew->pWin = 0; + pNew->pWinDefn = 0; +#endif + if( pParse->db->mallocFailed ) { + clearSelect(pParse->db, pNew, pNew!=&standin); pNew = 0; }else{ assert( pNew->pSrc!=0 || pParse->nErr>0 ); @@ -117655,23 +131688,27 @@ SQLITE_PRIVATE Select *sqlite3SelectNew( return pNew; } -#if SELECTTRACE_ENABLED + /* -** Set the name of a Select object +** Delete the given Select structure and all of its substructures. */ -SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){ - if( p && zName ){ - sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName); - } +SQLITE_PRIVATE void tdsqlite3SelectDelete(tdsqlite3 *db, Select *p){ + if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1); } -#endif - /* -** Delete the given Select structure and all of its substructures. +** Delete all the substructure for p, but keep p allocated. Redefine +** p to be a single SELECT where every column of the result set has a +** value of NULL. */ -SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){ - if( p ) clearSelect(db, p, 1); +SQLITE_PRIVATE void tdsqlite3SelectReset(Parse *pParse, Select *p){ + if( ALWAYS(p) ){ + clearSelect(pParse->db, p, 0); + memset(&p->iLimit, 0, sizeof(Select) - offsetof(Select,iLimit)); + p->pEList = tdsqlite3ExprListAppend(pParse, 0, + tdsqlite3ExprAlloc(pParse->db,TK_NULL,0,0)); + p->pSrc = tdsqlite3DbMallocZero(pParse->db, sizeof(SrcList)); + } } /* @@ -117699,7 +131736,7 @@ static Select *findRightmost(Select *p){ ** If an illegal or unsupported join type is seen, then still return ** a join type, but put an error in the pParse structure. */ -SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ +SQLITE_PRIVATE int tdsqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ int jointype = 0; Token *apAll[3]; Token *p; @@ -117726,7 +131763,7 @@ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *p p = apAll[i]; for(j=0; j<ArraySize(aKeyword); j++){ if( p->n==aKeyword[j].nChar - && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ + && tdsqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ jointype |= aKeyword[j].code; break; } @@ -117744,12 +131781,12 @@ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *p const char *zSp = " "; assert( pB!=0 ); if( pC==0 ){ zSp++; } - sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " + tdsqlite3ErrorMsg(pParse, "unknown or unsupported join type: " "%T %T%s%T", pA, pB, zSp, pC); jointype = JT_INNER; }else if( (jointype & JT_OUTER)!=0 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "RIGHT and FULL OUTER JOINs are not currently supported"); jointype = JT_INNER; } @@ -117763,7 +131800,7 @@ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *p static int columnIndex(Table *pTab, const char *zCol){ int i; for(i=0; i<pTab->nCol; i++){ - if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; + if( tdsqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; } return -1; } @@ -117782,7 +131819,8 @@ static int tableAndColumnIndex( int N, /* Number of tables in pSrc->a[] to search */ const char *zCol, /* Name of the column we are looking for */ int *piTab, /* Write index of pSrc->a[] here */ - int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ + int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ + int bIgnoreHidden /* True to ignore hidden columns */ ){ int i; /* For looping over tables in pSrc */ int iCol; /* Index of column matching zCol */ @@ -117790,7 +131828,9 @@ static int tableAndColumnIndex( assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ for(i=0; i<N; i++){ iCol = columnIndex(pSrc->a[i].pTab, zCol); - if( iCol>=0 ){ + if( iCol>=0 + && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0) + ){ if( piTab ){ *piTab = i; *piCol = iCol; @@ -117822,7 +131862,7 @@ static void addWhereTerm( int isOuterJoin, /* True if this is an OUTER join */ Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Expr *pE1; Expr *pE2; Expr *pEq; @@ -117832,17 +131872,17 @@ static void addWhereTerm( assert( pSrc->a[iLeft].pTab ); assert( pSrc->a[iRight].pTab ); - pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); - pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); + pE1 = tdsqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); + pE2 = tdsqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); - pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0); + pEq = tdsqlite3PExpr(pParse, TK_EQ, pE1, pE2); if( pEq && isOuterJoin ){ ExprSetProperty(pEq, EP_FromJoin); assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(pEq, EP_NoReduce); pEq->iRightJoinTable = (i16)pE2->iTable; } - *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); + *ppWhere = tdsqlite3ExprAnd(pParse, *ppWhere, pEq); } /* @@ -117871,7 +131911,7 @@ static void addWhereTerm( ** after the t1 loop and rows with t1.x!=5 will never appear in ** the output, which is incorrect. */ -static void setJoinExpr(Expr *p, int iTable){ +SQLITE_PRIVATE void tdsqlite3SetJoinExpr(Expr *p, int iTable){ while( p ){ ExprSetProperty(p, EP_FromJoin); assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); @@ -117880,10 +131920,33 @@ static void setJoinExpr(Expr *p, int iTable){ if( p->op==TK_FUNCTION && p->x.pList ){ int i; for(i=0; i<p->x.pList->nExpr; i++){ - setJoinExpr(p->x.pList->a[i].pExpr, iTable); + tdsqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable); } } - setJoinExpr(p->pLeft, iTable); + tdsqlite3SetJoinExpr(p->pLeft, iTable); + p = p->pRight; + } +} + +/* Undo the work of tdsqlite3SetJoinExpr(). In the expression p, convert every +** term that is marked with EP_FromJoin and iRightJoinTable==iTable into +** an ordinary term that omits the EP_FromJoin mark. +** +** This happens when a LEFT JOIN is simplified into an ordinary JOIN. +*/ +static void unsetJoinExpr(Expr *p, int iTable){ + while( p ){ + if( ExprHasProperty(p, EP_FromJoin) + && (iTable<0 || p->iRightJoinTable==iTable) ){ + ExprClearProperty(p, EP_FromJoin); + } + if( p->op==TK_FUNCTION && p->x.pList ){ + int i; + for(i=0; i<p->x.pList->nExpr; i++){ + unsetJoinExpr(p->x.pList->a[i].pExpr, iTable); + } + } + unsetJoinExpr(p->pLeft, iTable); p = p->pRight; } } @@ -117912,11 +131975,10 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ pLeft = &pSrc->a[0]; pRight = &pLeft[1]; for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ - Table *pLeftTab = pLeft->pTab; Table *pRightTab = pRight->pTab; int isOuter; - if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; + if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue; isOuter = (pRight->fg.jointype & JT_OUTER)!=0; /* When the NATURAL keyword is present, add WHERE clause terms for @@ -117924,7 +131986,7 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ */ if( pRight->fg.jointype & JT_NATURAL ){ if( pRight->pOn || pRight->pUsing ){ - sqlite3ErrorMsg(pParse, "a NATURAL join may not have " + tdsqlite3ErrorMsg(pParse, "a NATURAL join may not have " "an ON or USING clause", 0); return 1; } @@ -117933,10 +131995,11 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ int iLeft; /* Matching left table */ int iLeftCol; /* Matching column in the left table */ + if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue; zName = pRightTab->aCol[j].zName; - if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ + if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 1) ){ addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, - isOuter, &p->pWhere); + isOuter, &p->pWhere); } } } @@ -117944,7 +132007,7 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ /* Disallow both ON and USING clauses in the same join */ if( pRight->pOn && pRight->pUsing ){ - sqlite3ErrorMsg(pParse, "cannot have both ON and USING " + tdsqlite3ErrorMsg(pParse, "cannot have both ON and USING " "clauses in the same join"); return 1; } @@ -117953,8 +132016,8 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ ** an AND operator. */ if( pRight->pOn ){ - if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); - p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); + if( isOuter ) tdsqlite3SetJoinExpr(pRight->pOn, pRight->iCursor); + p->pWhere = tdsqlite3ExprAnd(pParse, p->pWhere, pRight->pOn); pRight->pOn = 0; } @@ -117976,9 +132039,9 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ zName = pList->a[j].zName; iRightCol = columnIndex(pRightTab, zName); if( iRightCol<0 - || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) + || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 0) ){ - sqlite3ErrorMsg(pParse, "cannot join using column %s - column " + tdsqlite3ErrorMsg(pParse, "cannot join using column %s - column " "not present in both tables", zName); return 1; } @@ -117990,13 +132053,61 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ return 0; } -/* Forward reference */ -static KeyInfo *keyInfoFromExprList( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* Form the KeyInfo object from this ExprList */ - int iStart, /* Begin with this column of pList */ - int nExtra /* Add this many extra columns to the end */ -); +/* +** An instance of this object holds information (beyond pParse and pSelect) +** needed to load the next result row that is to be added to the sorter. +*/ +typedef struct RowLoadInfo RowLoadInfo; +struct RowLoadInfo { + int regResult; /* Store results in array of registers here */ + u8 ecelFlags; /* Flag argument to ExprCodeExprList() */ +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + ExprList *pExtra; /* Extra columns needed by sorter refs */ + int regExtraResult; /* Where to load the extra columns */ +#endif +}; + +/* +** This routine does the work of loading query data into an array of +** registers so that it can be added to the sorter. +*/ +static void innerLoopLoadRow( + Parse *pParse, /* Statement under construction */ + Select *pSelect, /* The query being coded */ + RowLoadInfo *pInfo /* Info needed to complete the row load */ +){ + tdsqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult, + 0, pInfo->ecelFlags); +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + if( pInfo->pExtra ){ + tdsqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0); + tdsqlite3ExprListDelete(pParse->db, pInfo->pExtra); + } +#endif +} + +/* +** Code the OP_MakeRecord instruction that generates the entry to be +** added into the sorter. +** +** Return the register in which the result is stored. +*/ +static int makeSorterRecord( + Parse *pParse, + SortCtx *pSort, + Select *pSelect, + int regBase, + int nBase +){ + int nOBSat = pSort->nOBSat; + Vdbe *v = pParse->pVdbe; + int regOut = ++pParse->nMem; + if( pSort->pDeferredRowLoad ){ + innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad); + } + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut); + return regOut; +} /* ** Generate code that will push the record in registers regData @@ -118008,7 +132119,7 @@ static void pushOntoSorter( Select *pSelect, /* The whole SELECT statement */ int regData, /* First register holding data to be sorted */ int regOrigData, /* First register holding data before packing */ - int nData, /* Number of elements in the data array */ + int nData, /* Number of elements in the regData data array */ int nPrefixReg /* No. of reg prior to regData available for use */ ){ Vdbe *v = pParse->pVdbe; /* Stmt under construction */ @@ -118016,32 +132127,47 @@ static void pushOntoSorter( int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ int regBase; /* Regs for sorter record */ - int regRecord = ++pParse->nMem; /* Assembled sorter record */ + int regRecord = 0; /* Assembled sorter record */ int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ int op; /* Opcode to add sorter record to sorter */ int iLimit; /* LIMIT counter */ + int iSkip = 0; /* End of the sorter insert loop */ assert( bSeq==0 || bSeq==1 ); - assert( nData==1 || regData==regOrigData ); + + /* Three cases: + ** (1) The data to be sorted has already been packed into a Record + ** by a prior OP_MakeRecord. In this case nData==1 and regData + ** will be completely unrelated to regOrigData. + ** (2) All output columns are included in the sort record. In that + ** case regData==regOrigData. + ** (3) Some output columns are omitted from the sort record due to + ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the + ** SQLITE_ECEL_OMITREF optimization, or due to the + ** SortCtx.pDeferredRowLoad optimiation. In any of these cases + ** regOrigData is 0 to prevent this routine from trying to copy + ** values that might not yet exist. + */ + assert( nData==1 || regData==regOrigData || regOrigData==0 ); + if( nPrefixReg ){ assert( nPrefixReg==nExpr+bSeq ); - regBase = regData - nExpr - bSeq; + regBase = regData - nPrefixReg; }else{ regBase = pParse->nMem + 1; pParse->nMem += nBase; } assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; - pSort->labelDone = sqlite3VdbeMakeLabel(v); - sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, - SQLITE_ECEL_DUP|SQLITE_ECEL_REF); + pSort->labelDone = tdsqlite3VdbeMakeLabel(pParse); + tdsqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, + SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); if( bSeq ){ - sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); + tdsqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); } - if( nPrefixReg==0 ){ - sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); + if( nPrefixReg==0 && nData>0 ){ + tdsqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord); if( nOBSat>0 ){ int regPrevKey; /* The first nOBSat columns of the previous row */ int addrFirst; /* Address of the OP_IfNot opcode */ @@ -118050,72 +132176,79 @@ static void pushOntoSorter( int nKey; /* Number of sorting key columns, including OP_Sequence */ KeyInfo *pKI; /* Original KeyInfo on the sorter table */ + regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); regPrevKey = pParse->nMem+1; pParse->nMem += pSort->nOBSat; nKey = nExpr - pSort->nOBSat + bSeq; if( bSeq ){ - addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); + addrFirst = tdsqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); }else{ - addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); + addrFirst = tdsqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); } VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); - pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); + tdsqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); + pOp = tdsqlite3VdbeGetOp(v, pSort->addrSortIndex); if( pParse->db->mallocFailed ) return; pOp->p2 = nKey + nData; pKI = pOp->p4.pKeyInfo; - memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */ - sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); - testcase( pKI->nXField>2 ); - pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, - pKI->nXField-1); - addrJmp = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); - pSort->labelBkOut = sqlite3VdbeMakeLabel(v); + memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */ + tdsqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); + testcase( pKI->nAllField > pKI->nKeyField+2 ); + pOp->p4.pKeyInfo = tdsqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat, + pKI->nAllField-pKI->nKeyField-1); + pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */ + addrJmp = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); + pSort->labelBkOut = tdsqlite3VdbeMakeLabel(pParse); pSort->regReturn = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); - sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); + tdsqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); + tdsqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); if( iLimit ){ - sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); + tdsqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); VdbeCoverage(v); } - sqlite3VdbeJumpHere(v, addrFirst); - sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); - sqlite3VdbeJumpHere(v, addrJmp); + tdsqlite3VdbeJumpHere(v, addrFirst); + tdsqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); + tdsqlite3VdbeJumpHere(v, addrJmp); + } + if( iLimit ){ + /* At this point the values for the new sorter entry are stored + ** in an array of registers. They need to be composed into a record + ** and inserted into the sorter if either (a) there are currently + ** less than LIMIT+OFFSET items or (b) the new record is smaller than + ** the largest record currently in the sorter. If (b) is true and there + ** are already LIMIT+OFFSET items in the sorter, delete the largest + ** entry before inserting the new one. This way there are never more + ** than LIMIT+OFFSET items in the sorter. + ** + ** If the new record does not need to be inserted into the sorter, + ** jump to the next iteration of the loop. If the pSort->labelOBLopt + ** value is not zero, then it is a label of where to jump. Otherwise, + ** just bypass the row insert logic. See the header comment on the + ** tdsqlite3WhereOrderByLimitOptLabel() function for additional info. + */ + int iCsr = pSort->iECursor; + tdsqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, tdsqlite3VdbeCurrentAddr(v)+4); + VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_Last, iCsr, 0); + iSkip = tdsqlite3VdbeAddOp4Int(v, OP_IdxLE, + iCsr, 0, regBase+nOBSat, nExpr-nOBSat); + VdbeCoverage(v); + tdsqlite3VdbeAddOp1(v, OP_Delete, iCsr); + } + if( regRecord==0 ){ + regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); } if( pSort->sortFlags & SORTFLAG_UseSorter ){ op = OP_SorterInsert; }else{ op = OP_IdxInsert; } - sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord); - if( iLimit ){ - int addr; - int r1 = 0; - /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit - ** register is initialized with value of LIMIT+OFFSET.) After the sorter - ** fills up, delete the least entry in the sorter after each insert. - ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */ - addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v); - sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor); - if( pSort->bOrderedInnerLoop ){ - r1 = ++pParse->nMem; - sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1); - VdbeComment((v, "seq")); - } - sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor); - if( pSort->bOrderedInnerLoop ){ - /* If the inner loop is driven by an index such that values from - ** the same iteration of the inner loop are in sorted order, then - ** immediately jump to the next iteration of an inner loop if the - ** entry from the current iteration does not fit into the top - ** LIMIT+OFFSET entries of the sorter. */ - int iBrk = sqlite3VdbeCurrentAddr(v) + 2; - sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1); - sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); - VdbeCoverage(v); - } - sqlite3VdbeJumpHere(v, addr); + tdsqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, + regBase+nOBSat, nBase-nOBSat); + if( iSkip ){ + tdsqlite3VdbeChangeP2(v, iSkip, + pSort->labelOBLopt ? pSort->labelOBLopt : tdsqlite3VdbeCurrentAddr(v)); } } @@ -118128,7 +132261,7 @@ static void codeOffset( int iContinue /* Jump here to skip the current record */ ){ if( iOffset>0 ){ - sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); VdbeComment((v, "OFFSET")); } } @@ -118153,27 +132286,108 @@ static void codeDistinct( int r1; v = pParse->pVdbe; - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); - sqlite3ReleaseTempReg(pParse, r1); + r1 = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N); + tdsqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + tdsqlite3ReleaseTempReg(pParse, r1); +} + +#ifdef SQLITE_ENABLE_SORTER_REFERENCES +/* +** This function is called as part of inner-loop generation for a SELECT +** statement with an ORDER BY that is not optimized by an index. It +** determines the expressions, if any, that the sorter-reference +** optimization should be used for. The sorter-reference optimization +** is used for SELECT queries like: +** +** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10 +** +** If the optimization is used for expression "bigblob", then instead of +** storing values read from that column in the sorter records, the PK of +** the row from table t1 is stored instead. Then, as records are extracted from +** the sorter to return to the user, the required value of bigblob is +** retrieved directly from table t1. If the values are very large, this +** can be more efficient than storing them directly in the sorter records. +** +** The ExprList_item.bSorterRef flag is set for each expression in pEList +** for which the sorter-reference optimization should be enabled. +** Additionally, the pSort->aDefer[] array is populated with entries +** for all cursors required to evaluate all selected expressions. Finally. +** output variable (*ppExtra) is set to an expression list containing +** expressions for all extra PK values that should be stored in the +** sorter records. +*/ +static void selectExprDefer( + Parse *pParse, /* Leave any error here */ + SortCtx *pSort, /* Sorter context */ + ExprList *pEList, /* Expressions destined for sorter */ + ExprList **ppExtra /* Expressions to append to sorter record */ +){ + int i; + int nDefer = 0; + ExprList *pExtra = 0; + for(i=0; i<pEList->nExpr; i++){ + struct ExprList_item *pItem = &pEList->a[i]; + if( pItem->u.x.iOrderByCol==0 ){ + Expr *pExpr = pItem->pExpr; + Table *pTab = pExpr->y.pTab; + if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab) + && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF) + ){ + int j; + for(j=0; j<nDefer; j++){ + if( pSort->aDefer[j].iCsr==pExpr->iTable ) break; + } + if( j==nDefer ){ + if( nDefer==ArraySize(pSort->aDefer) ){ + continue; + }else{ + int nKey = 1; + int k; + Index *pPk = 0; + if( !HasRowid(pTab) ){ + pPk = tdsqlite3PrimaryKeyIndex(pTab); + nKey = pPk->nKeyCol; + } + for(k=0; k<nKey; k++){ + Expr *pNew = tdsqlite3PExpr(pParse, TK_COLUMN, 0, 0); + if( pNew ){ + pNew->iTable = pExpr->iTable; + pNew->y.pTab = pExpr->y.pTab; + pNew->iColumn = pPk ? pPk->aiColumn[k] : -1; + pExtra = tdsqlite3ExprListAppend(pParse, pExtra, pNew); + } + } + pSort->aDefer[nDefer].pTab = pExpr->y.pTab; + pSort->aDefer[nDefer].iCsr = pExpr->iTable; + pSort->aDefer[nDefer].nKey = nKey; + nDefer++; + } + } + pItem->bSorterRef = 1; + } + } + } + pSort->nDefer = (u8)nDefer; + *ppExtra = pExtra; } +#endif /* ** This routine generates the code for the inside of the inner loop ** of a SELECT. ** -** If srcTab is negative, then the pEList expressions +** If srcTab is negative, then the p->pEList expressions ** are evaluated in order to get the data for this row. If srcTab is -** zero or more, then data is pulled from srcTab and pEList is used only -** to get number columns and the datatype for each column. +** zero or more, then data is pulled from srcTab and p->pEList is used only +** to get the number of columns and the collation sequence for each column. */ static void selectInnerLoop( Parse *pParse, /* The parser context */ Select *p, /* The complete select statement being coded */ - ExprList *pEList, /* List of values being extracted */ - int srcTab, /* Pull data from this table */ + int srcTab, /* Pull data from this table if non-negative */ SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ SelectDest *pDest, /* How to dispose of the results */ @@ -118182,15 +132396,23 @@ static void selectInnerLoop( ){ Vdbe *v = pParse->pVdbe; int i; - int hasDistinct; /* True if the DISTINCT keyword is present */ - int regResult; /* Start of memory holding result set */ + int hasDistinct; /* True if the DISTINCT keyword is present */ int eDest = pDest->eDest; /* How to dispose of results */ int iParm = pDest->iSDParm; /* First argument to disposal method */ int nResultCol; /* Number of result columns */ int nPrefixReg = 0; /* Number of extra registers before regResult */ + RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */ + + /* Usually, regResult is the first cell in an array of memory cells + ** containing the current result row. In this case regOrig is set to the + ** same value. However, if the results are being sent to the sorter, the + ** values for any expressions that are also part of the sort-key are omitted + ** from this array. In this case regOrig is set to zero. */ + int regResult; /* Start of memory holding current results */ + int regOrig; /* Start of memory holding full result (or 0) */ assert( v ); - assert( pEList!=0 ); + assert( p->pEList!=0 ); hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; if( pSort && pSort->pOrderBy==0 ) pSort = 0; if( pSort==0 && !hasDistinct ){ @@ -118200,7 +132422,7 @@ static void selectInnerLoop( /* Pull the requested columns. */ - nResultCol = pEList->nExpr; + nResultCol = p->pEList->nExpr; if( pDest->iSdst==0 ){ if( pSort ){ @@ -118219,23 +132441,96 @@ static void selectInnerLoop( pParse->nMem += nResultCol; } pDest->nSdst = nResultCol; - regResult = pDest->iSdst; + regOrig = regResult = pDest->iSdst; if( srcTab>=0 ){ for(i=0; i<nResultCol; i++){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); - VdbeComment((v, "%s", pEList->a[i].zName)); + tdsqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); + VdbeComment((v, "%s", p->pEList->a[i].zEName)); } }else if( eDest!=SRT_Exists ){ +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + ExprList *pExtra = 0; +#endif /* If the destination is an EXISTS(...) expression, the actual ** values returned by the SELECT are not required. */ - u8 ecelFlags; + u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */ + ExprList *pEList; if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ ecelFlags = SQLITE_ECEL_DUP; }else{ ecelFlags = 0; } - sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags); + if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ + /* For each expression in p->pEList that is a copy of an expression in + ** the ORDER BY clause (pSort->pOrderBy), set the associated + ** iOrderByCol value to one more than the index of the ORDER BY + ** expression within the sort-key that pushOntoSorter() will generate. + ** This allows the p->pEList field to be omitted from the sorted record, + ** saving space and CPU cycles. */ + ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); + + for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){ + int j; + if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ + p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; + } + } +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + selectExprDefer(pParse, pSort, p->pEList, &pExtra); + if( pExtra && pParse->db->mallocFailed==0 ){ + /* If there are any extra PK columns to add to the sorter records, + ** allocate extra memory cells and adjust the OpenEphemeral + ** instruction to account for the larger records. This is only + ** required if there are one or more WITHOUT ROWID tables with + ** composite primary keys in the SortCtx.aDefer[] array. */ + VdbeOp *pOp = tdsqlite3VdbeGetOp(v, pSort->addrSortIndex); + pOp->p2 += (pExtra->nExpr - pSort->nDefer); + pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer); + pParse->nMem += pExtra->nExpr; + } +#endif + + /* Adjust nResultCol to account for columns that are omitted + ** from the sorter by the optimizations in this branch */ + pEList = p->pEList; + for(i=0; i<pEList->nExpr; i++){ + if( pEList->a[i].u.x.iOrderByCol>0 +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + || pEList->a[i].bSorterRef +#endif + ){ + nResultCol--; + regOrig = 0; + } + } + + testcase( regOrig ); + testcase( eDest==SRT_Set ); + testcase( eDest==SRT_Mem ); + testcase( eDest==SRT_Coroutine ); + testcase( eDest==SRT_Output ); + assert( eDest==SRT_Set || eDest==SRT_Mem + || eDest==SRT_Coroutine || eDest==SRT_Output ); + } + sRowLoadInfo.regResult = regResult; + sRowLoadInfo.ecelFlags = ecelFlags; +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + sRowLoadInfo.pExtra = pExtra; + sRowLoadInfo.regExtraResult = regResult + nResultCol; + if( pExtra ) nResultCol += pExtra->nExpr; +#endif + if( p->iLimit + && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 + && nPrefixReg>0 + ){ + assert( pSort!=0 ); + assert( hasDistinct==0 ); + pSort->pDeferredRowLoad = &sRowLoadInfo; + regOrig = 0; + }else{ + innerLoopLoadRow(pParse, p, &sRowLoadInfo); + } } /* If the DISTINCT keyword was present on the SELECT statement @@ -118259,32 +132554,33 @@ static void selectInnerLoop( ** fail on the first iteration of the loop even if the first ** row is all NULLs. */ - sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); - pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); + tdsqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); + pOp = tdsqlite3VdbeGetOp(v, pDistinct->addrTnct); pOp->opcode = OP_Null; pOp->p1 = 1; pOp->p2 = regPrev; + pOp = 0; /* Ensure pOp is not used after tdsqlite3VdbeAddOp() */ - iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; + iJump = tdsqlite3VdbeCurrentAddr(v) + nResultCol; for(i=0; i<nResultCol; i++){ - CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr); + CollSeq *pColl = tdsqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr); if( i<nResultCol-1 ){ - sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); + tdsqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); VdbeCoverage(v); }else{ - sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); + tdsqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); VdbeCoverage(v); } - sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); - sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); + tdsqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); + tdsqlite3VdbeChangeP5(v, SQLITE_NULLEQ); } - assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); - sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); + assert( tdsqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); + tdsqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); break; } case WHERE_DISTINCT_UNIQUE: { - sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); + tdsqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); break; } @@ -118307,10 +132603,10 @@ static void selectInnerLoop( #ifndef SQLITE_OMIT_COMPOUND_SELECT case SRT_Union: { int r1; - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); - sqlite3ReleaseTempReg(pParse, r1); + r1 = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); + tdsqlite3ReleaseTempReg(pParse, r1); break; } @@ -118319,7 +132615,7 @@ static void selectInnerLoop( ** the temporary table iParm. */ case SRT_Except: { - sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); + tdsqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); break; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ @@ -118330,12 +132626,12 @@ static void selectInnerLoop( case SRT_DistFifo: case SRT_Table: case SRT_EphemTab: { - int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); + int r1 = tdsqlite3GetTempRange(pParse, nPrefixReg+1); testcase( eDest==SRT_Table ); testcase( eDest==SRT_EphemTab ); testcase( eDest==SRT_Fifo ); testcase( eDest==SRT_DistFifo ); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); #ifndef SQLITE_OMIT_CTE if( eDest==SRT_DistFifo ){ /* If the destination is DistFifo, then cursor (iParm+1) is open @@ -118343,23 +132639,24 @@ static void selectInnerLoop( ** in the index, do not write it to the output. If not, add the ** current row to the index and proceed with writing it to the ** output table as well. */ - int addr = sqlite3VdbeCurrentAddr(v) + 4; - sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); + int addr = tdsqlite3VdbeCurrentAddr(v) + 4; + tdsqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); assert( pSort==0 ); } #endif if( pSort ){ - pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg); + assert( regResult==regOrig ); + pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg); }else{ - int r2 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); - sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3ReleaseTempReg(pParse, r2); + int r2 = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); + tdsqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); + tdsqlite3VdbeChangeP5(v, OPFLAG_APPEND); + tdsqlite3ReleaseTempReg(pParse, r2); } - sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); + tdsqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); break; } @@ -118375,15 +132672,14 @@ static void selectInnerLoop( ** does not matter. But there might be a LIMIT clause, in which ** case the order does matter */ pushOntoSorter( - pParse, pSort, p, regResult, regResult, nResultCol, nPrefixReg); + pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); }else{ - int r1 = sqlite3GetTempReg(pParse); - assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, + int r1 = tdsqlite3GetTempReg(pParse); + assert( tdsqlite3Strlen30(pDest->zAffSdst)==nResultCol ); + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, r1, pDest->zAffSdst, nResultCol); - sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); - sqlite3ReleaseTempReg(pParse, r1); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); + tdsqlite3ReleaseTempReg(pParse, r1); } break; } @@ -118391,7 +132687,7 @@ static void selectInnerLoop( /* If any row exist in the result set, record that fact and abort. */ case SRT_Exists: { - sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); /* The LIMIT clause will terminate the loop for us */ break; } @@ -118401,11 +132697,12 @@ static void selectInnerLoop( ** memory cells and break out of the scan loop. */ case SRT_Mem: { - assert( nResultCol==pDest->nSdst ); if( pSort ){ + assert( nResultCol<=pDest->nSdst ); pushOntoSorter( - pParse, pSort, p, regResult, regResult, nResultCol, nPrefixReg); + pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); }else{ + assert( nResultCol==pDest->nSdst ); assert( regResult==iParm ); /* The LIMIT clause will jump out of the loop for us */ } @@ -118418,13 +132715,12 @@ static void selectInnerLoop( testcase( eDest==SRT_Coroutine ); testcase( eDest==SRT_Output ); if( pSort ){ - pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol, + pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); }else if( eDest==SRT_Coroutine ){ - sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); + tdsqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); }else{ - sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); - sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); } break; } @@ -118445,33 +132741,33 @@ static void selectInnerLoop( pSO = pDest->pOrderBy; assert( pSO ); nKey = pSO->nExpr; - r1 = sqlite3GetTempReg(pParse); - r2 = sqlite3GetTempRange(pParse, nKey+2); + r1 = tdsqlite3GetTempReg(pParse); + r2 = tdsqlite3GetTempRange(pParse, nKey+2); r3 = r2+nKey+1; if( eDest==SRT_DistQueue ){ /* If the destination is DistQueue, then cursor (iParm+1) is open ** on a second ephemeral index that holds all values every previously ** added to the queue. */ - addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, + addrTest = tdsqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, regResult, nResultCol); VdbeCoverage(v); } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); if( eDest==SRT_DistQueue ){ - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); - sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + tdsqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); + tdsqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); } for(i=0; i<nKey; i++){ - sqlite3VdbeAddOp2(v, OP_SCopy, + tdsqlite3VdbeAddOp2(v, OP_SCopy, regResult + pSO->a[i].u.x.iOrderByCol - 1, r2+i); } - sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); - sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); - if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); - sqlite3ReleaseTempReg(pParse, r1); - sqlite3ReleaseTempRange(pParse, r2, nKey+2); + tdsqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); + if( addrTest ) tdsqlite3VdbeJumpHere(v, addrTest); + tdsqlite3ReleaseTempReg(pParse, r1); + tdsqlite3ReleaseTempRange(pParse, r2, nKey+2); break; } #endif /* SQLITE_OMIT_CTE */ @@ -118496,7 +132792,7 @@ static void selectInnerLoop( ** the output for us. */ if( pSort==0 && p->iLimit ){ - sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); } } @@ -118504,19 +132800,19 @@ static void selectInnerLoop( ** Allocate a KeyInfo object sufficient for an index of N key columns and ** X extra columns. */ -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ - int nExtra = (N+X)*(sizeof(CollSeq*)+1); - KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); +SQLITE_PRIVATE KeyInfo *tdsqlite3KeyInfoAlloc(tdsqlite3 *db, int N, int X){ + int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*); + KeyInfo *p = tdsqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); if( p ){ - p->aSortOrder = (u8*)&p->aColl[N+X]; - p->nField = (u16)N; - p->nXField = (u16)X; + p->aSortFlags = (u8*)&p->aColl[N+X]; + p->nKeyField = (u16)N; + p->nAllField = (u16)(N+X); p->enc = ENC(db); p->db = db; p->nRef = 1; memset(&p[1], 0, nExtra); }else{ - sqlite3OomFault(db); + tdsqlite3OomFault(db); } return p; } @@ -118524,18 +132820,18 @@ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ /* ** Deallocate a KeyInfo object */ -SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){ +SQLITE_PRIVATE void tdsqlite3KeyInfoUnref(KeyInfo *p){ if( p ){ assert( p->nRef>0 ); p->nRef--; - if( p->nRef==0 ) sqlite3DbFree(p->db, p); + if( p->nRef==0 ) tdsqlite3DbFreeNN(p->db, p); } } /* ** Make a new pointer to a KeyInfo object */ -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ +SQLITE_PRIVATE KeyInfo *tdsqlite3KeyInfoRef(KeyInfo *p){ if( p ){ assert( p->nRef>0 ); p->nRef++; @@ -118550,7 +132846,7 @@ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ ** ** This routine is used only inside of assert() statements. */ -SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } +SQLITE_PRIVATE int tdsqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } #endif /* SQLITE_DEBUG */ /* @@ -118567,7 +132863,7 @@ SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } ** function is responsible for seeing that this structure is eventually ** freed. */ -static KeyInfo *keyInfoFromExprList( +SQLITE_PRIVATE KeyInfo *tdsqlite3KeyInfoFromExprList( Parse *pParse, /* Parsing context */ ExprList *pList, /* Form the KeyInfo object from this ExprList */ int iStart, /* Begin with this column of pList */ @@ -118576,19 +132872,16 @@ static KeyInfo *keyInfoFromExprList( int nExpr; KeyInfo *pInfo; struct ExprList_item *pItem; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; int i; nExpr = pList->nExpr; - pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); + pInfo = tdsqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); if( pInfo ){ - assert( sqlite3KeyInfoIsWriteable(pInfo) ); + assert( tdsqlite3KeyInfoIsWriteable(pInfo) ); for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ - CollSeq *pColl; - pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); - if( !pColl ) pColl = db->pDfltColl; - pInfo->aColl[i-iStart] = pColl; - pInfo->aSortOrder[i-iStart] = pItem->sortOrder; + pInfo->aColl[i-iStart] = tdsqlite3ExprNNCollSeq(pParse, pItem->pExpr); + pInfo->aSortFlags[i-iStart] = pItem->sortFlags; } } return pInfo; @@ -118620,17 +132913,13 @@ static const char *selectOpName(int id){ ** is determined by the zUsage argument. */ static void explainTempTable(Parse *pParse, const char *zUsage){ - if( pParse->explain==2 ){ - Vdbe *v = pParse->pVdbe; - char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); - sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); - } + ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage)); } /* ** Assign expression b to lvalue a. A second, no-op, version of this macro ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code -** in sqlite3Select() to assign values to structure member variables that +** in tdsqlite3Select() to assign values to structure member variables that ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the ** code with #ifndef directives. */ @@ -118642,42 +132931,6 @@ static void explainTempTable(Parse *pParse, const char *zUsage){ # define explainSetInteger(y,z) #endif -#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) -/* -** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function -** is a no-op. Otherwise, it adds a single row of output to the EQP result, -** where the caption is of one of the two forms: -** -** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" -** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" -** -** where iSub1 and iSub2 are the integers passed as the corresponding -** function parameters, and op is the text representation of the parameter -** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, -** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is -** false, or the second form if it is true. -*/ -static void explainComposite( - Parse *pParse, /* Parse context */ - int op, /* One of TK_UNION, TK_EXCEPT etc. */ - int iSub1, /* Subquery id 1 */ - int iSub2, /* Subquery id 2 */ - int bUseTmp /* True if a temp table was used */ -){ - assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); - if( pParse->explain==2 ){ - Vdbe *v = pParse->pVdbe; - char *zMsg = sqlite3MPrintf( - pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, - bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) - ); - sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); - } -} -#else -/* No-op versions of the explainXXX() functions and macros. */ -# define explainComposite(v,w,x,y,z) -#endif /* ** If the inner loop was generated using a non-null pOrderBy argument, @@ -118694,8 +132947,8 @@ static void generateSortTail( ){ Vdbe *v = pParse->pVdbe; /* The prepared statement */ int addrBreak = pSort->labelDone; /* Jump here to exit loop */ - int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ - int addr; + int addrContinue = tdsqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */ + int addr; /* Top of output loop. Jump for Next. */ int addrOnce = 0; int iTab; ExprList *pOrderBy = pSort->pOrderBy; @@ -118703,69 +132956,134 @@ static void generateSortTail( int iParm = pDest->iSDParm; int regRow; int regRowid; - int nKey; + int iCol; + int nKey; /* Number of key columns in sorter record */ int iSortTab; /* Sorter cursor to read from */ - int nSortData; /* Trailing values to read from sorter */ int i; int bSeq; /* True if sorter record includes seq. no. */ -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS + int nRefKey = 0; struct ExprList_item *aOutEx = p->pEList->a; -#endif assert( addrBreak<0 ); if( pSort->labelBkOut ){ - sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); - sqlite3VdbeGoto(v, addrBreak); - sqlite3VdbeResolveLabel(v, pSort->labelBkOut); + tdsqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); + tdsqlite3VdbeGoto(v, addrBreak); + tdsqlite3VdbeResolveLabel(v, pSort->labelBkOut); + } + +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + /* Open any cursors needed for sorter-reference expressions */ + for(i=0; i<pSort->nDefer; i++){ + Table *pTab = pSort->aDefer[i].pTab; + int iDb = tdsqlite3SchemaToIndex(pParse->db, pTab->pSchema); + tdsqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead); + nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey); } +#endif + iTab = pSort->iECursor; if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ regRowid = 0; regRow = pDest->iSdst; - nSortData = nColumn; }else{ - regRowid = sqlite3GetTempReg(pParse); - regRow = sqlite3GetTempRange(pParse, nColumn); - nSortData = nColumn; + regRowid = tdsqlite3GetTempReg(pParse); + if( eDest==SRT_EphemTab || eDest==SRT_Table ){ + regRow = tdsqlite3GetTempReg(pParse); + nColumn = 0; + }else{ + regRow = tdsqlite3GetTempRange(pParse, nColumn); + } } nKey = pOrderBy->nExpr - pSort->nOBSat; if( pSort->sortFlags & SORTFLAG_UseSorter ){ int regSortOut = ++pParse->nMem; iSortTab = pParse->nTab++; if( pSort->labelBkOut ){ - addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); + addrOnce = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } - sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData); - if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); - addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); + tdsqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, + nKey+1+nColumn+nRefKey); + if( addrOnce ) tdsqlite3VdbeJumpHere(v, addrOnce); + addr = 1 + tdsqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); VdbeCoverage(v); codeOffset(v, p->iOffset, addrContinue); - sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); + tdsqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); bSeq = 0; }else{ - addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); + addr = 1 + tdsqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); codeOffset(v, p->iOffset, addrContinue); iSortTab = iTab; bSeq = 1; } - for(i=0; i<nSortData; i++){ - sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i); - VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan)); + for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){ +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + if( aOutEx[i].bSorterRef ) continue; +#endif + if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++; + } +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + if( pSort->nDefer ){ + int iKey = iCol+1; + int regKey = tdsqlite3GetTempRange(pParse, nRefKey); + + for(i=0; i<pSort->nDefer; i++){ + int iCsr = pSort->aDefer[i].iCsr; + Table *pTab = pSort->aDefer[i].pTab; + int nKey = pSort->aDefer[i].nKey; + + tdsqlite3VdbeAddOp1(v, OP_NullRow, iCsr); + if( HasRowid(pTab) ){ + tdsqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey); + tdsqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, + tdsqlite3VdbeCurrentAddr(v)+1, regKey); + }else{ + int k; + int iJmp; + assert( tdsqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey ); + for(k=0; k<nKey; k++){ + tdsqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k); + } + iJmp = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey); + tdsqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey); + tdsqlite3VdbeAddOp1(v, OP_NullRow, iCsr); + } + } + tdsqlite3ReleaseTempRange(pParse, regKey, nRefKey); + } +#endif + for(i=nColumn-1; i>=0; i--){ +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + if( aOutEx[i].bSorterRef ){ + tdsqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i); + }else +#endif + { + int iRead; + if( aOutEx[i].u.x.iOrderByCol ){ + iRead = aOutEx[i].u.x.iOrderByCol-1; + }else{ + iRead = iCol--; + } + tdsqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); + VdbeComment((v, "%s", aOutEx[i].zEName)); + } } switch( eDest ){ + case SRT_Table: case SRT_EphemTab: { - sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + tdsqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow); + tdsqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); + tdsqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); + tdsqlite3VdbeChangeP5(v, OPFLAG_APPEND); break; } #ifndef SQLITE_OMIT_SUBQUERY case SRT_Set: { - assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, + assert( nColumn==tdsqlite3Strlen30(pDest->zAffSdst) ); + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, pDest->zAffSdst, nColumn); - sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); break; } case SRT_Mem: { @@ -118778,32 +133096,31 @@ static void generateSortTail( testcase( eDest==SRT_Output ); testcase( eDest==SRT_Coroutine ); if( eDest==SRT_Output ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); - sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); }else{ - sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); + tdsqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); } break; } } if( regRowid ){ if( eDest==SRT_Set ){ - sqlite3ReleaseTempRange(pParse, regRow, nColumn); + tdsqlite3ReleaseTempRange(pParse, regRow, nColumn); }else{ - sqlite3ReleaseTempReg(pParse, regRow); + tdsqlite3ReleaseTempReg(pParse, regRow); } - sqlite3ReleaseTempReg(pParse, regRowid); + tdsqlite3ReleaseTempReg(pParse, regRowid); } /* The bottom of the loop */ - sqlite3VdbeResolveLabel(v, addrContinue); + tdsqlite3VdbeResolveLabel(v, addrContinue); if( pSort->sortFlags & SORTFLAG_UseSorter ){ - sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); }else{ - sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); } - if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); - sqlite3VdbeResolveLabel(v, addrBreak); + if( pSort->regReturn ) tdsqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); + tdsqlite3VdbeResolveLabel(v, addrBreak); } /* @@ -118831,23 +133148,23 @@ static void generateSortTail( ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. */ #ifdef SQLITE_ENABLE_COLUMN_METADATA -# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F) +# define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E) #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ -# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F) +# define columnType(A,B,C,D,E) columnTypeImpl(A,B) #endif static const char *columnTypeImpl( NameContext *pNC, +#ifndef SQLITE_ENABLE_COLUMN_METADATA + Expr *pExpr +#else Expr *pExpr, -#ifdef SQLITE_ENABLE_COLUMN_METADATA const char **pzOrigDb, const char **pzOrigTab, - const char **pzOrigCol, + const char **pzOrigCol #endif - u8 *pEstWidth ){ char const *zType = 0; int j; - u8 estWidth = 1; #ifdef SQLITE_ENABLE_COLUMN_METADATA char const *zOrigDb = 0; char const *zOrigTab = 0; @@ -118857,7 +133174,6 @@ static const char *columnTypeImpl( assert( pExpr!=0 ); assert( pNC->pSrcList!=0 ); switch( pExpr->op ){ - case TK_AGG_COLUMN: case TK_COLUMN: { /* The expression is a column. Locate the table the column is being ** extracted from in NameContext.pSrcList. This table may be real @@ -118866,8 +133182,6 @@ static const char *columnTypeImpl( Table *pTab = 0; /* Table structure column is extracted from */ Select *pS = 0; /* Select the column is extracted from */ int iCol = pExpr->iColumn; /* Index of column in pTab */ - testcase( pExpr->op==TK_AGG_COLUMN ); - testcase( pExpr->op==TK_COLUMN ); while( pNC && !pTab ){ SrcList *pTabList = pNC->pSrcList; for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); @@ -118900,52 +133214,48 @@ static const char *columnTypeImpl( break; } - assert( pTab && pExpr->pTab==pTab ); + assert( pTab && pExpr->y.pTab==pTab ); if( pS ){ /* The "table" is actually a sub-select or a view in the FROM clause ** of the SELECT statement. Return the declaration type and origin ** data for the result-set column of the sub-select. */ - if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ + if( iCol>=0 && iCol<pS->pEList->nExpr ){ /* If iCol is less than zero, then the expression requests the ** rowid of the sub-select or view. This expression is legal (see ** test case misc2.2.2) - it always evaluates to NULL. - ** - ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been - ** caught already by name resolution. */ NameContext sNC; Expr *p = pS->pEList->a[iCol].pExpr; sNC.pSrcList = pS->pSrc; sNC.pNext = pNC; sNC.pParse = pNC->pParse; - zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); + zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); } - }else if( pTab->pSchema ){ - /* A real table */ + }else{ + /* A real table or a CTE table */ assert( !pS ); - if( iCol<0 ) iCol = pTab->iPKey; - assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); #ifdef SQLITE_ENABLE_COLUMN_METADATA + if( iCol<0 ) iCol = pTab->iPKey; + assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); if( iCol<0 ){ zType = "INTEGER"; zOrigCol = "rowid"; }else{ zOrigCol = pTab->aCol[iCol].zName; - zType = sqlite3ColumnType(&pTab->aCol[iCol],0); - estWidth = pTab->aCol[iCol].szEst; + zType = tdsqlite3ColumnType(&pTab->aCol[iCol],0); } zOrigTab = pTab->zName; - if( pNC->pParse ){ - int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); + if( pNC->pParse && pTab->pSchema ){ + int iDb = tdsqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; } #else + assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); if( iCol<0 ){ zType = "INTEGER"; }else{ - zType = sqlite3ColumnType(&pTab->aCol[iCol],0); - estWidth = pTab->aCol[iCol].szEst; + zType = tdsqlite3ColumnType(&pTab->aCol[iCol],0); } #endif } @@ -118964,7 +133274,7 @@ static const char *columnTypeImpl( sNC.pSrcList = pS->pSrc; sNC.pNext = pNC; sNC.pParse = pNC->pParse; - zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); + zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); break; } #endif @@ -118978,7 +133288,6 @@ static const char *columnTypeImpl( *pzOrigCol = zOrigCol; } #endif - if( pEstWidth ) *pEstWidth = estWidth; return zType; } @@ -118997,6 +133306,7 @@ static void generateColumnTypes( NameContext sNC; sNC.pSrcList = pTabList; sNC.pParse = pParse; + sNC.pNext = 0; for(i=0; i<pEList->nExpr; i++){ Expr *p = pEList->a[i].pExpr; const char *zType; @@ -119004,37 +133314,66 @@ static void generateColumnTypes( const char *zOrigDb = 0; const char *zOrigTab = 0; const char *zOrigCol = 0; - zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0); + zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); /* The vdbe must make its own copy of the column-type and other ** column specific strings, in case the schema is reset before this ** virtual machine is deleted. */ - sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); - sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); - sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); + tdsqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); + tdsqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); + tdsqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); #else - zType = columnType(&sNC, p, 0, 0, 0, 0); + zType = columnType(&sNC, p, 0, 0, 0); #endif - sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); + tdsqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); } #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ } + /* -** Generate code that will tell the VDBE the names of columns -** in the result set. This information is used to provide the -** azCol[] values in the callback. +** Compute the column names for a SELECT statement. +** +** The only guarantee that SQLite makes about column names is that if the +** column has an AS clause assigning it a name, that will be the name used. +** That is the only documented guarantee. However, countless applications +** developed over the years have made baseless assumptions about column names +** and will break if those assumptions changes. Hence, use extreme caution +** when modifying this routine to avoid breaking legacy. +** +** See Also: tdsqlite3ColumnsFromExprList() +** +** The PRAGMA short_column_names and PRAGMA full_column_names settings are +** deprecated. The default setting is short=ON, full=OFF. 99.9% of all +** applications should operate this way. Nevertheless, we need to support the +** other modes for legacy: +** +** short=OFF, full=OFF: Column name is the text of the expression has it +** originally appears in the SELECT statement. In +** other words, the zSpan of the result expression. +** +** short=ON, full=OFF: (This is the default setting). If the result +** refers directly to a table column, then the +** result column name is just the table column +** name: COLUMN. Otherwise use zSpan. +** +** full=ON, short=ANY: If the result refers directly to a table column, +** then the result column name with the table name +** prefix, ex: TABLE.COLUMN. Otherwise use zSpan. */ static void generateColumnNames( Parse *pParse, /* Parser context */ - SrcList *pTabList, /* List of tables */ - ExprList *pEList /* Expressions defining the result set */ + Select *pSelect /* Generate column names for this SELECT statement */ ){ Vdbe *v = pParse->pVdbe; - int i, j; - sqlite3 *db = pParse->db; - int fullNames, shortNames; + int i; + Table *pTab; + SrcList *pTabList; + ExprList *pEList; + tdsqlite3 *db = pParse->db; + int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */ + int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */ #ifndef SQLITE_OMIT_EXPLAIN /* If this is an EXPLAIN, skip this step */ @@ -119043,29 +133382,33 @@ static void generateColumnNames( } #endif - if( pParse->colNamesSet || db->mallocFailed ) return; + if( pParse->colNamesSet ) return; + /* Column names are determined by the left-most term of a compound select */ + while( pSelect->pPrior ) pSelect = pSelect->pPrior; + SELECTTRACE(1,pParse,pSelect,("generating column names\n")); + pTabList = pSelect->pSrc; + pEList = pSelect->pEList; assert( v!=0 ); assert( pTabList!=0 ); pParse->colNamesSet = 1; - fullNames = (db->flags & SQLITE_FullColNames)!=0; - shortNames = (db->flags & SQLITE_ShortColNames)!=0; - sqlite3VdbeSetNumCols(v, pEList->nExpr); + fullName = (db->flags & SQLITE_FullColNames)!=0; + srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName; + tdsqlite3VdbeSetNumCols(v, pEList->nExpr); for(i=0; i<pEList->nExpr; i++){ - Expr *p; - p = pEList->a[i].pExpr; - if( NEVER(p==0) ) continue; - if( pEList->a[i].zName ){ - char *zName = pEList->a[i].zName; - sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); - }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){ - Table *pTab; + Expr *p = pEList->a[i].pExpr; + + assert( p!=0 ); + assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */ + assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */ + if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){ + /* An AS clause always takes first priority */ + char *zName = pEList->a[i].zEName; + tdsqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); + }else if( srcName && p->op==TK_COLUMN ){ char *zCol; int iCol = p->iColumn; - for(j=0; ALWAYS(j<pTabList->nSrc); j++){ - if( pTabList->a[j].iCursor==p->iTable ) break; - } - assert( j<pTabList->nSrc ); - pTab = pTabList->a[j].pTab; + pTab = p->y.pTab; + assert( pTab!=0 ); if( iCol<0 ) iCol = pTab->iPKey; assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); if( iCol<0 ){ @@ -119073,20 +133416,17 @@ static void generateColumnNames( }else{ zCol = pTab->aCol[iCol].zName; } - if( !shortNames && !fullNames ){ - sqlite3VdbeSetColName(v, i, COLNAME_NAME, - sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); - }else if( fullNames ){ + if( fullName ){ char *zName = 0; - zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); - sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); + zName = tdsqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); + tdsqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); }else{ - sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); + tdsqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); } }else{ - const char *z = pEList->a[i].zSpan; - z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); - sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); + const char *z = pEList->a[i].zEName; + z = z==0 ? tdsqlite3MPrintf(db, "column%d", i+1) : tdsqlite3DbStrDup(db, z); + tdsqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); } } generateColumnTypes(pParse, pTabList, pEList); @@ -119104,28 +133444,37 @@ static void generateColumnNames( ** ** Return SQLITE_OK on success. If a memory allocation error occurs, ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. +** +** The only guarantee that SQLite makes about column names is that if the +** column has an AS clause assigning it a name, that will be the name used. +** That is the only documented guarantee. However, countless applications +** developed over the years have made baseless assumptions about column names +** and will break if those assumptions changes. Hence, use extreme caution +** when modifying this routine to avoid breaking legacy. +** +** See Also: generateColumnNames() */ -SQLITE_PRIVATE int sqlite3ColumnsFromExprList( +SQLITE_PRIVATE int tdsqlite3ColumnsFromExprList( Parse *pParse, /* Parsing context */ ExprList *pEList, /* Expr list from which to derive column names */ i16 *pnCol, /* Write the number of columns here */ Column **paCol /* Write the new column list here */ ){ - sqlite3 *db = pParse->db; /* Database connection */ + tdsqlite3 *db = pParse->db; /* Database connection */ int i, j; /* Loop counters */ u32 cnt; /* Index added to make the name unique */ Column *aCol, *pCol; /* For looping over result columns */ int nCol; /* Number of columns in the result set */ - Expr *p; /* Expression for a single result column */ char *zName; /* Column name */ int nName; /* Size of name in zName[] */ Hash ht; /* Hash table of column names */ - sqlite3HashInit(&ht); + tdsqlite3HashInit(&ht); if( pEList ){ nCol = pEList->nExpr; - aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); + aCol = tdsqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); testcase( aCol==0 ); + if( nCol>32767 ) nCol = 32767; }else{ nCol = 0; aCol = 0; @@ -119137,20 +133486,19 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList( for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){ /* Get an appropriate name for the column */ - p = sqlite3ExprSkipCollate(pEList->a[i].pExpr); - if( (zName = pEList->a[i].zName)!=0 ){ + if( (zName = pEList->a[i].zEName)!=0 && pEList->a[i].eEName==ENAME_NAME ){ /* If the column contains an "AS <name>" phrase, use <name> as the name */ }else{ - Expr *pColExpr = p; /* The expression that is the result column name */ - Table *pTab; /* Table associated with this expression */ + Expr *pColExpr = tdsqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr); while( pColExpr->op==TK_DOT ){ pColExpr = pColExpr->pRight; assert( pColExpr!=0 ); } - if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){ + if( pColExpr->op==TK_COLUMN ){ /* For columns use the column name name */ int iCol = pColExpr->iColumn; - pTab = pColExpr->pTab; + Table *pTab = pColExpr->y.pTab; + assert( pTab!=0 ); if( iCol<0 ) iCol = pTab->iPKey; zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; }else if( pColExpr->op==TK_ID ){ @@ -119158,36 +133506,40 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList( zName = pColExpr->u.zToken; }else{ /* Use the original text of the column expression as its name */ - zName = pEList->a[i].zSpan; + zName = pEList->a[i].zEName; } } - zName = sqlite3MPrintf(db, "%s", zName); + if( zName && !tdsqlite3IsTrueOrFalse(zName) ){ + zName = tdsqlite3DbStrDup(db, zName); + }else{ + zName = tdsqlite3MPrintf(db,"column%d",i+1); + } /* Make sure the column name is unique. If the name is not unique, ** append an integer to the name so that it becomes unique. */ cnt = 0; - while( zName && sqlite3HashFind(&ht, zName)!=0 ){ - nName = sqlite3Strlen30(zName); + while( zName && tdsqlite3HashFind(&ht, zName)!=0 ){ + nName = tdsqlite3Strlen30(zName); if( nName>0 ){ - for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} + for(j=nName-1; j>0 && tdsqlite3Isdigit(zName[j]); j--){} if( zName[j]==':' ) nName = j; } - zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); - if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); + zName = tdsqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); + if( cnt>3 ) tdsqlite3_randomness(sizeof(cnt), &cnt); } pCol->zName = zName; - sqlite3ColumnPropertiesFromName(0, pCol); - if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ - sqlite3OomFault(db); + tdsqlite3ColumnPropertiesFromName(0, pCol); + if( zName && tdsqlite3HashInsert(&ht, zName, pCol)==pCol ){ + tdsqlite3OomFault(db); } } - sqlite3HashClear(&ht); + tdsqlite3HashClear(&ht); if( db->mallocFailed ){ for(j=0; j<i; j++){ - sqlite3DbFree(db, aCol[j].zName); + tdsqlite3DbFree(db, aCol[j].zName); } - sqlite3DbFree(db, aCol); + tdsqlite3DbFree(db, aCol); *paCol = 0; *pnCol = 0; return SQLITE_NOMEM_BKPT; @@ -119206,19 +133558,19 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList( ** This routine requires that all identifiers in the SELECT ** statement be resolved. */ -SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation( +SQLITE_PRIVATE void tdsqlite3SelectAddColumnTypeAndCollation( Parse *pParse, /* Parsing contexts */ Table *pTab, /* Add column type information to this table */ - Select *pSelect /* SELECT used to determine types and collations */ + Select *pSelect, /* SELECT used to determine types and collations */ + char aff /* Default affinity for columns */ ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; NameContext sNC; Column *pCol; CollSeq *pColl; int i; Expr *p; struct ExprList_item *a; - u64 szAll = 0; assert( pSelect!=0 ); assert( (pSelect->selFlags & SF_Resolved)!=0 ); @@ -119231,57 +133583,55 @@ SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation( const char *zType; int n, m; p = a[i].pExpr; - zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst); - szAll += pCol->szEst; - pCol->affinity = sqlite3ExprAffinity(p); - if( zType && (m = sqlite3Strlen30(zType))>0 ){ - n = sqlite3Strlen30(pCol->zName); - pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); + zType = columnType(&sNC, p, 0, 0, 0); + /* pCol->szEst = ... // Column size est for SELECT tables never used */ + pCol->affinity = tdsqlite3ExprAffinity(p); + if( zType ){ + m = tdsqlite3Strlen30(zType); + n = tdsqlite3Strlen30(pCol->zName); + pCol->zName = tdsqlite3DbReallocOrFree(db, pCol->zName, n+m+2); if( pCol->zName ){ memcpy(&pCol->zName[n+1], zType, m+1); pCol->colFlags |= COLFLAG_HASTYPE; } } - if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB; - pColl = sqlite3ExprCollSeq(pParse, p); + if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff; + pColl = tdsqlite3ExprCollSeq(pParse, p); if( pColl && pCol->zColl==0 ){ - pCol->zColl = sqlite3DbStrDup(db, pColl->zName); + pCol->zColl = tdsqlite3DbStrDup(db, pColl->zName); } } - pTab->szTabRow = sqlite3LogEst(szAll*4); + pTab->szTabRow = 1; /* Any non-zero value works */ } /* ** Given a SELECT statement, generate a Table structure that describes ** the result set of that SELECT. */ -SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ +SQLITE_PRIVATE Table *tdsqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){ Table *pTab; - sqlite3 *db = pParse->db; - int savedFlags; + tdsqlite3 *db = pParse->db; + u64 savedFlags; savedFlags = db->flags; - db->flags &= ~SQLITE_FullColNames; + db->flags &= ~(u64)SQLITE_FullColNames; db->flags |= SQLITE_ShortColNames; - sqlite3SelectPrep(pParse, pSelect, 0); + tdsqlite3SelectPrep(pParse, pSelect, 0); + db->flags = savedFlags; if( pParse->nErr ) return 0; while( pSelect->pPrior ) pSelect = pSelect->pPrior; - db->flags = savedFlags; - pTab = sqlite3DbMallocZero(db, sizeof(Table) ); + pTab = tdsqlite3DbMallocZero(db, sizeof(Table) ); if( pTab==0 ){ return 0; } - /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside - ** is disabled */ - assert( db->lookaside.bDisable ); - pTab->nRef = 1; + pTab->nTabRef = 1; pTab->zName = 0; - pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); - sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); - sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect); + pTab->nRowLogEst = 200; assert( 200==tdsqlite3LogEst(1048576) ); + tdsqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); + tdsqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff); pTab->iPKey = -1; if( db->mallocFailed ){ - sqlite3DeleteTable(db, pTab); + tdsqlite3DeleteTable(db, pTab); return 0; } return pTab; @@ -119291,25 +133641,22 @@ SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ ** Get a VDBE for the given parser context. Create a new one if necessary. ** If an error occurs, return NULL and leave a message in pParse. */ -static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){ - Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse); - if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1); +SQLITE_PRIVATE Vdbe *tdsqlite3GetVdbe(Parse *pParse){ + if( pParse->pVdbe ){ + return pParse->pVdbe; + } if( pParse->pToplevel==0 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) ){ pParse->okConstFactor = 1; } - return v; -} -SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){ - Vdbe *v = pParse->pVdbe; - return v ? v : allocVdbe(pParse); + return tdsqlite3VdbeCreate(pParse); } /* ** Compute the iLimit and iOffset fields of the SELECT based on the -** pLimit and pOffset expressions. pLimit and pOffset hold the expressions +** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions ** that appear in the original SQL statement after the LIMIT and OFFSET ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset ** are the integer memory register numbers for counters used to compute @@ -119317,15 +133664,15 @@ SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){ ** iLimit and iOffset are negative. ** ** This routine changes the values of iLimit and iOffset only if -** a limit or offset is defined by pLimit and pOffset. iLimit and -** iOffset should have been preset to appropriate default values (zero) +** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit +** and iOffset should have been preset to appropriate default values (zero) ** prior to calling this routine. ** ** The iOffset register (if it exists) is initialized to the value ** of the OFFSET. The iLimit register is initialized to LIMIT. Register ** iOffset+1 is initialized to LIMIT+OFFSET. ** -** Only if pLimit!=0 or pOffset!=0 do the limit registers get +** Only if pLimit->pLeft!=0 do the limit registers get ** redefined. The UNION ALL operator uses this property to force ** the reuse of the same limit and offset registers across multiple ** SELECT statements. @@ -119335,6 +133682,8 @@ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ int iLimit = 0; int iOffset; int n; + Expr *pLimit = p->pLimit; + if( p->iLimit ) return; /* @@ -119343,34 +133692,34 @@ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ ** The current implementation interprets "LIMIT 0" to mean ** no rows. */ - sqlite3ExprCacheClear(pParse); - assert( p->pOffset==0 || p->pLimit!=0 ); - if( p->pLimit ){ + if( pLimit ){ + assert( pLimit->op==TK_LIMIT ); + assert( pLimit->pLeft!=0 ); p->iLimit = iLimit = ++pParse->nMem; - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); assert( v!=0 ); - if( sqlite3ExprIsInteger(p->pLimit, &n) ){ - sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); + if( tdsqlite3ExprIsInteger(pLimit->pLeft, &n) ){ + tdsqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); VdbeComment((v, "LIMIT counter")); if( n==0 ){ - sqlite3VdbeGoto(v, iBreak); - }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ - p->nSelectRow = sqlite3LogEst((u64)n); + tdsqlite3VdbeGoto(v, iBreak); + }else if( n>=0 && p->nSelectRow>tdsqlite3LogEst((u64)n) ){ + p->nSelectRow = tdsqlite3LogEst((u64)n); p->selFlags |= SF_FixedLimit; } }else{ - sqlite3ExprCode(pParse, p->pLimit, iLimit); - sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); + tdsqlite3ExprCode(pParse, pLimit->pLeft, iLimit); + tdsqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); VdbeComment((v, "LIMIT counter")); - sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); } - if( p->pOffset ){ + if( pLimit->pRight ){ p->iOffset = iOffset = ++pParse->nMem; pParse->nMem++; /* Allocate an extra register for limit+offset */ - sqlite3ExprCode(pParse, p->pOffset, iOffset); - sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); + tdsqlite3ExprCode(pParse, pLimit->pRight, iOffset); + tdsqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); VdbeComment((v, "OFFSET counter")); - sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); + tdsqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); VdbeComment((v, "LIMIT+OFFSET")); } } @@ -119397,7 +133746,7 @@ static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ ** have been thrown during name resolution and we would not have gotten ** this far */ if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ - pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); + pRet = tdsqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); } return pRet; } @@ -119414,8 +133763,8 @@ static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ ExprList *pOrderBy = p->pOrderBy; int nOrderBy = p->pOrderBy->nExpr; - sqlite3 *db = pParse->db; - KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); + tdsqlite3 *db = pParse->db; + KeyInfo *pRet = tdsqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); if( pRet ){ int i; for(i=0; i<nOrderBy; i++){ @@ -119424,16 +133773,16 @@ static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ CollSeq *pColl; if( pTerm->flags & EP_Collate ){ - pColl = sqlite3ExprCollSeq(pParse, pTerm); + pColl = tdsqlite3ExprCollSeq(pParse, pTerm); }else{ pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); if( pColl==0 ) pColl = db->pDfltColl; pOrderBy->a[i].pExpr = - sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); + tdsqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); } - assert( sqlite3KeyInfoIsWriteable(pRet) ); + assert( tdsqlite3KeyInfoIsWriteable(pRet) ); pRet->aColl[i] = pColl; - pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder; + pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags; } } @@ -119497,20 +133846,27 @@ static void generateWithRecursiveQuery( int i; /* Loop counter */ int rc; /* Result code */ ExprList *pOrderBy; /* The ORDER BY clause */ - Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */ + Expr *pLimit; /* Saved LIMIT and OFFSET */ int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ +#ifndef SQLITE_OMIT_WINDOWFUNC + if( p->pWin ){ + tdsqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries"); + return; + } +#endif + /* Obtain authorization to do a recursive query */ - if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; + if( tdsqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; /* Process the LIMIT and OFFSET clauses, if they exist */ - addrBreak = sqlite3VdbeMakeLabel(v); + addrBreak = tdsqlite3VdbeMakeLabel(pParse); + p->nSelectRow = 320; /* 4 billion rows */ computeLimitRegisters(pParse, p, addrBreak); pLimit = p->pLimit; - pOffset = p->pOffset; regLimit = p->iLimit; regOffset = p->iOffset; - p->pLimit = p->pOffset = 0; + p->pLimit = 0; p->iLimit = p->iOffset = 0; pOrderBy = p->pOrderBy; @@ -119532,22 +133888,22 @@ static void generateWithRecursiveQuery( }else{ eDest = pOrderBy ? SRT_Queue : SRT_Fifo; } - sqlite3SelectDestInit(&destQueue, eDest, iQueue); + tdsqlite3SelectDestInit(&destQueue, eDest, iQueue); /* Allocate cursors for Current, Queue, and Distinct. */ regCurrent = ++pParse->nMem; - sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); + tdsqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); if( pOrderBy ){ KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); - sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, + tdsqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, (char*)pKeyInfo, P4_KEYINFO); destQueue.pOrderBy = pOrderBy; }else{ - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); + tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); } VdbeComment((v, "Queue table")); if( iDistinct ){ - p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); + p->addrOpenEphm[0] = tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); p->selFlags |= SF_UsesEphemeral; } @@ -119556,54 +133912,55 @@ static void generateWithRecursiveQuery( /* Store the results of the setup-query in Queue. */ pSetup->pNext = 0; - rc = sqlite3Select(pParse, pSetup, &destQueue); + ExplainQueryPlan((pParse, 1, "SETUP")); + rc = tdsqlite3Select(pParse, pSetup, &destQueue); pSetup->pNext = p; if( rc ) goto end_of_recursive_query; /* Find the next row in the Queue and output that row */ - addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); + addrTop = tdsqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); /* Transfer the next row in Queue over to Current */ - sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ + tdsqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ if( pOrderBy ){ - sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); + tdsqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); }else{ - sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); + tdsqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); } - sqlite3VdbeAddOp1(v, OP_Delete, iQueue); + tdsqlite3VdbeAddOp1(v, OP_Delete, iQueue); /* Output the single row in Current */ - addrCont = sqlite3VdbeMakeLabel(v); + addrCont = tdsqlite3VdbeMakeLabel(pParse); codeOffset(v, regOffset, addrCont); - selectInnerLoop(pParse, p, p->pEList, iCurrent, + selectInnerLoop(pParse, p, iCurrent, 0, 0, pDest, addrCont, addrBreak); if( regLimit ){ - sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); + tdsqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); VdbeCoverage(v); } - sqlite3VdbeResolveLabel(v, addrCont); + tdsqlite3VdbeResolveLabel(v, addrCont); /* Execute the recursive SELECT taking the single row in Current as ** the value for the recursive-table. Store the results in the Queue. */ if( p->selFlags & SF_Aggregate ){ - sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); + tdsqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); }else{ p->pPrior = 0; - sqlite3Select(pParse, p, &destQueue); + ExplainQueryPlan((pParse, 1, "RECURSIVE STEP")); + tdsqlite3Select(pParse, p, &destQueue); assert( p->pPrior==0 ); p->pPrior = pSetup; } /* Keep running the loop until the Queue is empty */ - sqlite3VdbeGoto(v, addrTop); - sqlite3VdbeResolveLabel(v, addrBreak); + tdsqlite3VdbeGoto(v, addrTop); + tdsqlite3VdbeResolveLabel(v, addrBreak); end_of_recursive_query: - sqlite3ExprListDelete(pParse->db, p->pOrderBy); + tdsqlite3ExprListDelete(pParse->db, p->pOrderBy); p->pOrderBy = pOrderBy; p->pLimit = pLimit; - p->pOffset = pOffset; return; } #endif /* SQLITE_OMIT_CTE */ @@ -119622,36 +133979,41 @@ static int multiSelectOrderBy( ** on a VALUES clause. ** ** Because the Select object originates from a VALUES clause: -** (1) It has no LIMIT or OFFSET +** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1 ** (2) All terms are UNION ALL ** (3) There is no ORDER BY clause +** +** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES +** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))"). +** The tdsqlite3CodeSubselect will have added the LIMIT 1 clause in tht case. +** Since the limit is exactly 1, we only need to evalutes the left-most VALUES. */ static int multiSelectValues( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ - Select *pPrior; int nRow = 1; int rc = 0; + int bShowAll = p->pLimit==0; assert( p->selFlags & SF_MultiValue ); do{ assert( p->selFlags & SF_Values ); assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); - assert( p->pLimit==0 ); - assert( p->pOffset==0 ); assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); +#ifndef SQLITE_OMIT_WINDOWFUNC + if( p->pWin ) return -1; +#endif if( p->pPrior==0 ) break; assert( p->pPrior->pNext==p ); p = p->pPrior; - nRow++; + nRow += bShowAll; }while(1); + ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow, + nRow==1 ? "" : "S")); while( p ){ - pPrior = p->pPrior; - p->pPrior = 0; - rc = sqlite3Select(pParse, p, pDest); - p->pPrior = pPrior; - if( rc ) break; + selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1); + if( !bShowAll ) break; p->nSelectRow = nRow; p = p->pNext; } @@ -119699,41 +134061,32 @@ static int multiSelect( Vdbe *v; /* Generate code to this VDBE */ SelectDest dest; /* Alternative data destination */ Select *pDelete = 0; /* Chain of simple selects to delete */ - sqlite3 *db; /* Database connection */ -#ifndef SQLITE_OMIT_EXPLAIN - int iSub1 = 0; /* EQP id of left-hand query */ - int iSub2 = 0; /* EQP id of right-hand query */ -#endif + tdsqlite3 *db; /* Database connection */ /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. */ assert( p && p->pPrior ); /* Calling function guarantees this much */ assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); + assert( p->selFlags & SF_Compound ); db = pParse->db; pPrior = p->pPrior; dest = *pDest; - if( pPrior->pOrderBy ){ - sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", - selectOpName(p->op)); - rc = 1; - goto multi_select_end; - } - if( pPrior->pLimit ){ - sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", - selectOpName(p->op)); + if( pPrior->pOrderBy || pPrior->pLimit ){ + tdsqlite3ErrorMsg(pParse,"%s clause should come after %s not before", + pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op)); rc = 1; goto multi_select_end; } - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); assert( v!=0 ); /* The VDBE already created by calling function */ /* Create the destination temporary table if necessary */ if( dest.eDest==SRT_EphemTab ){ assert( p->pEList ); - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); + tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); dest.eDest = SRT_Table; } @@ -119741,7 +134094,8 @@ static int multiSelect( */ if( p->selFlags & SF_MultiValue ){ rc = multiSelectValues(pParse, p, &dest); - goto multi_select_end; + if( rc>=0 ) goto multi_select_end; + rc = SQLITE_OK; } /* Make sure all SELECTs in the statement have the same number of elements @@ -119760,236 +134114,232 @@ static int multiSelect( */ if( p->pOrderBy ){ return multiSelectOrderBy(pParse, p, pDest); - }else + }else{ - /* Generate code for the left and right SELECT statements. - */ - switch( p->op ){ - case TK_ALL: { - int addr = 0; - int nLimit; - assert( !pPrior->pLimit ); - pPrior->iLimit = p->iLimit; - pPrior->iOffset = p->iOffset; - pPrior->pLimit = p->pLimit; - pPrior->pOffset = p->pOffset; - explainSetInteger(iSub1, pParse->iNextSelectId); - rc = sqlite3Select(pParse, pPrior, &dest); - p->pLimit = 0; - p->pOffset = 0; - if( rc ){ - goto multi_select_end; - } - p->pPrior = 0; - p->iLimit = pPrior->iLimit; - p->iOffset = pPrior->iOffset; - if( p->iLimit ){ - addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); - VdbeComment((v, "Jump ahead if LIMIT reached")); - if( p->iOffset ){ - sqlite3VdbeAddOp3(v, OP_OffsetLimit, - p->iLimit, p->iOffset+1, p->iOffset); +#ifndef SQLITE_OMIT_EXPLAIN + if( pPrior->pPrior==0 ){ + ExplainQueryPlan((pParse, 1, "COMPOUND QUERY")); + ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY")); + } +#endif + + /* Generate code for the left and right SELECT statements. + */ + switch( p->op ){ + case TK_ALL: { + int addr = 0; + int nLimit; + assert( !pPrior->pLimit ); + pPrior->iLimit = p->iLimit; + pPrior->iOffset = p->iOffset; + pPrior->pLimit = p->pLimit; + rc = tdsqlite3Select(pParse, pPrior, &dest); + p->pLimit = 0; + if( rc ){ + goto multi_select_end; + } + p->pPrior = 0; + p->iLimit = pPrior->iLimit; + p->iOffset = pPrior->iOffset; + if( p->iLimit ){ + addr = tdsqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); + VdbeComment((v, "Jump ahead if LIMIT reached")); + if( p->iOffset ){ + tdsqlite3VdbeAddOp3(v, OP_OffsetLimit, + p->iLimit, p->iOffset+1, p->iOffset); + } } + ExplainQueryPlan((pParse, 1, "UNION ALL")); + rc = tdsqlite3Select(pParse, p, &dest); + testcase( rc!=SQLITE_OK ); + pDelete = p->pPrior; + p->pPrior = pPrior; + p->nSelectRow = tdsqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); + if( pPrior->pLimit + && tdsqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit) + && nLimit>0 && p->nSelectRow > tdsqlite3LogEst((u64)nLimit) + ){ + p->nSelectRow = tdsqlite3LogEst((u64)nLimit); + } + if( addr ){ + tdsqlite3VdbeJumpHere(v, addr); + } + break; } - explainSetInteger(iSub2, pParse->iNextSelectId); - rc = sqlite3Select(pParse, p, &dest); - testcase( rc!=SQLITE_OK ); - pDelete = p->pPrior; - p->pPrior = pPrior; - p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); - if( pPrior->pLimit - && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) - && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) - ){ - p->nSelectRow = sqlite3LogEst((u64)nLimit); - } - if( addr ){ - sqlite3VdbeJumpHere(v, addr); - } - break; - } - case TK_EXCEPT: - case TK_UNION: { - int unionTab; /* Cursor number of the temporary table holding result */ - u8 op = 0; /* One of the SRT_ operations to apply to self */ - int priorOp; /* The SRT_ operation to apply to prior selects */ - Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ - int addr; - SelectDest uniondest; - - testcase( p->op==TK_EXCEPT ); - testcase( p->op==TK_UNION ); - priorOp = SRT_Union; - if( dest.eDest==priorOp ){ - /* We can reuse a temporary table generated by a SELECT to our - ** right. + case TK_EXCEPT: + case TK_UNION: { + int unionTab; /* Cursor number of the temp table holding result */ + u8 op = 0; /* One of the SRT_ operations to apply to self */ + int priorOp; /* The SRT_ operation to apply to prior selects */ + Expr *pLimit; /* Saved values of p->nLimit */ + int addr; + SelectDest uniondest; + + testcase( p->op==TK_EXCEPT ); + testcase( p->op==TK_UNION ); + priorOp = SRT_Union; + if( dest.eDest==priorOp ){ + /* We can reuse a temporary table generated by a SELECT to our + ** right. + */ + assert( p->pLimit==0 ); /* Not allowed on leftward elements */ + unionTab = dest.iSDParm; + }else{ + /* We will need to create our own temporary table to hold the + ** intermediate results. + */ + unionTab = pParse->nTab++; + assert( p->pOrderBy==0 ); + addr = tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); + assert( p->addrOpenEphm[0] == -1 ); + p->addrOpenEphm[0] = addr; + findRightmost(p)->selFlags |= SF_UsesEphemeral; + assert( p->pEList ); + } + + /* Code the SELECT statements to our left */ - assert( p->pLimit==0 ); /* Not allowed on leftward elements */ - assert( p->pOffset==0 ); /* Not allowed on leftward elements */ - unionTab = dest.iSDParm; - }else{ - /* We will need to create our own temporary table to hold the - ** intermediate results. + assert( !pPrior->pOrderBy ); + tdsqlite3SelectDestInit(&uniondest, priorOp, unionTab); + rc = tdsqlite3Select(pParse, pPrior, &uniondest); + if( rc ){ + goto multi_select_end; + } + + /* Code the current SELECT statement */ - unionTab = pParse->nTab++; + if( p->op==TK_EXCEPT ){ + op = SRT_Except; + }else{ + assert( p->op==TK_UNION ); + op = SRT_Union; + } + p->pPrior = 0; + pLimit = p->pLimit; + p->pLimit = 0; + uniondest.eDest = op; + ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", + selectOpName(p->op))); + rc = tdsqlite3Select(pParse, p, &uniondest); + testcase( rc!=SQLITE_OK ); + /* Query flattening in tdsqlite3Select() might refill p->pOrderBy. + ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ + tdsqlite3ExprListDelete(db, p->pOrderBy); + pDelete = p->pPrior; + p->pPrior = pPrior; + p->pOrderBy = 0; + if( p->op==TK_UNION ){ + p->nSelectRow = tdsqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); + } + tdsqlite3ExprDelete(db, p->pLimit); + p->pLimit = pLimit; + p->iLimit = 0; + p->iOffset = 0; + + /* Convert the data in the temporary table into whatever form + ** it is that we currently need. + */ + assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); + assert( p->pEList || db->mallocFailed ); + if( dest.eDest!=priorOp && db->mallocFailed==0 ){ + int iCont, iBreak, iStart; + iBreak = tdsqlite3VdbeMakeLabel(pParse); + iCont = tdsqlite3VdbeMakeLabel(pParse); + computeLimitRegisters(pParse, p, iBreak); + tdsqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); + iStart = tdsqlite3VdbeCurrentAddr(v); + selectInnerLoop(pParse, p, unionTab, + 0, 0, &dest, iCont, iBreak); + tdsqlite3VdbeResolveLabel(v, iCont); + tdsqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); + tdsqlite3VdbeResolveLabel(v, iBreak); + tdsqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); + } + break; + } + default: assert( p->op==TK_INTERSECT ); { + int tab1, tab2; + int iCont, iBreak, iStart; + Expr *pLimit; + int addr; + SelectDest intersectdest; + int r1; + + /* INTERSECT is different from the others since it requires + ** two temporary tables. Hence it has its own case. Begin + ** by allocating the tables we will need. + */ + tab1 = pParse->nTab++; + tab2 = pParse->nTab++; assert( p->pOrderBy==0 ); - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); + + addr = tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); assert( p->addrOpenEphm[0] == -1 ); p->addrOpenEphm[0] = addr; findRightmost(p)->selFlags |= SF_UsesEphemeral; assert( p->pEList ); - } - - /* Code the SELECT statements to our left - */ - assert( !pPrior->pOrderBy ); - sqlite3SelectDestInit(&uniondest, priorOp, unionTab); - explainSetInteger(iSub1, pParse->iNextSelectId); - rc = sqlite3Select(pParse, pPrior, &uniondest); - if( rc ){ - goto multi_select_end; - } - - /* Code the current SELECT statement - */ - if( p->op==TK_EXCEPT ){ - op = SRT_Except; - }else{ - assert( p->op==TK_UNION ); - op = SRT_Union; - } - p->pPrior = 0; - pLimit = p->pLimit; - p->pLimit = 0; - pOffset = p->pOffset; - p->pOffset = 0; - uniondest.eDest = op; - explainSetInteger(iSub2, pParse->iNextSelectId); - rc = sqlite3Select(pParse, p, &uniondest); - testcase( rc!=SQLITE_OK ); - /* Query flattening in sqlite3Select() might refill p->pOrderBy. - ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ - sqlite3ExprListDelete(db, p->pOrderBy); - pDelete = p->pPrior; - p->pPrior = pPrior; - p->pOrderBy = 0; - if( p->op==TK_UNION ){ - p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); - } - sqlite3ExprDelete(db, p->pLimit); - p->pLimit = pLimit; - p->pOffset = pOffset; - p->iLimit = 0; - p->iOffset = 0; - - /* Convert the data in the temporary table into whatever form - ** it is that we currently need. - */ - assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); - if( dest.eDest!=priorOp ){ - int iCont, iBreak, iStart; - assert( p->pEList ); - if( dest.eDest==SRT_Output ){ - Select *pFirst = p; - while( pFirst->pPrior ) pFirst = pFirst->pPrior; - generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); + + /* Code the SELECTs to our left into temporary table "tab1". + */ + tdsqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); + rc = tdsqlite3Select(pParse, pPrior, &intersectdest); + if( rc ){ + goto multi_select_end; } - iBreak = sqlite3VdbeMakeLabel(v); - iCont = sqlite3VdbeMakeLabel(v); + + /* Code the current SELECT into temporary table "tab2" + */ + addr = tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); + assert( p->addrOpenEphm[1] == -1 ); + p->addrOpenEphm[1] = addr; + p->pPrior = 0; + pLimit = p->pLimit; + p->pLimit = 0; + intersectdest.iSDParm = tab2; + ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", + selectOpName(p->op))); + rc = tdsqlite3Select(pParse, p, &intersectdest); + testcase( rc!=SQLITE_OK ); + pDelete = p->pPrior; + p->pPrior = pPrior; + if( p->nSelectRow>pPrior->nSelectRow ){ + p->nSelectRow = pPrior->nSelectRow; + } + tdsqlite3ExprDelete(db, p->pLimit); + p->pLimit = pLimit; + + /* Generate code to take the intersection of the two temporary + ** tables. + */ + assert( p->pEList ); + iBreak = tdsqlite3VdbeMakeLabel(pParse); + iCont = tdsqlite3VdbeMakeLabel(pParse); computeLimitRegisters(pParse, p, iBreak); - sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); - iStart = sqlite3VdbeCurrentAddr(v); - selectInnerLoop(pParse, p, p->pEList, unionTab, + tdsqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); + r1 = tdsqlite3GetTempReg(pParse); + iStart = tdsqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); + tdsqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); + VdbeCoverage(v); + tdsqlite3ReleaseTempReg(pParse, r1); + selectInnerLoop(pParse, p, tab1, 0, 0, &dest, iCont, iBreak); - sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); - sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); + tdsqlite3VdbeResolveLabel(v, iCont); + tdsqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); + tdsqlite3VdbeResolveLabel(v, iBreak); + tdsqlite3VdbeAddOp2(v, OP_Close, tab2, 0); + tdsqlite3VdbeAddOp2(v, OP_Close, tab1, 0); + break; } - break; } - default: assert( p->op==TK_INTERSECT ); { - int tab1, tab2; - int iCont, iBreak, iStart; - Expr *pLimit, *pOffset; - int addr; - SelectDest intersectdest; - int r1; - - /* INTERSECT is different from the others since it requires - ** two temporary tables. Hence it has its own case. Begin - ** by allocating the tables we will need. - */ - tab1 = pParse->nTab++; - tab2 = pParse->nTab++; - assert( p->pOrderBy==0 ); - - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); - assert( p->addrOpenEphm[0] == -1 ); - p->addrOpenEphm[0] = addr; - findRightmost(p)->selFlags |= SF_UsesEphemeral; - assert( p->pEList ); - - /* Code the SELECTs to our left into temporary table "tab1". - */ - sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); - explainSetInteger(iSub1, pParse->iNextSelectId); - rc = sqlite3Select(pParse, pPrior, &intersectdest); - if( rc ){ - goto multi_select_end; - } - - /* Code the current SELECT into temporary table "tab2" - */ - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); - assert( p->addrOpenEphm[1] == -1 ); - p->addrOpenEphm[1] = addr; - p->pPrior = 0; - pLimit = p->pLimit; - p->pLimit = 0; - pOffset = p->pOffset; - p->pOffset = 0; - intersectdest.iSDParm = tab2; - explainSetInteger(iSub2, pParse->iNextSelectId); - rc = sqlite3Select(pParse, p, &intersectdest); - testcase( rc!=SQLITE_OK ); - pDelete = p->pPrior; - p->pPrior = pPrior; - if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; - sqlite3ExprDelete(db, p->pLimit); - p->pLimit = pLimit; - p->pOffset = pOffset; - - /* Generate code to take the intersection of the two temporary - ** tables. - */ - assert( p->pEList ); - if( dest.eDest==SRT_Output ){ - Select *pFirst = p; - while( pFirst->pPrior ) pFirst = pFirst->pPrior; - generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); - } - iBreak = sqlite3VdbeMakeLabel(v); - iCont = sqlite3VdbeMakeLabel(v); - computeLimitRegisters(pParse, p, iBreak); - sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); - r1 = sqlite3GetTempReg(pParse); - iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); - sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, r1); - selectInnerLoop(pParse, p, p->pEList, tab1, - 0, 0, &dest, iCont, iBreak); - sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); - sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); - sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); - break; + + #ifndef SQLITE_OMIT_EXPLAIN + if( p->pNext==0 ){ + ExplainQueryPlanPop(pParse); } + #endif } - - explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); - + if( pParse->nErr ) goto multi_select_end; + /* Compute collating sequences used by ** temporary tables needed to implement the compound select. ** Attach the KeyInfo structure to all temporary tables. @@ -120008,7 +134358,7 @@ static int multiSelect( assert( p->pNext==0 ); nCol = p->pEList->nExpr; - pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); + pKeyInfo = tdsqlite3KeyInfoAlloc(db, nCol, 1); if( !pKeyInfo ){ rc = SQLITE_NOMEM_BKPT; goto multi_select_end; @@ -120029,19 +134379,19 @@ static int multiSelect( assert( pLoop->addrOpenEphm[1]<0 ); break; } - sqlite3VdbeChangeP2(v, addr, nCol); - sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), + tdsqlite3VdbeChangeP2(v, addr, nCol); + tdsqlite3VdbeChangeP4(v, addr, (char*)tdsqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); pLoop->addrOpenEphm[i] = -1; } } - sqlite3KeyInfoUnref(pKeyInfo); + tdsqlite3KeyInfoUnref(pKeyInfo); } multi_select_end: pDest->iSdst = dest.iSdst; pDest->nSdst = dest.nSdst; - sqlite3SelectDelete(db, pDelete); + tdsqlite3SelectDelete(db, pDelete); return rc; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ @@ -120050,11 +134400,11 @@ multi_select_end: ** Error message for when two or more terms of a compound select have different ** size result sets. */ -SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ +SQLITE_PRIVATE void tdsqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ if( p->selFlags & SF_Values ){ - sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); + tdsqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); }else{ - sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" + tdsqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" " do not have the same number of result columns", selectOpName(p->op)); } } @@ -120093,20 +134443,20 @@ static int generateOutputSubroutine( int iContinue; int addr; - addr = sqlite3VdbeCurrentAddr(v); - iContinue = sqlite3VdbeMakeLabel(v); + addr = tdsqlite3VdbeCurrentAddr(v); + iContinue = tdsqlite3VdbeMakeLabel(pParse); /* Suppress duplicates for UNION, EXCEPT, and INTERSECT */ if( regPrev ){ int addr1, addr2; - addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); - addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, - (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); - sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); - sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); + addr1 = tdsqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); + addr2 = tdsqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, + (char*)tdsqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); + tdsqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addr1); + tdsqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); } if( pParse->db->mallocFailed ) return 0; @@ -120120,14 +134470,14 @@ static int generateOutputSubroutine( /* Store the result as data using a unique key. */ case SRT_EphemTab: { - int r1 = sqlite3GetTempReg(pParse); - int r2 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); - sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); - sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3ReleaseTempReg(pParse, r2); - sqlite3ReleaseTempReg(pParse, r1); + int r1 = tdsqlite3GetTempReg(pParse); + int r2 = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); + tdsqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); + tdsqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); + tdsqlite3VdbeChangeP5(v, OPFLAG_APPEND); + tdsqlite3ReleaseTempReg(pParse, r2); + tdsqlite3ReleaseTempReg(pParse, r1); break; } @@ -120137,22 +134487,25 @@ static int generateOutputSubroutine( case SRT_Set: { int r1; testcase( pIn->nSdst>1 ); - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, + r1 = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1, pDest->zAffSdst, pIn->nSdst); - sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); - sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1); - sqlite3ReleaseTempReg(pParse, r1); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, + pIn->iSdst, pIn->nSdst); + tdsqlite3ReleaseTempReg(pParse, r1); break; } /* If this is a scalar select that is part of an expression, then ** store the results in the appropriate memory cell and break out - ** of the scan loop. + ** of the scan loop. Note that the select might return multiple columns + ** if it is the RHS of a row-value IN operator. */ case SRT_Mem: { - assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 ); - sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); + if( pParse->nErr==0 ){ + testcase( pIn->nSdst>1 ); + tdsqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst); + } /* The LIMIT clause will jump out of the loop for us */ break; } @@ -120163,11 +134516,11 @@ static int generateOutputSubroutine( */ case SRT_Coroutine: { if( pDest->iSdst==0 ){ - pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); + pDest->iSdst = tdsqlite3GetTempRange(pParse, pIn->nSdst); pDest->nSdst = pIn->nSdst; } - sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); - sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); + tdsqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); + tdsqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); break; } @@ -120176,13 +134529,12 @@ static int generateOutputSubroutine( ** destination other than the ones handled above or SRT_Output. ** ** For SRT_Output, results are stored in a sequence of registers. - ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to + ** Then the OP_ResultRow opcode is used to cause tdsqlite3_step() to ** return the next row of result. */ default: { assert( pDest->eDest==SRT_Output ); - sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); - sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); + tdsqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); break; } } @@ -120190,13 +134542,13 @@ static int generateOutputSubroutine( /* Jump to the end of the loop if the LIMIT is reached. */ if( p->iLimit ){ - sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); } /* Generate the subroutine return */ - sqlite3VdbeResolveLabel(v, iContinue); - sqlite3VdbeAddOp1(v, OP_Return, regReturn); + tdsqlite3VdbeResolveLabel(v, iContinue); + tdsqlite3VdbeAddOp1(v, OP_Return, regReturn); return addr; } @@ -120322,22 +134674,18 @@ static int multiSelectOrderBy( int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ KeyInfo *pKeyMerge; /* Comparison information for merging rows */ - sqlite3 *db; /* Database connection */ + tdsqlite3 *db; /* Database connection */ ExprList *pOrderBy; /* The ORDER BY clause */ int nOrderBy; /* Number of terms in the ORDER BY clause */ int *aPermute; /* Mapping from ORDER BY terms to result set columns */ -#ifndef SQLITE_OMIT_EXPLAIN - int iSub1; /* EQP id of left-hand query */ - int iSub2; /* EQP id of right-hand query */ -#endif assert( p->pOrderBy!=0 ); assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ db = pParse->db; v = pParse->pVdbe; assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ - labelEnd = sqlite3VdbeMakeLabel(v); - labelCmpr = sqlite3VdbeMakeLabel(v); + labelEnd = tdsqlite3VdbeMakeLabel(pParse); + labelCmpr = tdsqlite3VdbeMakeLabel(pParse); /* Patch up the ORDER BY clause @@ -120361,11 +134709,11 @@ static int multiSelectOrderBy( if( pItem->u.x.iOrderByCol==i ) break; } if( j==nOrderBy ){ - Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); + Expr *pNew = tdsqlite3Expr(db, TK_INTEGER, 0); if( pNew==0 ) return SQLITE_NOMEM_BKPT; pNew->flags |= EP_IntValue; pNew->u.iValue = i; - pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); + p->pOrderBy = pOrderBy = tdsqlite3ExprListAppend(pParse, pOrderBy, pNew); if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; } } @@ -120378,7 +134726,7 @@ static int multiSelectOrderBy( ** to the right and the left are evaluated, they use the correct ** collation. */ - aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1)); + aPermute = tdsqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1)); if( aPermute ){ struct ExprList_item *pItem; aPermute[0] = nOrderBy; @@ -120395,7 +134743,7 @@ static int multiSelectOrderBy( /* Reattach the ORDER BY clause to the query. */ p->pOrderBy = pOrderBy; - pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); + pPrior->pOrderBy = tdsqlite3ExprListDup(pParse->db, pOrderBy, 0); /* Allocate a range of temporary registers and the KeyInfo needed ** for the logic that removes duplicate result rows when the @@ -120408,13 +134756,13 @@ static int multiSelectOrderBy( assert( nOrderBy>=nExpr || db->mallocFailed ); regPrev = pParse->nMem+1; pParse->nMem += nExpr+1; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); - pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); + pKeyDup = tdsqlite3KeyInfoAlloc(db, nExpr, 1); if( pKeyDup ){ - assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); + assert( tdsqlite3KeyInfoIsWriteable(pKeyDup) ); for(i=0; i<nExpr; i++){ pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); - pKeyDup->aSortOrder[i] = 0; + pKeyDup->aSortFlags[i] = 0; } } } @@ -120423,9 +134771,9 @@ static int multiSelectOrderBy( */ p->pPrior = 0; pPrior->pNext = 0; - sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); + tdsqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); if( pPrior->pPrior==0 ){ - sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); + tdsqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); } /* Compute the limit registers */ @@ -120433,51 +134781,51 @@ static int multiSelectOrderBy( if( p->iLimit && op==TK_ALL ){ regLimitA = ++pParse->nMem; regLimitB = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, + tdsqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, regLimitA); - sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); + tdsqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); }else{ regLimitA = regLimitB = 0; } - sqlite3ExprDelete(db, p->pLimit); + tdsqlite3ExprDelete(db, p->pLimit); p->pLimit = 0; - sqlite3ExprDelete(db, p->pOffset); - p->pOffset = 0; regAddrA = ++pParse->nMem; regAddrB = ++pParse->nMem; regOutA = ++pParse->nMem; regOutB = ++pParse->nMem; - sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); - sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); + tdsqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); + tdsqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); + + ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op))); /* Generate a coroutine to evaluate the SELECT statement to the ** left of the compound operator - the "A" select. */ - addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; - addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); + addrSelectA = tdsqlite3VdbeCurrentAddr(v) + 1; + addr1 = tdsqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); VdbeComment((v, "left SELECT")); pPrior->iLimit = regLimitA; - explainSetInteger(iSub1, pParse->iNextSelectId); - sqlite3Select(pParse, pPrior, &destA); - sqlite3VdbeEndCoroutine(v, regAddrA); - sqlite3VdbeJumpHere(v, addr1); + ExplainQueryPlan((pParse, 1, "LEFT")); + tdsqlite3Select(pParse, pPrior, &destA); + tdsqlite3VdbeEndCoroutine(v, regAddrA); + tdsqlite3VdbeJumpHere(v, addr1); /* Generate a coroutine to evaluate the SELECT statement on ** the right - the "B" select */ - addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; - addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); + addrSelectB = tdsqlite3VdbeCurrentAddr(v) + 1; + addr1 = tdsqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); VdbeComment((v, "right SELECT")); savedLimit = p->iLimit; savedOffset = p->iOffset; p->iLimit = regLimitB; p->iOffset = 0; - explainSetInteger(iSub2, pParse->iNextSelectId); - sqlite3Select(pParse, p, &destB); + ExplainQueryPlan((pParse, 1, "RIGHT")); + tdsqlite3Select(pParse, p, &destB); p->iLimit = savedLimit; p->iOffset = savedOffset; - sqlite3VdbeEndCoroutine(v, regAddrB); + tdsqlite3VdbeEndCoroutine(v, regAddrB); /* Generate a subroutine that outputs the current row of the A ** select as the next output row of the compound select. @@ -120496,7 +134844,7 @@ static int multiSelectOrderBy( p, &destB, pDest, regOutB, regPrev, pKeyDup, labelEnd); } - sqlite3KeyInfoUnref(pKeyDup); + tdsqlite3KeyInfoUnref(pKeyDup); /* Generate a subroutine to run when the results from select A ** are exhausted and only data in select B remains. @@ -120505,11 +134853,11 @@ static int multiSelectOrderBy( addrEofA_noB = addrEofA = labelEnd; }else{ VdbeNoopComment((v, "eof-A subroutine")); - addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); - addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); + addrEofA = tdsqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); + addrEofA_noB = tdsqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); VdbeCoverage(v); - sqlite3VdbeGoto(v, addrEofA); - p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); + tdsqlite3VdbeGoto(v, addrEofA); + p->nSelectRow = tdsqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); } /* Generate a subroutine to run when the results from select B @@ -120520,17 +134868,17 @@ static int multiSelectOrderBy( if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; }else{ VdbeNoopComment((v, "eof-B subroutine")); - addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); - sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); - sqlite3VdbeGoto(v, addrEofB); + addrEofB = tdsqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); + tdsqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); + tdsqlite3VdbeGoto(v, addrEofB); } /* Generate code to handle the case of A<B */ VdbeNoopComment((v, "A-lt-B subroutine")); - addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); - sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); - sqlite3VdbeGoto(v, labelCmpr); + addrAltB = tdsqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); + tdsqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); + tdsqlite3VdbeGoto(v, labelCmpr); /* Generate code to handle the case of A==B */ @@ -120542,66 +134890,73 @@ static int multiSelectOrderBy( }else{ VdbeNoopComment((v, "A-eq-B subroutine")); addrAeqB = - sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); - sqlite3VdbeGoto(v, labelCmpr); + tdsqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); + tdsqlite3VdbeGoto(v, labelCmpr); } /* Generate code to handle the case of A>B */ VdbeNoopComment((v, "A-gt-B subroutine")); - addrAgtB = sqlite3VdbeCurrentAddr(v); + addrAgtB = tdsqlite3VdbeCurrentAddr(v); if( op==TK_ALL || op==TK_UNION ){ - sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); + tdsqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); } - sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); - sqlite3VdbeGoto(v, labelCmpr); + tdsqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); + tdsqlite3VdbeGoto(v, labelCmpr); /* This code runs once to initialize everything. */ - sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addr1); + tdsqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); /* Implement the main merge loop */ - sqlite3VdbeResolveLabel(v, labelCmpr); - sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); - sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, + tdsqlite3VdbeResolveLabel(v, labelCmpr); + tdsqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); + tdsqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, (char*)pKeyMerge, P4_KEYINFO); - sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); - sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); + tdsqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); + tdsqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); /* Jump to the this point in order to terminate the query. */ - sqlite3VdbeResolveLabel(v, labelEnd); - - /* Set the number of output columns - */ - if( pDest->eDest==SRT_Output ){ - Select *pFirst = pPrior; - while( pFirst->pPrior ) pFirst = pFirst->pPrior; - generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); - } + tdsqlite3VdbeResolveLabel(v, labelEnd); /* Reassembly the compound query so that it will be freed correctly ** by the calling function */ if( p->pPrior ){ - sqlite3SelectDelete(db, p->pPrior); + tdsqlite3SelectDelete(db, p->pPrior); } p->pPrior = pPrior; pPrior->pNext = p; /*** TBD: Insert subroutine calls to close cursors on incomplete **** subqueries ****/ - explainComposite(pParse, p->op, iSub1, iSub2, 0); + ExplainQueryPlanPop(pParse); return pParse->nErr!=0; } #endif #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) + +/* An instance of the SubstContext object describes an substitution edit +** to be performed on a parse tree. +** +** All references to columns in table iTable are to be replaced by corresponding +** expressions in pEList. +*/ +typedef struct SubstContext { + Parse *pParse; /* The parsing context */ + int iTable; /* Replace references to this table */ + int iNewTable; /* New table number */ + int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */ + ExprList *pEList; /* Replacement expressions */ +} SubstContext; + /* Forward Declarations */ -static void substExprList(sqlite3*, ExprList*, int, ExprList*); -static void substSelect(sqlite3*, Select *, int, ExprList*, int); +static void substExprList(SubstContext*, ExprList*); +static void substSelect(SubstContext*, Select*, int); /* ** Scan through the expression pExpr. Replace every reference to @@ -120612,74 +134967,118 @@ static void substSelect(sqlite3*, Select *, int, ExprList*, int); ** This routine is part of the flattening procedure. A subquery ** whose result set is defined by pEList appears as entry in the ** FROM clause of a SELECT such that the VDBE cursor assigned to that -** FORM clause entry is iTable. This routine make the necessary +** FORM clause entry is iTable. This routine makes the necessary ** changes to pExpr so that it refers directly to the source table ** of the subquery rather the result set of the subquery. */ static Expr *substExpr( - sqlite3 *db, /* Report malloc errors to this connection */ - Expr *pExpr, /* Expr in which substitution occurs */ - int iTable, /* Table to be substituted */ - ExprList *pEList /* Substitute expressions */ + SubstContext *pSubst, /* Description of the substitution */ + Expr *pExpr /* Expr in which substitution occurs */ ){ if( pExpr==0 ) return 0; - if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ + if( ExprHasProperty(pExpr, EP_FromJoin) + && pExpr->iRightJoinTable==pSubst->iTable + ){ + pExpr->iRightJoinTable = pSubst->iNewTable; + } + if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){ if( pExpr->iColumn<0 ){ pExpr->op = TK_NULL; }else{ Expr *pNew; - assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); - assert( pExpr->pLeft==0 && pExpr->pRight==0 ); - pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0); - sqlite3ExprDelete(db, pExpr); - pExpr = pNew; + Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr; + Expr ifNullRow; + assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr ); + assert( pExpr->pRight==0 ); + if( tdsqlite3ExprIsVector(pCopy) ){ + tdsqlite3VectorErrorMsg(pSubst->pParse, pCopy); + }else{ + tdsqlite3 *db = pSubst->pParse->db; + if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){ + memset(&ifNullRow, 0, sizeof(ifNullRow)); + ifNullRow.op = TK_IF_NULL_ROW; + ifNullRow.pLeft = pCopy; + ifNullRow.iTable = pSubst->iNewTable; + pCopy = &ifNullRow; + } + testcase( ExprHasProperty(pCopy, EP_Subquery) ); + pNew = tdsqlite3ExprDup(db, pCopy, 0); + if( pNew && pSubst->isLeftJoin ){ + ExprSetProperty(pNew, EP_CanBeNull); + } + if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){ + pNew->iRightJoinTable = pExpr->iRightJoinTable; + ExprSetProperty(pNew, EP_FromJoin); + } + tdsqlite3ExprDelete(db, pExpr); + pExpr = pNew; + + /* Ensure that the expression now has an implicit collation sequence, + ** just as it did when it was a column of a view or sub-query. */ + if( pExpr ){ + if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){ + CollSeq *pColl = tdsqlite3ExprCollSeq(pSubst->pParse, pExpr); + pExpr = tdsqlite3ExprAddCollateString(pSubst->pParse, pExpr, + (pColl ? pColl->zName : "BINARY") + ); + } + ExprClearProperty(pExpr, EP_Collate); + } + } } }else{ - pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList); - pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList); + if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){ + pExpr->iTable = pSubst->iNewTable; + } + pExpr->pLeft = substExpr(pSubst, pExpr->pLeft); + pExpr->pRight = substExpr(pSubst, pExpr->pRight); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - substSelect(db, pExpr->x.pSelect, iTable, pEList, 1); + substSelect(pSubst, pExpr->x.pSelect, 1); }else{ - substExprList(db, pExpr->x.pList, iTable, pEList); + substExprList(pSubst, pExpr->x.pList); + } +#ifndef SQLITE_OMIT_WINDOWFUNC + if( ExprHasProperty(pExpr, EP_WinFunc) ){ + Window *pWin = pExpr->y.pWin; + pWin->pFilter = substExpr(pSubst, pWin->pFilter); + substExprList(pSubst, pWin->pPartition); + substExprList(pSubst, pWin->pOrderBy); } +#endif } return pExpr; } static void substExprList( - sqlite3 *db, /* Report malloc errors here */ - ExprList *pList, /* List to scan and in which to make substitutes */ - int iTable, /* Table to be substituted */ - ExprList *pEList /* Substitute values */ + SubstContext *pSubst, /* Description of the substitution */ + ExprList *pList /* List to scan and in which to make substitutes */ ){ int i; if( pList==0 ) return; for(i=0; i<pList->nExpr; i++){ - pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList); + pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr); } } static void substSelect( - sqlite3 *db, /* Report malloc errors here */ - Select *p, /* SELECT statement in which to make substitutions */ - int iTable, /* Table to be replaced */ - ExprList *pEList, /* Substitute values */ - int doPrior /* Do substitutes on p->pPrior too */ + SubstContext *pSubst, /* Description of the substitution */ + Select *p, /* SELECT statement in which to make substitutions */ + int doPrior /* Do substitutes on p->pPrior too */ ){ SrcList *pSrc; struct SrcList_item *pItem; int i; if( !p ) return; do{ - substExprList(db, p->pEList, iTable, pEList); - substExprList(db, p->pGroupBy, iTable, pEList); - substExprList(db, p->pOrderBy, iTable, pEList); - p->pHaving = substExpr(db, p->pHaving, iTable, pEList); - p->pWhere = substExpr(db, p->pWhere, iTable, pEList); + substExprList(pSubst, p->pEList); + substExprList(pSubst, p->pGroupBy); + substExprList(pSubst, p->pOrderBy); + p->pHaving = substExpr(pSubst, p->pHaving); + p->pWhere = substExpr(pSubst, p->pWhere); pSrc = p->pSrc; assert( pSrc!=0 ); for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ - substSelect(db, pItem->pSelect, iTable, pEList, 1); + substSelect(pSubst, pItem->pSelect, 1); if( pItem->fg.isTabFunc ){ - substExprList(db, pItem->u1.pFuncArg, iTable, pEList); + substExprList(pSubst, pItem->u1.pFuncArg); } } }while( doPrior && (p = p->pPrior)!=0 ); @@ -120713,66 +135112,76 @@ static void substSelect( ** exist on the table t1, a complete scan of the data might be ** avoided. ** -** Flattening is only attempted if all of the following are true: +** Flattening is subject to the following constraints: ** -** (1) The subquery and the outer query do not both use aggregates. +** (**) We no longer attempt to flatten aggregate subqueries. Was: +** The subquery and the outer query cannot both be aggregates. ** -** (2) The subquery is not an aggregate or (2a) the outer query is not a join -** and (2b) the outer query does not use subqueries other than the one -** FROM-clause subquery that is a candidate for flattening. (2b is -** due to ticket [2f7170d73bf9abf80] from 2015-02-09.) +** (**) We no longer attempt to flatten aggregate subqueries. Was: +** (2) If the subquery is an aggregate then +** (2a) the outer query must not be a join and +** (2b) the outer query must not use subqueries +** other than the one FROM-clause subquery that is a candidate +** for flattening. (This is due to ticket [2f7170d73bf9abf80] +** from 2015-02-09.) ** -** (3) The subquery is not the right operand of a left outer join -** (Originally ticket #306. Strengthened by ticket #3300) +** (3) If the subquery is the right operand of a LEFT JOIN then +** (3a) the subquery may not be a join and +** (3b) the FROM clause of the subquery may not contain a virtual +** table and +** (3c) the outer query may not be an aggregate. +** (3d) the outer query may not be DISTINCT. ** -** (4) The subquery is not DISTINCT. +** (4) The subquery can not be DISTINCT. ** ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT ** sub-queries that were excluded from this optimization. Restriction ** (4) has since been expanded to exclude all DISTINCT subqueries. ** -** (6) The subquery does not use aggregates or the outer query is not -** DISTINCT. +** (**) We no longer attempt to flatten aggregate subqueries. Was: +** If the subquery is aggregate, the outer query may not be DISTINCT. ** -** (7) The subquery has a FROM clause. TODO: For subqueries without -** A FROM clause, consider adding a FROM close with the special +** (7) The subquery must have a FROM clause. TODO: For subqueries without +** A FROM clause, consider adding a FROM clause with the special ** table sqlite_once that consists of a single row containing a ** single NULL. ** -** (8) The subquery does not use LIMIT or the outer query is not a join. +** (8) If the subquery uses LIMIT then the outer query may not be a join. ** -** (9) The subquery does not use LIMIT or the outer query does not use -** aggregates. +** (9) If the subquery uses LIMIT then the outer query may not be aggregate. ** ** (**) Restriction (10) was removed from the code on 2005-02-05 but we ** accidently carried the comment forward until 2014-09-15. Original -** text: "The subquery does not use aggregates or the outer query -** does not use LIMIT." +** constraint: "If the subquery is aggregate then the outer query +** may not use LIMIT." ** -** (11) The subquery and the outer query do not both have ORDER BY clauses. +** (11) The subquery and the outer query may not both have ORDER BY clauses. ** ** (**) Not implemented. Subsumed into restriction (3). Was previously ** a separate restriction deriving from ticket #350. ** -** (13) The subquery and outer query do not both use LIMIT. +** (13) The subquery and outer query may not both use LIMIT. ** -** (14) The subquery does not use OFFSET. +** (14) The subquery may not use OFFSET. ** -** (15) The outer query is not part of a compound select or the -** subquery does not have a LIMIT clause. +** (15) If the outer query is part of a compound select, then the +** subquery may not use LIMIT. ** (See ticket #2339 and ticket [02a8e81d44]). ** -** (16) The outer query is not an aggregate or the subquery does -** not contain ORDER BY. (Ticket #2942) This used to not matter +** (16) If the outer query is aggregate, then the subquery may not +** use ORDER BY. (Ticket #2942) This used to not matter ** until we introduced the group_concat() function. ** -** (17) The sub-query is not a compound select, or it is a UNION ALL -** compound clause made up entirely of non-aggregate queries, and -** the parent query: -** -** * is not itself part of a compound select, -** * is not an aggregate or DISTINCT query, and -** * is not a join +** (17) If the subquery is a compound select, then +** (17a) all compound operators must be a UNION ALL, and +** (17b) no terms within the subquery compound may be aggregate +** or DISTINCT, and +** (17c) every term within the subquery compound must have a FROM clause +** (17d) the outer query may not be +** (17d1) aggregate, or +** (17d2) DISTINCT, or +** (17d3) a join. +** (17e) the subquery may not contain window functions ** ** The parent and sub-query may contain WHERE clauses. Subject to ** rules (11), (13) and (14), they may also contain ORDER BY, @@ -120788,10 +135197,10 @@ static void substSelect( ** syntax error and return a detailed message. ** ** (18) If the sub-query is a compound select, then all terms of the -** ORDER by clause of the parent must be simple references to +** ORDER BY clause of the parent must be simple references to ** columns of the sub-query. ** -** (19) The subquery does not use LIMIT or the outer query does not +** (19) If the subquery uses LIMIT then the outer query may not ** have a WHERE clause. ** ** (20) If the sub-query is a compound select, then it must not use @@ -120800,25 +135209,31 @@ static void substSelect( ** appear as unmodified result columns in the outer query. But we ** have other optimizations in mind to deal with that case. ** -** (21) The subquery does not use LIMIT or the outer query is not +** (21) If the subquery uses LIMIT then the outer query may not be ** DISTINCT. (See ticket [752e1646fc]). ** -** (22) The subquery is not a recursive CTE. +** (22) The subquery may not be a recursive CTE. ** -** (23) The parent is not a recursive CTE, or the sub-query is not a -** compound query. This restriction is because transforming the +** (**) Subsumed into restriction (17d3). Was: If the outer query is +** a recursive CTE, then the sub-query may not be a compound query. +** This restriction is because transforming the ** parent to a compound query confuses the code that handles ** recursive queries in multiSelect(). ** -** (24) The subquery is not an aggregate that uses the built-in min() or +** (**) We no longer attempt to flatten aggregate subqueries. Was: +** The subquery may not be an aggregate that uses the built-in min() or ** or max() functions. (Without this restriction, a query like: ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily ** return the value X for which Y was maximal.) ** +** (25) If either the subquery or the parent query contains a window +** function in the select list or ORDER BY clause, flattening +** is not attempted. +** ** ** In this routine, the "p" parameter is a pointer to the outer query. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query -** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. +** uses aggregates. ** ** If flattening is not attempted, this routine is a no-op and returns 0. ** If flattening is attempted this routine returns 1. @@ -120830,8 +135245,7 @@ static int flattenSubquery( Parse *pParse, /* Parsing context */ Select *p, /* The parent or outer SELECT statement */ int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ - int isAgg, /* True if outer SELECT uses aggregate functions */ - int subqueryIsAgg /* True if the subquery uses aggregate functions */ + int isAgg /* True if outer SELECT uses aggregate functions */ ){ const char *zSavedAuthContext = pParse->zAuthContext; Select *pParent; /* Current UNION ALL term of the other query */ @@ -120839,17 +135253,18 @@ static int flattenSubquery( Select *pSub1; /* Pointer to the rightmost select in sub-query */ SrcList *pSrc; /* The FROM clause of the outer query */ SrcList *pSubSrc; /* The FROM clause of the subquery */ - ExprList *pList; /* The result set of the outer query */ int iParent; /* VDBE cursor number of the pSub result set temp table */ + int iNewParent = -1;/* Replacement table for iParent */ + int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ int i; /* Loop counter */ Expr *pWhere; /* The WHERE clause */ struct SrcList_item *pSubitem; /* The subquery */ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; /* Check to see if flattening is permitted. Return 0 if not. */ assert( p!=0 ); - assert( p->pPrior==0 ); /* Unable to flatten compound queries */ + assert( p->pPrior==0 ); if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; pSrc = p->pSrc; assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); @@ -120857,17 +135272,11 @@ static int flattenSubquery( iParent = pSubitem->iCursor; pSub = pSubitem->pSelect; assert( pSub!=0 ); - if( subqueryIsAgg ){ - if( isAgg ) return 0; /* Restriction (1) */ - if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */ - if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery)) - || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0 - || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0 - ){ - return 0; /* Restriction (2b) */ - } - } - + +#ifndef SQLITE_OMIT_WINDOWFUNC + if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ +#endif + pSubSrc = pSub->pSrc; assert( pSubSrc ); /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, @@ -120876,18 +135285,15 @@ static int flattenSubquery( ** became arbitrary expressions, we were forced to add restrictions (13) ** and (14). */ if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ - if( pSub->pOffset ) return 0; /* Restriction (14) */ + if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ return 0; /* Restriction (15) */ } if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ - if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ + if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ return 0; /* Restrictions (8)(9) */ } - if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ - return 0; /* Restriction (6) */ - } if( p->pOrderBy && pSub->pOrderBy ){ return 0; /* Restriction (11) */ } @@ -120896,19 +135302,14 @@ static int flattenSubquery( if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ return 0; /* Restriction (21) */ } - testcase( pSub->selFlags & SF_Recursive ); - testcase( pSub->selFlags & SF_MinMaxAgg ); - if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){ - return 0; /* Restrictions (22) and (24) */ - } - if( (p->selFlags & SF_Recursive) && pSub->pPrior ){ - return 0; /* Restriction (23) */ + if( pSub->selFlags & (SF_Recursive) ){ + return 0; /* Restrictions (22) */ } - /* OBSOLETE COMMENT 1: - ** Restriction 3: If the subquery is a join, make sure the subquery is - ** not used as the right operand of an outer join. Examples of why this - ** is not allowed: + /* + ** If the subquery is the right operand of a LEFT JOIN, then the + ** subquery may not be a join itself (3a). Example of why this is not + ** allowed: ** ** t1 LEFT OUTER JOIN (t2 JOIN t3) ** @@ -120918,56 +135319,63 @@ static int flattenSubquery( ** ** which is not at all the same thing. ** - ** OBSOLETE COMMENT 2: - ** Restriction 12: If the subquery is the right operand of a left outer - ** join, make sure the subquery has no WHERE clause. - ** An examples of why this is not allowed: - ** - ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) - ** - ** If we flatten the above, we would get - ** - ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 - ** - ** But the t2.x>0 test will always fail on a NULL row of t2, which - ** effectively converts the OUTER JOIN into an INNER JOIN. + ** If the subquery is the right operand of a LEFT JOIN, then the outer + ** query cannot be an aggregate. (3c) This is an artifact of the way + ** aggregates are processed - there is no mechanism to determine if + ** the LEFT JOIN table should be all-NULL. ** - ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE: - ** Ticket #3300 shows that flattening the right term of a LEFT JOIN - ** is fraught with danger. Best to avoid the whole thing. If the - ** subquery is the right term of a LEFT JOIN, then do not flatten. + ** See also tickets #306, #350, and #3300. */ if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ - return 0; + isLeftJoin = 1; + if( pSubSrc->nSrc>1 /* (3a) */ + || isAgg /* (3b) */ + || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */ + || (p->selFlags & SF_Distinct)!=0 /* (3d) */ + ){ + return 0; + } } +#ifdef SQLITE_EXTRA_IFNULLROW + else if( iFrom>0 && !isAgg ){ + /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for + ** every reference to any result column from subquery in a join, even + ** though they are not necessary. This will stress-test the OP_IfNullRow + ** opcode. */ + isLeftJoin = -1; + } +#endif - /* Restriction 17: If the sub-query is a compound SELECT, then it must + /* Restriction (17): If the sub-query is a compound SELECT, then it must ** use only the UNION ALL operator. And none of the simple select queries ** that make up the compound SELECT are allowed to be aggregate or distinct ** queries. */ if( pSub->pPrior ){ if( pSub->pOrderBy ){ - return 0; /* Restriction 20 */ + return 0; /* Restriction (20) */ } if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ - return 0; + return 0; /* (17d1), (17d2), or (17d3) */ } for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); assert( pSub->pSrc!=0 ); assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); - if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 - || (pSub1->pPrior && pSub1->op!=TK_ALL) - || pSub1->pSrc->nSrc<1 + if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ + || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ + || pSub1->pSrc->nSrc<1 /* (17c) */ +#ifndef SQLITE_OMIT_WINDOWFUNC + || pSub1->pWin /* (17e) */ +#endif ){ return 0; } testcase( pSub1->pSrc->nSrc>1 ); } - /* Restriction 18. */ + /* Restriction (18). */ if( p->pOrderBy ){ int ii; for(ii=0; ii<p->pOrderBy->nExpr; ii++){ @@ -120976,13 +135384,21 @@ static int flattenSubquery( } } + /* Ex-restriction (23): + ** The only way that the recursive part of a CTE can contain a compound + ** subquery is for the subquery to be one term of a join. But if the + ** subquery is a join, then the flattening has already been stopped by + ** restriction (17d3) + */ + assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); + /***** If we reach this point, flattening is permitted. *****/ - SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n", - pSub->zSelName, pSub, iFrom)); + SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n", + pSub->selId, pSub, iFrom)); /* Authorize the subquery */ pParse->zAuthContext = pSubitem->zName; - TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); + TESTONLY(i =) tdsqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); testcase( i==SQLITE_DENY ); pParse->zAuthContext = zSavedAuthContext; @@ -121023,16 +135439,12 @@ static int flattenSubquery( Select *pNew; ExprList *pOrderBy = p->pOrderBy; Expr *pLimit = p->pLimit; - Expr *pOffset = p->pOffset; Select *pPrior = p->pPrior; p->pOrderBy = 0; p->pSrc = 0; p->pPrior = 0; p->pLimit = 0; - p->pOffset = 0; - pNew = sqlite3SelectDup(db, p, 0); - sqlite3SelectSetName(pNew, pSub->zSelName); - p->pOffset = pOffset; + pNew = tdsqlite3SelectDup(db, p, 0); p->pLimit = pLimit; p->pOrderBy = pOrderBy; p->pSrc = pSrc; @@ -121044,9 +135456,8 @@ static int flattenSubquery( if( pPrior ) pPrior->pNext = pNew; pNew->pNext = p; p->pPrior = pNew; - SELECTTRACE(2,pParse,p, - ("compound-subquery flattener creates %s.%p as peer\n", - pNew->zSelName, pNew)); + SELECTTRACE(2,pParse,p,("compound-subquery flattener" + " creates %u as peer\n",pNew->selId)); } if( db->mallocFailed ) return 1; } @@ -121059,9 +135470,9 @@ static int flattenSubquery( /* Delete the transient table structure associated with the ** subquery */ - sqlite3DbFree(db, pSubitem->zDatabase); - sqlite3DbFree(db, pSubitem->zName); - sqlite3DbFree(db, pSubitem->zAlias); + tdsqlite3DbFree(db, pSubitem->zDatabase); + tdsqlite3DbFree(db, pSubitem->zName); + tdsqlite3DbFree(db, pSubitem->zAlias); pSubitem->zDatabase = 0; pSubitem->zName = 0; pSubitem->zAlias = 0; @@ -121076,12 +135487,12 @@ static int flattenSubquery( */ if( ALWAYS(pSubitem->pTab!=0) ){ Table *pTabToDel = pSubitem->pTab; - if( pTabToDel->nRef==1 ){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); + if( pTabToDel->nTabRef==1 ){ + Parse *pToplevel = tdsqlite3ParseToplevel(pParse); pTabToDel->pNextZombie = pToplevel->pZombieTab; pToplevel->pZombieTab = pTabToDel; }else{ - pTabToDel->nRef--; + pTabToDel->nTabRef--; } pSubitem->pTab = 0; } @@ -121102,6 +135513,7 @@ static int flattenSubquery( for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ int nSubSrc; u8 jointype = 0; + assert( pSub!=0 ); pSubSrc = pSub->pSrc; /* FROM clause of subquery */ nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ pSrc = pParent->pSrc; /* FROM clause of the outer query */ @@ -121111,11 +135523,9 @@ static int flattenSubquery( jointype = pSubitem->fg.jointype; }else{ assert( pParent!=p ); /* 2nd and subsequent times through the loop */ - pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); - if( pSrc==0 ){ - assert( db->mallocFailed ); - break; - } + pSrc = tdsqlite3SrcListAppend(pParse, 0, 0, 0); + if( pSrc==0 ) break; + pParent->pSrc = pSrc; } /* The subquery uses a single slot of the FROM clause of the outer @@ -121134,19 +135544,19 @@ static int flattenSubquery( ** for the two elements in the FROM clause of the subquery. */ if( nSubSrc>1 ){ - pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); - if( db->mallocFailed ){ - break; - } + pSrc = tdsqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1); + if( pSrc==0 ) break; + pParent->pSrc = pSrc; } /* Transfer the FROM clause terms from the subquery into the ** outer query. */ for(i=0; i<nSubSrc; i++){ - sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); + tdsqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); pSrc->a[i+iFrom] = pSubSrc->a[i]; + iNewParent = pSubSrc->a[i].iCursor; memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); } pSrc->a[iFrom].fg.jointype = jointype; @@ -121163,14 +135573,6 @@ static int flattenSubquery( ** We look at every expression in the outer query and every place we see ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". */ - pList = pParent->pEList; - for(i=0; i<pList->nExpr; i++){ - if( pList->a[i].zName==0 ){ - char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); - sqlite3Dequote(zName); - pList->a[i].zName = zName; - } - } if( pSub->pOrderBy ){ /* At this point, any non-zero iOrderByCol values indicate that the ** ORDER BY column expression is identical to the iOrderByCol'th @@ -121187,29 +135589,29 @@ static int flattenSubquery( pOrderBy->a[i].u.x.iOrderByCol = 0; } assert( pParent->pOrderBy==0 ); - assert( pSub->pPrior==0 ); pParent->pOrderBy = pOrderBy; pSub->pOrderBy = 0; } - pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); - if( subqueryIsAgg ){ - assert( pParent->pHaving==0 ); - pParent->pHaving = pParent->pWhere; - pParent->pWhere = pWhere; - pParent->pHaving = sqlite3ExprAnd(db, - sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving - ); - assert( pParent->pGroupBy==0 ); - pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); - }else{ - pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere); + pWhere = pSub->pWhere; + pSub->pWhere = 0; + if( isLeftJoin>0 ){ + tdsqlite3SetJoinExpr(pWhere, iNewParent); + } + pParent->pWhere = tdsqlite3ExprAnd(pParse, pWhere, pParent->pWhere); + if( db->mallocFailed==0 ){ + SubstContext x; + x.pParse = pParse; + x.iTable = iParent; + x.iNewTable = iNewParent; + x.isLeftJoin = isLeftJoin; + x.pEList = pSub->pEList; + substSelect(&x, pParent, 0); } - substSelect(db, pParent, iParent, pSub->pEList, 0); - /* The flattened query is distinct if either the inner or the - ** outer query is distinct. - */ - pParent->selFlags |= pSub->selFlags & SF_Distinct; + /* The flattened query is a compound if either the inner or the + ** outer query is a compound. */ + pParent->selFlags |= pSub->selFlags & SF_Compound; + assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */ /* ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; @@ -121226,12 +135628,12 @@ static int flattenSubquery( /* Finially, delete what is left of the subquery and return ** success. */ - sqlite3SelectDelete(db, pSub1); + tdsqlite3SelectDelete(db, pSub1); #if SELECTTRACE_ENABLED - if( sqlite3SelectTrace & 0x100 ){ + if( tdsqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,("After flattening:\n")); - sqlite3TreeViewSelect(0, p, 0); + tdsqlite3TreeViewSelect(0, p, 0); } #endif @@ -121239,7 +135641,193 @@ static int flattenSubquery( } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ +/* +** A structure to keep track of all of the column values that are fixed to +** a known value due to WHERE clause constraints of the form COLUMN=VALUE. +*/ +typedef struct WhereConst WhereConst; +struct WhereConst { + Parse *pParse; /* Parsing context */ + int nConst; /* Number for COLUMN=CONSTANT terms */ + int nChng; /* Number of times a constant is propagated */ + Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */ +}; + +/* +** Add a new entry to the pConst object. Except, do not add duplicate +** pColumn entires. Also, do not add if doing so would not be appropriate. +** +** The caller guarantees the pColumn is a column and pValue is a constant. +** This routine has to do some additional checks before completing the +** insert. +*/ +static void constInsert( + WhereConst *pConst, /* The WhereConst into which we are inserting */ + Expr *pColumn, /* The COLUMN part of the constraint */ + Expr *pValue, /* The VALUE part of the constraint */ + Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */ +){ + int i; + assert( pColumn->op==TK_COLUMN ); + assert( tdsqlite3ExprIsConstant(pValue) ); + + if( !ExprHasProperty(pValue, EP_FixedCol) && tdsqlite3ExprAffinity(pValue)!=0 ){ + return; + } + if( !tdsqlite3IsBinary(tdsqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){ + return; + } + + /* 2018-10-25 ticket [cf5ed20f] + ** Make sure the same pColumn is not inserted more than once */ + for(i=0; i<pConst->nConst; i++){ + const Expr *pE2 = pConst->apExpr[i*2]; + assert( pE2->op==TK_COLUMN ); + if( pE2->iTable==pColumn->iTable + && pE2->iColumn==pColumn->iColumn + ){ + return; /* Already present. Return without doing anything. */ + } + } + + pConst->nConst++; + pConst->apExpr = tdsqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr, + pConst->nConst*2*sizeof(Expr*)); + if( pConst->apExpr==0 ){ + pConst->nConst = 0; + }else{ + if( ExprHasProperty(pValue, EP_FixedCol) ){ + pValue = pValue->pLeft; + } + pConst->apExpr[pConst->nConst*2-2] = pColumn; + pConst->apExpr[pConst->nConst*2-1] = pValue; + } +} + +/* +** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE +** is a constant expression and where the term must be true because it +** is part of the AND-connected terms of the expression. For each term +** found, add it to the pConst structure. +*/ +static void findConstInWhere(WhereConst *pConst, Expr *pExpr){ + Expr *pRight, *pLeft; + if( pExpr==0 ) return; + if( ExprHasProperty(pExpr, EP_FromJoin) ) return; + if( pExpr->op==TK_AND ){ + findConstInWhere(pConst, pExpr->pRight); + findConstInWhere(pConst, pExpr->pLeft); + return; + } + if( pExpr->op!=TK_EQ ) return; + pRight = pExpr->pRight; + pLeft = pExpr->pLeft; + assert( pRight!=0 ); + assert( pLeft!=0 ); + if( pRight->op==TK_COLUMN && tdsqlite3ExprIsConstant(pLeft) ){ + constInsert(pConst,pRight,pLeft,pExpr); + } + if( pLeft->op==TK_COLUMN && tdsqlite3ExprIsConstant(pRight) ){ + constInsert(pConst,pLeft,pRight,pExpr); + } +} + +/* +** This is a Walker expression callback. pExpr is a candidate expression +** to be replaced by a value. If pExpr is equivalent to one of the +** columns named in pWalker->u.pConst, then overwrite it with its +** corresponding value. +*/ +static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ + int i; + WhereConst *pConst; + if( pExpr->op!=TK_COLUMN ) return WRC_Continue; + if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){ + testcase( ExprHasProperty(pExpr, EP_FixedCol) ); + testcase( ExprHasProperty(pExpr, EP_FromJoin) ); + return WRC_Continue; + } + pConst = pWalker->u.pConst; + for(i=0; i<pConst->nConst; i++){ + Expr *pColumn = pConst->apExpr[i*2]; + if( pColumn==pExpr ) continue; + if( pColumn->iTable!=pExpr->iTable ) continue; + if( pColumn->iColumn!=pExpr->iColumn ) continue; + /* A match is found. Add the EP_FixedCol property */ + pConst->nChng++; + ExprClearProperty(pExpr, EP_Leaf); + ExprSetProperty(pExpr, EP_FixedCol); + assert( pExpr->pLeft==0 ); + pExpr->pLeft = tdsqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0); + break; + } + return WRC_Prune; +} +/* +** The WHERE-clause constant propagation optimization. +** +** If the WHERE clause contains terms of the form COLUMN=CONSTANT or +** CONSTANT=COLUMN that are top-level AND-connected terms that are not +** part of a ON clause from a LEFT JOIN, then throughout the query +** replace all other occurrences of COLUMN with CONSTANT. +** +** For example, the query: +** +** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b +** +** Is transformed into +** +** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39 +** +** Return true if any transformations where made and false if not. +** +** Implementation note: Constant propagation is tricky due to affinity +** and collating sequence interactions. Consider this example: +** +** CREATE TABLE t1(a INT,b TEXT); +** INSERT INTO t1 VALUES(123,'0123'); +** SELECT * FROM t1 WHERE a=123 AND b=a; +** SELECT * FROM t1 WHERE a=123 AND b=123; +** +** The two SELECT statements above should return different answers. b=a +** is alway true because the comparison uses numeric affinity, but b=123 +** is false because it uses text affinity and '0123' is not the same as '123'. +** To work around this, the expression tree is not actually changed from +** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol +** and the "123" value is hung off of the pLeft pointer. Code generator +** routines know to generate the constant "123" instead of looking up the +** column value. Also, to avoid collation problems, this optimization is +** only attempted if the "a=123" term uses the default BINARY collation. +*/ +static int propagateConstants( + Parse *pParse, /* The parsing context */ + Select *p /* The query in which to propagate constants */ +){ + WhereConst x; + Walker w; + int nChng = 0; + x.pParse = pParse; + do{ + x.nConst = 0; + x.nChng = 0; + x.apExpr = 0; + findConstInWhere(&x, p->pWhere); + if( x.nConst ){ + memset(&w, 0, sizeof(w)); + w.pParse = pParse; + w.xExprCallback = propagateConstantExprRewrite; + w.xSelectCallback = tdsqlite3SelectWalkNoop; + w.xSelectCallback2 = 0; + w.walkerDepth = 0; + w.u.pConst = &x; + tdsqlite3WalkExpr(&w, p->pWhere); + tdsqlite3DbFree(x.pParse->db, x.apExpr); + nChng += x.nChng; + } + }while( x.nChng ); + return nChng; +} #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* @@ -121258,57 +135846,106 @@ static int flattenSubquery( ** ** Do not attempt this optimization if: ** -** (1) The inner query is an aggregate. (In that case, we'd really want -** to copy the outer WHERE-clause terms onto the HAVING clause of the -** inner query. But they probably won't help there so do not bother.) +** (1) (** This restriction was removed on 2017-09-29. We used to +** disallow this optimization for aggregate subqueries, but now +** it is allowed by putting the extra terms on the HAVING clause. +** The added HAVING clause is pointless if the subquery lacks +** a GROUP BY clause. But such a HAVING clause is also harmless +** so there does not appear to be any reason to add extra logic +** to suppress it. **) ** ** (2) The inner query is the recursive part of a common table expression. ** ** (3) The inner query has a LIMIT clause (since the changes to the WHERE -** close would change the meaning of the LIMIT). +** clause would change the meaning of the LIMIT). ** -** (4) The inner query is the right operand of a LEFT JOIN. (The caller -** enforces this restriction since this routine does not have enough -** information to know.) +** (4) The inner query is the right operand of a LEFT JOIN and the +** expression to be pushed down does not come from the ON clause +** on that LEFT JOIN. ** ** (5) The WHERE clause expression originates in the ON or USING clause -** of a LEFT JOIN. +** of a LEFT JOIN where iCursor is not the right-hand table of that +** left join. An example: +** +** SELECT * +** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa +** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2) +** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2); +** +** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9). +** But if the (b2=2) term were to be pushed down into the bb subquery, +** then the (1,1,NULL) row would be suppressed. +** +** (6) The inner query features one or more window-functions (since +** changes to the WHERE clause of the inner query could change the +** window over which window functions are calculated). ** ** Return 0 if no changes are made and non-zero if one or more WHERE clause ** terms are duplicated into the subquery. */ static int pushDownWhereTerms( - sqlite3 *db, /* The database connection (for malloc()) */ + Parse *pParse, /* Parse context (for malloc() and error reporting) */ Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ Expr *pWhere, /* The WHERE clause of the outer query */ - int iCursor /* Cursor number of the subquery */ + int iCursor, /* Cursor number of the subquery */ + int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */ ){ Expr *pNew; int nChng = 0; - Select *pX; /* For looping over compound SELECTs in pSubq */ if( pWhere==0 ) return 0; - for(pX=pSubq; pX; pX=pX->pPrior){ - if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){ - testcase( pX->selFlags & SF_Aggregate ); - testcase( pX->selFlags & SF_Recursive ); - testcase( pX!=pSubq ); - return 0; /* restrictions (1) and (2) */ + if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */ + +#ifndef SQLITE_OMIT_WINDOWFUNC + if( pSubq->pWin ) return 0; /* restriction (6) */ +#endif + +#ifdef SQLITE_DEBUG + /* Only the first term of a compound can have a WITH clause. But make + ** sure no other terms are marked SF_Recursive in case something changes + ** in the future. + */ + { + Select *pX; + for(pX=pSubq; pX; pX=pX->pPrior){ + assert( (pX->selFlags & (SF_Recursive))==0 ); } } +#endif + if( pSubq->pLimit!=0 ){ return 0; /* restriction (3) */ } while( pWhere->op==TK_AND ){ - nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor); + nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, + iCursor, isLeftJoin); pWhere = pWhere->pLeft; } - if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */ - if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ + if( isLeftJoin + && (ExprHasProperty(pWhere,EP_FromJoin)==0 + || pWhere->iRightJoinTable!=iCursor) + ){ + return 0; /* restriction (4) */ + } + if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){ + return 0; /* restriction (5) */ + } + if( tdsqlite3ExprIsTableConstant(pWhere, iCursor) ){ nChng++; while( pSubq ){ - pNew = sqlite3ExprDup(db, pWhere, 0); - pNew = substExpr(db, pNew, iCursor, pSubq->pEList); - pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew); + SubstContext x; + pNew = tdsqlite3ExprDup(pParse->db, pWhere, 0); + unsetJoinExpr(pNew, -1); + x.pParse = pParse; + x.iTable = iCursor; + x.iNewTable = iCursor; + x.isLeftJoin = 0; + x.pEList = pSubq->pEList; + pNew = substExpr(&x, pNew); + if( pSubq->selFlags & SF_Aggregate ){ + pSubq->pHaving = tdsqlite3ExprAnd(pParse, pSubq->pHaving, pNew); + }else{ + pSubq->pWhere = tdsqlite3ExprAnd(pParse, pSubq->pWhere, pNew); + } pSubq = pSubq->pPrior; } } @@ -121317,42 +135954,47 @@ static int pushDownWhereTerms( #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ /* -** Based on the contents of the AggInfo structure indicated by the first -** argument, this function checks if the following are true: +** The pFunc is the only aggregate function in the query. Check to see +** if the query is a candidate for the min/max optimization. ** -** * the query contains just a single aggregate function, -** * the aggregate function is either min() or max(), and -** * the argument to the aggregate function is a column value. +** If the query is a candidate for the min/max optimization, then set +** *ppMinMax to be an ORDER BY clause to be used for the optimization +** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on +** whether pFunc is a min() or max() function. ** -** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX -** is returned as appropriate. Also, *ppMinMax is set to point to the -** list of arguments passed to the aggregate before returning. +** If the query is not a candidate for the min/max optimization, return +** WHERE_ORDERBY_NORMAL (which must be zero). ** -** Or, if the conditions above are not met, *ppMinMax is set to 0 and -** WHERE_ORDERBY_NORMAL is returned. +** This routine must be called after aggregate functions have been +** located but before their arguments have been subjected to aggregate +** analysis. */ -static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){ - int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ - - *ppMinMax = 0; - if( pAggInfo->nFunc==1 ){ - Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */ - ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */ - - assert( pExpr->op==TK_AGG_FUNCTION ); - if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){ - const char *zFunc = pExpr->u.zToken; - if( sqlite3StrICmp(zFunc, "min")==0 ){ - eRet = WHERE_ORDERBY_MIN; - *ppMinMax = pEList; - }else if( sqlite3StrICmp(zFunc, "max")==0 ){ - eRet = WHERE_ORDERBY_MAX; - *ppMinMax = pEList; - } - } - } - - assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 ); +static u8 minMaxQuery(tdsqlite3 *db, Expr *pFunc, ExprList **ppMinMax){ + int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ + ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */ + const char *zFunc; /* Name of aggregate function pFunc */ + ExprList *pOrderBy; + u8 sortFlags; + + assert( *ppMinMax==0 ); + assert( pFunc->op==TK_AGG_FUNCTION ); + assert( !IsWindowFunc(pFunc) ); + if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){ + return eRet; + } + zFunc = pFunc->u.zToken; + if( tdsqlite3StrICmp(zFunc, "min")==0 ){ + eRet = WHERE_ORDERBY_MIN; + sortFlags = KEYINFO_ORDER_BIGNULL; + }else if( tdsqlite3StrICmp(zFunc, "max")==0 ){ + eRet = WHERE_ORDERBY_MAX; + sortFlags = KEYINFO_ORDER_DESC; + }else{ + return eRet; + } + *ppMinMax = pOrderBy = tdsqlite3ExprListDup(db, pEList, 0); + assert( pOrderBy!=0 || db->mallocFailed ); + if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags; return eRet; } @@ -121386,7 +136028,7 @@ static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ if( pExpr->op!=TK_AGG_FUNCTION ) return 0; if( NEVER(pAggInfo->nFunc==0) ) return 0; if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; - if( pExpr->flags&EP_Distinct ) return 0; + if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0; return pTab; } @@ -121398,17 +136040,17 @@ static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate ** pFrom->pIndex and return SQLITE_OK. */ -SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ +SQLITE_PRIVATE int tdsqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ if( pFrom->pTab && pFrom->fg.isIndexedBy ){ Table *pTab = pFrom->pTab; char *zIndexedBy = pFrom->u1.zIndexedBy; Index *pIdx; for(pIdx=pTab->pIndex; - pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); + pIdx && tdsqlite3StrICmp(pIdx->zName, zIndexedBy); pIdx=pIdx->pNext ); if( !pIdx ){ - sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); + tdsqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); pParse->checkSchema = 1; return SQLITE_ERROR; } @@ -121441,7 +136083,7 @@ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ int i; Select *pNew; Select *pX; - sqlite3 *db; + tdsqlite3 *db; struct ExprList_item *a; SrcList *pNewSrc; Parse *pParse; @@ -121461,14 +136103,14 @@ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ pParse = pWalker->pParse; db = pParse->db; - pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); + pNew = tdsqlite3DbMallocZero(db, sizeof(*pNew) ); if( pNew==0 ) return WRC_Abort; memset(&dummy, 0, sizeof(dummy)); - pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); + pNewSrc = tdsqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); if( pNewSrc==0 ) return WRC_Abort; *pNew = *p; p->pSrc = pNewSrc; - p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); + p->pEList = tdsqlite3ExprListAppend(pParse, 0, tdsqlite3Expr(db, TK_ASTERISK, 0)); p->op = TK_SELECT; p->pWhere = 0; pNew->pGroupBy = 0; @@ -121477,13 +136119,15 @@ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ p->pPrior = 0; p->pNext = 0; p->pWith = 0; +#ifndef SQLITE_OMIT_WINDOWFUNC + p->pWinDefn = 0; +#endif p->selFlags &= ~SF_Compound; assert( (p->selFlags & SF_Converted)==0 ); p->selFlags |= SF_Converted; assert( pNew->pPrior!=0 ); pNew->pPrior->pNext = pNew; pNew->pLimit = 0; - pNew->pOffset = 0; return WRC_Continue; } @@ -121494,7 +136138,7 @@ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ */ static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ if( pFrom->fg.isTabFunc ){ - sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); + tdsqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); return 1; } return 0; @@ -121522,7 +136166,7 @@ static struct Cte *searchWith( for(p=pWith; p; p=p->pOuter){ int i; for(i=0; i<p->nCte; i++){ - if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ + if( tdsqlite3StrICmp(zName, p->a[i].zName)==0 ){ *ppContext = p; return &p->a[i]; } @@ -121542,7 +136186,7 @@ static struct Cte *searchWith( ** bFree==0, the With object will be freed along with the SELECT ** statement with which it is associated. */ -SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ +SQLITE_PRIVATE void tdsqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); if( pWith ){ assert( pParse->pWith!=pWith ); @@ -121572,11 +136216,14 @@ static int withExpand( struct SrcList_item *pFrom ){ Parse *pParse = pWalker->pParse; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; struct Cte *pCte; /* Matched CTE (or NULL if no match) */ With *pWith; /* WITH clause that pCte belongs to */ assert( pFrom->pTab==0 ); + if( pParse->nErr ){ + return SQLITE_ERROR; + } pCte = searchWith(pParse->pWith, pFrom, &pWith); if( pCte ){ @@ -121592,20 +136239,20 @@ static int withExpand( ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. ** In this case, proceed. */ if( pCte->zCteErr ){ - sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); + tdsqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); return SQLITE_ERROR; } if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; assert( pFrom->pTab==0 ); - pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); + pFrom->pTab = pTab = tdsqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ) return WRC_Abort; - pTab->nRef = 1; - pTab->zName = sqlite3DbStrDup(db, pCte->zName); + pTab->nTabRef = 1; + pTab->zName = tdsqlite3DbStrDup(db, pCte->zName); pTab->iPKey = -1; - pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); + pTab->nRowLogEst = 200; assert( 200==tdsqlite3LogEst(1048576) ); pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; - pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); + pFrom->pSelect = tdsqlite3SelectDup(db, pCte->pSelect, 0); if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; assert( pFrom->pSelect ); @@ -121619,36 +136266,45 @@ static int withExpand( struct SrcList_item *pItem = &pSrc->a[i]; if( pItem->zDatabase==0 && pItem->zName!=0 - && 0==sqlite3StrICmp(pItem->zName, pCte->zName) + && 0==tdsqlite3StrICmp(pItem->zName, pCte->zName) ){ pItem->pTab = pTab; pItem->fg.isRecursive = 1; - pTab->nRef++; + pTab->nTabRef++; pSel->selFlags |= SF_Recursive; } } } /* Only one recursive reference is permitted. */ - if( pTab->nRef>2 ){ - sqlite3ErrorMsg( + if( pTab->nTabRef>2 ){ + tdsqlite3ErrorMsg( pParse, "multiple references to recursive table: %s", pCte->zName ); return SQLITE_ERROR; } - assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 )); + assert( pTab->nTabRef==1 || + ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 )); pCte->zCteErr = "circular reference: %s"; pSavedWith = pParse->pWith; pParse->pWith = pWith; - sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel); + if( bMayRecursive ){ + Select *pPrior = pSel->pPrior; + assert( pPrior->pWith==0 ); + pPrior->pWith = pSel->pWith; + tdsqlite3WalkSelect(pWalker, pPrior); + pPrior->pWith = 0; + }else{ + tdsqlite3WalkSelect(pWalker, pSel); + } pParse->pWith = pWith; for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); pEList = pLeft->pEList; if( pCte->pCols ){ if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ - sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", + tdsqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", pCte->zName, pEList->nExpr, pCte->pCols->nExpr ); pParse->pWith = pSavedWith; @@ -121657,14 +136313,14 @@ static int withExpand( pEList = pCte->pCols; } - sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); + tdsqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); if( bMayRecursive ){ if( pSel->selFlags & SF_Recursive ){ pCte->zCteErr = "multiple recursive references: %s"; }else{ pCte->zCteErr = "recursive reference in a subquery: %s"; } - sqlite3WalkSelect(pWalker, pSel); + tdsqlite3WalkSelect(pWalker, pSel); } pCte->zCteErr = 0; pParse->pWith = pSavedWith; @@ -121680,15 +136336,17 @@ static int withExpand( ** clause, pop it from the stack stored as part of the Parse object. ** ** This function is used as the xSelectCallback2() callback by -** sqlite3SelectExpand() when walking a SELECT tree to resolve table +** tdsqlite3SelectExpand() when walking a SELECT tree to resolve table ** names and other FROM clause elements. */ static void selectPopWith(Walker *pWalker, Select *p){ Parse *pParse = pWalker->pParse; - With *pWith = findRightmost(p)->pWith; - if( pWith!=0 ){ - assert( pParse->pWith==pWith ); - pParse->pWith = pWith->pOuter; + if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){ + With *pWith = findRightmost(p)->pWith; + if( pWith!=0 ){ + assert( pParse->pWith==pWith || pParse->nErr ); + pParse->pWith = pWith->pOuter; + } } } #else @@ -121696,6 +136354,35 @@ static void selectPopWith(Walker *pWalker, Select *p){ #endif /* +** The SrcList_item structure passed as the second argument represents a +** sub-query in the FROM clause of a SELECT statement. This function +** allocates and populates the SrcList_item.pTab object. If successful, +** SQLITE_OK is returned. Otherwise, if an OOM error is encountered, +** SQLITE_NOMEM. +*/ +SQLITE_PRIVATE int tdsqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){ + Select *pSel = pFrom->pSelect; + Table *pTab; + + assert( pSel ); + pFrom->pTab = pTab = tdsqlite3DbMallocZero(pParse->db, sizeof(Table)); + if( pTab==0 ) return SQLITE_NOMEM; + pTab->nTabRef = 1; + if( pFrom->zAlias ){ + pTab->zName = tdsqlite3DbStrDup(pParse->db, pFrom->zAlias); + }else{ + pTab->zName = tdsqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId); + } + while( pSel->pPrior ){ pSel = pSel->pPrior; } + tdsqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); + pTab->iPKey = -1; + pTab->nRowLogEst = 200; assert( 200==tdsqlite3LogEst(1048576) ); + pTab->tabFlags |= TF_Ephemeral; + + return pParse->nErr ? SQLITE_ERROR : SQLITE_OK; +} + +/* ** This routine is a Walker callback for "expanding" a SELECT statement. ** "Expanding" means to do the following: ** @@ -121725,27 +136412,31 @@ static int selectExpander(Walker *pWalker, Select *p){ SrcList *pTabList; ExprList *pEList; struct SrcList_item *pFrom; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Expr *pE, *pRight, *pExpr; u16 selFlags = p->selFlags; + u32 elistFlags = 0; p->selFlags |= SF_Expanded; if( db->mallocFailed ){ return WRC_Abort; } - if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ + assert( p->pSrc!=0 ); + if( (selFlags & SF_Expanded)!=0 ){ return WRC_Prune; } + if( pWalker->eCode ){ + /* Renumber selId because it has been copied from a view */ + p->selId = ++pParse->nSelect; + } pTabList = p->pSrc; pEList = p->pEList; - if( pWalker->xSelectCallback2==selectPopWith ){ - sqlite3WithPush(pParse, findRightmost(p)->pWith, 0); - } + tdsqlite3WithPush(pParse, p->pWith, 0); /* Make sure cursor numbers have been assigned to all entries in ** the FROM clause of the SELECT statement. */ - sqlite3SrcListAssignCursors(pParse, pTabList); + tdsqlite3SrcListAssignCursors(pParse, pTabList); /* Look up every table named in the FROM clause of the select. If ** an entry of the FROM clause is a subquery instead of a table or view, @@ -121766,56 +136457,64 @@ static int selectExpander(Walker *pWalker, Select *p){ /* A sub-query in the FROM clause of a SELECT */ assert( pSel!=0 ); assert( pFrom->pTab==0 ); - if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; - pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); - if( pTab==0 ) return WRC_Abort; - pTab->nRef = 1; - pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab); - while( pSel->pPrior ){ pSel = pSel->pPrior; } - sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); - pTab->iPKey = -1; - pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); - pTab->tabFlags |= TF_Ephemeral; + if( tdsqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; + if( tdsqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort; #endif }else{ /* An ordinary table or view name in the FROM clause */ assert( pFrom->pTab==0 ); - pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); + pFrom->pTab = pTab = tdsqlite3LocateTableItem(pParse, 0, pFrom); if( pTab==0 ) return WRC_Abort; - if( pTab->nRef==0xffff ){ - sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", + if( pTab->nTabRef>=0xffff ){ + tdsqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", pTab->zName); pFrom->pTab = 0; return WRC_Abort; } - pTab->nRef++; + pTab->nTabRef++; if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ return WRC_Abort; } -#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) if( IsVirtual(pTab) || pTab->pSelect ){ i16 nCol; - if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; + u8 eCodeOrig = pWalker->eCode; + if( tdsqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; assert( pFrom->pSelect==0 ); - pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); - sqlite3SelectSetName(pFrom->pSelect, pTab->zName); + if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){ + tdsqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited", + pTab->zName); + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + if( IsVirtual(pTab) + && pFrom->fg.fromDDL + && ALWAYS(pTab->pVTable!=0) + && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0) + ){ + tdsqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"", + pTab->zName); + } +#endif + pFrom->pSelect = tdsqlite3SelectDup(db, pTab->pSelect, 0); nCol = pTab->nCol; pTab->nCol = -1; - sqlite3WalkSelect(pWalker, pFrom->pSelect); + pWalker->eCode = 1; /* Turn on Select.selId renumbering */ + tdsqlite3WalkSelect(pWalker, pFrom->pSelect); + pWalker->eCode = eCodeOrig; pTab->nCol = nCol; } #endif } /* Locate the index named by the INDEXED BY clause, if any. */ - if( sqlite3IndexedByLookup(pParse, pFrom) ){ + if( tdsqlite3IndexedByLookup(pParse, pFrom) ){ return WRC_Abort; } } /* Process NATURAL keywords, and ON and USING clauses of joins. */ - if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ + if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){ return WRC_Abort; } @@ -121836,6 +136535,7 @@ static int selectExpander(Walker *pWalker, Select *p){ assert( pE->op!=TK_DOT || pE->pRight!=0 ); assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; + elistFlags |= pE->flags; } if( k<pEList->nExpr ){ /* @@ -121851,6 +136551,7 @@ static int selectExpander(Walker *pWalker, Select *p){ for(k=0; k<pEList->nExpr; k++){ pE = a[k].pExpr; + elistFlags |= pE->flags; pRight = pE->pRight; assert( pE->op!=TK_DOT || pRight!=0 ); if( pE->op!=TK_ASTERISK @@ -121858,12 +136559,11 @@ static int selectExpander(Walker *pWalker, Select *p){ ){ /* This particular expression does not need to be expanded. */ - pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); + pNew = tdsqlite3ExprListAppend(pParse, pNew, a[k].pExpr); if( pNew ){ - pNew->a[pNew->nExpr-1].zName = a[k].zName; - pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; - a[k].zName = 0; - a[k].zSpan = 0; + pNew->a[pNew->nExpr-1].zEName = a[k].zEName; + pNew->a[pNew->nExpr-1].eEName = a[k].eEName; + a[k].zEName = 0; } a[k].pExpr = 0; }else{ @@ -121888,10 +136588,10 @@ static int selectExpander(Walker *pWalker, Select *p){ if( db->mallocFailed ) break; if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ pSub = 0; - if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ + if( zTName && tdsqlite3StrICmp(zTName, zTabName)!=0 ){ continue; } - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; } for(j=0; j<pTab->nCol; j++){ @@ -121902,7 +136602,7 @@ static int selectExpander(Walker *pWalker, Select *p){ assert( zName ); if( zTName && pSub - && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 + && tdsqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0 ){ continue; } @@ -121920,72 +136620,76 @@ static int selectExpander(Walker *pWalker, Select *p){ if( i>0 && zTName==0 ){ if( (pFrom->fg.jointype & JT_NATURAL)!=0 - && tableAndColumnIndex(pTabList, i, zName, 0, 0) + && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1) ){ /* In a NATURAL join, omit the join columns from the ** table to the right of the join */ continue; } - if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ + if( tdsqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ /* In a join with a USING clause, omit columns in the ** using clause from the table on the right. */ continue; } } - pRight = sqlite3Expr(db, TK_ID, zName); + pRight = tdsqlite3Expr(db, TK_ID, zName); zColname = zName; zToFree = 0; if( longNames || pTabList->nSrc>1 ){ Expr *pLeft; - pLeft = sqlite3Expr(db, TK_ID, zTabName); - pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); + pLeft = tdsqlite3Expr(db, TK_ID, zTabName); + pExpr = tdsqlite3PExpr(pParse, TK_DOT, pLeft, pRight); if( zSchemaName ){ - pLeft = sqlite3Expr(db, TK_ID, zSchemaName); - pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0); + pLeft = tdsqlite3Expr(db, TK_ID, zSchemaName); + pExpr = tdsqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); } if( longNames ){ - zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); + zColname = tdsqlite3MPrintf(db, "%s.%s", zTabName, zName); zToFree = zColname; } }else{ pExpr = pRight; } - pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); - sqlite3TokenInit(&sColname, zColname); - sqlite3ExprListSetName(pParse, pNew, &sColname, 0); + pNew = tdsqlite3ExprListAppend(pParse, pNew, pExpr); + tdsqlite3TokenInit(&sColname, zColname); + tdsqlite3ExprListSetName(pParse, pNew, &sColname, 0); if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; + tdsqlite3DbFree(db, pX->zEName); if( pSub ){ - pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); - testcase( pX->zSpan==0 ); + pX->zEName = tdsqlite3DbStrDup(db, pSub->pEList->a[j].zEName); + testcase( pX->zEName==0 ); }else{ - pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", + pX->zEName = tdsqlite3MPrintf(db, "%s.%s.%s", zSchemaName, zTabName, zColname); - testcase( pX->zSpan==0 ); + testcase( pX->zEName==0 ); } - pX->bSpanIsTab = 1; + pX->eEName = ENAME_TAB; } - sqlite3DbFree(db, zToFree); + tdsqlite3DbFree(db, zToFree); } } if( !tableSeen ){ if( zTName ){ - sqlite3ErrorMsg(pParse, "no such table: %s", zTName); + tdsqlite3ErrorMsg(pParse, "no such table: %s", zTName); }else{ - sqlite3ErrorMsg(pParse, "no tables specified"); + tdsqlite3ErrorMsg(pParse, "no tables specified"); } } } } - sqlite3ExprListDelete(db, pEList); + tdsqlite3ExprListDelete(db, pEList); p->pEList = pNew; } -#if SQLITE_MAX_COLUMN - if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many columns in result set"); - return WRC_Abort; + if( p->pEList ){ + if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + tdsqlite3ErrorMsg(pParse, "too many columns in result set"); + return WRC_Abort; + } + if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){ + p->selFlags |= SF_ComplexResult; + } } -#endif return WRC_Continue; } @@ -121998,12 +136702,31 @@ static int selectExpander(Walker *pWalker, Select *p){ ** Walker.xSelectCallback is set to do something useful for every ** subquery in the parser tree. */ -SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ +SQLITE_PRIVATE int tdsqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return WRC_Continue; } /* +** No-op routine for the parse-tree walker for SELECT statements. +** subquery in the parser tree. +*/ +SQLITE_PRIVATE int tdsqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + return WRC_Continue; +} + +#if SQLITE_DEBUG +/* +** Always assert. This xSelectCallback2 implementation proves that the +** xSelectCallback2 is never invoked. +*/ +SQLITE_PRIVATE void tdsqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){ + UNUSED_PARAMETER2(NotUsed, NotUsed2); + assert( 0 ); +} +#endif +/* ** This routine "expands" a SELECT statement and all of its subqueries. ** For additional information on what it means to "expand" a SELECT ** statement, see the comment on the selectExpand worker callback above. @@ -122016,26 +136739,25 @@ SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ ** The calling function can detect the problem by looking at pParse->nErr ** and/or pParse->db->mallocFailed. */ -static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ +static void tdsqlite3SelectExpand(Parse *pParse, Select *pSelect){ Walker w; - memset(&w, 0, sizeof(w)); - w.xExprCallback = sqlite3ExprWalkNoop; + w.xExprCallback = tdsqlite3ExprWalkNoop; w.pParse = pParse; - if( pParse->hasCompound ){ + if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){ w.xSelectCallback = convertCompoundSelectToSubquery; - sqlite3WalkSelect(&w, pSelect); + w.xSelectCallback2 = 0; + tdsqlite3WalkSelect(&w, pSelect); } w.xSelectCallback = selectExpander; - if( (pSelect->selFlags & SF_MultiValue)==0 ){ - w.xSelectCallback2 = selectPopWith; - } - sqlite3WalkSelect(&w, pSelect); + w.xSelectCallback2 = selectPopWith; + w.eCode = 0; + tdsqlite3WalkSelect(&w, pSelect); } #ifndef SQLITE_OMIT_SUBQUERY /* -** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() +** This is a Walker.xSelectCallback callback for the tdsqlite3SelectTypeInfo() ** interface. ** ** For each FROM-clause subquery, add Column.zType and Column.zColl @@ -122054,7 +136776,7 @@ static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ struct SrcList_item *pFrom; assert( p->selFlags & SF_Resolved ); - assert( (p->selFlags & SF_HasTypeInfo)==0 ); + if( p->selFlags & SF_HasTypeInfo ) return; p->selFlags |= SF_HasTypeInfo; pParse = pWalker->pParse; pTabList = p->pSrc; @@ -122066,7 +136788,8 @@ static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ Select *pSel = pFrom->pSelect; if( pSel ){ while( pSel->pPrior ) pSel = pSel->pPrior; - sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel); + tdsqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel, + SQLITE_AFF_NONE); } } } @@ -122081,14 +136804,14 @@ static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ ** ** Use this routine after name resolution. */ -static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ +static void tdsqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ #ifndef SQLITE_OMIT_SUBQUERY Walker w; - memset(&w, 0, sizeof(w)); + w.xSelectCallback = tdsqlite3SelectWalkNoop; w.xSelectCallback2 = selectAddSubqueryTypeInfo; - w.xExprCallback = sqlite3ExprWalkNoop; + w.xExprCallback = tdsqlite3ExprWalkNoop; w.pParse = pParse; - sqlite3WalkSelect(&w, pSelect); + tdsqlite3WalkSelect(&w, pSelect); #endif } @@ -122105,21 +136828,19 @@ static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ ** ** This routine acts recursively on all subqueries within the SELECT. */ -SQLITE_PRIVATE void sqlite3SelectPrep( +SQLITE_PRIVATE void tdsqlite3SelectPrep( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ NameContext *pOuterNC /* Name context for container */ ){ - sqlite3 *db; - if( NEVER(p==0) ) return; - db = pParse->db; - if( db->mallocFailed ) return; + assert( p!=0 || pParse->db->mallocFailed ); + if( pParse->db->mallocFailed ) return; if( p->selFlags & SF_HasTypeInfo ) return; - sqlite3SelectExpand(pParse, p); - if( pParse->nErr || db->mallocFailed ) return; - sqlite3ResolveSelectNames(pParse, p, pOuterNC); - if( pParse->nErr || db->mallocFailed ) return; - sqlite3SelectAddTypeInfo(pParse, p); + tdsqlite3SelectExpand(pParse, p); + if( pParse->nErr || pParse->db->mallocFailed ) return; + tdsqlite3ResolveSelectNames(pParse, p, pOuterNC); + if( pParse->nErr || pParse->db->mallocFailed ) return; + tdsqlite3SelectAddTypeInfo(pParse, p); } /* @@ -122149,18 +136870,18 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); } #endif - sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); + tdsqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ if( pFunc->iDistinct>=0 ){ Expr *pE = pFunc->pExpr; assert( !ExprHasProperty(pE, EP_xIsSelect) ); if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ - sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " + tdsqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " "argument"); pFunc->iDistinct = -1; }else{ - KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0); - sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, + KeyInfo *pKeyInfo = tdsqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0); + tdsqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO); } } @@ -122178,16 +136899,22 @@ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ ExprList *pList = pF->pExpr->x.pList; assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); - sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, - (void*)pF->pFunc, P4_FUNCDEF); + tdsqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); + tdsqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); } } + /* ** Update the accumulator memory cells for an aggregate based on ** the current cursor position. +** +** If regAcc is non-zero and there are no min() or max() aggregates +** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator +** registers if register regAcc contains 0. The caller will take care +** of setting and clearing regAcc. */ -static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ +static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; int regHit = 0; @@ -122202,16 +136929,37 @@ static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ int regAgg; ExprList *pList = pF->pExpr->x.pList; assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); + assert( !IsWindowFunc(pF->pExpr) ); + if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){ + Expr *pFilter = pF->pExpr->y.pWin->pFilter; + if( pAggInfo->nAccumulator + && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) + ){ + if( regHit==0 ) regHit = ++pParse->nMem; + /* If this is the first row of the group (regAcc==0), clear the + ** "magnet" register regHit so that the accumulator registers + ** are populated if the FILTER clause jumps over the the + ** invocation of min() or max() altogether. Or, if this is not + ** the first row (regAcc==1), set the magnet register so that the + ** accumulators are not populated unless the min()/max() is invoked and + ** indicates that they should be. */ + tdsqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit); + } + addrNext = tdsqlite3VdbeMakeLabel(pParse); + tdsqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL); + } if( pList ){ nArg = pList->nExpr; - regAgg = sqlite3GetTempRange(pParse, nArg); - sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); + regAgg = tdsqlite3GetTempRange(pParse, nArg); + tdsqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); }else{ nArg = 0; regAgg = 0; } if( pF->iDistinct>=0 ){ - addrNext = sqlite3VdbeMakeLabel(v); + if( addrNext==0 ){ + addrNext = tdsqlite3VdbeMakeLabel(pParse); + } testcase( nArg==0 ); /* Error condition */ testcase( nArg>1 ); /* Also an error */ codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); @@ -122222,46 +136970,35 @@ static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ int j; assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ - pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); + pColl = tdsqlite3ExprCollSeq(pParse, pItem->pExpr); } if( !pColl ){ pColl = pParse->db->pDfltColl; } if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; - sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); + tdsqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); } - sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem, - (void*)pF->pFunc, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, (u8)nArg); - sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); - sqlite3ReleaseTempRange(pParse, regAgg, nArg); + tdsqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem); + tdsqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); + tdsqlite3VdbeChangeP5(v, (u8)nArg); + tdsqlite3ReleaseTempRange(pParse, regAgg, nArg); if( addrNext ){ - sqlite3VdbeResolveLabel(v, addrNext); - sqlite3ExprCacheClear(pParse); + tdsqlite3VdbeResolveLabel(v, addrNext); } } - - /* Before populating the accumulator registers, clear the column cache. - ** Otherwise, if any of the required column values are already present - ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value - ** to pC->iMem. But by the time the value is used, the original register - ** may have been used, invalidating the underlying buffer holding the - ** text or blob value. See ticket [883034dcb5]. - ** - ** Another solution would be to change the OP_SCopy used to copy cached - ** values to an OP_Copy. - */ + if( regHit==0 && pAggInfo->nAccumulator ){ + regHit = regAcc; + } if( regHit ){ - addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); + addrHitTest = tdsqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); } - sqlite3ExprCacheClear(pParse); for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ - sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); + tdsqlite3ExprCode(pParse, pC->pExpr, pC->iMem); } + pAggInfo->directMode = 0; - sqlite3ExprCacheClear(pParse); if( addrHitTest ){ - sqlite3VdbeJumpHere(v, addrHitTest); + tdsqlite3VdbeJumpHere(v, addrHitTest); } } @@ -122277,14 +137014,11 @@ static void explainSimpleCount( ){ if( pParse->explain==2 ){ int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); - char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", + tdsqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s", pTab->zName, bCover ? " USING COVERING INDEX " : "", bCover ? pIdx->zName : "" ); - sqlite3VdbeAddOp4( - pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC - ); } } #else @@ -122292,6 +137026,190 @@ static void explainSimpleCount( #endif /* +** tdsqlite3WalkExpr() callback used by havingToWhere(). +** +** If the node passed to the callback is a TK_AND node, return +** WRC_Continue to tell tdsqlite3WalkExpr() to iterate through child nodes. +** +** Otherwise, return WRC_Prune. In this case, also check if the +** sub-expression matches the criteria for being moved to the WHERE +** clause. If so, add it to the WHERE clause and replace the sub-expression +** within the HAVING expression with a constant "1". +*/ +static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){ + if( pExpr->op!=TK_AND ){ + Select *pS = pWalker->u.pSelect; + if( tdsqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){ + tdsqlite3 *db = pWalker->pParse->db; + Expr *pNew = tdsqlite3Expr(db, TK_INTEGER, "1"); + if( pNew ){ + Expr *pWhere = pS->pWhere; + SWAP(Expr, *pNew, *pExpr); + pNew = tdsqlite3ExprAnd(pWalker->pParse, pWhere, pNew); + pS->pWhere = pNew; + pWalker->eCode = 1; + } + } + return WRC_Prune; + } + return WRC_Continue; +} + +/* +** Transfer eligible terms from the HAVING clause of a query, which is +** processed after grouping, to the WHERE clause, which is processed before +** grouping. For example, the query: +** +** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=? +** +** can be rewritten as: +** +** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=? +** +** A term of the HAVING expression is eligible for transfer if it consists +** entirely of constants and expressions that are also GROUP BY terms that +** use the "BINARY" collation sequence. +*/ +static void havingToWhere(Parse *pParse, Select *p){ + Walker sWalker; + memset(&sWalker, 0, sizeof(sWalker)); + sWalker.pParse = pParse; + sWalker.xExprCallback = havingToWhereExprCb; + sWalker.u.pSelect = p; + tdsqlite3WalkExpr(&sWalker, p->pHaving); +#if SELECTTRACE_ENABLED + if( sWalker.eCode && (tdsqlite3SelectTrace & 0x100)!=0 ){ + SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n")); + tdsqlite3TreeViewSelect(0, p, 0); + } +#endif +} + +/* +** Check to see if the pThis entry of pTabList is a self-join of a prior view. +** If it is, then return the SrcList_item for the prior view. If it is not, +** then return 0. +*/ +static struct SrcList_item *isSelfJoinView( + SrcList *pTabList, /* Search for self-joins in this FROM clause */ + struct SrcList_item *pThis /* Search for prior reference to this subquery */ +){ + struct SrcList_item *pItem; + for(pItem = pTabList->a; pItem<pThis; pItem++){ + Select *pS1; + if( pItem->pSelect==0 ) continue; + if( pItem->fg.viaCoroutine ) continue; + if( pItem->zName==0 ) continue; + assert( pItem->pTab!=0 ); + assert( pThis->pTab!=0 ); + if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue; + if( tdsqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue; + pS1 = pItem->pSelect; + if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){ + /* The query flattener left two different CTE tables with identical + ** names in the same FROM clause. */ + continue; + } + if( tdsqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1) + || tdsqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1) + ){ + /* The view was modified by some other optimization such as + ** pushDownWhereTerms() */ + continue; + } + return pItem; + } + return 0; +} + +#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION +/* +** Attempt to transform a query of the form +** +** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2) +** +** Into this: +** +** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2) +** +** The transformation only works if all of the following are true: +** +** * The subquery is a UNION ALL of two or more terms +** * The subquery does not have a LIMIT clause +** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries +** * The outer query is a simple count(*) with no WHERE clause or other +** extraneous syntax. +** +** Return TRUE if the optimization is undertaken. +*/ +static int countOfViewOptimization(Parse *pParse, Select *p){ + Select *pSub, *pPrior; + Expr *pExpr; + Expr *pCount; + tdsqlite3 *db; + if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */ + if( p->pEList->nExpr!=1 ) return 0; /* Single result column */ + if( p->pWhere ) return 0; + if( p->pGroupBy ) return 0; + pExpr = p->pEList->a[0].pExpr; + if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */ + if( tdsqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */ + if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */ + if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */ + pSub = p->pSrc->a[0].pSelect; + if( pSub==0 ) return 0; /* The FROM is a subquery */ + if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */ + do{ + if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */ + if( pSub->pWhere ) return 0; /* No WHERE clause */ + if( pSub->pLimit ) return 0; /* No LIMIT clause */ + if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */ + pSub = pSub->pPrior; /* Repeat over compound */ + }while( pSub ); + + /* If we reach this point then it is OK to perform the transformation */ + + db = pParse->db; + pCount = pExpr; + pExpr = 0; + pSub = p->pSrc->a[0].pSelect; + p->pSrc->a[0].pSelect = 0; + tdsqlite3SrcListDelete(db, p->pSrc); + p->pSrc = tdsqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc)); + while( pSub ){ + Expr *pTerm; + pPrior = pSub->pPrior; + pSub->pPrior = 0; + pSub->pNext = 0; + pSub->selFlags |= SF_Aggregate; + pSub->selFlags &= ~SF_Compound; + pSub->nSelectRow = 0; + tdsqlite3ExprListDelete(db, pSub->pEList); + pTerm = pPrior ? tdsqlite3ExprDup(db, pCount, 0) : pCount; + pSub->pEList = tdsqlite3ExprListAppend(pParse, 0, pTerm); + pTerm = tdsqlite3PExpr(pParse, TK_SELECT, 0, 0); + tdsqlite3PExprAddSelect(pParse, pTerm, pSub); + if( pExpr==0 ){ + pExpr = pTerm; + }else{ + pExpr = tdsqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr); + } + pSub = pPrior; + } + p->pEList->a[0].pExpr = pExpr; + p->selFlags &= ~SF_Aggregate; + +#if SELECTTRACE_ENABLED + if( tdsqlite3SelectTrace & 0x400 ){ + SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n")); + tdsqlite3TreeViewSelect(0, p, 0); + } +#endif + return 1; +} +#endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */ + +/* ** Generate code for the SELECT statement given in the p argument. ** ** The results are returned according to the SelectDest structure. @@ -122304,13 +137222,13 @@ static void explainSimpleCount( ** This routine does NOT free the Select structure passed in. The ** calling function needs to do that. */ -SQLITE_PRIVATE int sqlite3Select( +SQLITE_PRIVATE int tdsqlite3Select( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ SelectDest *pDest /* What to do with the query results */ ){ int i, j; /* Loop counters */ - WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ + WhereInfo *pWInfo; /* Return from tdsqlite3WhereBegin() */ Vdbe *v; /* The virtual machine under construction */ int isAgg; /* True for select lists like "count(*)" */ ExprList *pEList = 0; /* List of columns to extract. */ @@ -122323,24 +137241,21 @@ SQLITE_PRIVATE int sqlite3Select( SortCtx sSort; /* Info on how to code the ORDER BY clause */ AggInfo sAggInfo; /* Information used by aggregate queries */ int iEnd; /* Address of the end of the query */ - sqlite3 *db; /* The database connection */ - -#ifndef SQLITE_OMIT_EXPLAIN - int iRestoreSelectId = pParse->iSelectId; - pParse->iSelectId = pParse->iNextSelectId++; -#endif + tdsqlite3 *db; /* The database connection */ + ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */ + u8 minMaxFlag; /* Flag for min/max queries */ db = pParse->db; + v = tdsqlite3GetVdbe(pParse); if( p==0 || db->mallocFailed || pParse->nErr ){ return 1; } - if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; + if( tdsqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; memset(&sAggInfo, 0, sizeof(sAggInfo)); #if SELECTTRACE_ENABLED - pParse->nSelectIndent++; - SELECTTRACE(1,pParse,p, ("begin processing:\n")); - if( sqlite3SelectTrace & 0x100 ){ - sqlite3TreeViewSelect(0, p, 0); + SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain)); + if( tdsqlite3SelectTrace & 0x100 ){ + tdsqlite3TreeViewSelect(0, p, 0); } #endif @@ -122355,51 +137270,117 @@ SQLITE_PRIVATE int sqlite3Select( pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); /* If ORDER BY makes no difference in the output then neither does ** DISTINCT so it can be removed too. */ - sqlite3ExprListDelete(db, p->pOrderBy); + tdsqlite3ExprListDelete(db, p->pOrderBy); p->pOrderBy = 0; p->selFlags &= ~SF_Distinct; } - sqlite3SelectPrep(pParse, p, 0); - memset(&sSort, 0, sizeof(sSort)); - sSort.pOrderBy = p->pOrderBy; - pTabList = p->pSrc; + tdsqlite3SelectPrep(pParse, p, 0); if( pParse->nErr || db->mallocFailed ){ goto select_end; } assert( p->pEList!=0 ); - isAgg = (p->selFlags & SF_Aggregate)!=0; #if SELECTTRACE_ENABLED - if( sqlite3SelectTrace & 0x100 ){ - SELECTTRACE(0x100,pParse,p, ("after name resolution:\n")); - sqlite3TreeViewSelect(0, p, 0); + if( tdsqlite3SelectTrace & 0x104 ){ + SELECTTRACE(0x104,pParse,p, ("after name resolution:\n")); + tdsqlite3TreeViewSelect(0, p, 0); } #endif - /* Try to flatten subqueries in the FROM clause up into the main query + if( pDest->eDest==SRT_Output ){ + generateColumnNames(pParse, p); + } + +#ifndef SQLITE_OMIT_WINDOWFUNC + rc = tdsqlite3WindowRewrite(pParse, p); + if( rc ){ + assert( db->mallocFailed || pParse->nErr>0 ); + goto select_end; + } +#if SELECTTRACE_ENABLED + if( p->pWin && (tdsqlite3SelectTrace & 0x108)!=0 ){ + SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n")); + tdsqlite3TreeViewSelect(0, p, 0); + } +#endif +#endif /* SQLITE_OMIT_WINDOWFUNC */ + pTabList = p->pSrc; + isAgg = (p->selFlags & SF_Aggregate)!=0; + memset(&sSort, 0, sizeof(sSort)); + sSort.pOrderBy = p->pOrderBy; + + /* Try to various optimizations (flattening subqueries, and strength + ** reduction of join operators) in the FROM clause up into the main query */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ struct SrcList_item *pItem = &pTabList->a[i]; Select *pSub = pItem->pSelect; - int isAggSub; Table *pTab = pItem->pTab; + + /* Convert LEFT JOIN into JOIN if there are terms of the right table + ** of the LEFT JOIN used in the WHERE clause. + */ + if( (pItem->fg.jointype & JT_LEFT)!=0 + && tdsqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor) + && OptimizationEnabled(db, SQLITE_SimplifyJoin) + ){ + SELECTTRACE(0x100,pParse,p, + ("LEFT-JOIN simplifies to JOIN on term %d\n",i)); + pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER); + unsetJoinExpr(p->pWhere, pItem->iCursor); + } + + /* No futher action if this term of the FROM clause is no a subquery */ if( pSub==0 ) continue; /* Catch mismatch in the declared columns of a view and the number of ** columns in the SELECT on the RHS */ if( pTab->nCol!=pSub->pEList->nExpr ){ - sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", + tdsqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", pTab->nCol, pTab->zName, pSub->pEList->nExpr); goto select_end; } - isAggSub = (pSub->selFlags & SF_Aggregate)!=0; - if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ + /* Do not try to flatten an aggregate subquery. + ** + ** Flattening an aggregate subquery is only possible if the outer query + ** is not a join. But if the outer query is not a join, then the subquery + ** will be implemented as a co-routine and there is no advantage to + ** flattening in that case. + */ + if( (pSub->selFlags & SF_Aggregate)!=0 ) continue; + assert( pSub->pGroupBy==0 ); + + /* If the outer query contains a "complex" result set (that is, + ** if the result set of the outer query uses functions or subqueries) + ** and if the subquery contains an ORDER BY clause and if + ** it will be implemented as a co-routine, then do not flatten. This + ** restriction allows SQL constructs like this: + ** + ** SELECT expensive_function(x) + ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10); + ** + ** The expensive_function() is only computed on the 10 rows that + ** are output, rather than every row of the table. + ** + ** The requirement that the outer query have a complex result set + ** means that flattening does occur on simpler SQL constraints without + ** the expensive_function() like: + ** + ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10); + */ + if( pSub->pOrderBy!=0 + && i==0 + && (p->selFlags & SF_ComplexResult)!=0 + && (pTabList->nSrc==1 + || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) + ){ + continue; + } + + if( flattenSubquery(pParse, p, i, isAgg) ){ + if( pParse->nErr ) goto select_end; /* This subquery can be absorbed into its parent. */ - if( isAggSub ){ - isAgg = 1; - p->selFlags |= SF_Aggregate; - } i = -1; } pTabList = p->pSrc; @@ -122410,48 +137391,104 @@ SQLITE_PRIVATE int sqlite3Select( } #endif - /* Get a pointer the VDBE under construction, allocating a new VDBE if one - ** does not already exist */ - v = sqlite3GetVdbe(pParse); - if( v==0 ) goto select_end; - #ifndef SQLITE_OMIT_COMPOUND_SELECT /* Handle compound SELECT statements using the separate multiSelect() ** procedure. */ if( p->pPrior ){ rc = multiSelect(pParse, p, pDest); - explainSetInteger(pParse->iSelectId, iRestoreSelectId); #if SELECTTRACE_ENABLED - SELECTTRACE(1,pParse,p,("end compound-select processing\n")); - pParse->nSelectIndent--; + SELECTTRACE(0x1,pParse,p,("end compound-select processing\n")); + if( (tdsqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ + tdsqlite3TreeViewSelect(0, p, 0); + } #endif + if( p->pNext==0 ) ExplainQueryPlanPop(pParse); return rc; } #endif - /* Generate code for all sub-queries in the FROM clause + /* Do the WHERE-clause constant propagation optimization if this is + ** a join. No need to speed time on this operation for non-join queries + ** as the equivalent optimization will be handled by query planner in + ** tdsqlite3WhereBegin(). + */ + if( pTabList->nSrc>1 + && OptimizationEnabled(db, SQLITE_PropagateConst) + && propagateConstants(pParse, p) + ){ +#if SELECTTRACE_ENABLED + if( tdsqlite3SelectTrace & 0x100 ){ + SELECTTRACE(0x100,pParse,p,("After constant propagation:\n")); + tdsqlite3TreeViewSelect(0, p, 0); + } +#endif + }else{ + SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n")); + } + +#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION + if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView) + && countOfViewOptimization(pParse, p) + ){ + if( db->mallocFailed ) goto select_end; + pEList = p->pEList; + pTabList = p->pSrc; + } +#endif + + /* For each term in the FROM clause, do two things: + ** (1) Authorized unreferenced tables + ** (2) Generate code for all sub-queries */ -#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) for(i=0; i<pTabList->nSrc; i++){ struct SrcList_item *pItem = &pTabList->a[i]; SelectDest dest; - Select *pSub = pItem->pSelect; - if( pSub==0 ) continue; + Select *pSub; +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) + const char *zSavedAuthContext; +#endif - /* Sometimes the code for a subquery will be generated more than - ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, - ** for example. In that case, do not regenerate the code to manifest - ** a view or the co-routine to implement a view. The first instance - ** is sufficient, though the subroutine to manifest the view does need - ** to be invoked again. */ - if( pItem->addrFillSub ){ - if( pItem->fg.viaCoroutine==0 ){ - sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); - } - continue; + /* Issue SQLITE_READ authorizations with a fake column name for any + ** tables that are referenced but from which no values are extracted. + ** Examples of where these kinds of null SQLITE_READ authorizations + ** would occur: + ** + ** SELECT count(*) FROM t1; -- SQLITE_READ t1."" + ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2."" + ** + ** The fake column name is an empty string. It is possible for a table to + ** have a column named by the empty string, in which case there is no way to + ** distinguish between an unreferenced table and an actual reference to the + ** "" column. The original design was for the fake column name to be a NULL, + ** which would be unambiguous. But legacy authorization callbacks might + ** assume the column name is non-NULL and segfault. The use of an empty + ** string for the fake column name seems safer. + */ + if( pItem->colUsed==0 && pItem->zName!=0 ){ + tdsqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase); } +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) + /* Generate code for all sub-queries in the FROM clause + */ + pSub = pItem->pSelect; + if( pSub==0 ) continue; + + /* The code for a subquery should only be generated once, though it is + ** technically harmless for it to be generated multiple times. The + ** following assert() will detect if something changes to cause + ** the same subquery to be coded multiple times, as a signal to the + ** developers to try to optimize the situation. + ** + ** Update 2019-07-24: + ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40. + ** The dbsqlfuzz fuzzer found a case where the same subquery gets + ** coded twice. So this assert() now becomes a testcase(). It should + ** be very rare, though. + */ + testcase( pItem->addrFillSub!=0 ); + /* Increment Parse.nHeight by the height of the largest expression ** tree referred to by this, the parent select. The child select ** may contain expression trees of at most @@ -122459,32 +137496,34 @@ SQLITE_PRIVATE int sqlite3Select( ** more conservative than necessary, but much easier than enforcing ** an exact limit. */ - pParse->nHeight += sqlite3SelectExprHeight(p); + pParse->nHeight += tdsqlite3SelectExprHeight(p); /* Make copies of constant WHERE-clause terms in the outer query down ** inside the subquery. This can help the subquery to run more efficiently. */ - if( (pItem->fg.jointype & JT_OUTER)==0 - && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor) + if( OptimizationEnabled(db, SQLITE_PushDown) + && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor, + (pItem->fg.jointype & JT_OUTER)!=0) ){ #if SELECTTRACE_ENABLED - if( sqlite3SelectTrace & 0x100 ){ - SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n")); - sqlite3TreeViewSelect(0, p, 0); + if( tdsqlite3SelectTrace & 0x100 ){ + SELECTTRACE(0x100,pParse,p, + ("After WHERE-clause push-down into subquery %d:\n", pSub->selId)); + tdsqlite3TreeViewSelect(0, p, 0); } #endif + }else{ + SELECTTRACE(0x100,pParse,p,("Push-down not possible\n")); } + zSavedAuthContext = pParse->zAuthContext; + pParse->zAuthContext = pItem->zName; + /* Generate code to implement the subquery ** - ** The subquery is implemented as a co-routine if all of these are true: - ** (1) The subquery is guaranteed to be the outer loop (so that it - ** does not need to be computed more than once) - ** (2) The ALL keyword after SELECT is omitted. (Applications are - ** allowed to say "SELECT ALL" instead of just "SELECT" to disable - ** the use of co-routines.) - ** (3) Co-routines are not disabled using sqlite3_test_control() - ** with SQLITE_TESTCTRL_OPTIMIZATIONS. + ** The subquery is implemented as a co-routine if the subquery is + ** guaranteed to be the outer loop (so that it does not need to be + ** computed more than once) ** ** TODO: Are there other reasons beside (1) to use a co-routine ** implementation? @@ -122492,26 +137531,25 @@ SQLITE_PRIVATE int sqlite3Select( if( i==0 && (pTabList->nSrc==1 || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ - && (p->selFlags & SF_All)==0 /* (2) */ - && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */ ){ /* Implement a co-routine that will return a single row of the result ** set on each invocation. */ - int addrTop = sqlite3VdbeCurrentAddr(v)+1; + int addrTop = tdsqlite3VdbeCurrentAddr(v)+1; + pItem->regReturn = ++pParse->nMem; - sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); + tdsqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); VdbeComment((v, "%s", pItem->pTab->zName)); pItem->addrFillSub = addrTop; - sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); - explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); - sqlite3Select(pParse, pSub, &dest); + tdsqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); + ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId)); + tdsqlite3Select(pParse, pSub, &dest); pItem->pTab->nRowLogEst = pSub->nSelectRow; pItem->fg.viaCoroutine = 1; pItem->regResult = dest.iSdst; - sqlite3VdbeEndCoroutine(v, pItem->regReturn); - sqlite3VdbeJumpHere(v, addrTop-1); - sqlite3ClearTempRegCache(pParse); + tdsqlite3VdbeEndCoroutine(v, pItem->regReturn); + tdsqlite3VdbeJumpHere(v, addrTop-1); + tdsqlite3ClearTempRegCache(pParse); }else{ /* Generate a subroutine that will fill an ephemeral table with ** the content of this subquery. pItem->addrFillSub will point @@ -122521,33 +137559,43 @@ SQLITE_PRIVATE int sqlite3Select( int topAddr; int onceAddr = 0; int retAddr; - assert( pItem->addrFillSub==0 ); + struct SrcList_item *pPrior; + + testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */ pItem->regReturn = ++pParse->nMem; - topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); + topAddr = tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); pItem->addrFillSub = topAddr+1; if( pItem->fg.isCorrelated==0 ){ /* If the subquery is not correlated and if we are not inside of ** a trigger, then we only need to compute the value of the subquery ** once. */ - onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); + onceAddr = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); }else{ VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); } - sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); - explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); - sqlite3Select(pParse, pSub, &dest); + pPrior = isSelfJoinView(pTabList, pItem); + if( pPrior ){ + tdsqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor); + assert( pPrior->pSelect!=0 ); + pSub->nSelectRow = pPrior->pSelect->nSelectRow; + }else{ + tdsqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); + ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId)); + tdsqlite3Select(pParse, pSub, &dest); + } pItem->pTab->nRowLogEst = pSub->nSelectRow; - if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); - retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); + if( onceAddr ) tdsqlite3VdbeJumpHere(v, onceAddr); + retAddr = tdsqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); VdbeComment((v, "end %s", pItem->pTab->zName)); - sqlite3VdbeChangeP1(v, topAddr, retAddr); - sqlite3ClearTempRegCache(pParse); + tdsqlite3VdbeChangeP1(v, topAddr, retAddr); + tdsqlite3ClearTempRegCache(pParse); } if( db->mallocFailed ) goto select_end; - pParse->nHeight -= sqlite3SelectExprHeight(p); - } + pParse->nHeight -= tdsqlite3SelectExprHeight(p); + pParse->zAuthContext = zSavedAuthContext; #endif + } /* Various elements of the SELECT copied into local variables for ** convenience */ @@ -122558,9 +137606,9 @@ SQLITE_PRIVATE int sqlite3Select( sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; #if SELECTTRACE_ENABLED - if( sqlite3SelectTrace & 0x400 ){ + if( tdsqlite3SelectTrace & 0x400 ){ SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); - sqlite3TreeViewSelect(0, p, 0); + tdsqlite3TreeViewSelect(0, p, 0); } #endif @@ -122580,19 +137628,23 @@ SQLITE_PRIVATE int sqlite3Select( ** BY and DISTINCT, and an index or separate temp-table for the other. */ if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct - && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 + && tdsqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 +#ifndef SQLITE_OMIT_WINDOWFUNC + && p->pWin==0 +#endif ){ p->selFlags &= ~SF_Distinct; - pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); + pGroupBy = p->pGroupBy = tdsqlite3ExprListDup(db, pEList, 0); + p->selFlags |= SF_Aggregate; /* Notice that even thought SF_Distinct has been cleared from p->selFlags, ** the sDistinct.isTnct is still set. Hence, isTnct represents the ** original setting of the SF_Distinct flag, not the current setting */ assert( sDistinct.isTnct ); #if SELECTTRACE_ENABLED - if( sqlite3SelectTrace & 0x400 ){ + if( tdsqlite3SelectTrace & 0x400 ){ SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); - sqlite3TreeViewSelect(0, p, 0); + tdsqlite3TreeViewSelect(0, p, 0); } #endif } @@ -122607,10 +137659,11 @@ SQLITE_PRIVATE int sqlite3Select( */ if( sSort.pOrderBy ){ KeyInfo *pKeyInfo; - pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr); + pKeyInfo = tdsqlite3KeyInfoFromExprList( + pParse, sSort.pOrderBy, 0, pEList->nExpr); sSort.iECursor = pParse->nTab++; sSort.addrSortIndex = - sqlite3VdbeAddOp4(v, OP_OpenEphemeral, + tdsqlite3VdbeAddOp4(v, OP_OpenEphemeral, sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, (char*)pKeyInfo, P4_KEYINFO ); @@ -122621,16 +137674,18 @@ SQLITE_PRIVATE int sqlite3Select( /* If the output is destined for a temporary table, open that table. */ if( pDest->eDest==SRT_EphemTab ){ - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); + tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); } /* Set the limiter. */ - iEnd = sqlite3VdbeMakeLabel(v); - p->nSelectRow = 320; /* 4 billion rows */ + iEnd = tdsqlite3VdbeMakeLabel(pParse); + if( (p->selFlags & SF_FixedLimit)==0 ){ + p->nSelectRow = 320; /* 4 billion rows */ + } computeLimitRegisters(pParse, p, iEnd); if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ - sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); + tdsqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); sSort.sortFlags |= SORTFLAG_UseSorter; } @@ -122638,11 +137693,11 @@ SQLITE_PRIVATE int sqlite3Select( */ if( p->selFlags & SF_Distinct ){ sDistinct.tabTnct = pParse->nTab++; - sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, - sDistinct.tabTnct, 0, 0, - (char*)keyInfoFromExprList(pParse, p->pEList,0,0), - P4_KEYINFO); - sqlite3VdbeChangeP5(v, BTREE_UNORDERED); + sDistinct.addrTnct = tdsqlite3VdbeAddOp4(v, OP_OpenEphemeral, + sDistinct.tabTnct, 0, 0, + (char*)tdsqlite3KeyInfoFromExprList(pParse, p->pEList,0,0), + P4_KEYINFO); + tdsqlite3VdbeChangeP5(v, BTREE_UNORDERED); sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; }else{ sDistinct.eTnctType = WHERE_DISTINCT_NOOP; @@ -122650,23 +137705,31 @@ SQLITE_PRIVATE int sqlite3Select( if( !isAgg && pGroupBy==0 ){ /* No aggregate functions and no GROUP BY clause */ - u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); + u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0) + | (p->selFlags & SF_FixedLimit); +#ifndef SQLITE_OMIT_WINDOWFUNC + Window *pWin = p->pWin; /* Master window object (or NULL) */ + if( pWin ){ + tdsqlite3WindowCodeInit(pParse, p); + } +#endif assert( WHERE_USE_LIMIT==SF_FixedLimit ); - wctrlFlags |= p->selFlags & SF_FixedLimit; + /* Begin the database scan. */ - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, + SELECTTRACE(1,pParse,p,("WhereBegin\n")); + pWInfo = tdsqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, p->pEList, wctrlFlags, p->nSelectRow); if( pWInfo==0 ) goto select_end; - if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ - p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); + if( tdsqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ + p->nSelectRow = tdsqlite3WhereOutputRowCount(pWInfo); } - if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ - sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); + if( sDistinct.isTnct && tdsqlite3WhereIsDistinct(pWInfo) ){ + sDistinct.eTnctType = tdsqlite3WhereIsDistinct(pWInfo); } if( sSort.pOrderBy ){ - sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); - sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo); + sSort.nOBSat = tdsqlite3WhereIsOrdered(pWInfo); + sSort.labelOBLopt = tdsqlite3WhereOrderByLimitOptLabel(pWInfo); if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ sSort.pOrderBy = 0; } @@ -122677,17 +137740,40 @@ SQLITE_PRIVATE int sqlite3Select( ** into an OP_Noop. */ if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ - sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); - } - - /* Use the standard inner loop. */ - selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest, - sqlite3WhereContinueLabel(pWInfo), - sqlite3WhereBreakLabel(pWInfo)); + tdsqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); + } + + assert( p->pEList==pEList ); +#ifndef SQLITE_OMIT_WINDOWFUNC + if( pWin ){ + int addrGosub = tdsqlite3VdbeMakeLabel(pParse); + int iCont = tdsqlite3VdbeMakeLabel(pParse); + int iBreak = tdsqlite3VdbeMakeLabel(pParse); + int regGosub = ++pParse->nMem; + + tdsqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub); + + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); + tdsqlite3VdbeResolveLabel(v, addrGosub); + VdbeNoopComment((v, "inner-loop subroutine")); + sSort.labelOBLopt = 0; + selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak); + tdsqlite3VdbeResolveLabel(v, iCont); + tdsqlite3VdbeAddOp1(v, OP_Return, regGosub); + VdbeComment((v, "end inner-loop subroutine")); + tdsqlite3VdbeResolveLabel(v, iBreak); + }else +#endif /* SQLITE_OMIT_WINDOWFUNC */ + { + /* Use the standard inner loop. */ + selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, + tdsqlite3WhereContinueLabel(pWInfo), + tdsqlite3WhereBreakLabel(pWInfo)); - /* End the database scan loop. - */ - sqlite3WhereEnd(pWInfo); + /* End the database scan loop. + */ + tdsqlite3WhereEnd(pWInfo); + } }else{ /* This case when there exist aggregate functions or a GROUP BY clause ** or both */ @@ -122717,27 +137803,39 @@ SQLITE_PRIVATE int sqlite3Select( for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ pItem->u.x.iAlias = 0; } - assert( 66==sqlite3LogEst(100) ); + assert( 66==tdsqlite3LogEst(100) ); if( p->nSelectRow>66 ) p->nSelectRow = 66; + + /* If there is both a GROUP BY and an ORDER BY clause and they are + ** identical, then it may be possible to disable the ORDER BY clause + ** on the grounds that the GROUP BY will cause elements to come out + ** in the correct order. It also may not - the GROUP BY might use a + ** database index that causes rows to be grouped together as required + ** but not actually sorted. Either way, record the fact that the + ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp + ** variable. */ + if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){ + int ii; + /* The GROUP BY processing doesn't care whether rows are delivered in + ** ASC or DESC order - only that each group is returned contiguously. + ** So set the ASC/DESC flags in the GROUP BY to match those in the + ** ORDER BY to maximize the chances of rows being delivered in an + ** order that makes the ORDER BY redundant. */ + for(ii=0; ii<pGroupBy->nExpr; ii++){ + u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC; + pGroupBy->a[ii].sortFlags = sortFlags; + } + if( tdsqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ + orderByGrp = 1; + } + } }else{ - assert( 0==sqlite3LogEst(1) ); + assert( 0==tdsqlite3LogEst(1) ); p->nSelectRow = 0; } - /* If there is both a GROUP BY and an ORDER BY clause and they are - ** identical, then it may be possible to disable the ORDER BY clause - ** on the grounds that the GROUP BY will cause elements to come out - ** in the correct order. It also may not - the GROUP BY might use a - ** database index that causes rows to be grouped together as required - ** but not actually sorted. Either way, record the fact that the - ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp - ** variable. */ - if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ - orderByGrp = 1; - } - /* Create a label to jump to when we want to abort the query */ - addrEnd = sqlite3VdbeMakeLabel(v); + addrEnd = tdsqlite3VdbeMakeLabel(pParse); /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the @@ -122746,24 +137844,62 @@ SQLITE_PRIVATE int sqlite3Select( memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; - sNC.pAggInfo = &sAggInfo; + sNC.uNC.pAggInfo = &sAggInfo; + VVA_ONLY( sNC.ncFlags = NC_UAggInfo; ) sAggInfo.mnReg = pParse->nMem+1; sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; sAggInfo.pGroupBy = pGroupBy; - sqlite3ExprAnalyzeAggList(&sNC, pEList); - sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); + tdsqlite3ExprAnalyzeAggList(&sNC, pEList); + tdsqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); if( pHaving ){ - sqlite3ExprAnalyzeAggregates(&sNC, pHaving); + if( pGroupBy ){ + assert( pWhere==p->pWhere ); + assert( pHaving==p->pHaving ); + assert( pGroupBy==p->pGroupBy ); + havingToWhere(pParse, p); + pWhere = p->pWhere; + } + tdsqlite3ExprAnalyzeAggregates(&sNC, pHaving); } sAggInfo.nAccumulator = sAggInfo.nColumn; + if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){ + minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy); + }else{ + minMaxFlag = WHERE_ORDERBY_NORMAL; + } for(i=0; i<sAggInfo.nFunc; i++){ - assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); + Expr *pExpr = sAggInfo.aFunc[i].pExpr; + assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); sNC.ncFlags |= NC_InAggFunc; - sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); + tdsqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList); +#ifndef SQLITE_OMIT_WINDOWFUNC + assert( !IsWindowFunc(pExpr) ); + if( ExprHasProperty(pExpr, EP_WinFunc) ){ + tdsqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter); + } +#endif sNC.ncFlags &= ~NC_InAggFunc; } sAggInfo.mxReg = pParse->nMem; if( db->mallocFailed ) goto select_end; +#if SELECTTRACE_ENABLED + if( tdsqlite3SelectTrace & 0x400 ){ + int ii; + SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n")); + tdsqlite3TreeViewSelect(0, p, 0); + for(ii=0; ii<sAggInfo.nColumn; ii++){ + tdsqlite3DebugPrintf("agg-column[%d] iMem=%d\n", + ii, sAggInfo.aCol[ii].iMem); + tdsqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0); + } + for(ii=0; ii<sAggInfo.nFunc; ii++){ + tdsqlite3DebugPrintf("agg-func[%d]: iMem=%d\n", + ii, sAggInfo.aFunc[ii].iMem); + tdsqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0); + } + } +#endif + /* Processing for aggregates with GROUP BY is very different and ** much more complex than aggregates without a GROUP BY. @@ -122785,8 +137921,8 @@ SQLITE_PRIVATE int sqlite3Select( ** will be converted into a Noop. */ sAggInfo.sortingIdx = pParse->nTab++; - pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn); - addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, + pKeyInfo = tdsqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn); + addrSortingIdx = tdsqlite3VdbeAddOp4(v, OP_SorterOpen, sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 0, (char*)pKeyInfo, P4_KEYINFO); @@ -122795,30 +137931,29 @@ SQLITE_PRIVATE int sqlite3Select( iUseFlag = ++pParse->nMem; iAbortFlag = ++pParse->nMem; regOutputRow = ++pParse->nMem; - addrOutputRow = sqlite3VdbeMakeLabel(v); + addrOutputRow = tdsqlite3VdbeMakeLabel(pParse); regReset = ++pParse->nMem; - addrReset = sqlite3VdbeMakeLabel(v); + addrReset = tdsqlite3VdbeMakeLabel(pParse); iAMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; iBMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; - sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); VdbeComment((v, "clear abort flag")); - sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); - VdbeComment((v, "indicate accumulator empty")); - sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); + tdsqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); /* Begin a loop that will extract all source rows in GROUP BY order. ** This might involve two separate loops with an OP_Sort in between, or ** it might be a single loop that uses an index to extract information ** in the right order to begin with. */ - sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, + tdsqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); + SELECTTRACE(1,pParse,p,("WhereBegin\n")); + pWInfo = tdsqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 ); if( pWInfo==0 ) goto select_end; - if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ + if( tdsqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ /* The optimizer is able to deliver rows in group by order so ** we do not have to sort. The OP_OpenEphemeral table will be ** cancelled later because we still need to use the pKeyInfo @@ -122849,33 +137984,30 @@ SQLITE_PRIVATE int sqlite3Select( j++; } } - regBase = sqlite3GetTempRange(pParse, nCol); - sqlite3ExprCacheClear(pParse); - sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); + regBase = tdsqlite3GetTempRange(pParse, nCol); + tdsqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); j = nGroupBy; for(i=0; i<sAggInfo.nColumn; i++){ struct AggInfo_col *pCol = &sAggInfo.aCol[i]; if( pCol->iSorterColumn>=j ){ int r1 = j + regBase; - sqlite3ExprCodeGetColumnToReg(pParse, - pCol->pTab, pCol->iColumn, pCol->iTable, r1); + tdsqlite3ExprCodeGetColumnOfTable(v, + pCol->pTab, pCol->iTable, pCol->iColumn, r1); j++; } } - regRecord = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); - sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); - sqlite3ReleaseTempReg(pParse, regRecord); - sqlite3ReleaseTempRange(pParse, regBase, nCol); - sqlite3WhereEnd(pWInfo); + regRecord = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); + tdsqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); + tdsqlite3ReleaseTempReg(pParse, regRecord); + tdsqlite3ReleaseTempRange(pParse, regBase, nCol); + tdsqlite3WhereEnd(pWInfo); sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; - sortOut = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); - sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); + sortOut = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); + tdsqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); sAggInfo.useSortingIdx = 1; - sqlite3ExprCacheClear(pParse); - } /* If the index or temporary table used by the GROUP BY sort @@ -122886,10 +138018,10 @@ SQLITE_PRIVATE int sqlite3Select( ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to ** disable this optimization for testing purposes. */ if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) - && (groupBySort || sqlite3WhereIsSorted(pWInfo)) + && (groupBySort || tdsqlite3WhereIsSorted(pWInfo)) ){ sSort.pOrderBy = 0; - sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); + tdsqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); } /* Evaluate the current GROUP BY terms and store in b0, b1, b2... @@ -122897,24 +138029,23 @@ SQLITE_PRIVATE int sqlite3Select( ** Then compare the current GROUP BY terms against the GROUP BY terms ** from the previous row currently stored in a0, a1, a2... */ - addrTopOfLoop = sqlite3VdbeCurrentAddr(v); - sqlite3ExprCacheClear(pParse); + addrTopOfLoop = tdsqlite3VdbeCurrentAddr(v); if( groupBySort ){ - sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, + tdsqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut, sortPTab); } for(j=0; j<pGroupBy->nExpr; j++){ if( groupBySort ){ - sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); + tdsqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); }else{ sAggInfo.directMode = 1; - sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); + tdsqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); } } - sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, - (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); - addr1 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); + tdsqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, + (char*)tdsqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); + addr1 = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); /* Generate code that runs whenever the GROUP BY changes. ** Changes in the GROUP BY are detected by the previous code @@ -122925,40 +138056,40 @@ SQLITE_PRIVATE int sqlite3Select( ** and resets the aggregate accumulator registers in preparation ** for the next GROUP BY batch. */ - sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); - sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); + tdsqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); + tdsqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); VdbeComment((v, "output one row")); - sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); VdbeComment((v, "check abort flag")); - sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); + tdsqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); VdbeComment((v, "reset accumulator")); /* Update the aggregate accumulators based on the content of ** the current row */ - sqlite3VdbeJumpHere(v, addr1); - updateAccumulator(pParse, &sAggInfo); - sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); + tdsqlite3VdbeJumpHere(v, addr1); + updateAccumulator(pParse, iUseFlag, &sAggInfo); + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); VdbeComment((v, "indicate data in accumulator")); /* End of the loop */ if( groupBySort ){ - sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); + tdsqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); VdbeCoverage(v); }else{ - sqlite3WhereEnd(pWInfo); - sqlite3VdbeChangeToNoop(v, addrSortingIdx); + tdsqlite3WhereEnd(pWInfo); + tdsqlite3VdbeChangeToNoop(v, addrSortingIdx); } /* Output the final row of result */ - sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); + tdsqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); VdbeComment((v, "output final row")); /* Jump over the subroutines */ - sqlite3VdbeGoto(v, addrEnd); + tdsqlite3VdbeGoto(v, addrEnd); /* Generate a subroutine that outputs a single row of the result ** set. This subroutine first looks at the iUseFlag. If iUseFlag @@ -122967,33 +138098,34 @@ SQLITE_PRIVATE int sqlite3Select( ** increments the iAbortFlag memory location before returning in ** order to signal the caller to abort. */ - addrSetAbort = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); + addrSetAbort = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); VdbeComment((v, "set abort flag")); - sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); - sqlite3VdbeResolveLabel(v, addrOutputRow); - addrOutputRow = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); + tdsqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + tdsqlite3VdbeResolveLabel(v, addrOutputRow); + addrOutputRow = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v); VdbeComment((v, "Groupby result generator entry point")); - sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + tdsqlite3VdbeAddOp1(v, OP_Return, regOutputRow); finalizeAggFunctions(pParse, &sAggInfo); - sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); - selectInnerLoop(pParse, p, p->pEList, -1, &sSort, + tdsqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); + selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, addrOutputRow+1, addrSetAbort); - sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + tdsqlite3VdbeAddOp1(v, OP_Return, regOutputRow); VdbeComment((v, "end groupby result generator")); /* Generate a subroutine that will reset the group-by accumulator */ - sqlite3VdbeResolveLabel(v, addrReset); + tdsqlite3VdbeResolveLabel(v, addrReset); resetAccumulator(pParse, &sAggInfo); - sqlite3VdbeAddOp1(v, OP_Return, regReset); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); + VdbeComment((v, "indicate accumulator empty")); + tdsqlite3VdbeAddOp1(v, OP_Return, regReset); } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ else { - ExprList *pDel = 0; #ifndef SQLITE_OMIT_BTREECOUNT Table *pTab; if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ @@ -123010,15 +138142,15 @@ SQLITE_PRIVATE int sqlite3Select( ** is better to execute the op on an index, as indexes are almost ** always spread across less pages than their corresponding tables. */ - const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + const int iDb = tdsqlite3SchemaToIndex(pParse->db, pTab->pSchema); const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ Index *pIdx; /* Iterator variable */ KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ Index *pBest = 0; /* Best index found so far */ int iRoot = pTab->tnum; /* Root page of scanned b-tree */ - sqlite3CodeVerifySchema(pParse, iDb); - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + tdsqlite3CodeVerifySchema(pParse, iDb); + tdsqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); /* Search for the index that has the lowest scan cost. ** @@ -123029,7 +138161,7 @@ SQLITE_PRIVATE int sqlite3Select( ** In practice the KeyInfo structure will not be used. It is only ** passed to keep OP_OpenRead happy. */ - if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); + if( !HasRowid(pTab) ) pBest = tdsqlite3PrimaryKeyIndex(pTab); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->bUnordered==0 && pIdx->szIdxRow<pTab->szTabRow @@ -123041,93 +138173,80 @@ SQLITE_PRIVATE int sqlite3Select( } if( pBest ){ iRoot = pBest->tnum; - pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); + pKeyInfo = tdsqlite3KeyInfoOfIndex(pParse, pBest); } /* Open a read-only cursor, execute the OP_Count, close the cursor. */ - sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); + tdsqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); if( pKeyInfo ){ - sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); + tdsqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); } - sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); - sqlite3VdbeAddOp1(v, OP_Close, iCsr); + tdsqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); + tdsqlite3VdbeAddOp1(v, OP_Close, iCsr); explainSimpleCount(pParse, pTab, pBest); }else #endif /* SQLITE_OMIT_BTREECOUNT */ { - /* Check if the query is of one of the following forms: - ** - ** SELECT min(x) FROM ... - ** SELECT max(x) FROM ... - ** - ** If it is, then ask the code in where.c to attempt to sort results - ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. - ** If where.c is able to produce results sorted in this order, then - ** add vdbe code to break out of the processing loop after the - ** first iteration (since the first iteration of the loop is - ** guaranteed to operate on the row with the minimum or maximum - ** value of x, the only row required). - ** - ** A special flag must be passed to sqlite3WhereBegin() to slightly - ** modify behavior as follows: - ** - ** + If the query is a "SELECT min(x)", then the loop coded by - ** where.c should not iterate over any values with a NULL value - ** for x. - ** - ** + The optimizer code in where.c (the thing that decides which - ** index or indices to use) should place a different priority on - ** satisfying the 'ORDER BY' clause than it does in other cases. - ** Refer to code and comments in where.c for details. - */ - ExprList *pMinMax = 0; - u8 flag = WHERE_ORDERBY_NORMAL; - - assert( p->pGroupBy==0 ); - assert( flag==0 ); - if( p->pHaving==0 ){ - flag = minMaxQuery(&sAggInfo, &pMinMax); - } - assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) ); - - if( flag ){ - pMinMax = sqlite3ExprListDup(db, pMinMax, 0); - pDel = pMinMax; - assert( db->mallocFailed || pMinMax!=0 ); - if( !db->mallocFailed ){ - pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; - pMinMax->a[0].pExpr->op = TK_COLUMN; + int regAcc = 0; /* "populate accumulators" flag */ + + /* If there are accumulator registers but no min() or max() functions + ** without FILTER clauses, allocate register regAcc. Register regAcc + ** will contain 0 the first time the inner loop runs, and 1 thereafter. + ** The code generated by updateAccumulator() uses this to ensure + ** that the accumulator registers are (a) updated only once if + ** there are no min() or max functions or (b) always updated for the + ** first row visited by the aggregate, so that they are updated at + ** least once even if the FILTER clause means the min() or max() + ** function visits zero rows. */ + if( sAggInfo.nAccumulator ){ + for(i=0; i<sAggInfo.nFunc; i++){ + if( ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_WinFunc) ) continue; + if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break; + } + if( i==sAggInfo.nFunc ){ + regAcc = ++pParse->nMem; + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc); } } - + /* This case runs if the aggregate has no GROUP BY clause. The ** processing is much simpler since there is only a single row ** of output. */ + assert( p->pGroupBy==0 ); resetAccumulator(pParse, &sAggInfo); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0); + + /* If this query is a candidate for the min/max optimization, then + ** minMaxFlag will have been previously set to either + ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will + ** be an appropriate ORDER BY expression for the optimization. + */ + assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 ); + assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 ); + + SELECTTRACE(1,pParse,p,("WhereBegin\n")); + pWInfo = tdsqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy, + 0, minMaxFlag, 0); if( pWInfo==0 ){ - sqlite3ExprListDelete(db, pDel); goto select_end; } - updateAccumulator(pParse, &sAggInfo); - assert( pMinMax==0 || pMinMax->nExpr==1 ); - if( sqlite3WhereIsOrdered(pWInfo)>0 ){ - sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); + updateAccumulator(pParse, regAcc, &sAggInfo); + if( regAcc ) tdsqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc); + if( tdsqlite3WhereIsOrdered(pWInfo)>0 ){ + tdsqlite3VdbeGoto(v, tdsqlite3WhereBreakLabel(pWInfo)); VdbeComment((v, "%s() by index", - (flag==WHERE_ORDERBY_MIN?"min":"max"))); + (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max"))); } - sqlite3WhereEnd(pWInfo); + tdsqlite3WhereEnd(pWInfo); finalizeAggFunctions(pParse, &sAggInfo); } sSort.pOrderBy = 0; - sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); - selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, + tdsqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); + selectInnerLoop(pParse, p, -1, 0, 0, pDest, addrEnd, addrEnd); - sqlite3ExprListDelete(db, pDel); } - sqlite3VdbeResolveLabel(v, addrEnd); + tdsqlite3VdbeResolveLabel(v, addrEnd); } /* endif aggregate query */ @@ -123141,12 +138260,13 @@ SQLITE_PRIVATE int sqlite3Select( if( sSort.pOrderBy ){ explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); + assert( p->pEList==pEList ); generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); } /* Jump here to skip this query */ - sqlite3VdbeResolveLabel(v, iEnd); + tdsqlite3VdbeResolveLabel(v, iEnd); /* The SELECT has been coded. If there is an error in the Parse structure, ** set the return code to 1. Otherwise 0. */ @@ -123156,20 +138276,16 @@ SQLITE_PRIVATE int sqlite3Select( ** successful coding of the SELECT. */ select_end: - explainSetInteger(pParse->iSelectId, iRestoreSelectId); - - /* Identify column names if results of the SELECT are to be output. - */ - if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ - generateColumnNames(pParse, pTabList, pEList); - } - - sqlite3DbFree(db, sAggInfo.aCol); - sqlite3DbFree(db, sAggInfo.aFunc); + tdsqlite3ExprListDelete(db, pMinMaxOrderBy); + tdsqlite3DbFree(db, sAggInfo.aCol); + tdsqlite3DbFree(db, sAggInfo.aFunc); #if SELECTTRACE_ENABLED - SELECTTRACE(1,pParse,p,("end processing\n")); - pParse->nSelectIndent--; + SELECTTRACE(0x1,pParse,p,("end processing\n")); + if( (tdsqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ + tdsqlite3TreeViewSelect(0, p, 0); + } #endif + ExplainQueryPlanPop(pParse); return rc; } @@ -123186,21 +138302,19 @@ select_end: ** May you share freely, never taking more than you give. ** ************************************************************************* -** This file contains the sqlite3_get_table() and sqlite3_free_table() +** This file contains the tdsqlite3_get_table() and tdsqlite3_free_table() ** interface routines. These are just wrappers around the main -** interface routine of sqlite3_exec(). +** interface routine of tdsqlite3_exec(). ** ** These routines are in a separate files so that they will not be linked ** if they are not used. */ /* #include "sqliteInt.h" */ -/* #include <stdlib.h> */ -/* #include <string.h> */ #ifndef SQLITE_OMIT_GET_TABLE /* -** This structure is used to pass data from sqlite3_get_table() through +** This structure is used to pass data from tdsqlite3_get_table() through ** to the callback function is uses to build the result. */ typedef struct TabResult { @@ -123210,7 +138324,7 @@ typedef struct TabResult { u32 nRow; /* Number of rows in the result */ u32 nColumn; /* Number of columns in the result */ u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */ - int rc; /* Return code from sqlite3_exec() */ + int rc; /* Return code from tdsqlite3_exec() */ } TabResult; /* @@ -123218,7 +138332,7 @@ typedef struct TabResult { ** is to fill in the TabResult structure appropriately, allocating new ** memory as necessary. */ -static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ +static int tdsqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ TabResult *p = (TabResult*)pArg; /* Result accumulator */ int need; /* Slots needed in p->azResult[] */ int i; /* Loop counter */ @@ -123235,7 +138349,7 @@ static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ if( p->nData + need > p->nAlloc ){ char **azNew; p->nAlloc = p->nAlloc*2 + need; - azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc ); + azNew = tdsqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc ); if( azNew==0 ) goto malloc_failed; p->azResult = azNew; } @@ -123246,14 +138360,14 @@ static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ if( p->nRow==0 ){ p->nColumn = nCol; for(i=0; i<nCol; i++){ - z = sqlite3_mprintf("%s", colv[i]); + z = tdsqlite3_mprintf("%s", colv[i]); if( z==0 ) goto malloc_failed; p->azResult[p->nData++] = z; } }else if( (int)p->nColumn!=nCol ){ - sqlite3_free(p->zErrMsg); - p->zErrMsg = sqlite3_mprintf( - "sqlite3_get_table() called with two or more incompatible queries" + tdsqlite3_free(p->zErrMsg); + p->zErrMsg = tdsqlite3_mprintf( + "tdsqlite3_get_table() called with two or more incompatible queries" ); p->rc = SQLITE_ERROR; return 1; @@ -123266,8 +138380,8 @@ static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ if( argv[i]==0 ){ z = 0; }else{ - int n = sqlite3Strlen30(argv[i])+1; - z = sqlite3_malloc64( n ); + int n = tdsqlite3Strlen30(argv[i])+1; + z = tdsqlite3_malloc64( n ); if( z==0 ) goto malloc_failed; memcpy(z, argv[i], n); } @@ -123289,11 +138403,11 @@ malloc_failed: ** ** The result that is written to ***pazResult is held in memory obtained ** from malloc(). But the caller cannot free this memory directly. -** Instead, the entire table should be passed to sqlite3_free_table() when +** Instead, the entire table should be passed to tdsqlite3_free_table() when ** the calling procedure is finished using it. */ -SQLITE_API int sqlite3_get_table( - sqlite3 *db, /* The database on which the SQL executes */ +SQLITE_API int tdsqlite3_get_table( + tdsqlite3 *db, /* The database on which the SQL executes */ const char *zSql, /* The SQL to be executed */ char ***pazResult, /* Write the result table here */ int *pnRow, /* Write the number of rows in the result here */ @@ -123304,7 +138418,7 @@ SQLITE_API int sqlite3_get_table( TabResult res; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT; #endif *pazResult = 0; if( pnColumn ) *pnColumn = 0; @@ -123316,37 +138430,37 @@ SQLITE_API int sqlite3_get_table( res.nData = 1; res.nAlloc = 20; res.rc = SQLITE_OK; - res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc ); + res.azResult = tdsqlite3_malloc64(sizeof(char*)*res.nAlloc ); if( res.azResult==0 ){ db->errCode = SQLITE_NOMEM; return SQLITE_NOMEM_BKPT; } res.azResult[0] = 0; - rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg); + rc = tdsqlite3_exec(db, zSql, tdsqlite3_get_table_cb, &res, pzErrMsg); assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); res.azResult[0] = SQLITE_INT_TO_PTR(res.nData); if( (rc&0xff)==SQLITE_ABORT ){ - sqlite3_free_table(&res.azResult[1]); + tdsqlite3_free_table(&res.azResult[1]); if( res.zErrMsg ){ if( pzErrMsg ){ - sqlite3_free(*pzErrMsg); - *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); + tdsqlite3_free(*pzErrMsg); + *pzErrMsg = tdsqlite3_mprintf("%s",res.zErrMsg); } - sqlite3_free(res.zErrMsg); + tdsqlite3_free(res.zErrMsg); } db->errCode = res.rc; /* Assume 32-bit assignment is atomic */ return res.rc; } - sqlite3_free(res.zErrMsg); + tdsqlite3_free(res.zErrMsg); if( rc!=SQLITE_OK ){ - sqlite3_free_table(&res.azResult[1]); + tdsqlite3_free_table(&res.azResult[1]); return rc; } if( res.nAlloc>res.nData ){ char **azNew; - azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData ); + azNew = tdsqlite3_realloc64( res.azResult, sizeof(char*)*res.nData ); if( azNew==0 ){ - sqlite3_free_table(&res.azResult[1]); + tdsqlite3_free_table(&res.azResult[1]); db->errCode = SQLITE_NOMEM; return SQLITE_NOMEM_BKPT; } @@ -123359,18 +138473,18 @@ SQLITE_API int sqlite3_get_table( } /* -** This routine frees the space the sqlite3_get_table() malloced. +** This routine frees the space the tdsqlite3_get_table() malloced. */ -SQLITE_API void sqlite3_free_table( - char **azResult /* Result returned from sqlite3_get_table() */ +SQLITE_API void tdsqlite3_free_table( + char **azResult /* Result returned from tdsqlite3_get_table() */ ){ if( azResult ){ int i, n; azResult--; assert( azResult!=0 ); n = SQLITE_PTR_TO_INT(azResult[0]); - for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); } - sqlite3_free(azResult); + for(i=1; i<n; i++){ if( azResult[i] ) tdsqlite3_free(azResult[i]); } + tdsqlite3_free(azResult); } } @@ -123396,17 +138510,19 @@ SQLITE_API void sqlite3_free_table( /* ** Delete a linked list of TriggerStep structures. */ -SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){ +SQLITE_PRIVATE void tdsqlite3DeleteTriggerStep(tdsqlite3 *db, TriggerStep *pTriggerStep){ while( pTriggerStep ){ TriggerStep * pTmp = pTriggerStep; pTriggerStep = pTriggerStep->pNext; - sqlite3ExprDelete(db, pTmp->pWhere); - sqlite3ExprListDelete(db, pTmp->pExprList); - sqlite3SelectDelete(db, pTmp->pSelect); - sqlite3IdListDelete(db, pTmp->pIdList); + tdsqlite3ExprDelete(db, pTmp->pWhere); + tdsqlite3ExprListDelete(db, pTmp->pExprList); + tdsqlite3SelectDelete(db, pTmp->pSelect); + tdsqlite3IdListDelete(db, pTmp->pIdList); + tdsqlite3UpsertDelete(db, pTmp->pUpsert); + tdsqlite3DbFree(db, pTmp->zSpan); - sqlite3DbFree(db, pTmp); + tdsqlite3DbFree(db, pTmp); } } @@ -123424,7 +138540,7 @@ SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerS ** that fire off of pTab. The list will include any TEMP triggers on ** pTab as well as the triggers lised in pTab->pTrigger. */ -SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ +SQLITE_PRIVATE Trigger *tdsqlite3TriggerList(Parse *pParse, Table *pTab){ Schema * const pTmpSchema = pParse->db->aDb[1].pSchema; Trigger *pList = 0; /* List of triggers to return */ @@ -123434,11 +138550,11 @@ SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ if( pTmpSchema!=pTab->pSchema ){ HashElem *p; - assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) ); + assert( tdsqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) ); for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){ Trigger *pTrig = (Trigger *)sqliteHashData(p); if( pTrig->pTabSchema==pTab->pSchema - && 0==sqlite3StrICmp(pTrig->table, pTab->zName) + && 0==tdsqlite3StrICmp(pTrig->table, pTab->zName) ){ pTrig->pNext = (pList ? pList : pTab->pTrigger); pList = pTrig; @@ -123454,10 +138570,10 @@ SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ ** up to the point of the BEGIN before the trigger actions. A Trigger ** structure is generated based on the information available and stored ** in pParse->pNewTrigger. After the trigger actions have been parsed, the -** sqlite3FinishTrigger() function is called to complete the trigger +** tdsqlite3FinishTrigger() function is called to complete the trigger ** construction process. */ -SQLITE_PRIVATE void sqlite3BeginTrigger( +SQLITE_PRIVATE void tdsqlite3BeginTrigger( Parse *pParse, /* The parse context of the CREATE TRIGGER statement */ Token *pName1, /* The name of the trigger */ Token *pName2, /* The name of the trigger */ @@ -123472,7 +138588,7 @@ SQLITE_PRIVATE void sqlite3BeginTrigger( Trigger *pTrigger = 0; /* The new trigger */ Table *pTab; /* Table that the trigger fires off of */ char *zName = 0; /* Name of the trigger */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ int iDb; /* The database to store the trigger in */ Token *pName; /* The unqualified db name */ DbFixer sFix; /* State vector for the DB fixer */ @@ -123484,14 +138600,14 @@ SQLITE_PRIVATE void sqlite3BeginTrigger( if( isTemp ){ /* If TEMP was specified, then the trigger name may not be qualified. */ if( pName2->n>0 ){ - sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name"); + tdsqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name"); goto trigger_cleanup; } iDb = 1; pName = pName1; }else{ /* Figure out the db that the trigger will be created in */ - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); + iDb = tdsqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ){ goto trigger_cleanup; } @@ -123509,16 +138625,16 @@ SQLITE_PRIVATE void sqlite3BeginTrigger( ** name on pTableName if we are reparsing out of SQLITE_MASTER. */ if( db->init.busy && iDb!=1 ){ - sqlite3DbFree(db, pTableName->a[0].zDatabase); + tdsqlite3DbFree(db, pTableName->a[0].zDatabase); pTableName->a[0].zDatabase = 0; } /* If the trigger name was unqualified, and the table is a temp table, ** then set iDb to 1 to create the trigger in the temporary database. - ** If sqlite3SrcListLookup() returns 0, indicating the table does not + ** If tdsqlite3SrcListLookup() returns 0, indicating the table does not ** exist, the error is caught by the block below. */ - pTab = sqlite3SrcListLookup(pParse, pTableName); + pTab = tdsqlite3SrcListLookup(pParse, pTableName); if( db->init.busy==0 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ iDb = 1; @@ -123527,11 +138643,11 @@ SQLITE_PRIVATE void sqlite3BeginTrigger( /* Ensure the table name matches database name and that the table exists */ if( db->mallocFailed ) goto trigger_cleanup; assert( pTableName->nSrc==1 ); - sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName); - if( sqlite3FixSrcList(&sFix, pTableName) ){ + tdsqlite3FixInit(&sFix, pParse, iDb, "trigger", pName); + if( tdsqlite3FixSrcList(&sFix, pTableName) ){ goto trigger_cleanup; } - pTab = sqlite3SrcListLookup(pParse, pTableName); + pTab = tdsqlite3SrcListLookup(pParse, pTableName); if( !pTab ){ /* The table does not exist. */ if( db->init.iDb==1 ){ @@ -123548,30 +138664,36 @@ SQLITE_PRIVATE void sqlite3BeginTrigger( goto trigger_cleanup; } if( IsVirtual(pTab) ){ - sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables"); + tdsqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables"); goto trigger_cleanup; } /* Check that the trigger name is not reserved and that no trigger of the ** specified name exists */ - zName = sqlite3NameFromToken(db, pName); - if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ + zName = tdsqlite3NameFromToken(db, pName); + if( zName==0 ){ + assert( db->mallocFailed ); goto trigger_cleanup; } - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){ - if( !noErr ){ - sqlite3ErrorMsg(pParse, "trigger %T already exists", pName); - }else{ - assert( !db->init.busy ); - sqlite3CodeVerifySchema(pParse, iDb); - } + if( tdsqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){ goto trigger_cleanup; } + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); + if( !IN_RENAME_OBJECT ){ + if( tdsqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){ + if( !noErr ){ + tdsqlite3ErrorMsg(pParse, "trigger %T already exists", pName); + }else{ + assert( !db->init.busy ); + tdsqlite3CodeVerifySchema(pParse, iDb); + } + goto trigger_cleanup; + } + } /* Do not create a trigger on a system table */ - if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ - sqlite3ErrorMsg(pParse, "cannot create trigger on system table"); + if( tdsqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ + tdsqlite3ErrorMsg(pParse, "cannot create trigger on system table"); goto trigger_cleanup; } @@ -123579,27 +138701,27 @@ SQLITE_PRIVATE void sqlite3BeginTrigger( ** of triggers. */ if( pTab->pSelect && tr_tm!=TK_INSTEAD ){ - sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", + tdsqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0); goto trigger_cleanup; } if( !pTab->pSelect && tr_tm==TK_INSTEAD ){ - sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF" + tdsqlite3ErrorMsg(pParse, "cannot create INSTEAD OF" " trigger on table: %S", pTableName, 0); goto trigger_cleanup; } #ifndef SQLITE_OMIT_AUTHORIZATION - { - int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); + if( !IN_RENAME_OBJECT ){ + int iTabDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); int code = SQLITE_CREATE_TRIGGER; const char *zDb = db->aDb[iTabDb].zDbSName; const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb; if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER; - if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){ + if( tdsqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){ goto trigger_cleanup; } - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){ + if( tdsqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){ goto trigger_cleanup; } } @@ -123615,27 +138737,34 @@ SQLITE_PRIVATE void sqlite3BeginTrigger( } /* Build the Trigger object */ - pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger)); + pTrigger = (Trigger*)tdsqlite3DbMallocZero(db, sizeof(Trigger)); if( pTrigger==0 ) goto trigger_cleanup; pTrigger->zName = zName; zName = 0; - pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName); + pTrigger->table = tdsqlite3DbStrDup(db, pTableName->a[0].zName); pTrigger->pSchema = db->aDb[iDb].pSchema; pTrigger->pTabSchema = pTab->pSchema; pTrigger->op = (u8)op; pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER; - pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); - pTrigger->pColumns = sqlite3IdListDup(db, pColumns); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName); + pTrigger->pWhen = pWhen; + pWhen = 0; + }else{ + pTrigger->pWhen = tdsqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); + } + pTrigger->pColumns = pColumns; + pColumns = 0; assert( pParse->pNewTrigger==0 ); pParse->pNewTrigger = pTrigger; trigger_cleanup: - sqlite3DbFree(db, zName); - sqlite3SrcListDelete(db, pTableName); - sqlite3IdListDelete(db, pColumns); - sqlite3ExprDelete(db, pWhen); + tdsqlite3DbFree(db, zName); + tdsqlite3SrcListDelete(db, pTableName); + tdsqlite3IdListDelete(db, pColumns); + tdsqlite3ExprDelete(db, pWhen); if( !pParse->pNewTrigger ){ - sqlite3DeleteTrigger(db, pTrigger); + tdsqlite3DeleteTrigger(db, pTrigger); }else{ assert( pParse->pNewTrigger==pTrigger ); } @@ -123645,14 +138774,14 @@ trigger_cleanup: ** This routine is called after all of the trigger actions have been parsed ** in order to complete the process of building the trigger. */ -SQLITE_PRIVATE void sqlite3FinishTrigger( +SQLITE_PRIVATE void tdsqlite3FinishTrigger( Parse *pParse, /* Parser context */ TriggerStep *pStepList, /* The triggered program */ Token *pAll /* Token that describes the complete CREATE TRIGGER */ ){ Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */ char *zName; /* Name of trigger */ - sqlite3 *db = pParse->db; /* The database */ + tdsqlite3 *db = pParse->db; /* The database */ DbFixer sFix; /* Fixer object */ int iDb; /* Database containing the trigger */ Token nameToken; /* Trigger name for error reporting */ @@ -123660,20 +138789,28 @@ SQLITE_PRIVATE void sqlite3FinishTrigger( pParse->pNewTrigger = 0; if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup; zName = pTrig->zName; - iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); + iDb = tdsqlite3SchemaToIndex(pParse->db, pTrig->pSchema); pTrig->step_list = pStepList; while( pStepList ){ pStepList->pTrig = pTrig; pStepList = pStepList->pNext; } - sqlite3TokenInit(&nameToken, pTrig->zName); - sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken); - if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) - || sqlite3FixExpr(&sFix, pTrig->pWhen) + tdsqlite3TokenInit(&nameToken, pTrig->zName); + tdsqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken); + if( tdsqlite3FixTriggerStep(&sFix, pTrig->step_list) + || tdsqlite3FixExpr(&sFix, pTrig->pWhen) ){ goto triggerfinish_cleanup; } +#ifndef SQLITE_OMIT_ALTERTABLE + if( IN_RENAME_OBJECT ){ + assert( !db->init.busy ); + pParse->pNewTrigger = pTrig; + pTrig = 0; + }else +#endif + /* if we are not initializing, ** build the sqlite_master entry */ @@ -123682,30 +138819,32 @@ SQLITE_PRIVATE void sqlite3FinishTrigger( char *z; /* Make an entry in the sqlite_master table */ - v = sqlite3GetVdbe(pParse); + v = tdsqlite3GetVdbe(pParse); if( v==0 ) goto triggerfinish_cleanup; - sqlite3BeginWriteOperation(pParse, 0, iDb); - z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n); - sqlite3NestedParse(pParse, + tdsqlite3BeginWriteOperation(pParse, 0, iDb); + z = tdsqlite3DbStrNDup(db, (char*)pAll->z, pAll->n); + testcase( z==0 ); + tdsqlite3NestedParse(pParse, "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')", - db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), zName, + db->aDb[iDb].zDbSName, MASTER_NAME, zName, pTrig->table, z); - sqlite3DbFree(db, z); - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddParseSchemaOp(v, iDb, - sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName)); + tdsqlite3DbFree(db, z); + tdsqlite3ChangeCookie(pParse, iDb); + tdsqlite3VdbeAddParseSchemaOp(v, iDb, + tdsqlite3MPrintf(db, "type='trigger' AND name='%q'", zName)); } if( db->init.busy ){ Trigger *pLink = pTrig; Hash *pHash = &db->aDb[iDb].pSchema->trigHash; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - pTrig = sqlite3HashInsert(pHash, zName, pTrig); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( pLink!=0 ); + pTrig = tdsqlite3HashInsert(pHash, zName, pTrig); if( pTrig ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); }else if( pLink->pSchema==pLink->pTabSchema ){ Table *pTab; - pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table); + pTab = tdsqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table); assert( pTab!=0 ); pLink->pNext = pTab->pTrigger; pTab->pTrigger = pLink; @@ -123713,27 +138852,44 @@ SQLITE_PRIVATE void sqlite3FinishTrigger( } triggerfinish_cleanup: - sqlite3DeleteTrigger(db, pTrig); - assert( !pParse->pNewTrigger ); - sqlite3DeleteTriggerStep(db, pStepList); + tdsqlite3DeleteTrigger(db, pTrig); + assert( IN_RENAME_OBJECT || !pParse->pNewTrigger ); + tdsqlite3DeleteTriggerStep(db, pStepList); } /* +** Duplicate a range of text from an SQL statement, then convert all +** whitespace characters into ordinary space characters. +*/ +static char *triggerSpanDup(tdsqlite3 *db, const char *zStart, const char *zEnd){ + char *z = tdsqlite3DbSpanDup(db, zStart, zEnd); + int i; + if( z ) for(i=0; z[i]; i++) if( tdsqlite3Isspace(z[i]) ) z[i] = ' '; + return z; +} + +/* ** Turn a SELECT statement (that the pSelect parameter points to) into ** a trigger step. Return a pointer to a TriggerStep structure. ** ** The parser calls this routine when it finds a SELECT statement in ** body of a TRIGGER. */ -SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){ - TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); +SQLITE_PRIVATE TriggerStep *tdsqlite3TriggerSelectStep( + tdsqlite3 *db, /* Database connection */ + Select *pSelect, /* The SELECT statement */ + const char *zStart, /* Start of SQL text */ + const char *zEnd /* End of SQL text */ +){ + TriggerStep *pTriggerStep = tdsqlite3DbMallocZero(db, sizeof(TriggerStep)); if( pTriggerStep==0 ) { - sqlite3SelectDelete(db, pSelect); + tdsqlite3SelectDelete(db, pSelect); return 0; } pTriggerStep->op = TK_SELECT; pTriggerStep->pSelect = pSelect; pTriggerStep->orconf = OE_Default; + pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd); return pTriggerStep; } @@ -123744,19 +138900,26 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelec ** If an OOM error occurs, NULL is returned and db->mallocFailed is set. */ static TriggerStep *triggerStepAllocate( - sqlite3 *db, /* Database connection */ + Parse *pParse, /* Parser context */ u8 op, /* Trigger opcode */ - Token *pName /* The target name */ + Token *pName, /* The target name */ + const char *zStart, /* Start of SQL text */ + const char *zEnd /* End of SQL text */ ){ + tdsqlite3 *db = pParse->db; TriggerStep *pTriggerStep; - pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1); + pTriggerStep = tdsqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1); if( pTriggerStep ){ char *z = (char*)&pTriggerStep[1]; memcpy(z, pName->z, pName->n); - sqlite3Dequote(z); + tdsqlite3Dequote(z); pTriggerStep->zTarget = z; pTriggerStep->op = op; + pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName); + } } return pTriggerStep; } @@ -123768,26 +138931,42 @@ static TriggerStep *triggerStepAllocate( ** The parser calls this routine when it sees an INSERT inside the ** body of a trigger. */ -SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep( - sqlite3 *db, /* The database connection */ +SQLITE_PRIVATE TriggerStep *tdsqlite3TriggerInsertStep( + Parse *pParse, /* Parser */ Token *pTableName, /* Name of the table into which we insert */ IdList *pColumn, /* List of columns in pTableName to insert into */ Select *pSelect, /* A SELECT statement that supplies values */ - u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */ + u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */ + Upsert *pUpsert, /* ON CONFLICT clauses for upsert */ + const char *zStart, /* Start of SQL text */ + const char *zEnd /* End of SQL text */ ){ + tdsqlite3 *db = pParse->db; TriggerStep *pTriggerStep; assert(pSelect != 0 || db->mallocFailed); - pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName); + pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd); if( pTriggerStep ){ - pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + if( IN_RENAME_OBJECT ){ + pTriggerStep->pSelect = pSelect; + pSelect = 0; + }else{ + pTriggerStep->pSelect = tdsqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); + } pTriggerStep->pIdList = pColumn; + pTriggerStep->pUpsert = pUpsert; pTriggerStep->orconf = orconf; + if( pUpsert ){ + tdsqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget); + } }else{ - sqlite3IdListDelete(db, pColumn); + testcase( pColumn ); + tdsqlite3IdListDelete(db, pColumn); + testcase( pUpsert ); + tdsqlite3UpsertDelete(db, pUpsert); } - sqlite3SelectDelete(db, pSelect); + tdsqlite3SelectDelete(db, pSelect); return pTriggerStep; } @@ -123797,23 +138976,33 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep( ** a pointer to that trigger step. The parser calls this routine when it ** sees an UPDATE statement inside the body of a CREATE TRIGGER. */ -SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep( - sqlite3 *db, /* The database connection */ +SQLITE_PRIVATE TriggerStep *tdsqlite3TriggerUpdateStep( + Parse *pParse, /* Parser */ Token *pTableName, /* Name of the table to be updated */ ExprList *pEList, /* The SET clause: list of column and new values */ Expr *pWhere, /* The WHERE clause */ - u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */ + u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */ + const char *zStart, /* Start of SQL text */ + const char *zEnd /* End of SQL text */ ){ + tdsqlite3 *db = pParse->db; TriggerStep *pTriggerStep; - pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName); + pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd); if( pTriggerStep ){ - pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); - pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + if( IN_RENAME_OBJECT ){ + pTriggerStep->pExprList = pEList; + pTriggerStep->pWhere = pWhere; + pEList = 0; + pWhere = 0; + }else{ + pTriggerStep->pExprList = tdsqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); + pTriggerStep->pWhere = tdsqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + } pTriggerStep->orconf = orconf; } - sqlite3ExprListDelete(db, pEList); - sqlite3ExprDelete(db, pWhere); + tdsqlite3ExprListDelete(db, pEList); + tdsqlite3ExprDelete(db, pWhere); return pTriggerStep; } @@ -123822,79 +139011,87 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep( ** a pointer to that trigger step. The parser calls this routine when it ** sees a DELETE statement inside the body of a CREATE TRIGGER. */ -SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep( - sqlite3 *db, /* Database connection */ +SQLITE_PRIVATE TriggerStep *tdsqlite3TriggerDeleteStep( + Parse *pParse, /* Parser */ Token *pTableName, /* The table from which rows are deleted */ - Expr *pWhere /* The WHERE clause */ + Expr *pWhere, /* The WHERE clause */ + const char *zStart, /* Start of SQL text */ + const char *zEnd /* End of SQL text */ ){ + tdsqlite3 *db = pParse->db; TriggerStep *pTriggerStep; - pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName); + pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd); if( pTriggerStep ){ - pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + if( IN_RENAME_OBJECT ){ + pTriggerStep->pWhere = pWhere; + pWhere = 0; + }else{ + pTriggerStep->pWhere = tdsqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); + } pTriggerStep->orconf = OE_Default; } - sqlite3ExprDelete(db, pWhere); + tdsqlite3ExprDelete(db, pWhere); return pTriggerStep; } /* ** Recursively delete a Trigger structure */ -SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){ +SQLITE_PRIVATE void tdsqlite3DeleteTrigger(tdsqlite3 *db, Trigger *pTrigger){ if( pTrigger==0 ) return; - sqlite3DeleteTriggerStep(db, pTrigger->step_list); - sqlite3DbFree(db, pTrigger->zName); - sqlite3DbFree(db, pTrigger->table); - sqlite3ExprDelete(db, pTrigger->pWhen); - sqlite3IdListDelete(db, pTrigger->pColumns); - sqlite3DbFree(db, pTrigger); + tdsqlite3DeleteTriggerStep(db, pTrigger->step_list); + tdsqlite3DbFree(db, pTrigger->zName); + tdsqlite3DbFree(db, pTrigger->table); + tdsqlite3ExprDelete(db, pTrigger->pWhen); + tdsqlite3IdListDelete(db, pTrigger->pColumns); + tdsqlite3DbFree(db, pTrigger); } /* ** This function is called to drop a trigger from the database schema. ** ** This may be called directly from the parser and therefore identifies -** the trigger by name. The sqlite3DropTriggerPtr() routine does the +** the trigger by name. The tdsqlite3DropTriggerPtr() routine does the ** same job as this routine except it takes a pointer to the trigger ** instead of the trigger name. **/ -SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){ +SQLITE_PRIVATE void tdsqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){ Trigger *pTrigger = 0; int i; const char *zDb; const char *zName; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; if( db->mallocFailed ) goto drop_trigger_cleanup; - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ + if( SQLITE_OK!=tdsqlite3ReadSchema(pParse) ){ goto drop_trigger_cleanup; } assert( pName->nSrc==1 ); zDb = pName->a[0].zDatabase; zName = pName->a[0].zName; - assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); + assert( zDb!=0 || tdsqlite3BtreeHoldsAllMutexes(db) ); for(i=OMIT_TEMPDB; i<db->nDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ - if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue; - assert( sqlite3SchemaMutexHeld(db, j, 0) ); - pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName); + if( zDb && tdsqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue; + assert( tdsqlite3SchemaMutexHeld(db, j, 0) ); + pTrigger = tdsqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName); if( pTrigger ) break; } if( !pTrigger ){ if( !noErr ){ - sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0); + tdsqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0); }else{ - sqlite3CodeVerifyNamedSchema(pParse, zDb); + tdsqlite3CodeVerifyNamedSchema(pParse, zDb); } pParse->checkSchema = 1; goto drop_trigger_cleanup; } - sqlite3DropTriggerPtr(pParse, pTrigger); + tdsqlite3DropTriggerPtr(pParse, pTrigger); drop_trigger_cleanup: - sqlite3SrcListDelete(db, pName); + tdsqlite3SrcListDelete(db, pName); } /* @@ -123902,32 +139099,31 @@ drop_trigger_cleanup: ** is set on. */ static Table *tableOfTrigger(Trigger *pTrigger){ - return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table); + return tdsqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table); } /* ** Drop a trigger given a pointer to that trigger. */ -SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ +SQLITE_PRIVATE void tdsqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ Table *pTable; Vdbe *v; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; int iDb; - iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema); + iDb = tdsqlite3SchemaToIndex(pParse->db, pTrigger->pSchema); assert( iDb>=0 && iDb<db->nDb ); pTable = tableOfTrigger(pTrigger); - assert( pTable ); - assert( pTable->pSchema==pTrigger->pSchema || iDb==1 ); + assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 ); #ifndef SQLITE_OMIT_AUTHORIZATION - { + if( pTable ){ int code = SQLITE_DROP_TRIGGER; const char *zDb = db->aDb[iDb].zDbSName; const char *zTab = SCHEMA_TABLE(iDb); if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER; - if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) || - sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ + if( tdsqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) || + tdsqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ return; } } @@ -123935,36 +139131,41 @@ SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ /* Generate code to destroy the database record of the trigger. */ - assert( pTable!=0 ); - if( (v = sqlite3GetVdbe(pParse))!=0 ){ - sqlite3NestedParse(pParse, + if( (v = tdsqlite3GetVdbe(pParse))!=0 ){ + tdsqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'", - db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pTrigger->zName + db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName ); - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0); + tdsqlite3ChangeCookie(pParse, iDb); + tdsqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0); } } /* ** Remove a trigger from the hash tables of the sqlite* pointer. */ -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){ +SQLITE_PRIVATE void tdsqlite3UnlinkAndDeleteTrigger(tdsqlite3 *db, int iDb, const char *zName){ Trigger *pTrigger; Hash *pHash; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); + assert( tdsqlite3SchemaMutexHeld(db, iDb, 0) ); pHash = &(db->aDb[iDb].pSchema->trigHash); - pTrigger = sqlite3HashInsert(pHash, zName, 0); + pTrigger = tdsqlite3HashInsert(pHash, zName, 0); if( ALWAYS(pTrigger) ){ if( pTrigger->pSchema==pTrigger->pTabSchema ){ Table *pTab = tableOfTrigger(pTrigger); - Trigger **pp; - for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext)); - *pp = (*pp)->pNext; + if( pTab ){ + Trigger **pp; + for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){ + if( *pp==pTrigger ){ + *pp = (*pp)->pNext; + break; + } + } + } } - sqlite3DeleteTrigger(db, pTrigger); - db->flags |= SQLITE_InternChanges; + tdsqlite3DeleteTrigger(db, pTrigger); + db->mDbFlags |= DBFLAG_SchemaChange; } } @@ -123981,7 +139182,7 @@ static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){ int e; if( pIdList==0 || NEVER(pEList==0) ) return 1; for(e=0; e<pEList->nExpr; e++){ - if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1; + if( tdsqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1; } return 0; } @@ -123992,7 +139193,7 @@ static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){ ** performed on the table, and, if that operation is an UPDATE, if at ** least one of the columns in pChanges is being modified. */ -SQLITE_PRIVATE Trigger *sqlite3TriggersExist( +SQLITE_PRIVATE Trigger *tdsqlite3TriggersExist( Parse *pParse, /* Parse context */ Table *pTab, /* The table the contains the triggers */ int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */ @@ -124004,7 +139205,7 @@ SQLITE_PRIVATE Trigger *sqlite3TriggersExist( Trigger *p; if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){ - pList = sqlite3TriggerList(pParse, pTab); + pList = tdsqlite3TriggerList(pParse, pTab); } assert( pList==0 || IsVirtual(pTab)==0 ); for(p=pList; p; p=p->pNext){ @@ -124032,20 +139233,20 @@ static SrcList *targetSrcList( Parse *pParse, /* The parsing context */ TriggerStep *pStep /* The trigger containing the target token */ ){ - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; int iDb; /* Index of the database to use */ SrcList *pSrc; /* SrcList to be returned */ - pSrc = sqlite3SrcListAppend(db, 0, 0, 0); + pSrc = tdsqlite3SrcListAppend(pParse, 0, 0, 0); if( pSrc ){ assert( pSrc->nSrc>0 ); - pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget); - iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema); + pSrc->a[pSrc->nSrc-1].zName = tdsqlite3DbStrDup(db, pStep->zTarget); + iDb = tdsqlite3SchemaToIndex(db, pStep->pTrig->pSchema); if( iDb==0 || iDb>=2 ){ const char *zDb; assert( iDb<db->nDb ); zDb = db->aDb[iDb].zDbSName; - pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb); + pSrc->a[pSrc->nSrc-1].zDatabase = tdsqlite3DbStrDup(db, zDb); } } return pSrc; @@ -124062,7 +139263,7 @@ static int codeTriggerProgram( ){ TriggerStep *pStep; Vdbe *v = pParse->pVdbe; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; assert( pParse->pTriggerTab && pParse->pToplevel ); assert( pStepList ); @@ -124084,43 +139285,52 @@ static int codeTriggerProgram( pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf; assert( pParse->okConstFactor==0 ); +#ifndef SQLITE_OMIT_TRACE + if( pStep->zSpan ){ + tdsqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0, + tdsqlite3MPrintf(db, "-- %s", pStep->zSpan), + P4_DYNAMIC); + } +#endif + switch( pStep->op ){ case TK_UPDATE: { - sqlite3Update(pParse, + tdsqlite3Update(pParse, targetSrcList(pParse, pStep), - sqlite3ExprListDup(db, pStep->pExprList, 0), - sqlite3ExprDup(db, pStep->pWhere, 0), - pParse->eOrconf + tdsqlite3ExprListDup(db, pStep->pExprList, 0), + tdsqlite3ExprDup(db, pStep->pWhere, 0), + pParse->eOrconf, 0, 0, 0 ); break; } case TK_INSERT: { - sqlite3Insert(pParse, + tdsqlite3Insert(pParse, targetSrcList(pParse, pStep), - sqlite3SelectDup(db, pStep->pSelect, 0), - sqlite3IdListDup(db, pStep->pIdList), - pParse->eOrconf + tdsqlite3SelectDup(db, pStep->pSelect, 0), + tdsqlite3IdListDup(db, pStep->pIdList), + pParse->eOrconf, + tdsqlite3UpsertDup(db, pStep->pUpsert) ); break; } case TK_DELETE: { - sqlite3DeleteFrom(pParse, + tdsqlite3DeleteFrom(pParse, targetSrcList(pParse, pStep), - sqlite3ExprDup(db, pStep->pWhere, 0) + tdsqlite3ExprDup(db, pStep->pWhere, 0), 0, 0 ); break; } default: assert( pStep->op==TK_SELECT ); { SelectDest sDest; - Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0); - sqlite3SelectDestInit(&sDest, SRT_Discard, 0); - sqlite3Select(pParse, pSelect, &sDest); - sqlite3SelectDelete(db, pSelect); + Select *pSelect = tdsqlite3SelectDup(db, pStep->pSelect, 0); + tdsqlite3SelectDestInit(&sDest, SRT_Discard, 0); + tdsqlite3Select(pParse, pSelect, &sDest); + tdsqlite3SelectDelete(db, pSelect); break; } } if( pStep->op!=TK_SELECT ){ - sqlite3VdbeAddOp0(v, OP_ResetCount); + tdsqlite3VdbeAddOp0(v, OP_ResetCount); } } @@ -124158,7 +139368,7 @@ static void transferParseError(Parse *pTo, Parse *pFrom){ pTo->nErr = pFrom->nErr; pTo->rc = pFrom->rc; }else{ - sqlite3DbFree(pFrom->db, pFrom->zErrMsg); + tdsqlite3DbFree(pFrom->db, pFrom->zErrMsg); } } @@ -124172,8 +139382,8 @@ static TriggerPrg *codeRowTrigger( Table *pTab, /* The table pTrigger is attached to */ int orconf /* ON CONFLICT policy to code trigger program with */ ){ - Parse *pTop = sqlite3ParseToplevel(pParse); - sqlite3 *db = pParse->db; /* Database handle */ + Parse *pTop = tdsqlite3ParseToplevel(pParse); + tdsqlite3 *db = pParse->db; /* Database handle */ TriggerPrg *pPrg; /* Value to return */ Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */ Vdbe *v; /* Temporary VM */ @@ -124188,13 +139398,13 @@ static TriggerPrg *codeRowTrigger( /* Allocate the TriggerPrg and SubProgram objects. To ensure that they ** are freed if an error occurs, link them into the Parse.pTriggerPrg ** list of the top-level Parse object sooner rather than later. */ - pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg)); + pPrg = tdsqlite3DbMallocZero(db, sizeof(TriggerPrg)); if( !pPrg ) return 0; pPrg->pNext = pTop->pTriggerPrg; pTop->pTriggerPrg = pPrg; - pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram)); + pPrg->pProgram = pProgram = tdsqlite3DbMallocZero(db, sizeof(SubProgram)); if( !pProgram ) return 0; - sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram); + tdsqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram); pPrg->pTrigger = pTrigger; pPrg->orconf = orconf; pPrg->aColmask[0] = 0xffffffff; @@ -124202,7 +139412,7 @@ static TriggerPrg *codeRowTrigger( /* Allocate and populate a new Parse context to use for coding the ** trigger sub-program. */ - pSubParse = sqlite3StackAllocZero(db, sizeof(Parse)); + pSubParse = tdsqlite3StackAllocZero(db, sizeof(Parse)); if( !pSubParse ) return 0; memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pSubParse; @@ -124212,8 +139422,9 @@ static TriggerPrg *codeRowTrigger( pSubParse->zAuthContext = pTrigger->zName; pSubParse->eTriggerOp = pTrigger->op; pSubParse->nQueryLoop = pParse->nQueryLoop; + pSubParse->disableVtab = pParse->disableVtab; - v = sqlite3GetVdbe(pSubParse); + v = tdsqlite3GetVdbe(pSubParse); if( v ){ VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", pTrigger->zName, onErrorText(orconf), @@ -124224,23 +139435,25 @@ static TriggerPrg *codeRowTrigger( pTab->zName )); #ifndef SQLITE_OMIT_TRACE - sqlite3VdbeChangeP4(v, -1, - sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC - ); + if( pTrigger->zName ){ + tdsqlite3VdbeChangeP4(v, -1, + tdsqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC + ); + } #endif /* If one was specified, code the WHEN clause. If it evaluates to false ** (or NULL) the sub-vdbe is immediately halted by jumping to the ** OP_Halt inserted at the end of the program. */ if( pTrigger->pWhen ){ - pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0); - if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) + pWhen = tdsqlite3ExprDup(db, pTrigger->pWhen, 0); + if( SQLITE_OK==tdsqlite3ResolveExprNames(&sNC, pWhen) && db->mallocFailed==0 ){ - iEndTrigger = sqlite3VdbeMakeLabel(v); - sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL); + iEndTrigger = tdsqlite3VdbeMakeLabel(pSubParse); + tdsqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL); } - sqlite3ExprDelete(db, pWhen); + tdsqlite3ExprDelete(db, pWhen); } /* Code the trigger program into the sub-vdbe. */ @@ -124248,27 +139461,27 @@ static TriggerPrg *codeRowTrigger( /* Insert an OP_Halt at the end of the sub-program. */ if( iEndTrigger ){ - sqlite3VdbeResolveLabel(v, iEndTrigger); + tdsqlite3VdbeResolveLabel(v, iEndTrigger); } - sqlite3VdbeAddOp0(v, OP_Halt); + tdsqlite3VdbeAddOp0(v, OP_Halt); VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf))); transferParseError(pParse, pSubParse); - if( db->mallocFailed==0 ){ - pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg); + if( db->mallocFailed==0 && pParse->nErr==0 ){ + pProgram->aOp = tdsqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg); } pProgram->nMem = pSubParse->nMem; pProgram->nCsr = pSubParse->nTab; pProgram->token = (void *)pTrigger; pPrg->aColmask[0] = pSubParse->oldmask; pPrg->aColmask[1] = pSubParse->newmask; - sqlite3VdbeDelete(v); + tdsqlite3VdbeDelete(v); } assert( !pSubParse->pAinc && !pSubParse->pZombieTab ); assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg ); - sqlite3ParserReset(pSubParse); - sqlite3StackFree(db, pSubParse); + tdsqlite3ParserReset(pSubParse); + tdsqlite3StackFree(db, pSubParse); return pPrg; } @@ -124285,7 +139498,7 @@ static TriggerPrg *getRowTrigger( Table *pTab, /* The table trigger pTrigger is attached to */ int orconf /* ON CONFLICT algorithm. */ ){ - Parse *pRoot = sqlite3ParseToplevel(pParse); + Parse *pRoot = tdsqlite3ParseToplevel(pParse); TriggerPrg *pPrg; assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); @@ -124311,9 +139524,9 @@ static TriggerPrg *getRowTrigger( ** Generate code for the trigger program associated with trigger p on ** table pTab. The reg, orconf and ignoreJump parameters passed to this ** function are the same as those described in the header function for -** sqlite3CodeRowTrigger() +** tdsqlite3CodeRowTrigger() */ -SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( +SQLITE_PRIVATE void tdsqlite3CodeRowTriggerDirect( Parse *pParse, /* Parse context */ Trigger *p, /* Trigger to code */ Table *pTab, /* The table to code triggers from */ @@ -124321,7 +139534,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( int orconf, /* ON CONFLICT policy */ int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ ){ - Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */ + Vdbe *v = tdsqlite3GetVdbe(pParse); /* Main VM */ TriggerPrg *pPrg; pPrg = getRowTrigger(pParse, p, pTab, orconf); assert( pPrg || pParse->nErr || pParse->db->mallocFailed ); @@ -124331,7 +139544,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( if( pPrg ){ int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers)); - sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem, + tdsqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem, (const char *)pPrg->pProgram, P4_SUBPROGRAM); VdbeComment( (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf))); @@ -124341,7 +139554,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( ** invocation is disallowed if (a) the sub-program is really a trigger, ** not a foreign key action, and (b) the flag to enable recursive triggers ** is clear. */ - sqlite3VdbeChangeP5(v, (u8)bRecursive); + tdsqlite3VdbeChangeP5(v, (u8)bRecursive); } } @@ -124385,7 +139598,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( ** is the instruction that control should jump to if a trigger program ** raises an IGNORE exception. */ -SQLITE_PRIVATE void sqlite3CodeRowTrigger( +SQLITE_PRIVATE void tdsqlite3CodeRowTrigger( Parse *pParse, /* Parse context */ Trigger *pTrigger, /* List of triggers on table pTab */ int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */ @@ -124417,7 +139630,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTrigger( && p->tr_tm==tr_tm && checkColumnOverlap(p->pColumns, pChanges) ){ - sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump); + tdsqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump); } } } @@ -124447,7 +139660,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTrigger( ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm. */ -SQLITE_PRIVATE u32 sqlite3TriggerColmask( +SQLITE_PRIVATE u32 tdsqlite3TriggerColmask( Parse *pParse, /* Parse context */ Trigger *pTrigger, /* List of triggers on table pTab */ ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ @@ -124531,34 +139744,85 @@ static void updateVirtualTable( ** into the sqlite_master table.) ** ** Therefore, the P4 parameter is only required if the default value for -** the column is a literal number, string or null. The sqlite3ValueFromExpr() +** the column is a literal number, string or null. The tdsqlite3ValueFromExpr() ** function is capable of transforming these types of expressions into -** sqlite3_value objects. +** tdsqlite3_value objects. ** ** If parameter iReg is not negative, code an OP_RealAffinity instruction ** on register iReg. This is used when an equivalent integer value is ** stored in place of an 8-byte floating point value in order to save ** space. */ -SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ +SQLITE_PRIVATE void tdsqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ assert( pTab!=0 ); if( !pTab->pSelect ){ - sqlite3_value *pValue = 0; - u8 enc = ENC(sqlite3VdbeDb(v)); + tdsqlite3_value *pValue = 0; + u8 enc = ENC(tdsqlite3VdbeDb(v)); Column *pCol = &pTab->aCol[i]; VdbeComment((v, "%s.%s", pTab->zName, pCol->zName)); assert( i<pTab->nCol ); - sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, + tdsqlite3ValueFromExpr(tdsqlite3VdbeDb(v), pCol->pDflt, enc, pCol->affinity, &pValue); if( pValue ){ - sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM); + tdsqlite3VdbeAppendP4(v, pValue, P4_MEM); } + } #ifndef SQLITE_OMIT_FLOATING_POINT - if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); - } + if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){ + tdsqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); + } #endif +} + +/* +** Check to see if column iCol of index pIdx references any of the +** columns defined by aXRef and chngRowid. Return true if it does +** and false if not. This is an optimization. False-positives are a +** performance degradation, but false-negatives can result in a corrupt +** index and incorrect answers. +** +** aXRef[j] will be non-negative if column j of the original table is +** being updated. chngRowid will be true if the rowid of the table is +** being updated. +*/ +static int indexColumnIsBeingUpdated( + Index *pIdx, /* The index to check */ + int iCol, /* Which column of the index to check */ + int *aXRef, /* aXRef[j]>=0 if column j is being updated */ + int chngRowid /* true if the rowid is being updated */ +){ + i16 iIdxCol = pIdx->aiColumn[iCol]; + assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */ + if( iIdxCol>=0 ){ + return aXRef[iIdxCol]>=0; } + assert( iIdxCol==XN_EXPR ); + assert( pIdx->aColExpr!=0 ); + assert( pIdx->aColExpr->a[iCol].pExpr!=0 ); + return tdsqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr, + aXRef,chngRowid); +} + +/* +** Check to see if index pIdx is a partial index whose conditional +** expression might change values due to an UPDATE. Return true if +** the index is subject to change and false if the index is guaranteed +** to be unchanged. This is an optimization. False-positives are a +** performance degradation, but false-negatives can result in a corrupt +** index and incorrect answers. +** +** aXRef[j] will be non-negative if column j of the original table is +** being updated. chngRowid will be true if the rowid of the table is +** being updated. +*/ +static int indexWhereClauseMightChange( + Index *pIdx, /* The index to check */ + int *aXRef, /* aXRef[j]>=0 if column j is being updated */ + int chngRowid /* true if the rowid is being updated */ +){ + if( pIdx->pPartIdxWhere==0 ) return 0; + return tdsqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere, + aXRef, chngRowid); } /* @@ -124568,14 +139832,17 @@ SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ ** \_______/ \________/ \______/ \________________/ * onError pTabList pChanges pWhere */ -SQLITE_PRIVATE void sqlite3Update( +SQLITE_PRIVATE void tdsqlite3Update( Parse *pParse, /* The parser context */ SrcList *pTabList, /* The table in which we should change things */ ExprList *pChanges, /* Things to be changed */ Expr *pWhere, /* The WHERE clause. May be null */ - int onError /* How to handle constraint errors */ + int onError, /* How to handle constraint errors */ + ExprList *pOrderBy, /* ORDER BY clause. May be null */ + Expr *pLimit, /* LIMIT clause. May be null */ + Upsert *pUpsert /* ON CONFLICT clause, or null */ ){ - int i, j; /* Loop counters */ + int i, j, k; /* Loop counters */ Table *pTab; /* The table to be updated */ int addrTop = 0; /* VDBE instruction address of the start of the loop */ WhereInfo *pWInfo; /* Information about the WHERE clause */ @@ -124583,11 +139850,12 @@ SQLITE_PRIVATE void sqlite3Update( Index *pIdx; /* For looping over indices */ Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */ int nIdx; /* Number of indices that need updating */ + int nAllIdx; /* Total number of indexes */ int iBaseCur; /* Base cursor number */ int iDataCur; /* Cursor for the canonical data btree */ int iIdxCur; /* Cursor for the first index */ - sqlite3 *db; /* The database structure */ - int *aRegIdx = 0; /* One register assigned to each index to be updated */ + tdsqlite3 *db; /* The database structure */ + int *aRegIdx = 0; /* Registers for to each index and the main table */ int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the ** an expression for the i-th column of the table. ** aXRef[i]==-1 if the i-th column is not changed. */ @@ -124599,10 +139867,11 @@ SQLITE_PRIVATE void sqlite3Update( AuthContext sContext; /* The authorization context */ NameContext sNC; /* The name-context to resolve expressions in */ int iDb; /* Database containing the table being updated */ - int okOnePass; /* True for one-pass algorithm without the FIFO */ + int eOnePass; /* ONEPASS_XXX value from where.c */ int hasFK; /* True if foreign key processing is required */ int labelBreak; /* Jump here to break out of UPDATE loop */ int labelContinue; /* Jump here to continue next step of UPDATE loop */ + int flags; /* Flags for tdsqlite3WhereBegin() */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* True when updating a view (INSTEAD OF trigger) */ @@ -124613,6 +139882,11 @@ SQLITE_PRIVATE void sqlite3Update( int iEph = 0; /* Ephemeral table holding all primary key values */ int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */ int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ + int addrOpen = 0; /* Address of OP_OpenEphemeral */ + int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */ + i16 nPk = 0; /* Number of components of the PRIMARY KEY */ + int bReplace = 0; /* True if REPLACE conflict resolution might happen */ + int bFinishSeek = 1; /* The OP_FinishSeek opcode is needed */ /* Register Allocations */ int regRowCount = 0; /* A count of rows changed */ @@ -124632,15 +139906,15 @@ SQLITE_PRIVATE void sqlite3Update( /* Locate the table which we want to update. */ - pTab = sqlite3SrcListLookup(pParse, pTabList); + pTab = tdsqlite3SrcListLookup(pParse, pTabList); if( pTab==0 ) goto update_cleanup; - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(pParse->db, pTab->pSchema); /* Figure out if we have any triggers and if the table being ** updated is a view. */ #ifndef SQLITE_OMIT_TRIGGER - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask); + pTrigger = tdsqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask); isView = pTab->pSelect!=0; assert( pTrigger || tmask==0 ); #else @@ -124653,10 +139927,20 @@ SQLITE_PRIVATE void sqlite3Update( # define isView 0 #endif - if( sqlite3ViewGetColumnNames(pParse, pTab) ){ +#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT + if( !isView ){ + pWhere = tdsqlite3LimitWhere( + pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE" + ); + pOrderBy = 0; + pLimit = 0; + } +#endif + + if( tdsqlite3ViewGetColumnNames(pParse, pTab) ){ goto update_cleanup; } - if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ + if( tdsqlite3IsReadOnly(pParse, pTab, tmask) ){ goto update_cleanup; } @@ -124665,24 +139949,31 @@ SQLITE_PRIVATE void sqlite3Update( ** need to occur right after the database cursor. So go ahead and ** allocate enough space, just in case. */ - pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++; + iBaseCur = iDataCur = pParse->nTab++; iIdxCur = iDataCur+1; - pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); + pPk = HasRowid(pTab) ? 0 : tdsqlite3PrimaryKeyIndex(pTab); + testcase( pPk!=0 && pPk!=pTab->pIndex ); for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ - if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){ + if( pPk==pIdx ){ iDataCur = pParse->nTab; - pTabList->a[0].iCursor = iDataCur; } pParse->nTab++; } + if( pUpsert ){ + /* On an UPSERT, reuse the same cursors already opened by INSERT */ + iDataCur = pUpsert->iDataCur; + iIdxCur = pUpsert->iIdxCur; + pParse->nTab = iBaseCur; + } + pTabList->a[0].iCursor = iDataCur; /* Allocate space for aXRef[], aRegIdx[], and aToOpen[]. ** Initialize aXRef[] and aToOpen[] to their default values. */ - aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 ); + aXRef = tdsqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 ); if( aXRef==0 ) goto update_cleanup; aRegIdx = aXRef+pTab->nCol; - aToOpen = (u8*)(aRegIdx+nIdx); + aToOpen = (u8*)(aRegIdx+nIdx+1); memset(aToOpen, 1, nIdx+1); aToOpen[nIdx+1] = 0; for(i=0; i<pTab->nCol; i++) aXRef[i] = -1; @@ -124691,6 +139982,12 @@ SQLITE_PRIVATE void sqlite3Update( memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; + sNC.uNC.pUpsert = pUpsert; + sNC.ncFlags = NC_UUpsert; + + /* Begin generating code. */ + v = tdsqlite3GetVdbe(pParse); + if( v==0 ) goto update_cleanup; /* Resolve the column names in all the expressions of the ** of the UPDATE statement. Also find the column index @@ -124700,28 +139997,38 @@ SQLITE_PRIVATE void sqlite3Update( */ chngRowid = chngPk = 0; for(i=0; i<pChanges->nExpr; i++){ - if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ + if( tdsqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ goto update_cleanup; } for(j=0; j<pTab->nCol; j++){ - if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){ + if( tdsqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zEName)==0 ){ if( j==pTab->iPKey ){ chngRowid = 1; pRowidExpr = pChanges->a[i].pExpr; }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){ chngPk = 1; } +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){ + testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ); + testcase( pTab->aCol[j].colFlags & COLFLAG_STORED ); + tdsqlite3ErrorMsg(pParse, + "cannot UPDATE generated column \"%s\"", + pTab->aCol[j].zName); + goto update_cleanup; + } +#endif aXRef[j] = i; break; } } if( j>=pTab->nCol ){ - if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){ + if( pPk==0 && tdsqlite3IsRowid(pChanges->a[i].zEName) ){ j = -1; chngRowid = 1; pRowidExpr = pChanges->a[i].pExpr; }else{ - sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName); + tdsqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName); pParse->checkSchema = 1; goto update_cleanup; } @@ -124729,7 +140036,7 @@ SQLITE_PRIVATE void sqlite3Update( #ifndef SQLITE_OMIT_AUTHORIZATION { int rc; - rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName, + rc = tdsqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName, j<0 ? "ROWID" : pTab->aCol[j].zName, db->aDb[iDb].zDbSName); if( rc==SQLITE_DENY ){ @@ -124745,6 +140052,33 @@ SQLITE_PRIVATE void sqlite3Update( assert( chngPk==0 || chngPk==1 ); chngKey = chngRowid + chngPk; +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + /* Mark generated columns as changing if their generator expressions + ** reference any changing column. The actual aXRef[] value for + ** generated expressions is not used, other than to check to see that it + ** is non-negative, so the value of aXRef[] for generated columns can be + ** set to any non-negative number. We use 99999 so that the value is + ** obvious when looking at aXRef[] in a symbolic debugger. + */ + if( pTab->tabFlags & TF_HasGenerated ){ + int bProgress; + testcase( pTab->tabFlags & TF_HasVirtual ); + testcase( pTab->tabFlags & TF_HasStored ); + do{ + bProgress = 0; + for(i=0; i<pTab->nCol; i++){ + if( aXRef[i]>=0 ) continue; + if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue; + if( tdsqlite3ExprReferencesUpdatedColumn(pTab->aCol[i].pDflt, + aXRef, chngRowid) ){ + aXRef[i] = 99999; + bProgress = 1; + } + } + }while( bProgress ); + } +#endif + /* The SET expressions are not actually used inside the WHERE loop. ** So reset the colUsed mask. Unless this is a virtual table. In that ** case, set all bits of the colUsed mask (to ensure that the virtual @@ -124752,41 +140086,55 @@ SQLITE_PRIVATE void sqlite3Update( */ pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0; - hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey); + hasFK = tdsqlite3FkRequired(pParse, pTab, aXRef, chngKey); /* There is one entry in the aRegIdx[] array for each index on the table ** being updated. Fill in aRegIdx[] with a register number that will hold ** the key for accessing each index. - ** - ** FIXME: Be smarter about omitting indexes that use expressions. */ - for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + if( onError==OE_Replace ) bReplace = 1; + for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){ int reg; - if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){ + if( chngKey || hasFK>1 || pIdx==pPk + || indexWhereClauseMightChange(pIdx,aXRef,chngRowid) + ){ reg = ++pParse->nMem; + pParse->nMem += pIdx->nColumn; }else{ reg = 0; for(i=0; i<pIdx->nKeyCol; i++){ - i16 iIdxCol = pIdx->aiColumn[i]; - if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){ + if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){ reg = ++pParse->nMem; + pParse->nMem += pIdx->nColumn; + if( onError==OE_Default && pIdx->onError==OE_Replace ){ + bReplace = 1; + } break; } } } - if( reg==0 ) aToOpen[j+1] = 0; - aRegIdx[j] = reg; + if( reg==0 ) aToOpen[nAllIdx+1] = 0; + aRegIdx[nAllIdx] = reg; + } + aRegIdx[nAllIdx] = ++pParse->nMem; /* Register storing the table record */ + if( bReplace ){ + /* If REPLACE conflict resolution might be invoked, open cursors on all + ** indexes in case they are needed to delete records. */ + memset(aToOpen, 1, nIdx+1); } - /* Begin generating code. */ - v = sqlite3GetVdbe(pParse); - if( v==0 ) goto update_cleanup; - if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); - sqlite3BeginWriteOperation(pParse, 1, iDb); + if( pParse->nested==0 ) tdsqlite3VdbeCountChanges(v); + tdsqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb); /* Allocate required registers. */ if( !IsVirtual(pTab) ){ - regRowSet = ++pParse->nMem; + /* For now, regRowSet and aRegIdx[nAllIdx] share the same register. + ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be + ** reallocated. aRegIdx[nAllIdx] is the register in which the main + ** table record is written. regRowSet holds the RowSet for the + ** two-pass update algorithm. */ + assert( aRegIdx[nAllIdx]==pParse->nMem ); + regRowSet = aRegIdx[nAllIdx]; regOldRowid = regNewRowid = ++pParse->nMem; if( chngPk || pTrigger || hasFK ){ regOld = pParse->nMem + 1; @@ -124801,7 +140149,7 @@ SQLITE_PRIVATE void sqlite3Update( /* Start the view context. */ if( isView ){ - sqlite3AuthContextPush(pParse, &sContext, pTab->zName); + tdsqlite3AuthContextPush(pParse, &sContext, pTab->zName); } /* If we are trying to update a view, realize that view into @@ -124809,14 +140157,18 @@ SQLITE_PRIVATE void sqlite3Update( */ #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) if( isView ){ - sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur); + tdsqlite3MaterializeView(pParse, pTab, + pWhere, pOrderBy, pLimit, iDataCur + ); + pOrderBy = 0; + pLimit = 0; } #endif /* Resolve the column names in all the expressions in the ** WHERE clause. */ - if( sqlite3ResolveExprNames(&sNC, pWhere) ){ + if( tdsqlite3ResolveExprNames(&sNC, pWhere) ){ goto update_cleanup; } @@ -124829,150 +140181,199 @@ SQLITE_PRIVATE void sqlite3Update( } #endif - /* Begin the database scan - */ + /* Jump to labelBreak to abandon further processing of this UPDATE */ + labelContinue = labelBreak = tdsqlite3VdbeMakeLabel(pParse); + + /* Not an UPSERT. Normal processing. Begin by + ** initialize the count of updated rows */ + if( (db->flags&SQLITE_CountRows)!=0 + && !pParse->pTriggerTab + && !pParse->nested + && pUpsert==0 + ){ + regRowCount = ++pParse->nMem; + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); + } + if( HasRowid(pTab) ){ - sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); - pWInfo = sqlite3WhereBegin( - pParse, pTabList, pWhere, 0, 0, - WHERE_ONEPASS_DESIRED | WHERE_SEEK_TABLE, iIdxCur - ); - if( pWInfo==0 ) goto update_cleanup; - okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); - - /* Remember the rowid of every item to be updated. - */ - sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid); - if( !okOnePass ){ - sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); - } - - /* End the database scan loop. - */ - sqlite3WhereEnd(pWInfo); + tdsqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); }else{ - int iPk; /* First of nPk memory cells holding PRIMARY KEY value */ - i16 nPk; /* Number of components of the PRIMARY KEY */ - int addrOpen; /* Address of the OpenEphemeral instruction */ - assert( pPk!=0 ); nPk = pPk->nKeyCol; iPk = pParse->nMem+1; pParse->nMem += nPk; regKey = ++pParse->nMem; - iEph = pParse->nTab++; - sqlite3VdbeAddOp2(v, OP_Null, 0, iPk); - addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk); - sqlite3VdbeSetP4KeyInfo(pParse, pPk); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, - WHERE_ONEPASS_DESIRED, iIdxCur); + if( pUpsert==0 ){ + iEph = pParse->nTab++; + tdsqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1); + addrOpen = tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk); + tdsqlite3VdbeSetP4KeyInfo(pParse, pPk); + } + } + + if( pUpsert ){ + /* If this is an UPSERT, then all cursors have already been opened by + ** the outer INSERT and the data cursor should be pointing at the row + ** that is to be updated. So bypass the code that searches for the + ** row(s) to be updated. + */ + pWInfo = 0; + eOnePass = ONEPASS_SINGLE; + tdsqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL); + bFinishSeek = 0; + }else{ + /* Begin the database scan. + ** + ** Do not consider a single-pass strategy for a multi-row update if + ** there are any triggers or foreign keys to process, or rows may + ** be deleted as a result of REPLACE conflict handling. Any of these + ** things might disturb a cursor being used to scan through the table + ** or index, causing a single-pass approach to malfunction. */ + flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE; + if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){ + flags |= WHERE_ONEPASS_MULTIROW; + } + pWInfo = tdsqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur); if( pWInfo==0 ) goto update_cleanup; - okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); + + /* A one-pass strategy that might update more than one row may not + ** be used if any column of the index used for the scan is being + ** updated. Otherwise, if there is an index on "b", statements like + ** the following could create an infinite loop: + ** + ** UPDATE t1 SET b=b+1 WHERE b>? + ** + ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI + ** strategy that uses an index for which one or more columns are being + ** updated. */ + eOnePass = tdsqlite3WhereOkOnePass(pWInfo, aiCurOnePass); + bFinishSeek = tdsqlite3WhereUsesDeferredSeek(pWInfo); + if( eOnePass!=ONEPASS_SINGLE ){ + tdsqlite3MultiWrite(pParse); + if( eOnePass==ONEPASS_MULTI ){ + int iCur = aiCurOnePass[1]; + if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){ + eOnePass = ONEPASS_OFF; + } + assert( iCur!=iDataCur || !HasRowid(pTab) ); + } + } + } + + if( HasRowid(pTab) ){ + /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF + ** mode, write the rowid into the FIFO. In either of the one-pass modes, + ** leave it in register regOldRowid. */ + tdsqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid); + if( eOnePass==ONEPASS_OFF ){ + /* We need to use regRowSet, so reallocate aRegIdx[nAllIdx] */ + aRegIdx[nAllIdx] = ++pParse->nMem; + tdsqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); + } + }else{ + /* Read the PK of the current row into an array of registers. In + ** ONEPASS_OFF mode, serialize the array into a record and store it in + ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change + ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table + ** is not required) and leave the PK fields in the array of registers. */ for(i=0; i<nPk; i++){ assert( pPk->aiColumn[i]>=0 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i], - iPk+i); + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, + pPk->aiColumn[i], iPk+i); } - if( okOnePass ){ - sqlite3VdbeChangeToNoop(v, addrOpen); + if( eOnePass ){ + if( addrOpen ) tdsqlite3VdbeChangeToNoop(v, addrOpen); nKey = nPk; regKey = iPk; }else{ - sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey, - sqlite3IndexAffinityStr(db, pPk), nPk); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey); + tdsqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey, + tdsqlite3IndexAffinityStr(db, pPk), nPk); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk); } - sqlite3WhereEnd(pWInfo); - } - - /* Initialize the count of updated rows - */ - if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){ - regRowCount = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); } - labelBreak = sqlite3VdbeMakeLabel(v); - if( !isView ){ - /* - ** Open every index that needs updating. Note that if any - ** index could potentially invoke a REPLACE conflict resolution - ** action, then we need to open all indices because we might need - ** to be deleting some records. - */ - if( onError==OE_Replace ){ - memset(aToOpen, 1, nIdx+1); - }else{ - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - if( pIdx->onError==OE_Replace ){ - memset(aToOpen, 1, nIdx+1); - break; - } - } + if( pUpsert==0 ){ + if( eOnePass!=ONEPASS_MULTI ){ + tdsqlite3WhereEnd(pWInfo); } - if( okOnePass ){ - if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0; - if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0; + + if( !isView ){ + int addrOnce = 0; + + /* Open every index that needs updating. */ + if( eOnePass!=ONEPASS_OFF ){ + if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0; + if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0; + } + + if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){ + addrOnce = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); + } + tdsqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, + aToOpen, 0, 0); + if( addrOnce ) tdsqlite3VdbeJumpHere(v, addrOnce); } - sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen, - 0, 0); - } - - /* Top of the update loop */ - if( okOnePass ){ - if( aToOpen[iDataCur-iBaseCur] && !isView ){ - assert( pPk ); - sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey); - VdbeCoverageNeverTaken(v); + + /* Top of the update loop */ + if( eOnePass!=ONEPASS_OFF ){ + if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){ + assert( pPk ); + tdsqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey); + VdbeCoverage(v); + } + if( eOnePass!=ONEPASS_SINGLE ){ + labelContinue = tdsqlite3VdbeMakeLabel(pParse); + } + tdsqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak); + VdbeCoverageIf(v, pPk==0); + VdbeCoverageIf(v, pPk!=0); + }else if( pPk ){ + labelContinue = tdsqlite3VdbeMakeLabel(pParse); + tdsqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v); + addrTop = tdsqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey); + tdsqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0); + VdbeCoverage(v); + }else{ + labelContinue = tdsqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak, + regOldRowid); + VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); + VdbeCoverage(v); } - labelContinue = labelBreak; - sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak); - VdbeCoverageIf(v, pPk==0); - VdbeCoverageIf(v, pPk!=0); - }else if( pPk ){ - labelContinue = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v); - addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey); - sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0); - VdbeCoverage(v); - }else{ - labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak, - regOldRowid); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); - VdbeCoverage(v); } - /* If the record number will change, set register regNewRowid to - ** contain the new value. If the record number is not being modified, + /* If the rowid value will change, set register regNewRowid to + ** contain the new value. If the rowid is not being modified, ** then regNewRowid is the same register as regOldRowid, which is ** already populated. */ assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid ); if( chngRowid ){ - sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); - sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v); + tdsqlite3ExprCode(pParse, pRowidExpr, regNewRowid); + tdsqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v); } /* Compute the old pre-UPDATE content of the row being changed, if that ** information is needed */ if( chngPk || hasFK || pTrigger ){ - u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0); - oldmask |= sqlite3TriggerColmask(pParse, + u32 oldmask = (hasFK ? tdsqlite3FkOldmask(pParse, pTab) : 0); + oldmask |= tdsqlite3TriggerColmask(pParse, pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError ); for(i=0; i<pTab->nCol; i++){ + u32 colFlags = pTab->aCol[i].colFlags; + k = tdsqlite3TableColumnToStorage(pTab, i) + regOld; if( oldmask==0xffffffff || (i<32 && (oldmask & MASKBIT32(i))!=0) - || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 + || (colFlags & COLFLAG_PRIMKEY)!=0 ){ testcase( oldmask!=0xffffffff && i==31 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i); + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k); }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, k); } } if( chngRowid==0 && pPk==0 ){ - sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid); + tdsqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid); } } @@ -124989,16 +140390,18 @@ SQLITE_PRIVATE void sqlite3Update( ** may have modified them). So not loading those that are not going to ** be used eliminates some redundant opcodes. */ - newmask = sqlite3TriggerColmask( + newmask = tdsqlite3TriggerColmask( pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError ); - for(i=0; i<pTab->nCol; i++){ + for(i=0, k=regNew; i<pTab->nCol; i++, k++){ if( i==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, k); + }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){ + if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--; }else{ j = aXRef[i]; if( j>=0 ){ - sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i); + tdsqlite3ExprCode(pParse, pChanges->a[j].pExpr, k); }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){ /* This branch loads the value of a column that will not be changed ** into a register. This is done if there are no BEFORE triggers, or @@ -125007,19 +140410,27 @@ SQLITE_PRIVATE void sqlite3Update( */ testcase( i==31 ); testcase( i==32 ); - sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i); + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k); + bFinishSeek = 0; }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, k); } } } +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + if( pTab->tabFlags & TF_HasGenerated ){ + testcase( pTab->tabFlags & TF_HasVirtual ); + testcase( pTab->tabFlags & TF_HasStored ); + tdsqlite3ComputeGeneratedColumns(pParse, regNew, pTab); + } +#endif /* Fire any BEFORE UPDATE triggers. This happens before constraints are ** verified. One could argue that this is wrong. */ if( tmask&TRIGGER_BEFORE ){ - sqlite3TableAffinity(v, pTab, regNew); - sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, + tdsqlite3TableAffinity(v, pTab, regNew); + tdsqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue); /* The row-trigger may have deleted the row being updated. In this @@ -125029,50 +140440,73 @@ SQLITE_PRIVATE void sqlite3Update( ** documentation. */ if( pPk ){ - sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey); + tdsqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey); VdbeCoverage(v); }else{ - sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); + tdsqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); VdbeCoverage(v); } - /* If it did not delete it, the row-trigger may still have modified + /* After-BEFORE-trigger-reload-loop: + ** If it did not delete it, the BEFORE trigger may still have modified ** some of the columns of the row being updated. Load the values for - ** all columns not modified by the update statement into their - ** registers in case this has happened. + ** all columns not modified by the update statement into their registers + ** in case this has happened. Only unmodified columns are reloaded. + ** The values computed for modified columns use the values before the + ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26) + ** for an example. */ - for(i=0; i<pTab->nCol; i++){ - if( aXRef[i]<0 && i!=pTab->iPKey ){ - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i); + for(i=0, k=regNew; i<pTab->nCol; i++, k++){ + if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ + if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--; + }else if( aXRef[i]<0 && i!=pTab->iPKey ){ + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k); } } +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + if( pTab->tabFlags & TF_HasGenerated ){ + testcase( pTab->tabFlags & TF_HasVirtual ); + testcase( pTab->tabFlags & TF_HasStored ); + tdsqlite3ComputeGeneratedColumns(pParse, regNew, pTab); + } +#endif } if( !isView ){ - int addr1 = 0; /* Address of jump instruction */ - int bReplace = 0; /* True if REPLACE conflict resolution might happen */ - /* Do constraint checks. */ assert( regOldRowid>0 ); - sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, + tdsqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace, - aXRef); - - /* Do FK constraint checks. */ - if( hasFK ){ - sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey); - } + aXRef, 0); - /* Delete the index entries associated with the current record. */ + /* If REPLACE conflict handling may have been used, or if the PK of the + ** row is changing, then the GenerateConstraintChecks() above may have + ** moved cursor iDataCur. Reseek it. */ if( bReplace || chngKey ){ if( pPk ){ - addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey); + tdsqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey); }else{ - addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid); + tdsqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid); } VdbeCoverageNeverTaken(v); } - sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1); + + /* Do FK constraint checks. */ + if( hasFK ){ + tdsqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey); + } + + /* Delete the index entries associated with the current record. */ + tdsqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1); + + /* We must run the OP_FinishSeek opcode to resolve a prior + ** OP_DeferredSeek if there is any possibility that there have been + ** no OP_Column opcodes since the OP_DeferredSeek was issued. But + ** we want to avoid the OP_FinishSeek if possible, as running it + ** costs CPU cycles. */ + if( bFinishSeek ){ + tdsqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur); + } /* If changing the rowid value, or if there are foreign key constraints ** to process, delete the old record. Otherwise, add a noop OP_Delete @@ -125085,94 +140519,95 @@ SQLITE_PRIVATE void sqlite3Update( */ assert( regNew==regNewRowid+1 ); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3VdbeAddOp3(v, OP_Delete, iDataCur, - OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP), + tdsqlite3VdbeAddOp3(v, OP_Delete, iDataCur, + OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP), regNewRowid ); + if( eOnePass==ONEPASS_MULTI ){ + assert( hasFK==0 && chngKey==0 ); + tdsqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); + } if( !pParse->nested ){ - sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE); + tdsqlite3VdbeAppendP4(v, pTab, P4_TABLE); } #else - if( hasFK || chngKey || pPk!=0 ){ - sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0); + if( hasFK>1 || chngKey ){ + tdsqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0); } #endif - if( bReplace || chngKey ){ - sqlite3VdbeJumpHere(v, addr1); - } if( hasFK ){ - sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey); + tdsqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey); } /* Insert the new index entries and the new record. */ - sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, - regNewRowid, aRegIdx, 1, 0, 0); + tdsqlite3CompleteInsertion( + pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx, + OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0), + 0, 0 + ); /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just updated. */ if( hasFK ){ - sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey); + tdsqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey); } } /* Increment the row counter */ - if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){ - sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); + if( regRowCount ){ + tdsqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); } - sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, + tdsqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue); /* Repeat the above with the next record to be updated, until ** all record selected by the WHERE clause have been updated. */ - if( okOnePass ){ + if( eOnePass==ONEPASS_SINGLE ){ /* Nothing to do at end-of-loop for a single-pass */ + }else if( eOnePass==ONEPASS_MULTI ){ + tdsqlite3VdbeResolveLabel(v, labelContinue); + tdsqlite3WhereEnd(pWInfo); }else if( pPk ){ - sqlite3VdbeResolveLabel(v, labelContinue); - sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v); + tdsqlite3VdbeResolveLabel(v, labelContinue); + tdsqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v); }else{ - sqlite3VdbeGoto(v, labelContinue); - } - sqlite3VdbeResolveLabel(v, labelBreak); - - /* Close all tables */ - for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ - assert( aRegIdx ); - if( aToOpen[i+1] ){ - sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0); - } + tdsqlite3VdbeGoto(v, labelContinue); } - if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0); + tdsqlite3VdbeResolveLabel(v, labelBreak); /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ - if( pParse->nested==0 && pParse->pTriggerTab==0 ){ - sqlite3AutoincrementEnd(pParse); + if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){ + tdsqlite3AutoincrementEnd(pParse); } /* - ** Return the number of rows that were changed. If this routine is - ** generating code because of a call to sqlite3NestedParse(), do not - ** invoke the callback function. + ** Return the number of rows that were changed, if we are tracking + ** that information. */ - if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC); + if( regRowCount ){ + tdsqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); + tdsqlite3VdbeSetNumCols(v, 1); + tdsqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC); } update_cleanup: - sqlite3AuthContextPop(&sContext); - sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */ - sqlite3SrcListDelete(db, pTabList); - sqlite3ExprListDelete(db, pChanges); - sqlite3ExprDelete(db, pWhere); + tdsqlite3AuthContextPop(&sContext); + tdsqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */ + tdsqlite3SrcListDelete(db, pTabList); + tdsqlite3ExprListDelete(db, pChanges); + tdsqlite3ExprDelete(db, pWhere); +#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) + tdsqlite3ExprListDelete(db, pOrderBy); + tdsqlite3ExprDelete(db, pLimit); +#endif return; } /* Make sure "isView" and other macros defined above are undefined. Otherwise @@ -125220,98 +140655,379 @@ static void updateVirtualTable( Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */ int ephemTab; /* Table holding the result of the SELECT */ int i; /* Loop counter */ - sqlite3 *db = pParse->db; /* Database connection */ - const char *pVTab = (const char*)sqlite3GetVTable(db, pTab); + tdsqlite3 *db = pParse->db; /* Database connection */ + const char *pVTab = (const char*)tdsqlite3GetVTable(db, pTab); WhereInfo *pWInfo; int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */ int regArg; /* First register in VUpdate arg array */ int regRec; /* Register in which to assemble record */ int regRowid; /* Register for ephem table rowid */ int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */ - int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */ - int bOnePass; /* True to use onepass strategy */ + int aDummy[2]; /* Unused arg for tdsqlite3WhereOkOnePass() */ + int eOnePass; /* True to use onepass strategy */ int addr; /* Address of OP_OpenEphemeral */ - /* Allocate nArg registers to martial the arguments to VUpdate. Then + /* Allocate nArg registers in which to gather the arguments for VUpdate. Then ** create and open the ephemeral table in which the records created from ** these arguments will be temporarily stored. */ assert( v ); ephemTab = pParse->nTab++; - addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg); + addr= tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg); regArg = pParse->nMem + 1; pParse->nMem += nArg; regRec = ++pParse->nMem; regRowid = ++pParse->nMem; /* Start scanning the virtual table */ - pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0); + pWInfo = tdsqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0); if( pWInfo==0 ) return; /* Populate the argument registers. */ - sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg); - if( pRowid ){ - sqlite3ExprCode(pParse, pRowid, regArg+1); - }else{ - sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1); - } for(i=0; i<pTab->nCol; i++){ + assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ); if( aXRef[i]>=0 ){ - sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i); + tdsqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i); }else{ - sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i); + tdsqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i); + tdsqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* Enable tdsqlite3_vtab_nochange() */ } } + if( HasRowid(pTab) ){ + tdsqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg); + if( pRowid ){ + tdsqlite3ExprCode(pParse, pRowid, regArg+1); + }else{ + tdsqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1); + } + }else{ + Index *pPk; /* PRIMARY KEY index */ + i16 iPk; /* PRIMARY KEY column */ + pPk = tdsqlite3PrimaryKeyIndex(pTab); + assert( pPk!=0 ); + assert( pPk->nKeyCol==1 ); + iPk = pPk->aiColumn[0]; + tdsqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg); + tdsqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1); + } - bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy); + eOnePass = tdsqlite3WhereOkOnePass(pWInfo, aDummy); - if( bOnePass ){ + /* There is no ONEPASS_MULTI on virtual tables */ + assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); + + if( eOnePass ){ /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded - ** above. Also, if this is a top-level parse (not a trigger), clear the - ** multi-write flag so that the VM does not open a statement journal */ - sqlite3VdbeChangeToNoop(v, addr); - if( sqlite3IsToplevel(pParse) ){ - pParse->isMultiWrite = 0; - } + ** above. */ + tdsqlite3VdbeChangeToNoop(v, addr); + tdsqlite3VdbeAddOp1(v, OP_Close, iCsr); }else{ /* Create a record from the argument register contents and insert it into ** the ephemeral table. */ - sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec); - sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid); + tdsqlite3MultiWrite(pParse); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec); +#ifdef SQLITE_DEBUG + /* Signal an assert() within OP_MakeRecord that it is allowed to + ** accept no-change records with serial_type 10 */ + tdsqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC); +#endif + tdsqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid); + tdsqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid); } - if( bOnePass==0 ){ + if( eOnePass==ONEPASS_OFF ){ /* End the virtual table scan */ - sqlite3WhereEnd(pWInfo); + tdsqlite3WhereEnd(pWInfo); /* Begin scannning through the ephemeral table. */ - addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v); + addr = tdsqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v); /* Extract arguments from the current row of the ephemeral table and ** invoke the VUpdate method. */ for(i=0; i<nArg; i++){ - sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i); + tdsqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i); } } - sqlite3VtabMakeWritable(pParse, pTab); - sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB); - sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); - sqlite3MayAbort(pParse); + tdsqlite3VtabMakeWritable(pParse, pTab); + tdsqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB); + tdsqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); + tdsqlite3MayAbort(pParse); /* End of the ephemeral table scan. Or, if using the onepass strategy, ** jump to here if the scan visited zero rows. */ - if( bOnePass==0 ){ - sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr); - sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0); + if( eOnePass==ONEPASS_OFF ){ + tdsqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addr); + tdsqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0); }else{ - sqlite3WhereEnd(pWInfo); + tdsqlite3WhereEnd(pWInfo); } } #endif /* SQLITE_OMIT_VIRTUALTABLE */ /************** End of update.c **********************************************/ +/************** Begin file upsert.c ******************************************/ +/* +** 2018-04-12 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code to implement various aspects of UPSERT +** processing and handling of the Upsert object. +*/ +/* #include "sqliteInt.h" */ + +#ifndef SQLITE_OMIT_UPSERT +/* +** Free a list of Upsert objects +*/ +SQLITE_PRIVATE void tdsqlite3UpsertDelete(tdsqlite3 *db, Upsert *p){ + if( p ){ + tdsqlite3ExprListDelete(db, p->pUpsertTarget); + tdsqlite3ExprDelete(db, p->pUpsertTargetWhere); + tdsqlite3ExprListDelete(db, p->pUpsertSet); + tdsqlite3ExprDelete(db, p->pUpsertWhere); + tdsqlite3DbFree(db, p); + } +} + +/* +** Duplicate an Upsert object. +*/ +SQLITE_PRIVATE Upsert *tdsqlite3UpsertDup(tdsqlite3 *db, Upsert *p){ + if( p==0 ) return 0; + return tdsqlite3UpsertNew(db, + tdsqlite3ExprListDup(db, p->pUpsertTarget, 0), + tdsqlite3ExprDup(db, p->pUpsertTargetWhere, 0), + tdsqlite3ExprListDup(db, p->pUpsertSet, 0), + tdsqlite3ExprDup(db, p->pUpsertWhere, 0) + ); +} + +/* +** Create a new Upsert object. +*/ +SQLITE_PRIVATE Upsert *tdsqlite3UpsertNew( + tdsqlite3 *db, /* Determines which memory allocator to use */ + ExprList *pTarget, /* Target argument to ON CONFLICT, or NULL */ + Expr *pTargetWhere, /* Optional WHERE clause on the target */ + ExprList *pSet, /* UPDATE columns, or NULL for a DO NOTHING */ + Expr *pWhere /* WHERE clause for the ON CONFLICT UPDATE */ +){ + Upsert *pNew; + pNew = tdsqlite3DbMallocRaw(db, sizeof(Upsert)); + if( pNew==0 ){ + tdsqlite3ExprListDelete(db, pTarget); + tdsqlite3ExprDelete(db, pTargetWhere); + tdsqlite3ExprListDelete(db, pSet); + tdsqlite3ExprDelete(db, pWhere); + return 0; + }else{ + pNew->pUpsertTarget = pTarget; + pNew->pUpsertTargetWhere = pTargetWhere; + pNew->pUpsertSet = pSet; + pNew->pUpsertWhere = pWhere; + pNew->pUpsertIdx = 0; + } + return pNew; +} + +/* +** Analyze the ON CONFLICT clause described by pUpsert. Resolve all +** symbols in the conflict-target. +** +** Return SQLITE_OK if everything works, or an error code is something +** is wrong. +*/ +SQLITE_PRIVATE int tdsqlite3UpsertAnalyzeTarget( + Parse *pParse, /* The parsing context */ + SrcList *pTabList, /* Table into which we are inserting */ + Upsert *pUpsert /* The ON CONFLICT clauses */ +){ + Table *pTab; /* That table into which we are inserting */ + int rc; /* Result code */ + int iCursor; /* Cursor used by pTab */ + Index *pIdx; /* One of the indexes of pTab */ + ExprList *pTarget; /* The conflict-target clause */ + Expr *pTerm; /* One term of the conflict-target clause */ + NameContext sNC; /* Context for resolving symbolic names */ + Expr sCol[2]; /* Index column converted into an Expr */ + + assert( pTabList->nSrc==1 ); + assert( pTabList->a[0].pTab!=0 ); + assert( pUpsert!=0 ); + assert( pUpsert->pUpsertTarget!=0 ); + + /* Resolve all symbolic names in the conflict-target clause, which + ** includes both the list of columns and the optional partial-index + ** WHERE clause. + */ + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + rc = tdsqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget); + if( rc ) return rc; + rc = tdsqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere); + if( rc ) return rc; + + /* Check to see if the conflict target matches the rowid. */ + pTab = pTabList->a[0].pTab; + pTarget = pUpsert->pUpsertTarget; + iCursor = pTabList->a[0].iCursor; + if( HasRowid(pTab) + && pTarget->nExpr==1 + && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN + && pTerm->iColumn==XN_ROWID + ){ + /* The conflict-target is the rowid of the primary table */ + assert( pUpsert->pUpsertIdx==0 ); + return SQLITE_OK; + } + + /* Initialize sCol[0..1] to be an expression parse tree for a + ** single column of an index. The sCol[0] node will be the TK_COLLATE + ** operator and sCol[1] will be the TK_COLUMN operator. Code below + ** will populate the specific collation and column number values + ** prior to comparing against the conflict-target expression. + */ + memset(sCol, 0, sizeof(sCol)); + sCol[0].op = TK_COLLATE; + sCol[0].pLeft = &sCol[1]; + sCol[1].op = TK_COLUMN; + sCol[1].iTable = pTabList->a[0].iCursor; + + /* Check for matches against other indexes */ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + int ii, jj, nn; + if( !IsUniqueIndex(pIdx) ) continue; + if( pTarget->nExpr!=pIdx->nKeyCol ) continue; + if( pIdx->pPartIdxWhere ){ + if( pUpsert->pUpsertTargetWhere==0 ) continue; + if( tdsqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere, + pIdx->pPartIdxWhere, iCursor)!=0 ){ + continue; + } + } + nn = pIdx->nKeyCol; + for(ii=0; ii<nn; ii++){ + Expr *pExpr; + sCol[0].u.zToken = (char*)pIdx->azColl[ii]; + if( pIdx->aiColumn[ii]==XN_EXPR ){ + assert( pIdx->aColExpr!=0 ); + assert( pIdx->aColExpr->nExpr>ii ); + pExpr = pIdx->aColExpr->a[ii].pExpr; + if( pExpr->op!=TK_COLLATE ){ + sCol[0].pLeft = pExpr; + pExpr = &sCol[0]; + } + }else{ + sCol[0].pLeft = &sCol[1]; + sCol[1].iColumn = pIdx->aiColumn[ii]; + pExpr = &sCol[0]; + } + for(jj=0; jj<nn; jj++){ + if( tdsqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){ + break; /* Column ii of the index matches column jj of target */ + } + } + if( jj>=nn ){ + /* The target contains no match for column jj of the index */ + break; + } + } + if( ii<nn ){ + /* Column ii of the index did not match any term of the conflict target. + ** Continue the search with the next index. */ + continue; + } + pUpsert->pUpsertIdx = pIdx; + return SQLITE_OK; + } + tdsqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any " + "PRIMARY KEY or UNIQUE constraint"); + return SQLITE_ERROR; +} + +/* +** Generate bytecode that does an UPDATE as part of an upsert. +** +** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK. +** In this case parameter iCur is a cursor open on the table b-tree that +** currently points to the conflicting table row. Otherwise, if pIdx +** is not NULL, then pIdx is the constraint that failed and iCur is a +** cursor points to the conflicting row. +*/ +SQLITE_PRIVATE void tdsqlite3UpsertDoUpdate( + Parse *pParse, /* The parsing and code-generating context */ + Upsert *pUpsert, /* The ON CONFLICT clause for the upsert */ + Table *pTab, /* The table being updated */ + Index *pIdx, /* The UNIQUE constraint that failed */ + int iCur /* Cursor for pIdx (or pTab if pIdx==NULL) */ +){ + Vdbe *v = pParse->pVdbe; + tdsqlite3 *db = pParse->db; + SrcList *pSrc; /* FROM clause for the UPDATE */ + int iDataCur; + int i; + + assert( v!=0 ); + assert( pUpsert!=0 ); + VdbeNoopComment((v, "Begin DO UPDATE of UPSERT")); + iDataCur = pUpsert->iDataCur; + if( pIdx && iCur!=iDataCur ){ + if( HasRowid(pTab) ){ + int regRowid = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid); + tdsqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid); + VdbeCoverage(v); + tdsqlite3ReleaseTempReg(pParse, regRowid); + }else{ + Index *pPk = tdsqlite3PrimaryKeyIndex(pTab); + int nPk = pPk->nKeyCol; + int iPk = pParse->nMem+1; + pParse->nMem += nPk; + for(i=0; i<nPk; i++){ + int k; + assert( pPk->aiColumn[i]>=0 ); + k = tdsqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]); + tdsqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i); + VdbeComment((v, "%s.%s", pIdx->zName, + pTab->aCol[pPk->aiColumn[i]].zName)); + } + tdsqlite3VdbeVerifyAbortable(v, OE_Abort); + i = tdsqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk); + VdbeCoverage(v); + tdsqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0, + "corrupt database", P4_STATIC); + tdsqlite3MayAbort(pParse); + tdsqlite3VdbeJumpHere(v, i); + } + } + /* pUpsert does not own pUpsertSrc - the outer INSERT statement does. So + ** we have to make a copy before passing it down into tdsqlite3Update() */ + pSrc = tdsqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0); + /* excluded.* columns of type REAL need to be converted to a hard real */ + for(i=0; i<pTab->nCol; i++){ + if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){ + tdsqlite3VdbeAddOp1(v, OP_RealAffinity, pUpsert->regData+i); + } + } + tdsqlite3Update(pParse, pSrc, pUpsert->pUpsertSet, + pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert); + pUpsert->pUpsertSet = 0; /* Will have been deleted by tdsqlite3Update() */ + pUpsert->pUpsertWhere = 0; /* Will have been deleted by tdsqlite3Update() */ + VdbeNoopComment((v, "End DO UPDATE of UPSERT")); +} + +#endif /* SQLITE_OMIT_UPSERT */ + +/************** End of upsert.c **********************************************/ /************** Begin file vacuum.c ******************************************/ /* ** 2003 April 6 @@ -125344,18 +141060,24 @@ static void updateVirtualTable( ** The execSqlF() routine does the same thing, except it accepts ** a format string as its third argument */ -static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ - sqlite3_stmt *pStmt; +static int execSql(tdsqlite3 *db, char **pzErrMsg, const char *zSql){ + tdsqlite3_stmt *pStmt; int rc; /* printf("SQL: [%s]\n", zSql); fflush(stdout); */ - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + rc = tdsqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; - while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ - const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0); - assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 ); - if( zSubSql ){ - assert( zSubSql[0]!='S' ); + while( SQLITE_ROW==(rc = tdsqlite3_step(pStmt)) ){ + const char *zSubSql = (const char*)tdsqlite3_column_text(pStmt,0); + assert( tdsqlite3_strnicmp(zSql,"SELECT",6)==0 ); + /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX, + ** or INSERT. Historically there have been attacks that first + ** corrupt the sqlite_master.sql field with other kinds of statements + ** then run VACUUM to get those statements to execute at inappropriate + ** times. */ + if( zSubSql + && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0) + ){ rc = execSql(db, pzErrMsg, zSubSql); if( rc!=SQLITE_OK ) break; } @@ -125363,21 +141085,21 @@ static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ assert( rc!=SQLITE_ROW ); if( rc==SQLITE_DONE ) rc = SQLITE_OK; if( rc ){ - sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); + tdsqlite3SetString(pzErrMsg, db, tdsqlite3_errmsg(db)); } - (void)sqlite3_finalize(pStmt); + (void)tdsqlite3_finalize(pStmt); return rc; } -static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){ +static int execSqlF(tdsqlite3 *db, char **pzErrMsg, const char *zSql, ...){ char *z; va_list ap; int rc; va_start(ap, zSql); - z = sqlite3VMPrintf(db, zSql, ap); + z = tdsqlite3VMPrintf(db, zSql, ap); va_end(ap); if( z==0 ) return SQLITE_NOMEM; rc = execSql(db, pzErrMsg, z); - sqlite3DbFree(db, z); + tdsqlite3DbFree(db, z); return rc; } @@ -125411,63 +141133,110 @@ static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){ ** transient would cause the database file to appear to be deleted ** following reboot. */ -SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){ - Vdbe *v = sqlite3GetVdbe(pParse); - int iDb = pNm ? sqlite3TwoPartName(pParse, pNm, pNm, &pNm) : 0; - if( v && (iDb>=2 || iDb==0) ){ - sqlite3VdbeAddOp1(v, OP_Vacuum, iDb); - sqlite3VdbeUsesBtree(v, iDb); +SQLITE_PRIVATE void tdsqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){ + Vdbe *v = tdsqlite3GetVdbe(pParse); + int iDb = 0; + if( v==0 ) goto build_vacuum_end; + if( pParse->nErr ) goto build_vacuum_end; + if( pNm ){ +#ifndef SQLITE_BUG_COMPATIBLE_20160819 + /* Default behavior: Report an error if the argument to VACUUM is + ** not recognized */ + iDb = tdsqlite3TwoPartName(pParse, pNm, pNm, &pNm); + if( iDb<0 ) goto build_vacuum_end; +#else + /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments + ** to VACUUM are silently ignored. This is a back-out of a bug fix that + ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270). + ** The buggy behavior is required for binary compatibility with some + ** legacy applications. */ + iDb = tdsqlite3FindDb(pParse->db, pNm); + if( iDb<0 ) iDb = 0; +#endif + } + if( iDb!=1 ){ + int iIntoReg = 0; + if( pInto && tdsqlite3ResolveSelfReference(pParse,0,0,pInto,0)==0 ){ + iIntoReg = ++pParse->nMem; + tdsqlite3ExprCode(pParse, pInto, iIntoReg); + } + tdsqlite3VdbeAddOp2(v, OP_Vacuum, iDb, iIntoReg); + tdsqlite3VdbeUsesBtree(v, iDb); } +build_vacuum_end: + tdsqlite3ExprDelete(pParse->db, pInto); return; } /* ** This routine implements the OP_Vacuum opcode of the VDBE. */ -SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ +SQLITE_PRIVATE SQLITE_NOINLINE int tdsqlite3RunVacuum( + char **pzErrMsg, /* Write error message here */ + tdsqlite3 *db, /* Database connection */ + int iDb, /* Which attached DB to vacuum */ + tdsqlite3_value *pOut /* Write results here, if not NULL. VACUUM INTO */ +){ int rc = SQLITE_OK; /* Return code from service routines */ Btree *pMain; /* The database being vacuumed */ Btree *pTemp; /* The temporary database we vacuum into */ - int saved_flags; /* Saved value of the db->flags */ + u32 saved_mDbFlags; /* Saved value of db->mDbFlags */ + u64 saved_flags; /* Saved value of db->flags */ int saved_nChange; /* Saved value of db->nChange */ int saved_nTotalChange; /* Saved value of db->nTotalChange */ + u32 saved_openFlags; /* Saved value of db->openFlags */ u8 saved_mTrace; /* Saved trace settings */ Db *pDb = 0; /* Database to detach at end of vacuum */ int isMemDb; /* True if vacuuming a :memory: database */ int nRes; /* Bytes of reserved space at the end of each page */ int nDb; /* Number of attached databases */ const char *zDbMain; /* Schema name of database to vacuum */ + const char *zOut; /* Name of output file */ if( !db->autoCommit ){ - sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); - return SQLITE_ERROR; + tdsqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); + return SQLITE_ERROR; /* IMP: R-12218-18073 */ } if( db->nVdbeActive>1 ){ - sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress"); - return SQLITE_ERROR; + tdsqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress"); + return SQLITE_ERROR; /* IMP: R-15610-35227 */ + } + saved_openFlags = db->openFlags; + if( pOut ){ + if( tdsqlite3_value_type(pOut)!=SQLITE_TEXT ){ + tdsqlite3SetString(pzErrMsg, db, "non-text filename"); + return SQLITE_ERROR; + } + zOut = (const char*)tdsqlite3_value_text(pOut); + db->openFlags &= ~SQLITE_OPEN_READONLY; + db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE; + }else{ + zOut = ""; } /* Save the current value of the database flags so that it can be ** restored before returning. Then set the writable-schema flag, and ** disable CHECK and foreign key constraints. */ saved_flags = db->flags; + saved_mDbFlags = db->mDbFlags; saved_nChange = db->nChange; saved_nTotalChange = db->nTotalChange; saved_mTrace = db->mTrace; - db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks - | SQLITE_PreferBuiltin | SQLITE_Vacuum); - db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows); + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks; + db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum; + db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder + | SQLITE_Defensive | SQLITE_CountRows); db->mTrace = 0; zDbMain = db->aDb[iDb].zDbSName; pMain = db->aDb[iDb].pBt; - isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain)); + isMemDb = tdsqlite3PagerIsMemdb(tdsqlite3BtreePager(pMain)); /* Attach the temporary database as 'vacuum_db'. The synchronous pragma ** can be set to 'off' for this file, as it is not recovered if a crash ** occurs anyway. The integrity of the database is maintained by a ** (possibly synchronous) transaction opened on the main database before - ** sqlite3BtreeCopyFile() is called. + ** tdsqlite3BtreeCopyFile() is called. ** ** An optimisation would be to use a non-journaled pager. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but @@ -125478,53 +141247,57 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ ** to write the journal header file. */ nDb = db->nDb; - rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db"); + rc = execSqlF(db, pzErrMsg, "ATTACH %Q AS vacuum_db", zOut); + db->openFlags = saved_openFlags; if( rc!=SQLITE_OK ) goto end_of_vacuum; assert( (db->nDb-1)==nDb ); pDb = &db->aDb[nDb]; assert( strcmp(pDb->zDbSName,"vacuum_db")==0 ); pTemp = pDb->pBt; - - /* The call to execSql() to attach the temp database has left the file - ** locked (as there was more than one active statement when the transaction - ** to read the schema was concluded. Unlock it here so that this doesn't - ** cause problems for the call to BtreeSetPageSize() below. */ - sqlite3BtreeCommit(pTemp); - - nRes = sqlite3BtreeGetOptimalReserve(pMain); + if( pOut ){ + tdsqlite3_file *id = tdsqlite3PagerFile(tdsqlite3BtreePager(pTemp)); + i64 sz = 0; + if( id->pMethods!=0 && (tdsqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){ + rc = SQLITE_ERROR; + tdsqlite3SetString(pzErrMsg, db, "output file already exists"); + goto end_of_vacuum; + } + db->mDbFlags |= DBFLAG_VacuumInto; + } + nRes = tdsqlite3BtreeGetOptimalReserve(pMain); /* A VACUUM cannot change the pagesize of an encrypted database. */ #ifdef SQLITE_HAS_CODEC if( db->nextPagesize ){ - extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); + extern void tdsqlite3CodecGetKey(tdsqlite3*, int, void**, int*); int nKey; char *zKey; - sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); + tdsqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey); if( nKey ) db->nextPagesize = 0; } #endif - sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size); - sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0)); - sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL); + tdsqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size); + tdsqlite3BtreeSetSpillSize(pTemp, tdsqlite3BtreeSetSpillSize(pMain,0)); + tdsqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL); /* Begin a transaction and take an exclusive lock on the main database - ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below, + ** file. This is done before the tdsqlite3BtreeGetPageSize(pMain) call below, ** to ensure that we do not try to change the page-size on a WAL database. */ rc = execSql(db, pzErrMsg, "BEGIN"); if( rc!=SQLITE_OK ) goto end_of_vacuum; - rc = sqlite3BtreeBeginTrans(pMain, 2); + rc = tdsqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0); if( rc!=SQLITE_OK ) goto end_of_vacuum; /* Do not attempt to change the page size for a WAL database */ - if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain)) + if( tdsqlite3PagerGetJournalMode(tdsqlite3BtreePager(pMain)) ==PAGER_JOURNALMODE_WAL ){ db->nextPagesize = 0; } - if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0) - || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0)) + if( tdsqlite3BtreeSetPageSize(pTemp, tdsqlite3BtreeGetPageSize(pMain), nRes, 0) + || (!isMemDb && tdsqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0)) || NEVER(db->mallocFailed) ){ rc = SQLITE_NOMEM_BKPT; @@ -125532,8 +141305,8 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ } #ifndef SQLITE_OMIT_AUTOVACUUM - sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : - sqlite3BtreeGetAutoVacuum(pMain)); + tdsqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : + tdsqlite3BtreeGetAutoVacuum(pMain)); #endif /* Query the schema of the main database. Create a mirror schema @@ -125549,7 +141322,7 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ if( rc!=SQLITE_OK ) goto end_of_vacuum; rc = execSqlF(db, pzErrMsg, "SELECT sql FROM \"%w\".sqlite_master" - " WHERE type='index' AND length(sql)>10", + " WHERE type='index'", zDbMain ); if( rc!=SQLITE_OK ) goto end_of_vacuum; @@ -125566,8 +141339,8 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ "WHERE type='table'AND coalesce(rootpage,1)>0", zDbMain ); - assert( (db->flags & SQLITE_Vacuum)!=0 ); - db->flags &= ~SQLITE_Vacuum; + assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 ); + db->mDbFlags &= ~DBFLAG_Vacuum; if( rc!=SQLITE_OK ) goto end_of_vacuum; /* Copy the triggers, views, and virtual tables from the main database @@ -125587,8 +141360,8 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ /* At this point, there is a write transaction open on both the ** vacuum database and the main database. Assuming no error occurs, ** both transactions are closed by this block - the main database - ** transaction by sqlite3BtreeCopyFile() and the other by an explicit - ** call to sqlite3BtreeCommit(). + ** transaction by tdsqlite3BtreeCopyFile() and the other by an explicit + ** call to tdsqlite3BtreeCommit(). */ { u32 meta; @@ -125608,38 +141381,45 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ BTREE_APPLICATION_ID, 0, /* Preserve the application id */ }; - assert( 1==sqlite3BtreeIsInTrans(pTemp) ); - assert( 1==sqlite3BtreeIsInTrans(pMain) ); + assert( 1==tdsqlite3BtreeIsInTrans(pTemp) ); + assert( pOut!=0 || 1==tdsqlite3BtreeIsInTrans(pMain) ); /* Copy Btree meta values */ for(i=0; i<ArraySize(aCopy); i+=2){ /* GetMeta() and UpdateMeta() cannot fail in this context because ** we already have page 1 loaded into cache and marked dirty. */ - sqlite3BtreeGetMeta(pMain, aCopy[i], &meta); - rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]); + tdsqlite3BtreeGetMeta(pMain, aCopy[i], &meta); + rc = tdsqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]); if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum; } - rc = sqlite3BtreeCopyFile(pMain, pTemp); + if( pOut==0 ){ + rc = tdsqlite3BtreeCopyFile(pMain, pTemp); + } if( rc!=SQLITE_OK ) goto end_of_vacuum; - rc = sqlite3BtreeCommit(pTemp); + rc = tdsqlite3BtreeCommit(pTemp); if( rc!=SQLITE_OK ) goto end_of_vacuum; #ifndef SQLITE_OMIT_AUTOVACUUM - sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp)); + if( pOut==0 ){ + tdsqlite3BtreeSetAutoVacuum(pMain, tdsqlite3BtreeGetAutoVacuum(pTemp)); + } #endif } assert( rc==SQLITE_OK ); - rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1); + if( pOut==0 ){ + rc = tdsqlite3BtreeSetPageSize(pMain, tdsqlite3BtreeGetPageSize(pTemp), nRes,1); + } end_of_vacuum: /* Restore the original value of db->flags */ db->init.iDb = 0; + db->mDbFlags = saved_mDbFlags; db->flags = saved_flags; db->nChange = saved_nChange; db->nTotalChange = saved_nTotalChange; db->mTrace = saved_mTrace; - sqlite3BtreeSetPageSize(pMain, -1, -1, 1); + tdsqlite3BtreeSetPageSize(pMain, -1, -1, 1); /* Currently there is an SQL level transaction open on the vacuum ** database. No locks are held on any other files (since the main file @@ -125651,14 +141431,14 @@ end_of_vacuum: db->autoCommit = 1; if( pDb ){ - sqlite3BtreeClose(pDb->pBt); + tdsqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; pDb->pSchema = 0; } /* This both clears the schemas and reduces the size of the db->aDb[] ** array. */ - sqlite3ResetAllSchemasOfConnection(db); + tdsqlite3ResetAllSchemasOfConnection(db); return rc; } @@ -125687,59 +141467,86 @@ end_of_vacuum: ** Before a virtual table xCreate() or xConnect() method is invoked, the ** sqlite3.pVtabCtx member variable is set to point to an instance of ** this struct allocated on the stack. It is used by the implementation of -** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which +** the tdsqlite3_declare_vtab() and tdsqlite3_vtab_config() APIs, both of which ** are invoked only from within xCreate and xConnect methods. */ struct VtabCtx { VTable *pVTable; /* The virtual table being constructed */ Table *pTab; /* The Table object to which the virtual table belongs */ VtabCtx *pPrior; /* Parent context (if any) */ - int bDeclared; /* True after sqlite3_declare_vtab() is called */ + int bDeclared; /* True after tdsqlite3_declare_vtab() is called */ }; /* +** Construct and install a Module object for a virtual table. When this +** routine is called, it is guaranteed that all appropriate locks are held +** and the module is not already part of the connection. +** +** If there already exists a module with zName, replace it with the new one. +** If pModule==0, then delete the module zName if it exists. +*/ +SQLITE_PRIVATE Module *tdsqlite3VtabCreateModule( + tdsqlite3 *db, /* Database in which module is registered */ + const char *zName, /* Name assigned to this module */ + const tdsqlite3_module *pModule, /* The definition of the module */ + void *pAux, /* Context pointer for xCreate/xConnect */ + void (*xDestroy)(void *) /* Module destructor function */ +){ + Module *pMod; + Module *pDel; + char *zCopy; + if( pModule==0 ){ + zCopy = (char*)zName; + pMod = 0; + }else{ + int nName = tdsqlite3Strlen30(zName); + pMod = (Module *)tdsqlite3Malloc(sizeof(Module) + nName + 1); + if( pMod==0 ){ + tdsqlite3OomFault(db); + return 0; + } + zCopy = (char *)(&pMod[1]); + memcpy(zCopy, zName, nName+1); + pMod->zName = zCopy; + pMod->pModule = pModule; + pMod->pAux = pAux; + pMod->xDestroy = xDestroy; + pMod->pEpoTab = 0; + pMod->nRefModule = 1; + } + pDel = (Module *)tdsqlite3HashInsert(&db->aModule,zCopy,(void*)pMod); + if( pDel ){ + if( pDel==pMod ){ + tdsqlite3OomFault(db); + tdsqlite3DbFree(db, pDel); + pMod = 0; + }else{ + tdsqlite3VtabEponymousTableClear(db, pDel); + tdsqlite3VtabModuleUnref(db, pDel); + } + } + return pMod; +} + +/* ** The actual function that does the work of creating a new module. -** This function implements the sqlite3_create_module() and -** sqlite3_create_module_v2() interfaces. +** This function implements the tdsqlite3_create_module() and +** tdsqlite3_create_module_v2() interfaces. */ static int createModule( - sqlite3 *db, /* Database in which module is registered */ + tdsqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ - const sqlite3_module *pModule, /* The definition of the module */ + const tdsqlite3_module *pModule, /* The definition of the module */ void *pAux, /* Context pointer for xCreate/xConnect */ void (*xDestroy)(void *) /* Module destructor function */ ){ int rc = SQLITE_OK; - int nName; - sqlite3_mutex_enter(db->mutex); - nName = sqlite3Strlen30(zName); - if( sqlite3HashFind(&db->aModule, zName) ){ - rc = SQLITE_MISUSE_BKPT; - }else{ - Module *pMod; - pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1); - if( pMod ){ - Module *pDel; - char *zCopy = (char *)(&pMod[1]); - memcpy(zCopy, zName, nName+1); - pMod->zName = zCopy; - pMod->pModule = pModule; - pMod->pAux = pAux; - pMod->xDestroy = xDestroy; - pMod->pEpoTab = 0; - pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod); - assert( pDel==0 || pDel==pMod ); - if( pDel ){ - sqlite3OomFault(db); - sqlite3DbFree(db, pDel); - } - } - } - rc = sqlite3ApiExit(db, rc); + tdsqlite3_mutex_enter(db->mutex); + (void)tdsqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy); + rc = tdsqlite3ApiExit(db, rc); if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux); - - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -125747,14 +141554,14 @@ static int createModule( /* ** External API function used to create a new virtual-table module. */ -SQLITE_API int sqlite3_create_module( - sqlite3 *db, /* Database in which module is registered */ +SQLITE_API int tdsqlite3_create_module( + tdsqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ - const sqlite3_module *pModule, /* The definition of the module */ + const tdsqlite3_module *pModule, /* The definition of the module */ void *pAux /* Context pointer for xCreate/xConnect */ ){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif return createModule(db, zName, pModule, pAux, 0); } @@ -125762,20 +141569,58 @@ SQLITE_API int sqlite3_create_module( /* ** External API function used to create a new virtual-table module. */ -SQLITE_API int sqlite3_create_module_v2( - sqlite3 *db, /* Database in which module is registered */ +SQLITE_API int tdsqlite3_create_module_v2( + tdsqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ - const sqlite3_module *pModule, /* The definition of the module */ + const tdsqlite3_module *pModule, /* The definition of the module */ void *pAux, /* Context pointer for xCreate/xConnect */ void (*xDestroy)(void *) /* Module destructor function */ ){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif return createModule(db, zName, pModule, pAux, xDestroy); } /* +** External API to drop all virtual-table modules, except those named +** on the azNames list. +*/ +SQLITE_API int tdsqlite3_drop_modules(tdsqlite3 *db, const char** azNames){ + HashElem *pThis, *pNext; +#ifdef SQLITE_ENABLE_API_ARMOR + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; +#endif + for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){ + Module *pMod = (Module*)sqliteHashData(pThis); + pNext = sqliteHashNext(pThis); + if( azNames ){ + int ii; + for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){} + if( azNames[ii]!=0 ) continue; + } + createModule(db, pMod->zName, 0, 0, 0); + } + return SQLITE_OK; +} + +/* +** Decrement the reference count on a Module object. Destroy the +** module when the reference count reaches zero. +*/ +SQLITE_PRIVATE void tdsqlite3VtabModuleUnref(tdsqlite3 *db, Module *pMod){ + assert( pMod->nRefModule>0 ); + pMod->nRefModule--; + if( pMod->nRefModule==0 ){ + if( pMod->xDestroy ){ + pMod->xDestroy(pMod->pAux); + } + assert( pMod->pEpoTab==0 ); + tdsqlite3DbFree(db, pMod); + } +} + +/* ** Lock the virtual table so that it cannot be disconnected. ** Locks nest. Every lock should have a corresponding unlock. ** If an unlock is omitted, resources leaks will occur. @@ -125783,7 +141628,7 @@ SQLITE_API int sqlite3_create_module_v2( ** If a disconnect is attempted while a virtual table is locked, ** the disconnect is deferred until all locks have been removed. */ -SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){ +SQLITE_PRIVATE void tdsqlite3VtabLock(VTable *pVTab){ pVTab->nRef++; } @@ -125793,7 +141638,7 @@ SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){ ** Return a pointer to the VTable object used by connection db to access ** this virtual-table, if one has been created, or NULL otherwise. */ -SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){ +SQLITE_PRIVATE VTable *tdsqlite3GetVTable(tdsqlite3 *db, Table *pTab){ VTable *pVtab; assert( IsVirtual(pTab) ); for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext); @@ -125804,8 +141649,8 @@ SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){ ** Decrement the ref-count on a virtual table object. When the ref-count ** reaches zero, call the xDisconnect() method to delete the object. */ -SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){ - sqlite3 *db = pVTab->db; +SQLITE_PRIVATE void tdsqlite3VtabUnlock(VTable *pVTab){ + tdsqlite3 *db = pVTab->db; assert( db ); assert( pVTab->nRef>0 ); @@ -125813,11 +141658,12 @@ SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){ pVTab->nRef--; if( pVTab->nRef==0 ){ - sqlite3_vtab *p = pVTab->pVtab; + tdsqlite3_vtab *p = pVTab->pVtab; + tdsqlite3VtabModuleUnref(pVTab->db, pVTab->pMod); if( p ){ p->pModule->xDisconnect(p); } - sqlite3DbFree(db, pVTab); + tdsqlite3DbFree(db, pVTab); } } @@ -125828,21 +141674,21 @@ SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){ ** Except, if argument db is not NULL, then the entry associated with ** connection db is left in the p->pVTable list. */ -static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){ +static VTable *vtabDisconnectAll(tdsqlite3 *db, Table *p){ VTable *pRet = 0; VTable *pVTable = p->pVTable; p->pVTable = 0; /* Assert that the mutex (if any) associated with the BtShared database ** that contains table p is held by the caller. See header comments - ** above function sqlite3VtabUnlockList() for an explanation of why + ** above function tdsqlite3VtabUnlockList() for an explanation of why ** this makes it safe to access the sqlite3.pDisconnect list of any ** database connection that may have an entry in the p->pVTable list. */ - assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); + assert( db==0 || tdsqlite3SchemaMutexHeld(db, 0, p->pSchema) ); while( pVTable ){ - sqlite3 *db2 = pVTable->db; + tdsqlite3 *db2 = pVTable->db; VTable *pNext = pVTable->pNext; assert( db2 ); if( db2==db ){ @@ -125868,18 +141714,18 @@ static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){ ** objects without disturbing the rest of the Schema object (which may ** be being used by other shared-cache connections). */ -SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){ +SQLITE_PRIVATE void tdsqlite3VtabDisconnect(tdsqlite3 *db, Table *p){ VTable **ppVTab; assert( IsVirtual(p) ); - assert( sqlite3BtreeHoldsAllMutexes(db) ); - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3BtreeHoldsAllMutexes(db) ); + assert( tdsqlite3_mutex_held(db->mutex) ); for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){ if( (*ppVTab)->db==db ){ VTable *pVTab = *ppVTab; *ppVTab = pVTab->pNext; - sqlite3VtabUnlock(pVTab); + tdsqlite3VtabUnlock(pVTab); break; } } @@ -125906,18 +141752,18 @@ SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){ ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously ** by multiple threads. It is thread-safe. */ -SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3VtabUnlockList(tdsqlite3 *db){ VTable *p = db->pDisconnect; - db->pDisconnect = 0; - assert( sqlite3BtreeHoldsAllMutexes(db) ); - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3BtreeHoldsAllMutexes(db) ); + assert( tdsqlite3_mutex_held(db->mutex) ); if( p ){ - sqlite3ExpirePreparedStatements(db); + db->pDisconnect = 0; + tdsqlite3ExpirePreparedStatements(db, 0); do { VTable *pNext = p->pNext; - sqlite3VtabUnlock(p); + tdsqlite3VtabUnlock(p); p = pNext; }while( p ); } @@ -125930,21 +141776,21 @@ SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){ ** ** Since it is a virtual-table, the Table structure contains a pointer ** to the head of a linked list of VTable structures. Each VTable -** structure is associated with a single sqlite3* user of the schema. +** structure is associated with a single tdsqlite3* user of the schema. ** The reference count of the VTable structure associated with database ** connection db is decremented immediately (which may lead to the ** structure being xDisconnected and free). Any other VTable structures ** in the list are moved to the sqlite3.pDisconnect list of the associated ** database connection. */ -SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){ +SQLITE_PRIVATE void tdsqlite3VtabClear(tdsqlite3 *db, Table *p){ if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p); if( p->azModuleArg ){ int i; for(i=0; i<p->nModuleArg; i++){ - if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]); + if( i!=1 ) tdsqlite3DbFree(db, p->azModuleArg[i]); } - sqlite3DbFree(db, p->azModuleArg); + tdsqlite3DbFree(db, p->azModuleArg); } } @@ -125954,12 +141800,16 @@ SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){ ** string will be freed automatically when the table is ** deleted. */ -static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){ - int nBytes = sizeof(char *)*(2+pTable->nModuleArg); +static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){ + tdsqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg); char **azModuleArg; - azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes); + tdsqlite3 *db = pParse->db; + if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){ + tdsqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName); + } + azModuleArg = tdsqlite3DbRealloc(db, pTable->azModuleArg, nBytes); if( azModuleArg==0 ){ - sqlite3DbFree(db, zArg); + tdsqlite3DbFree(db, zArg); }else{ int i = pTable->nModuleArg++; azModuleArg[i] = zArg; @@ -125973,31 +141823,27 @@ static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){ ** statement. The module name has been parsed, but the optional list ** of parameters that follow the module name are still pending. */ -SQLITE_PRIVATE void sqlite3VtabBeginParse( +SQLITE_PRIVATE void tdsqlite3VtabBeginParse( Parse *pParse, /* Parsing context */ Token *pName1, /* Name of new table, or database name */ Token *pName2, /* Name of new table or NULL */ Token *pModuleName, /* Name of the module for the virtual table */ int ifNotExists /* No error if the table already exists */ ){ - int iDb; /* The database the table is being created in */ Table *pTable; /* The new virtual table */ - sqlite3 *db; /* Database connection */ + tdsqlite3 *db; /* Database connection */ - sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists); + tdsqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists); pTable = pParse->pNewTable; if( pTable==0 ) return; assert( 0==pTable->pIndex ); db = pParse->db; - iDb = sqlite3SchemaToIndex(db, pTable->pSchema); - assert( iDb>=0 ); - pTable->tabFlags |= TF_Virtual; - pTable->nModuleArg = 0; - addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName)); - addModuleArgument(db, pTable, 0); - addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName)); + assert( pTable->nModuleArg==0 ); + addModuleArgument(pParse, pTable, tdsqlite3NameFromToken(db, pModuleName)); + addModuleArgument(pParse, pTable, 0); + addModuleArgument(pParse, pTable, tdsqlite3DbStrDup(db, pTable->zName)); assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0) || (pParse->sNameToken.z==pName1->z && pName2->z==0) ); @@ -126008,11 +141854,13 @@ SQLITE_PRIVATE void sqlite3VtabBeginParse( #ifndef SQLITE_OMIT_AUTHORIZATION /* Creating a virtual table invokes the authorization callback twice. ** The first invocation, to obtain permission to INSERT a row into the - ** sqlite_master table, has already been made by sqlite3StartTable(). + ** sqlite_master table, has already been made by tdsqlite3StartTable(). ** The second call, to obtain permission to create the table, is made now. */ if( pTable->azModuleArg ){ - sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, + int iDb = tdsqlite3SchemaToIndex(db, pTable->pSchema); + assert( iDb>=0 ); /* The database the table is being created in */ + tdsqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName); } #endif @@ -126027,8 +141875,8 @@ static void addArgumentToVtab(Parse *pParse){ if( pParse->sArg.z && pParse->pNewTable ){ const char *z = (const char*)pParse->sArg.z; int n = pParse->sArg.n; - sqlite3 *db = pParse->db; - addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); + tdsqlite3 *db = pParse->db; + addModuleArgument(pParse, pParse->pNewTable, tdsqlite3DbStrNDup(db, z, n)); } } @@ -126036,9 +141884,9 @@ static void addArgumentToVtab(Parse *pParse){ ** The parser calls this routine after the CREATE VIRTUAL TABLE statement ** has been completely parsed. */ -SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ +SQLITE_PRIVATE void tdsqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ Table *pTab = pParse->pNewTable; /* The table being constructed */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ if( pTab==0 ) return; addArgumentToVtab(pParse); @@ -126058,11 +141906,13 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ int iReg; Vdbe *v; + tdsqlite3MayAbort(pParse); + /* Compute the complete text of the CREATE VIRTUAL TABLE statement */ if( pEnd ){ pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n; } - zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken); + zStmt = tdsqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken); /* A slot for the record has already been allocated in the ** SQLITE_MASTER table. We just need to update that slot with all @@ -126070,30 +141920,30 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ ** ** The VM register number pParse->regRowid holds the rowid of an ** entry in the sqlite_master table tht was created for this vtab - ** by sqlite3StartTable(). + ** by tdsqlite3StartTable(). */ - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - sqlite3NestedParse(pParse, + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); + tdsqlite3NestedParse(pParse, "UPDATE %Q.%s " "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " "WHERE rowid=#%d", - db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), + db->aDb[iDb].zDbSName, MASTER_NAME, pTab->zName, pTab->zName, zStmt, pParse->regRowid ); - sqlite3DbFree(db, zStmt); - v = sqlite3GetVdbe(pParse); - sqlite3ChangeCookie(pParse, iDb); + v = tdsqlite3GetVdbe(pParse); + tdsqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddOp0(v, OP_Expire); - zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName); - sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); + tdsqlite3VdbeAddOp0(v, OP_Expire); + zWhere = tdsqlite3MPrintf(db, "name=%Q AND sql=%Q", pTab->zName, zStmt); + tdsqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); + tdsqlite3DbFree(db, zStmt); iReg = ++pParse->nMem; - sqlite3VdbeLoadString(v, iReg, pTab->zName); - sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg); + tdsqlite3VdbeLoadString(v, iReg, pTab->zName); + tdsqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg); } /* If we are rereading the sqlite_master table create the in-memory @@ -126105,10 +141955,10 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ Table *pOld; Schema *pSchema = pTab->pSchema; const char *zName = pTab->zName; - assert( sqlite3SchemaMutexHeld(db, 0, pSchema) ); - pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab); + assert( tdsqlite3SchemaMutexHeld(db, 0, pSchema) ); + pOld = tdsqlite3HashInsert(&pSchema->tblHash, zName, pTab); if( pOld ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */ return; } @@ -126120,7 +141970,7 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ ** The parser calls this routine when it sees the first token ** of an argument to the module name in a CREATE VIRTUAL TABLE statement. */ -SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){ +SQLITE_PRIVATE void tdsqlite3VtabArgInit(Parse *pParse){ addArgumentToVtab(pParse); pParse->sArg.z = 0; pParse->sArg.n = 0; @@ -126130,7 +141980,7 @@ SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){ ** The parser calls this routine for each token after the first token ** in an argument to the module name in a CREATE VIRTUAL TABLE statement. */ -SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){ +SQLITE_PRIVATE void tdsqlite3VtabArgExtend(Parse *pParse, Token *p){ Token *pArg = &pParse->sArg; if( pArg->z==0 ){ pArg->z = p->z; @@ -126147,10 +141997,10 @@ SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){ ** to this procedure. */ static int vtabCallConstructor( - sqlite3 *db, + tdsqlite3 *db, Table *pTab, Module *pMod, - int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**), + int (*xConstruct)(tdsqlite3*,void*,int,const char*const*,tdsqlite3_vtab**,char**), char **pzErr ){ VtabCtx sCtx; @@ -126166,27 +142016,29 @@ static int vtabCallConstructor( /* Check that the virtual-table is not already being initialized */ for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){ if( pCtx->pTab==pTab ){ - *pzErr = sqlite3MPrintf(db, + *pzErr = tdsqlite3MPrintf(db, "vtable constructor called recursively: %s", pTab->zName ); return SQLITE_LOCKED; } } - zModuleName = sqlite3MPrintf(db, "%s", pTab->zName); + zModuleName = tdsqlite3DbStrDup(db, pTab->zName); if( !zModuleName ){ return SQLITE_NOMEM_BKPT; } - pVTable = sqlite3DbMallocZero(db, sizeof(VTable)); + pVTable = tdsqlite3MallocZero(sizeof(VTable)); if( !pVTable ){ - sqlite3DbFree(db, zModuleName); + tdsqlite3OomFault(db); + tdsqlite3DbFree(db, zModuleName); return SQLITE_NOMEM_BKPT; } pVTable->db = db; pVTable->pMod = pMod; + pVTable->eVtabRisk = SQLITE_VTABRISK_Normal; - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); pTab->azModuleArg[1] = db->aDb[iDb].zDbSName; /* Invoke the virtual table constructor */ @@ -126199,31 +142051,32 @@ static int vtabCallConstructor( db->pVtabCtx = &sCtx; rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr); db->pVtabCtx = sCtx.pPrior; - if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); + if( rc==SQLITE_NOMEM ) tdsqlite3OomFault(db); assert( sCtx.pTab==pTab ); if( SQLITE_OK!=rc ){ if( zErr==0 ){ - *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName); + *pzErr = tdsqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName); }else { - *pzErr = sqlite3MPrintf(db, "%s", zErr); - sqlite3_free(zErr); + *pzErr = tdsqlite3MPrintf(db, "%s", zErr); + tdsqlite3_free(zErr); } - sqlite3DbFree(db, pVTable); + tdsqlite3DbFree(db, pVTable); }else if( ALWAYS(pVTable->pVtab) ){ /* Justification of ALWAYS(): A correct vtab constructor must allocate - ** the sqlite3_vtab object if successful. */ + ** the tdsqlite3_vtab object if successful. */ memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0])); pVTable->pVtab->pModule = pMod->pModule; + pMod->nRefModule++; pVTable->nRef = 1; if( sCtx.bDeclared==0 ){ const char *zFormat = "vtable constructor did not declare schema: %s"; - *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName); - sqlite3VtabUnlock(pVTable); + *pzErr = tdsqlite3MPrintf(db, zFormat, pTab->zName); + tdsqlite3VtabUnlock(pVTable); rc = SQLITE_ERROR; }else{ int iCol; - u8 oooHidden = 0; + u16 oooHidden = 0; /* If everything went according to plan, link the new VTable structure ** into the linked list headed by pTab->pVTable. Then loop through the ** columns of the table to see if any of them contain the token "hidden". @@ -126233,12 +142086,12 @@ static int vtabCallConstructor( pTab->pVTable = pVTable; for(iCol=0; iCol<pTab->nCol; iCol++){ - char *zType = sqlite3ColumnType(&pTab->aCol[iCol], ""); + char *zType = tdsqlite3ColumnType(&pTab->aCol[iCol], ""); int nType; int i = 0; - nType = sqlite3Strlen30(zType); + nType = tdsqlite3Strlen30(zType); for(i=0; i<nType; i++){ - if( 0==sqlite3StrNICmp("hidden", &zType[i], 6) + if( 0==tdsqlite3StrNICmp("hidden", &zType[i], 6) && (i==0 || zType[i-1]==' ') && (zType[i+6]=='\0' || zType[i+6]==' ') ){ @@ -126264,7 +142117,7 @@ static int vtabCallConstructor( } } - sqlite3DbFree(db, zModuleName); + tdsqlite3DbFree(db, zModuleName); return rc; } @@ -126275,32 +142128,33 @@ static int vtabCallConstructor( ** ** This call is a no-op if table pTab is not a virtual table. */ -SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){ - sqlite3 *db = pParse->db; +SQLITE_PRIVATE int tdsqlite3VtabCallConnect(Parse *pParse, Table *pTab){ + tdsqlite3 *db = pParse->db; const char *zMod; Module *pMod; int rc; assert( pTab ); - if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){ + if( !IsVirtual(pTab) || tdsqlite3GetVTable(db, pTab) ){ return SQLITE_OK; } /* Locate the required virtual table module */ zMod = pTab->azModuleArg[0]; - pMod = (Module*)sqlite3HashFind(&db->aModule, zMod); + pMod = (Module*)tdsqlite3HashFind(&db->aModule, zMod); if( !pMod ){ const char *zModule = pTab->azModuleArg[0]; - sqlite3ErrorMsg(pParse, "no such module: %s", zModule); + tdsqlite3ErrorMsg(pParse, "no such module: %s", zModule); rc = SQLITE_ERROR; }else{ char *zErr = 0; rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr); if( rc!=SQLITE_OK ){ - sqlite3ErrorMsg(pParse, "%s", zErr); + tdsqlite3ErrorMsg(pParse, "%s", zErr); + pParse->rc = rc; } - sqlite3DbFree(db, zErr); + tdsqlite3DbFree(db, zErr); } return rc; @@ -126309,18 +142163,19 @@ SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){ ** Grow the db->aVTrans[] array so that there is room for at least one ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise. */ -static int growVTrans(sqlite3 *db){ +static int growVTrans(tdsqlite3 *db){ const int ARRAY_INCR = 5; /* Grow the sqlite3.aVTrans array if required */ if( (db->nVTrans%ARRAY_INCR)==0 ){ VTable **aVTrans; - int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR); - aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes); + tdsqlite3_int64 nBytes = sizeof(tdsqlite3_vtab*)* + ((tdsqlite3_int64)db->nVTrans + ARRAY_INCR); + aVTrans = tdsqlite3DbRealloc(db, (void *)db->aVTrans, nBytes); if( !aVTrans ){ return SQLITE_NOMEM_BKPT; } - memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR); + memset(&aVTrans[db->nVTrans], 0, sizeof(tdsqlite3_vtab *)*ARRAY_INCR); db->aVTrans = aVTrans; } @@ -126331,10 +142186,10 @@ static int growVTrans(sqlite3 *db){ ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should ** have already been reserved using growVTrans(). */ -static void addToVTrans(sqlite3 *db, VTable *pVTab){ +static void addToVTrans(tdsqlite3 *db, VTable *pVTab){ /* Add pVtab to the end of sqlite3.aVTrans */ db->aVTrans[db->nVTrans++] = pVTab; - sqlite3VtabLock(pVTab); + tdsqlite3VtabLock(pVTab); } /* @@ -126343,38 +142198,38 @@ static void addToVTrans(sqlite3 *db, VTable *pVTab){ ** ** If an error occurs, *pzErr is set to point to an English language ** description of the error and an SQLITE_XXX error code is returned. -** In this case the caller must call sqlite3DbFree(db, ) on *pzErr. +** In this case the caller must call tdsqlite3DbFree(db, ) on *pzErr. */ -SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){ +SQLITE_PRIVATE int tdsqlite3VtabCallCreate(tdsqlite3 *db, int iDb, const char *zTab, char **pzErr){ int rc = SQLITE_OK; Table *pTab; Module *pMod; const char *zMod; - pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); - assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable ); + pTab = tdsqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); + assert( pTab && IsVirtual(pTab) && !pTab->pVTable ); /* Locate the required virtual table module */ zMod = pTab->azModuleArg[0]; - pMod = (Module*)sqlite3HashFind(&db->aModule, zMod); + pMod = (Module*)tdsqlite3HashFind(&db->aModule, zMod); /* If the module has been registered and includes a Create method, ** invoke it now. If the module has not been registered, return an ** error. Otherwise, do nothing. */ if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){ - *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod); + *pzErr = tdsqlite3MPrintf(db, "no such module: %s", zMod); rc = SQLITE_ERROR; }else{ rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr); } /* Justification of ALWAYS(): The xConstructor method is required to - ** create a valid sqlite3_vtab if it returns SQLITE_OK. */ - if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){ + ** create a valid tdsqlite3_vtab if it returns SQLITE_OK. */ + if( rc==SQLITE_OK && ALWAYS(tdsqlite3GetVTable(db, pTab)) ){ rc = growVTrans(db); if( rc==SQLITE_OK ){ - addToVTrans(db, sqlite3GetVTable(db, pTab)); + addToVTrans(db, tdsqlite3GetVTable(db, pTab)); } } @@ -126386,81 +142241,81 @@ SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, ** valid to call this function from within the xCreate() or xConnect() of a ** virtual table module. */ -SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){ +SQLITE_API int tdsqlite3_declare_vtab(tdsqlite3 *db, const char *zCreateTable){ VtabCtx *pCtx; - Parse *pParse; int rc = SQLITE_OK; Table *pTab; char *zErr = 0; + Parse sParse; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){ + if( !tdsqlite3SafetyCheckOk(db) || zCreateTable==0 ){ return SQLITE_MISUSE_BKPT; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); pCtx = db->pVtabCtx; if( !pCtx || pCtx->bDeclared ){ - sqlite3Error(db, SQLITE_MISUSE); - sqlite3_mutex_leave(db->mutex); + tdsqlite3Error(db, SQLITE_MISUSE); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_MISUSE_BKPT; } pTab = pCtx->pTab; - assert( (pTab->tabFlags & TF_Virtual)!=0 ); + assert( IsVirtual(pTab) ); - pParse = sqlite3StackAllocZero(db, sizeof(*pParse)); - if( pParse==0 ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - pParse->declareVtab = 1; - pParse->db = db; - pParse->nQueryLoop = 1; - - if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) - && pParse->pNewTable - && !db->mallocFailed - && !pParse->pNewTable->pSelect - && (pParse->pNewTable->tabFlags & TF_Virtual)==0 - ){ - if( !pTab->aCol ){ - Table *pNew = pParse->pNewTable; - Index *pIdx; - pTab->aCol = pNew->aCol; - pTab->nCol = pNew->nCol; - pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid); - pNew->nCol = 0; - pNew->aCol = 0; - assert( pTab->pIndex==0 ); - if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){ - rc = SQLITE_ERROR; - } - pIdx = pNew->pIndex; - if( pIdx ){ - assert( pIdx->pNext==0 ); - pTab->pIndex = pIdx; - pNew->pIndex = 0; - pIdx->pTable = pTab; - } + memset(&sParse, 0, sizeof(sParse)); + sParse.eParseMode = PARSE_MODE_DECLARE_VTAB; + sParse.db = db; + sParse.nQueryLoop = 1; + if( SQLITE_OK==tdsqlite3RunParser(&sParse, zCreateTable, &zErr) + && sParse.pNewTable + && !db->mallocFailed + && !sParse.pNewTable->pSelect + && !IsVirtual(sParse.pNewTable) + ){ + if( !pTab->aCol ){ + Table *pNew = sParse.pNewTable; + Index *pIdx; + pTab->aCol = pNew->aCol; + pTab->nCol = pNew->nCol; + pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid); + pNew->nCol = 0; + pNew->aCol = 0; + assert( pTab->pIndex==0 ); + assert( HasRowid(pNew) || tdsqlite3PrimaryKeyIndex(pNew)!=0 ); + if( !HasRowid(pNew) + && pCtx->pVTable->pMod->pModule->xUpdate!=0 + && tdsqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1 + ){ + /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0) + ** or else must have a single-column PRIMARY KEY */ + rc = SQLITE_ERROR; + } + pIdx = pNew->pIndex; + if( pIdx ){ + assert( pIdx->pNext==0 ); + pTab->pIndex = pIdx; + pNew->pIndex = 0; + pIdx->pTable = pTab; } - pCtx->bDeclared = 1; - }else{ - sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr); - sqlite3DbFree(db, zErr); - rc = SQLITE_ERROR; - } - pParse->declareVtab = 0; - - if( pParse->pVdbe ){ - sqlite3VdbeFinalize(pParse->pVdbe); } - sqlite3DeleteTable(db, pParse->pNewTable); - sqlite3ParserReset(pParse); - sqlite3StackFree(db, pParse); + pCtx->bDeclared = 1; + }else{ + tdsqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr); + tdsqlite3DbFree(db, zErr); + rc = SQLITE_ERROR; + } + sParse.eParseMode = PARSE_MODE_NORMAL; + + if( sParse.pVdbe ){ + tdsqlite3VdbeFinalize(sParse.pVdbe); } + tdsqlite3DeleteTable(db, sParse.pNewTable); + tdsqlite3ParserReset(&sParse); assert( (rc&0xff)==rc ); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -126471,14 +142326,14 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){ ** ** This call is a no-op if zTab is not a virtual table. */ -SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){ +SQLITE_PRIVATE int tdsqlite3VtabCallDestroy(tdsqlite3 *db, int iDb, const char *zTab){ int rc = SQLITE_OK; Table *pTab; - pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); + pTab = tdsqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){ VTable *p; - int (*xDestroy)(sqlite3_vtab *); + int (*xDestroy)(tdsqlite3_vtab *); for(p=pTab->pVTable; p; p=p->pNext){ assert( p->pVtab ); if( p->pVtab->nRef>0 ){ @@ -126487,15 +142342,18 @@ SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab } p = vtabDisconnectAll(db, pTab); xDestroy = p->pMod->pModule->xDestroy; - assert( xDestroy!=0 ); /* Checked before the virtual table is created */ + if( xDestroy==0 ) xDestroy = p->pMod->pModule->xDisconnect; + assert( xDestroy!=0 ); + pTab->nTabRef++; rc = xDestroy(p->pVtab); - /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */ + /* Remove the tdsqlite3_vtab* from the aVTrans[] array, if applicable */ if( rc==SQLITE_OK ){ assert( pTab->pVTable==p && p->pNext==0 ); p->pVtab = 0; pTab->pVTable = 0; - sqlite3VtabUnlock(p); + tdsqlite3VtabUnlock(p); } + tdsqlite3DeleteTable(db, pTab); } return rc; @@ -126505,27 +142363,27 @@ SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab ** This function invokes either the xRollback or xCommit method ** of each of the virtual tables in the sqlite3.aVTrans array. The method ** called is identified by the second argument, "offset", which is -** the offset of the method to call in the sqlite3_module structure. +** the offset of the method to call in the tdsqlite3_module structure. ** ** The array is cleared after invoking the callbacks. */ -static void callFinaliser(sqlite3 *db, int offset){ +static void callFinaliser(tdsqlite3 *db, int offset){ int i; if( db->aVTrans ){ VTable **aVTrans = db->aVTrans; db->aVTrans = 0; for(i=0; i<db->nVTrans; i++){ VTable *pVTab = aVTrans[i]; - sqlite3_vtab *p = pVTab->pVtab; + tdsqlite3_vtab *p = pVTab->pVtab; if( p ){ - int (*x)(sqlite3_vtab *); - x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset); + int (*x)(tdsqlite3_vtab *); + x = *(int (**)(tdsqlite3_vtab *))((char *)p->pModule + offset); if( x ) x(p); } pVTab->iSavepoint = 0; - sqlite3VtabUnlock(pVTab); + tdsqlite3VtabUnlock(pVTab); } - sqlite3DbFree(db, aVTrans); + tdsqlite3DbFree(db, aVTrans); db->nVTrans = 0; } } @@ -126537,18 +142395,18 @@ static void callFinaliser(sqlite3 *db, int offset){ ** ** If an error message is available, leave it in p->zErrMsg. */ -SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){ +SQLITE_PRIVATE int tdsqlite3VtabSync(tdsqlite3 *db, Vdbe *p){ int i; int rc = SQLITE_OK; VTable **aVTrans = db->aVTrans; db->aVTrans = 0; for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){ - int (*x)(sqlite3_vtab *); - sqlite3_vtab *pVtab = aVTrans[i]->pVtab; + int (*x)(tdsqlite3_vtab *); + tdsqlite3_vtab *pVtab = aVTrans[i]->pVtab; if( pVtab && (x = pVtab->pModule->xSync)!=0 ){ rc = x(pVtab); - sqlite3VtabImportErrmsg(p, pVtab); + tdsqlite3VtabImportErrmsg(p, pVtab); } } db->aVTrans = aVTrans; @@ -126559,8 +142417,8 @@ SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){ ** Invoke the xRollback method of all virtual tables in the ** sqlite3.aVTrans array. Then clear the array itself. */ -SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){ - callFinaliser(db, offsetof(sqlite3_module,xRollback)); +SQLITE_PRIVATE int tdsqlite3VtabRollback(tdsqlite3 *db){ + callFinaliser(db, offsetof(tdsqlite3_module,xRollback)); return SQLITE_OK; } @@ -126568,8 +142426,8 @@ SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){ ** Invoke the xCommit method of all virtual tables in the ** sqlite3.aVTrans array. Then clear the array itself. */ -SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){ - callFinaliser(db, offsetof(sqlite3_module,xCommit)); +SQLITE_PRIVATE int tdsqlite3VtabCommit(tdsqlite3 *db){ + callFinaliser(db, offsetof(tdsqlite3_module,xCommit)); return SQLITE_OK; } @@ -126578,19 +142436,19 @@ SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){ ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is ** not currently open, invoke the xBegin method now. ** -** If the xBegin call is successful, place the sqlite3_vtab pointer +** If the xBegin call is successful, place the tdsqlite3_vtab pointer ** in the sqlite3.aVTrans array. */ -SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){ +SQLITE_PRIVATE int tdsqlite3VtabBegin(tdsqlite3 *db, VTable *pVTab){ int rc = SQLITE_OK; - const sqlite3_module *pModule; + const tdsqlite3_module *pModule; /* Special case: If db->aVTrans is NULL and db->nVTrans is greater ** than zero, then this function is being called from within a ** virtual module xSync() callback. It is illegal to write to ** virtual module tables in this case, so return SQLITE_LOCKED. */ - if( sqlite3VtabInSync(db) ){ + if( tdsqlite3VtabInSync(db) ){ return SQLITE_LOCKED; } if( !pVTab ){ @@ -126641,7 +142499,7 @@ SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){ ** function immediately. If all calls to virtual table methods are successful, ** SQLITE_OK is returned. */ -SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){ +SQLITE_PRIVATE int tdsqlite3VtabSavepoint(tdsqlite3 *db, int op, int iSavepoint){ int rc = SQLITE_OK; assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN ); @@ -126650,9 +142508,10 @@ SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){ int i; for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){ VTable *pVTab = db->aVTrans[i]; - const sqlite3_module *pMod = pVTab->pMod->pModule; + const tdsqlite3_module *pMod = pVTab->pMod->pModule; if( pVTab->pVtab && pMod->iVersion>=2 ){ - int (*xMethod)(sqlite3_vtab *, int); + int (*xMethod)(tdsqlite3_vtab *, int); + tdsqlite3VtabLock(pVTab); switch( op ){ case SAVEPOINT_BEGIN: xMethod = pMod->xSavepoint; @@ -126668,6 +142527,7 @@ SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){ if( xMethod && pVTab->iSavepoint>iSavepoint ){ rc = xMethod(pVTab->pVtab, iSavepoint); } + tdsqlite3VtabUnlock(pVTab); } } } @@ -126687,60 +142547,63 @@ SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){ ** new FuncDef structure that is marked as ephemeral using the ** SQLITE_FUNC_EPHEM flag. */ -SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction( - sqlite3 *db, /* Database connection for reporting malloc problems */ +SQLITE_PRIVATE FuncDef *tdsqlite3VtabOverloadFunction( + tdsqlite3 *db, /* Database connection for reporting malloc problems */ FuncDef *pDef, /* Function to possibly overload */ int nArg, /* Number of arguments to the function */ Expr *pExpr /* First argument to the function */ ){ Table *pTab; - sqlite3_vtab *pVtab; - sqlite3_module *pMod; - void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0; + tdsqlite3_vtab *pVtab; + tdsqlite3_module *pMod; + void (*xSFunc)(tdsqlite3_context*,int,tdsqlite3_value**) = 0; void *pArg = 0; FuncDef *pNew; int rc = 0; - char *zLowerName; - unsigned char *z; - /* Check to see the left operand is a column in a virtual table */ if( NEVER(pExpr==0) ) return pDef; if( pExpr->op!=TK_COLUMN ) return pDef; - pTab = pExpr->pTab; - if( NEVER(pTab==0) ) return pDef; - if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef; - pVtab = sqlite3GetVTable(db, pTab)->pVtab; + pTab = pExpr->y.pTab; + if( pTab==0 ) return pDef; + if( !IsVirtual(pTab) ) return pDef; + pVtab = tdsqlite3GetVTable(db, pTab)->pVtab; assert( pVtab!=0 ); assert( pVtab->pModule!=0 ); - pMod = (sqlite3_module *)pVtab->pModule; + pMod = (tdsqlite3_module *)pVtab->pModule; if( pMod->xFindFunction==0 ) return pDef; /* Call the xFindFunction method on the virtual table implementation - ** to see if the implementation wants to overload this function + ** to see if the implementation wants to overload this function. + ** + ** Though undocumented, we have historically always invoked xFindFunction + ** with an all lower-case function name. Continue in this tradition to + ** avoid any chance of an incompatibility. */ - zLowerName = sqlite3DbStrDup(db, pDef->zName); - if( zLowerName ){ - for(z=(unsigned char*)zLowerName; *z; z++){ - *z = sqlite3UpperToLower[*z]; +#ifdef SQLITE_DEBUG + { + int i; + for(i=0; pDef->zName[i]; i++){ + unsigned char x = (unsigned char)pDef->zName[i]; + assert( x==tdsqlite3UpperToLower[x] ); } - rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg); - sqlite3DbFree(db, zLowerName); } +#endif + rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg); if( rc==0 ){ return pDef; } /* Create a new ephemeral function definition for the overloaded ** function */ - pNew = sqlite3DbMallocZero(db, sizeof(*pNew) - + sqlite3Strlen30(pDef->zName) + 1); + pNew = tdsqlite3DbMallocZero(db, sizeof(*pNew) + + tdsqlite3Strlen30(pDef->zName) + 1); if( pNew==0 ){ return pDef; } *pNew = *pDef; pNew->zName = (const char*)&pNew[1]; - memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1); + memcpy((char*)&pNew[1], pDef->zName, tdsqlite3Strlen30(pDef->zName)+1); pNew->xSFunc = xSFunc; pNew->pUserData = pArg; pNew->funcFlags |= SQLITE_FUNC_EPHEM; @@ -126753,8 +142616,8 @@ SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction( ** array if it is missing. If pTab is already in the array, this routine ** is a no-op. */ -SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); +SQLITE_PRIVATE void tdsqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ + Parse *pToplevel = tdsqlite3ParseToplevel(pParse); int i, n; Table **apVtabLock; @@ -126763,12 +142626,12 @@ SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ if( pTab==pToplevel->apVtabLock[i] ) return; } n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]); - apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n); + apVtabLock = tdsqlite3_realloc64(pToplevel->apVtabLock, n); if( apVtabLock ){ pToplevel->apVtabLock = apVtabLock; pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab; }else{ - sqlite3OomFault(pToplevel->db); + tdsqlite3OomFault(pToplevel->db); } } @@ -126786,35 +142649,34 @@ SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ ** Any virtual table module for which xConnect and xCreate are the same ** method can have an eponymous virtual table instance. */ -SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){ - const sqlite3_module *pModule = pMod->pModule; +SQLITE_PRIVATE int tdsqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){ + const tdsqlite3_module *pModule = pMod->pModule; Table *pTab; char *zErr = 0; int rc; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; if( pMod->pEpoTab ) return 1; if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0; - pTab = sqlite3DbMallocZero(db, sizeof(Table)); + pTab = tdsqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ) return 0; - pTab->zName = sqlite3DbStrDup(db, pMod->zName); + pTab->zName = tdsqlite3DbStrDup(db, pMod->zName); if( pTab->zName==0 ){ - sqlite3DbFree(db, pTab); + tdsqlite3DbFree(db, pTab); return 0; } pMod->pEpoTab = pTab; - pTab->nRef = 1; + pTab->nTabRef = 1; pTab->pSchema = db->aDb[0].pSchema; - pTab->tabFlags |= TF_Virtual; - pTab->nModuleArg = 0; + assert( pTab->nModuleArg==0 ); pTab->iPKey = -1; - addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName)); - addModuleArgument(db, pTab, 0); - addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName)); + addModuleArgument(pParse, pTab, tdsqlite3DbStrDup(db, pTab->zName)); + addModuleArgument(pParse, pTab, 0); + addModuleArgument(pParse, pTab, tdsqlite3DbStrDup(db, pTab->zName)); rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr); if( rc ){ - sqlite3ErrorMsg(pParse, "%s", zErr); - sqlite3DbFree(db, zErr); - sqlite3VtabEponymousTableClear(db, pMod); + tdsqlite3ErrorMsg(pParse, "%s", zErr); + tdsqlite3DbFree(db, zErr); + tdsqlite3VtabEponymousTableClear(db, pMod); return 0; } return 1; @@ -126824,14 +142686,14 @@ SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){ ** Erase the eponymous virtual table instance associated with ** virtual table module pMod, if it exists. */ -SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){ +SQLITE_PRIVATE void tdsqlite3VtabEponymousTableClear(tdsqlite3 *db, Module *pMod){ Table *pTab = pMod->pEpoTab; if( pTab!=0 ){ /* Mark the table as Ephemeral prior to deleting it, so that the - ** sqlite3DeleteTable() routine will know that it is not stored in + ** tdsqlite3DeleteTable() routine will know that it is not stored in ** the schema. */ pTab->tabFlags |= TF_Ephemeral; - sqlite3DeleteTable(db, pTab); + tdsqlite3DeleteTable(db, pTab); pMod->pEpoTab = 0; } } @@ -126843,12 +142705,12 @@ SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){ ** The results of this routine are undefined unless it is called from ** within an xUpdate method. */ -SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){ +SQLITE_API int tdsqlite3_vtab_on_conflict(tdsqlite3 *db){ static const unsigned char aMap[] = { SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE }; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 ); assert( OE_Ignore==4 && OE_Replace==5 ); @@ -126861,34 +142723,44 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){ ** the SQLite core with additional information about the behavior ** of the virtual table being implemented. */ -SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){ +SQLITE_API int tdsqlite3_vtab_config(tdsqlite3 *db, int op, ...){ va_list ap; int rc = SQLITE_OK; + VtabCtx *p; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); - va_start(ap, op); - switch( op ){ - case SQLITE_VTAB_CONSTRAINT_SUPPORT: { - VtabCtx *p = db->pVtabCtx; - if( !p ){ - rc = SQLITE_MISUSE_BKPT; - }else{ - assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 ); + tdsqlite3_mutex_enter(db->mutex); + p = db->pVtabCtx; + if( !p ){ + rc = SQLITE_MISUSE_BKPT; + }else{ + assert( p->pTab==0 || IsVirtual(p->pTab) ); + va_start(ap, op); + switch( op ){ + case SQLITE_VTAB_CONSTRAINT_SUPPORT: { p->pVTable->bConstraint = (u8)va_arg(ap, int); + break; + } + case SQLITE_VTAB_INNOCUOUS: { + p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low; + break; + } + case SQLITE_VTAB_DIRECTONLY: { + p->pVTable->eVtabRisk = SQLITE_VTABRISK_High; + break; + } + default: { + rc = SQLITE_MISUSE_BKPT; + break; } - break; } - default: - rc = SQLITE_MISUSE_BKPT; - break; + va_end(ap); } - va_end(ap); - if( rc!=SQLITE_OK ) sqlite3Error(db, rc); - sqlite3_mutex_leave(db->mutex); + if( rc!=SQLITE_OK ) tdsqlite3Error(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -126934,16 +142806,18 @@ SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){ ** planner logic in "where.c". These definitions are broken out into ** a separate source file for easier editing. */ +#ifndef SQLITE_WHEREINT_H +#define SQLITE_WHEREINT_H /* ** Trace output macros */ #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) -/***/ int sqlite3WhereTrace; +/***/ extern int tdsqlite3WhereTrace; #endif #if defined(SQLITE_DEBUG) \ && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE)) -# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X +# define WHERETRACE(K,X) if(tdsqlite3WhereTrace&(K)) tdsqlite3DebugPrintf X # define WHERETRACE_ENABLED 1 #else # define WHERETRACE(K,X) @@ -126989,19 +142863,23 @@ struct WhereLevel { int addrCont; /* Jump here to continue with the next loop cycle */ int addrFirst; /* First instruction of interior of the loop */ int addrBody; /* Beginning of the body of this loop */ + int regBignull; /* big-null flag reg. True if a NULL-scan is needed */ + int addrBignull; /* Jump here for next part of big-null scan */ #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */ int addrLikeRep; /* LIKE range processing address */ #endif u8 iFrom; /* Which entry in the FROM clause */ u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */ - int p1, p2; /* Operands of the opcode used to ends the loop */ + int p1, p2; /* Operands of the opcode used to end the loop */ union { /* Information that depends on pWLoop->wsFlags */ struct { int nIn; /* Number of entries in aInLoop[] */ struct InLoop { int iCur; /* The VDBE cursor used by this IN operator */ int addrInTop; /* Top of the IN loop */ + int iBase; /* Base register of multi-key index record */ + int nPrefix; /* Number of prior entires in the key */ u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */ } *aInLoop; /* Information about each nested IN operator */ } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */ @@ -127044,11 +142922,12 @@ struct WhereLoop { u16 nEq; /* Number of equality constraints */ u16 nBtm; /* Size of BTM vector */ u16 nTop; /* Size of TOP vector */ + u16 nDistinctCol; /* Index columns used to sort for DISTINCT */ Index *pIndex; /* Index used, or NULL */ } btree; struct { /* Information for virtual tables */ int idxNum; /* Index number */ - u8 needFree; /* True if sqlite3_free(idxStr) is needed */ + u8 needFree; /* True if tdsqlite3_free(idxStr) is needed */ i8 isOrdered; /* True if satisfies ORDER BY */ u16 omitMask; /* Terms that may be omitted */ char *idxStr; /* Index identifier string */ @@ -127187,22 +143066,23 @@ struct WhereTerm { /* ** Allowed values of WhereTerm.wtFlags */ -#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */ -#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */ -#define TERM_CODED 0x04 /* This term is already coded */ -#define TERM_COPIED 0x08 /* Has a child */ -#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */ -#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */ -#define TERM_OR_OK 0x40 /* Used during OR-clause processing */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 -# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */ +#define TERM_DYNAMIC 0x0001 /* Need to call tdsqlite3ExprDelete(db, pExpr) */ +#define TERM_VIRTUAL 0x0002 /* Added by the optimizer. Do not code */ +#define TERM_CODED 0x0004 /* This term is already coded */ +#define TERM_COPIED 0x0008 /* Has a child */ +#define TERM_ORINFO 0x0010 /* Need to free the WhereTerm.u.pOrInfo object */ +#define TERM_ANDINFO 0x0020 /* Need to free the WhereTerm.u.pAndInfo obj */ +#define TERM_OR_OK 0x0040 /* Used during OR-clause processing */ +#ifdef SQLITE_ENABLE_STAT4 +# define TERM_VNULL 0x0080 /* Manufactured x>NULL or x<=NULL term */ #else -# define TERM_VNULL 0x00 /* Disabled if not using stat3 */ +# define TERM_VNULL 0x0000 /* Disabled if not using stat4 */ #endif -#define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */ -#define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */ -#define TERM_LIKE 0x400 /* The original LIKE operator */ -#define TERM_IS 0x800 /* Term.pExpr is an IS operator */ +#define TERM_LIKEOPT 0x0100 /* Virtual terms from the LIKE optimization */ +#define TERM_LIKECOND 0x0200 /* Conditionally this LIKE operator term */ +#define TERM_LIKE 0x0400 /* The original LIKE operator */ +#define TERM_IS 0x0800 /* Term.pExpr is an IS operator */ +#define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */ /* ** An instance of the WhereScan object is used as an iterator for locating @@ -127238,6 +143118,7 @@ struct WhereClause { WhereInfo *pWInfo; /* WHERE clause processing context */ WhereClause *pOuter; /* Outer conjunction */ u8 op; /* Split operator. TK_AND or TK_OR */ + u8 hasOr; /* True if any a[].eOperator is WO_OR */ int nTerm; /* Number of terms */ int nSlot; /* Number of entries in a[] */ WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */ @@ -127292,6 +143173,7 @@ struct WhereAndInfo { ** no gaps. */ struct WhereMaskSet { + int bVarSelect; /* Used by tdsqlite3WhereExprUsage() */ int n; /* Number of assigned cursor values */ int ix[BMS]; /* Cursor assigned to each bit */ }; @@ -127311,10 +143193,50 @@ struct WhereLoopBuilder { ExprList *pOrderBy; /* ORDER BY clause */ WhereLoop *pNew; /* Template WhereLoop */ WhereOrSet *pOrSet; /* Record best loops here, if not NULL */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 UnpackedRecord *pRec; /* Probe for stat4 (if required) */ int nRecValid; /* Number of valid fields currently in pRec */ #endif + unsigned int bldFlags; /* SQLITE_BLDF_* flags */ + unsigned int iPlanLimit; /* Search limiter */ +}; + +/* Allowed values for WhereLoopBuider.bldFlags */ +#define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */ +#define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */ + +/* The WhereLoopBuilder.iPlanLimit is used to limit the number of +** index+constraint combinations the query planner will consider for a +** particular query. If this parameter is unlimited, then certain +** pathological queries can spend excess time in the tdsqlite3WhereBegin() +** routine. The limit is high enough that is should not impact real-world +** queries. +** +** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit. The limit is +** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM +** clause is processed, so that every table in a join is guaranteed to be +** able to propose a some index+constraint combinations even if the initial +** baseline limit was exhausted by prior tables of the join. +*/ +#ifndef SQLITE_QUERY_PLANNER_LIMIT +# define SQLITE_QUERY_PLANNER_LIMIT 20000 +#endif +#ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR +# define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000 +#endif + +/* +** Each instance of this object records a change to a single node +** in an expression tree to cause that node to point to a column +** of an index rather than an expression or a virtual column. All +** such transformations need to be undone at the end of WHERE clause +** processing. +*/ +typedef struct WhereExprMod WhereExprMod; +struct WhereExprMod { + WhereExprMod *pNext; /* Next translation on a list of them all */ + Expr *pExpr; /* The Expr node that was transformed */ + Expr orig; /* Original value of the Expr node */ }; /* @@ -127331,24 +143253,27 @@ struct WhereInfo { Parse *pParse; /* Parsing and code generating context */ SrcList *pTabList; /* List of tables in the join */ ExprList *pOrderBy; /* The ORDER BY clause or NULL */ - ExprList *pDistinctSet; /* DISTINCT over all these values */ - LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */ + ExprList *pResultSet; /* Result set of the query */ + Expr *pWhere; /* The complete WHERE clause */ int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */ int iContinue; /* Jump here to continue with next record */ int iBreak; /* Jump here to break out of the loop */ int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */ - u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */ + u16 wctrlFlags; /* Flags originally passed to tdsqlite3WhereBegin() */ + LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */ u8 nLevel; /* Number of nested loop */ i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */ - u8 sorted; /* True if really sorted (not just grouped) */ u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */ - u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */ u8 eDistinct; /* One of the WHERE_DISTINCT_* values */ - u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */ + unsigned bDeferredSeek :1; /* Uses OP_DeferredSeek */ + unsigned untestedTerms :1; /* Not all WHERE terms resolved by outer loop */ + unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */ + unsigned sorted :1; /* True if really sorted (not just grouped) */ + LogEst nRowOut; /* Estimated number of output rows */ int iTop; /* The very beginning of the WHERE loop */ WhereLoop *pLoops; /* List of all WhereLoop objects */ + WhereExprMod *pExprMods; /* Expression modifications */ Bitmask revMask; /* Mask of ORDER BY terms that need reversing */ - LogEst nRowOut; /* Estimated number of output rows */ WhereClause sWC; /* Decomposition of the WHERE clause */ WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */ WhereLevel a[1]; /* Information about each nest loop in WHERE */ @@ -127359,11 +143284,13 @@ struct WhereInfo { ** ** where.c: */ -SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int); +SQLITE_PRIVATE Bitmask tdsqlite3WhereGetMask(WhereMaskSet*,int); #ifdef WHERETRACE_ENABLED -SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC); +SQLITE_PRIVATE void tdsqlite3WhereClausePrint(WhereClause *pWC); +SQLITE_PRIVATE void tdsqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm); +SQLITE_PRIVATE void tdsqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC); #endif -SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( +SQLITE_PRIVATE WhereTerm *tdsqlite3WhereFindTerm( WhereClause *pWC, /* The WHERE clause to be searched */ int iCur, /* Cursor number of LHS */ int iColumn, /* Column number of LHS */ @@ -127374,41 +143301,43 @@ SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( /* wherecode.c: */ #ifndef SQLITE_OMIT_EXPLAIN -SQLITE_PRIVATE int sqlite3WhereExplainOneScan( +SQLITE_PRIVATE int tdsqlite3WhereExplainOneScan( Parse *pParse, /* Parse context */ SrcList *pTabList, /* Table list this loop refers to */ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ - int iLevel, /* Value for "level" column of output */ - int iFrom, /* Value for "from" column of output */ - u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ + u16 wctrlFlags /* Flags passed to tdsqlite3WhereBegin() */ ); #else -# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0 +# define tdsqlite3WhereExplainOneScan(u,v,w,x) 0 #endif /* SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS -SQLITE_PRIVATE void sqlite3WhereAddScanStatus( +SQLITE_PRIVATE void tdsqlite3WhereAddScanStatus( Vdbe *v, /* Vdbe to add scanstatus entry to */ SrcList *pSrclist, /* FROM clause pLvl reads data from */ WhereLevel *pLvl, /* Level to add scanstatus() entry for */ int addrExplain /* Address of OP_Explain (or 0) */ ); #else -# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d) +# define tdsqlite3WhereAddScanStatus(a, b, c, d) ((void)d) #endif -SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( +SQLITE_PRIVATE Bitmask tdsqlite3WhereCodeOneLoopStart( + Parse *pParse, /* Parsing context */ + Vdbe *v, /* Prepared statement under construction */ WhereInfo *pWInfo, /* Complete information about the WHERE clause */ int iLevel, /* Which level of pWInfo->a[] should be coded */ + WhereLevel *pLevel, /* The current level pointer */ Bitmask notReady /* Which tables are currently available */ ); /* whereexpr.c: */ -SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*); -SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*); -SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8); -SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*); -SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*); -SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*); -SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*); +SQLITE_PRIVATE void tdsqlite3WhereClauseInit(WhereClause*,WhereInfo*); +SQLITE_PRIVATE void tdsqlite3WhereClauseClear(WhereClause*); +SQLITE_PRIVATE void tdsqlite3WhereSplit(WhereClause*,Expr*,u8); +SQLITE_PRIVATE Bitmask tdsqlite3WhereExprUsage(WhereMaskSet*, Expr*); +SQLITE_PRIVATE Bitmask tdsqlite3WhereExprUsageNN(WhereMaskSet*, Expr*); +SQLITE_PRIVATE Bitmask tdsqlite3WhereExprListUsage(WhereMaskSet*, ExprList*); +SQLITE_PRIVATE void tdsqlite3WhereExprAnalyze(SrcList*, WhereClause*); +SQLITE_PRIVATE void tdsqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*); @@ -127426,7 +143355,6 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereC ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE -** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH */ #define WO_IN 0x0001 #define WO_EQ 0x0002 @@ -127434,7 +143362,7 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereC #define WO_LE (WO_EQ<<(TK_LE-TK_EQ)) #define WO_GT (WO_EQ<<(TK_GT-TK_EQ)) #define WO_GE (WO_EQ<<(TK_GE-TK_EQ)) -#define WO_MATCH 0x0040 +#define WO_AUX 0x0040 /* Op useful to virtual tables only */ #define WO_IS 0x0080 #define WO_ISNULL 0x0100 #define WO_OR 0x0200 /* Two or more OR-connected terms */ @@ -127469,6 +143397,10 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereC #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */ #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/ #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */ +#define WHERE_IN_EARLYOUT 0x00040000 /* Perhaps quit IN loops early */ +#define WHERE_BIGNULL_SORT 0x00080000 /* Column nEq of index is BIGNULL */ + +#endif /* !defined(SQLITE_WHEREINT_H) */ /************** End of whereInt.h ********************************************/ /************** Continuing where we left off in wherecode.c ******************/ @@ -127504,23 +143436,23 @@ static void explainAppendTerm( int i; assert( nTerm>=1 ); - if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5); + if( bAnd ) tdsqlite3_str_append(pStr, " AND ", 5); - if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); + if( nTerm>1 ) tdsqlite3_str_append(pStr, "(", 1); for(i=0; i<nTerm; i++){ - if( i ) sqlite3StrAccumAppend(pStr, ",", 1); - sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i)); + if( i ) tdsqlite3_str_append(pStr, ",", 1); + tdsqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i)); } - if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1); + if( nTerm>1 ) tdsqlite3_str_append(pStr, ")", 1); - sqlite3StrAccumAppend(pStr, zOp, 1); + tdsqlite3_str_append(pStr, zOp, 1); - if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); + if( nTerm>1 ) tdsqlite3_str_append(pStr, "(", 1); for(i=0; i<nTerm; i++){ - if( i ) sqlite3StrAccumAppend(pStr, ",", 1); - sqlite3StrAccumAppend(pStr, "?", 1); + if( i ) tdsqlite3_str_append(pStr, ",", 1); + tdsqlite3_str_append(pStr, "?", 1); } - if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1); + if( nTerm>1 ) tdsqlite3_str_append(pStr, ")", 1); } /* @@ -127544,11 +143476,11 @@ static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ int i, j; if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; - sqlite3StrAccumAppend(pStr, " (", 2); + tdsqlite3_str_append(pStr, " (", 2); for(i=0; i<nEq; i++){ const char *z = explainIndexColumnName(pIndex, i); - if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5); - sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); + if( i ) tdsqlite3_str_append(pStr, " AND ", 5); + tdsqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); } j = i; @@ -127559,7 +143491,7 @@ static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<"); } - sqlite3StrAccumAppend(pStr, ")", 1); + tdsqlite3_str_append(pStr, ")", 1); } /* @@ -127571,23 +143503,20 @@ static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ ** If an OP_Explain opcode is added to the VM, its address is returned. ** Otherwise, if no OP_Explain is coded, zero is returned. */ -SQLITE_PRIVATE int sqlite3WhereExplainOneScan( +SQLITE_PRIVATE int tdsqlite3WhereExplainOneScan( Parse *pParse, /* Parse context */ SrcList *pTabList, /* Table list this loop refers to */ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ - int iLevel, /* Value for "level" column of output */ - int iFrom, /* Value for "from" column of output */ - u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ + u16 wctrlFlags /* Flags passed to tdsqlite3WhereBegin() */ ){ int ret = 0; #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) - if( pParse->explain==2 ) + if( tdsqlite3ParseToplevel(pParse)->explain==2 ) #endif { struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; Vdbe *v = pParse->pVdbe; /* VM being constructed */ - sqlite3 *db = pParse->db; /* Database handle */ - int iId = pParse->iSelectId; /* Select id (left-most output column) */ + tdsqlite3 *db = pParse->db; /* Database handle */ int isSearch; /* True for a SEARCH. False for SCAN. */ WhereLoop *pLoop; /* The controlling WhereLoop object */ u32 flags; /* Flags that describe this loop */ @@ -127603,16 +143532,16 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan( || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); - sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); - sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN"); + tdsqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); + tdsqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN"); if( pItem->pSelect ){ - sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId); + tdsqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId); }else{ - sqlite3XPrintf(&str, " TABLE %s", pItem->zName); + tdsqlite3_str_appendf(&str, " TABLE %s", pItem->zName); } if( pItem->zAlias ){ - sqlite3XPrintf(&str, " AS %s", pItem->zAlias); + tdsqlite3_str_appendf(&str, " AS %s", pItem->zAlias); } if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ const char *zFmt = 0; @@ -127635,8 +143564,8 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan( zFmt = "INDEX %s"; } if( zFmt ){ - sqlite3StrAccumAppend(&str, " USING ", 7); - sqlite3XPrintf(&str, zFmt, pIdx->zName); + tdsqlite3_str_append(&str, " USING ", 7); + tdsqlite3_str_appendf(&str, zFmt, pIdx->zName); explainIndexRange(&str, pLoop); } }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ @@ -127651,23 +143580,27 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan( assert( flags&WHERE_TOP_LIMIT); zRangeOp = "<"; } - sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); + tdsqlite3_str_appendf(&str, + " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); } #ifndef SQLITE_OMIT_VIRTUALTABLE else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ - sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s", + tdsqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s", pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); } #endif #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS if( pLoop->nOut>=10 ){ - sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); + tdsqlite3_str_appendf(&str, " (~%llu rows)", + tdsqlite3LogEstToInt(pLoop->nOut)); }else{ - sqlite3StrAccumAppend(&str, " (~1 row)", 9); + tdsqlite3_str_append(&str, " (~1 row)", 9); } #endif - zMsg = sqlite3StrAccumFinish(&str); - ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC); + zMsg = tdsqlite3StrAccumFinish(&str); + tdsqlite3ExplainBreakpoint("",zMsg); + ret = tdsqlite3VdbeAddOp4(v, OP_Explain, tdsqlite3VdbeCurrentAddr(v), + pParse->addrExplain, 0, zMsg,P4_DYNAMIC); } return ret; } @@ -127676,14 +143609,14 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan( #ifdef SQLITE_ENABLE_STMT_SCANSTATUS /* ** Configure the VM passed as the first argument with an -** sqlite3_stmt_scanstatus() entry corresponding to the scan used to +** tdsqlite3_stmt_scanstatus() entry corresponding to the scan used to ** implement level pLvl. Argument pSrclist is a pointer to the FROM ** clause that the scan reads data from. ** ** If argument addrExplain is not 0, it must be the address of an ** OP_Explain instruction that describes the same loop. */ -SQLITE_PRIVATE void sqlite3WhereAddScanStatus( +SQLITE_PRIVATE void tdsqlite3WhereAddScanStatus( Vdbe *v, /* Vdbe to add scanstatus entry to */ SrcList *pSrclist, /* FROM clause pLvl reads data from */ WhereLevel *pLvl, /* Level to add scanstatus() entry for */ @@ -127696,7 +143629,7 @@ SQLITE_PRIVATE void sqlite3WhereAddScanStatus( }else{ zObj = pSrclist->a[pLvl->iFrom].zName; } - sqlite3VdbeScanStatus( + tdsqlite3VdbeScanStatus( v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj ); } @@ -127747,8 +143680,8 @@ SQLITE_PRIVATE void sqlite3WhereAddScanStatus( */ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ int nLoop = 0; - while( ALWAYS(pTerm!=0) - && (pTerm->wtFlags & TERM_CODED)==0 + assert( pTerm!=0 ); + while( (pTerm->wtFlags & TERM_CODED)==0 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) && (pLevel->notReady & pTerm->prereqAll)==0 ){ @@ -127759,6 +143692,7 @@ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ } if( pTerm->iParent<0 ) break; pTerm = &pTerm->pWC->a[pTerm->iParent]; + assert( pTerm!=0 ); pTerm->nChild--; if( pTerm->nChild!=0 ) break; nLoop++; @@ -127769,9 +143703,9 @@ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ ** Code an OP_Affinity opcode to apply the column affinity string zAff ** to the n registers starting at base. ** -** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the -** beginning and end of zAff are ignored. If all entries in zAff are -** SQLITE_AFF_BLOB, then no code gets generated. +** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which +** are no-ops) at the beginning and end of zAff are ignored. If all entries +** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated. ** ** This routine makes its own copy of zAff so that the caller is free ** to modify zAff after this routine returns. @@ -127784,22 +143718,22 @@ static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ } assert( v!=0 ); - /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning - ** and end of the affinity string. + /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE + ** entries at the beginning and end of the affinity string. */ - while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){ + assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB ); + while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){ n--; base++; zAff++; } - while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){ + while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){ n--; } /* Code the OP_Affinity opcode if there is anything left to do. */ if( n>0 ){ - sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); - sqlite3ExprCacheAffinityChange(pParse, base, n); + tdsqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); } } @@ -127820,15 +143754,112 @@ static void updateRangeAffinityStr( ){ int i; for(i=0; i<n; i++){ - Expr *p = sqlite3VectorFieldSubexpr(pRight, i); - if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB - || sqlite3ExprNeedsNoAffinityChange(p, zAff[i]) + Expr *p = tdsqlite3VectorFieldSubexpr(pRight, i); + if( tdsqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB + || tdsqlite3ExprNeedsNoAffinityChange(p, zAff[i]) ){ zAff[i] = SQLITE_AFF_BLOB; } } } + +/* +** pX is an expression of the form: (vector) IN (SELECT ...) +** In other words, it is a vector IN operator with a SELECT clause on the +** LHS. But not all terms in the vector are indexable and the terms might +** not be in the correct order for indexing. +** +** This routine makes a copy of the input pX expression and then adjusts +** the vector on the LHS with corresponding changes to the SELECT so that +** the vector contains only index terms and those terms are in the correct +** order. The modified IN expression is returned. The caller is responsible +** for deleting the returned expression. +** +** Example: +** +** CREATE TABLE t1(a,b,c,d,e,f); +** CREATE INDEX t1x1 ON t1(e,c); +** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2) +** \_______________________________________/ +** The pX expression +** +** Since only columns e and c can be used with the index, in that order, +** the modified IN expression that is returned will be: +** +** (e,c) IN (SELECT z,x FROM t2) +** +** The reduced pX is different from the original (obviously) and thus is +** only used for indexing, to improve performance. The original unaltered +** IN expression must also be run on each output row for correctness. +*/ +static Expr *removeUnindexableInClauseTerms( + Parse *pParse, /* The parsing context */ + int iEq, /* Look at loop terms starting here */ + WhereLoop *pLoop, /* The current loop */ + Expr *pX /* The IN expression to be reduced */ +){ + tdsqlite3 *db = pParse->db; + Expr *pNew; + pNew = tdsqlite3ExprDup(db, pX, 0); + if( db->mallocFailed==0 ){ + ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */ + ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */ + ExprList *pRhs = 0; /* New RHS after modifications */ + ExprList *pLhs = 0; /* New LHS after mods */ + int i; /* Loop counter */ + Select *pSelect; /* Pointer to the SELECT on the RHS */ + + for(i=iEq; i<pLoop->nLTerm; i++){ + if( pLoop->aLTerm[i]->pExpr==pX ){ + int iField = pLoop->aLTerm[i]->iField - 1; + if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */ + pRhs = tdsqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr); + pOrigRhs->a[iField].pExpr = 0; + assert( pOrigLhs->a[iField].pExpr!=0 ); + pLhs = tdsqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr); + pOrigLhs->a[iField].pExpr = 0; + } + } + tdsqlite3ExprListDelete(db, pOrigRhs); + tdsqlite3ExprListDelete(db, pOrigLhs); + pNew->pLeft->x.pList = pLhs; + pNew->x.pSelect->pEList = pRhs; + if( pLhs && pLhs->nExpr==1 ){ + /* Take care here not to generate a TK_VECTOR containing only a + ** single value. Since the parser never creates such a vector, some + ** of the subroutines do not handle this case. */ + Expr *p = pLhs->a[0].pExpr; + pLhs->a[0].pExpr = 0; + tdsqlite3ExprDelete(db, pNew->pLeft); + pNew->pLeft = p; + } + pSelect = pNew->x.pSelect; + if( pSelect->pOrderBy ){ + /* If the SELECT statement has an ORDER BY clause, zero the + ** iOrderByCol variables. These are set to non-zero when an + ** ORDER BY term exactly matches one of the terms of the + ** result-set. Since the result-set of the SELECT statement may + ** have been modified or reordered, these variables are no longer + ** set correctly. Since setting them is just an optimization, + ** it's easiest just to zero them here. */ + ExprList *pOrderBy = pSelect->pOrderBy; + for(i=0; i<pOrderBy->nExpr; i++){ + pOrderBy->a[i].u.x.iOrderByCol = 0; + } + } + +#if 0 + printf("For indexing, change the IN expr:\n"); + tdsqlite3TreeViewExpr(0, pX, 0); + printf("Into:\n"); + tdsqlite3TreeViewExpr(0, pNew, 0); +#endif + } + return pNew; +} + + /* ** Generate code for a single equality term of the WHERE clause. An equality ** term can be either X=expr or X IN (...). pTerm is the term to be @@ -127859,10 +143890,10 @@ static int codeEqualityTerm( assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); assert( iTarget>0 ); if( pX->op==TK_EQ || pX->op==TK_IS ){ - iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); + iReg = tdsqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); }else if( pX->op==TK_ISNULL ){ iReg = iTarget; - sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, iReg); #ifndef SQLITE_OMIT_SUBQUERY }else{ int eType = IN_INDEX_NOOP; @@ -127891,89 +143922,44 @@ static int codeEqualityTerm( } } for(i=iEq;i<pLoop->nLTerm; i++){ - if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++; + assert( pLoop->aLTerm[i]!=0 ); + if( pLoop->aLTerm[i]->pExpr==pX ) nEq++; } + iTab = 0; if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ - eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0); + eType = tdsqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab); }else{ - Select *pSelect = pX->x.pSelect; - sqlite3 *db = pParse->db; - u16 savedDbOptFlags = db->dbOptFlags; - ExprList *pOrigRhs = pSelect->pEList; - ExprList *pOrigLhs = pX->pLeft->x.pList; - ExprList *pRhs = 0; /* New Select.pEList for RHS */ - ExprList *pLhs = 0; /* New pX->pLeft vector */ - - for(i=iEq;i<pLoop->nLTerm; i++){ - if( pLoop->aLTerm[i]->pExpr==pX ){ - int iField = pLoop->aLTerm[i]->iField - 1; - Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0); - Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0); + tdsqlite3 *db = pParse->db; + pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX); - pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs); - pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs); - } - } if( !db->mallocFailed ){ - Expr *pLeft = pX->pLeft; - - if( pSelect->pOrderBy ){ - /* If the SELECT statement has an ORDER BY clause, zero the - ** iOrderByCol variables. These are set to non-zero when an - ** ORDER BY term exactly matches one of the terms of the - ** result-set. Since the result-set of the SELECT statement may - ** have been modified or reordered, these variables are no longer - ** set correctly. Since setting them is just an optimization, - ** it's easiest just to zero them here. */ - ExprList *pOrderBy = pSelect->pOrderBy; - for(i=0; i<pOrderBy->nExpr; i++){ - pOrderBy->a[i].u.x.iOrderByCol = 0; - } - } - - /* Take care here not to generate a TK_VECTOR containing only a - ** single value. Since the parser never creates such a vector, some - ** of the subroutines do not handle this case. */ - if( pLhs->nExpr==1 ){ - pX->pLeft = pLhs->a[0].pExpr; - }else{ - pLeft->x.pList = pLhs; - aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq); - testcase( aiMap==0 ); - } - pSelect->pEList = pRhs; - db->dbOptFlags |= SQLITE_QueryFlattener; - eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap); - db->dbOptFlags = savedDbOptFlags; - testcase( aiMap!=0 && aiMap[0]!=0 ); - pSelect->pEList = pOrigRhs; - pLeft->x.pList = pOrigLhs; - pX->pLeft = pLeft; + aiMap = (int*)tdsqlite3DbMallocZero(pParse->db, sizeof(int)*nEq); + eType = tdsqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab); + pTerm->pExpr->iTable = iTab; } - sqlite3ExprListDelete(pParse->db, pLhs); - sqlite3ExprListDelete(pParse->db, pRhs); + tdsqlite3ExprDelete(db, pX); + pX = pTerm->pExpr; } if( eType==IN_INDEX_INDEX_DESC ){ testcase( bRev ); bRev = !bRev; } - iTab = pX->iTable; - sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); + tdsqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); VdbeCoverageIf(v, bRev); VdbeCoverageIf(v, !bRev); assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); pLoop->wsFlags |= WHERE_IN_ABLE; if( pLevel->u.in.nIn==0 ){ - pLevel->addrNxt = sqlite3VdbeMakeLabel(v); + pLevel->addrNxt = tdsqlite3VdbeMakeLabel(pParse); } i = pLevel->u.in.nIn; pLevel->u.in.nIn += nEq; pLevel->u.in.aInLoop = - sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, + tdsqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); pIn = pLevel->u.in.aInLoop; if( pIn ){ @@ -127983,16 +143969,22 @@ static int codeEqualityTerm( if( pLoop->aLTerm[i]->pExpr==pX ){ int iOut = iReg + i - iEq; if( eType==IN_INDEX_ROWID ){ - testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */ - pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); + pIn->addrInTop = tdsqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); }else{ int iCol = aiMap ? aiMap[iMap++] : 0; - pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); + pIn->addrInTop = tdsqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); } - sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); + tdsqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); if( i==iEq ){ pIn->iCur = iTab; - pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; + pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next; + if( iEq>0 ){ + pIn->iBase = iReg - i; + pIn->nPrefix = i; + pLoop->wsFlags |= WHERE_IN_EARLYOUT; + }else{ + pIn->nPrefix = 0; + } }else{ pIn->eEndLoopOp = OP_Noop; } @@ -128002,7 +143994,7 @@ static int codeEqualityTerm( }else{ pLevel->u.in.nIn = 0; } - sqlite3DbFree(pParse->db, aiMap); + tdsqlite3DbFree(pParse->db, aiMap); #endif } disableTerm(pLevel, pTerm); @@ -128041,7 +144033,7 @@ static int codeEqualityTerm( ** ** Before returning, *pzAff is set to point to a buffer containing a ** copy of the column affinity string of the index allocated using -** sqlite3DbMalloc(). Except, entries in the copy of the string associated +** tdsqlite3DbMalloc(). Except, entries in the copy of the string associated ** with equality constraints that use BLOB or NONE affinity are set to ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: ** @@ -128086,23 +144078,23 @@ static int codeAllEqualityTerms( nReg = pLoop->u.btree.nEq + nExtraReg; pParse->nMem += nReg; - zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); + zAff = tdsqlite3DbStrDup(pParse->db,tdsqlite3IndexAffinityStr(pParse->db,pIdx)); assert( zAff!=0 || pParse->db->mallocFailed ); if( nSkip ){ int iIdxCur = pLevel->iIdxCur; - sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); + tdsqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); - j = sqlite3VdbeAddOp0(v, OP_Goto); - pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), + j = tdsqlite3VdbeAddOp0(v, OP_Goto); + pLevel->addrSkip = tdsqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), iIdxCur, 0, regBase, nSkip); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); - sqlite3VdbeJumpHere(v, j); + tdsqlite3VdbeJumpHere(v, j); for(j=0; j<nSkip; j++){ - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); + tdsqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); testcase( pIdx->aiColumn[j]==XN_EXPR ); VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); } @@ -128122,31 +144114,31 @@ static int codeAllEqualityTerms( r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); if( r1!=regBase+j ){ if( nReg==1 ){ - sqlite3ReleaseTempReg(pParse, regBase); + tdsqlite3ReleaseTempReg(pParse, regBase); regBase = r1; }else{ - sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); + tdsqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); } } if( pTerm->eOperator & WO_IN ){ if( pTerm->pExpr->flags & EP_xIsSelect ){ /* No affinity ever needs to be (or should be) applied to a value ** from the RHS of an "? IN (SELECT ...)" expression. The - ** sqlite3FindInIndex() routine has already ensured that the + ** tdsqlite3FindInIndex() routine has already ensured that the ** affinity of the comparison has been applied to the value. */ if( zAff ) zAff[j] = SQLITE_AFF_BLOB; } }else if( (pTerm->eOperator & WO_ISNULL)==0 ){ Expr *pRight = pTerm->pExpr->pRight; - if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); + if( (pTerm->wtFlags & TERM_IS)==0 && tdsqlite3ExprCanBeNull(pRight) ){ + tdsqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); VdbeCoverage(v); } if( zAff ){ - if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ + if( tdsqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ zAff[j] = SQLITE_AFF_BLOB; } - if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ + if( tdsqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ zAff[j] = SQLITE_AFF_BLOB; } } @@ -128182,7 +144174,7 @@ static void whereLikeOptimizationStringFixup( if( pTerm->wtFlags & TERM_LIKEOPT ){ VdbeOp *pOp; assert( pLevel->iLikeRepCntr>0 ); - pOp = sqlite3VdbeGetOp(v, -1); + pOp = tdsqlite3VdbeGetOp(v, -1); assert( pOp!=0 ); assert( pOp->opcode==OP_String8 || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); @@ -128197,7 +144189,7 @@ static void whereLikeOptimizationStringFixup( #ifdef SQLITE_ENABLE_CURSOR_HINTS /* ** Information is passed from codeCursorHint() down to individual nodes of -** the expression tree (by sqlite3WalkExpr()) using an instance of this +** the expression tree (by tdsqlite3WalkExpr()) using an instance of this ** structure. */ struct CCurHint { @@ -128217,7 +144209,7 @@ static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ assert( pHint->pIdx!=0 ); if( pExpr->op==TK_COLUMN && pExpr->iTable==pHint->iTabCur - && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0 + && tdsqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0 ){ pWalker->eCode = 1; } @@ -128247,8 +144239,8 @@ static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ pWalker->eCode = 1; }else if( pExpr->op==TK_FUNCTION ){ int d1; - char d2[3]; - if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ + char d2[4]; + if( 0==tdsqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ pWalker->eCode = 1; } } @@ -128279,16 +144271,13 @@ static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ struct CCurHint *pHint = pWalker->u.pCCurHint; if( pExpr->op==TK_COLUMN ){ if( pExpr->iTable!=pHint->iTabCur ){ - Vdbe *v = pWalker->pParse->pVdbe; int reg = ++pWalker->pParse->nMem; /* Register for column value */ - sqlite3ExprCodeGetColumnOfTable( - v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg - ); + tdsqlite3ExprCode(pWalker->pParse, pExpr, reg); pExpr->op = TK_REGISTER; pExpr->iTable = reg; }else if( pHint->pIdx!=0 ){ pExpr->iTable = pHint->iIdxCur; - pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn); + pExpr->iColumn = tdsqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn); assert( pExpr->iColumn>=0 ); } }else if( pExpr->op==TK_AGG_FUNCTION ){ @@ -128314,7 +144303,7 @@ static void codeCursorHint( WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ ){ Parse *pParse = pWInfo->pParse; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; Vdbe *v = pParse->pVdbe; Expr *pExpr = 0; WhereLoop *pLoop = pLevel->pWLoop; @@ -128369,7 +144358,7 @@ static void codeCursorHint( ){ sWalker.eCode = 0; sWalker.xExprCallback = codeCursorHintIsOrFunction; - sqlite3WalkExpr(&sWalker, pTerm->pExpr); + tdsqlite3WalkExpr(&sWalker, pTerm->pExpr); if( sWalker.eCode ) continue; } }else{ @@ -128385,24 +144374,24 @@ static void codeCursorHint( } /* No subqueries or non-deterministic functions allowed */ - if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; + if( tdsqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; /* For an index scan, make sure referenced columns are actually in ** the index. */ if( sHint.pIdx!=0 ){ sWalker.eCode = 0; sWalker.xExprCallback = codeCursorHintCheckExpr; - sqlite3WalkExpr(&sWalker, pTerm->pExpr); + tdsqlite3WalkExpr(&sWalker, pTerm->pExpr); if( sWalker.eCode ) continue; } /* If we survive all prior tests, that means this term is worth hinting */ - pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); + pExpr = tdsqlite3ExprAnd(pParse, pExpr, tdsqlite3ExprDup(db, pTerm->pExpr, 0)); } if( pExpr!=0 ){ sWalker.xExprCallback = codeCursorHintFixExpr; - sqlite3WalkExpr(&sWalker, pExpr); - sqlite3VdbeAddOp4(v, OP_CursorHint, + tdsqlite3WalkExpr(&sWalker, pExpr); + tdsqlite3VdbeAddOp4(v, OP_CursorHint, (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, (const char*)pExpr, P4_EXPR); } @@ -128419,10 +144408,10 @@ static void codeCursorHint( ** ** Normally, this is just: ** -** OP_Seek $iCur $iRowid +** OP_DeferredSeek $iCur $iRowid ** ** However, if the scan currently being coded is a branch of an OR-loop and -** the statement currently being coded is a SELECT, then P3 of the OP_Seek +** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek ** is set to iIdxCur and P4 is set to point to an array of integers ** containing one entry for each column of the table cursor iCur is open ** on. For each table column, if the column is the i'th column of the @@ -128441,20 +144430,25 @@ static void codeDeferredSeek( assert( iIdxCur>0 ); assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); - sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur); + pWInfo->bDeferredSeek = 1; + tdsqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur); if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) - && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) + && DbMaskAllZero(tdsqlite3ParseToplevel(pParse)->writeMask) ){ int i; Table *pTab = pIdx->pTable; - int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); + int *ai = (int*)tdsqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); if( ai ){ ai[0] = pTab->nCol; for(i=0; i<pIdx->nColumn-1; i++){ + int x1, x2; assert( pIdx->aiColumn[i]<pTab->nCol ); - if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1; + x1 = pIdx->aiColumn[i]; + x2 = tdsqlite3TableColumnToStorage(pTab, x1); + testcase( x1!=x2 ); + if( x1>=0 ) ai[x2+1] = i+1; } - sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); + tdsqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); } } } @@ -128470,12 +144464,14 @@ static void codeDeferredSeek( */ static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ assert( nReg>0 ); - if( sqlite3ExprIsVector(p) ){ + if( p && tdsqlite3ExprIsVector(p) ){ #ifndef SQLITE_OMIT_SUBQUERY if( (p->flags & EP_xIsSelect) ){ Vdbe *v = pParse->pVdbe; - int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0); - sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); + int iSelect; + assert( p->op==TK_SELECT ); + iSelect = tdsqlite3CodeSubselect(pParse, p); + tdsqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); }else #endif { @@ -128483,12 +144479,176 @@ static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ ExprList *pList = p->x.pList; assert( nReg<=pList->nExpr ); for(i=0; i<nReg; i++){ - sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); + tdsqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); } } }else{ assert( nReg==1 ); - sqlite3ExprCode(pParse, p, iReg); + tdsqlite3ExprCode(pParse, p, iReg); + } +} + +/* An instance of the IdxExprTrans object carries information about a +** mapping from an expression on table columns into a column in an index +** down through the Walker. +*/ +typedef struct IdxExprTrans { + Expr *pIdxExpr; /* The index expression */ + int iTabCur; /* The cursor of the corresponding table */ + int iIdxCur; /* The cursor for the index */ + int iIdxCol; /* The column for the index */ + int iTabCol; /* The column for the table */ + WhereInfo *pWInfo; /* Complete WHERE clause information */ + tdsqlite3 *db; /* Database connection (for malloc()) */ +} IdxExprTrans; + +/* +** Preserve pExpr on the WhereETrans list of the WhereInfo. +*/ +static void preserveExpr(IdxExprTrans *pTrans, Expr *pExpr){ + WhereExprMod *pNew; + pNew = tdsqlite3DbMallocRaw(pTrans->db, sizeof(*pNew)); + if( pNew==0 ) return; + pNew->pNext = pTrans->pWInfo->pExprMods; + pTrans->pWInfo->pExprMods = pNew; + pNew->pExpr = pExpr; + memcpy(&pNew->orig, pExpr, sizeof(*pExpr)); +} + +/* The walker node callback used to transform matching expressions into +** a reference to an index column for an index on an expression. +** +** If pExpr matches, then transform it into a reference to the index column +** that contains the value of pExpr. +*/ +static int whereIndexExprTransNode(Walker *p, Expr *pExpr){ + IdxExprTrans *pX = p->u.pIdxTrans; + if( tdsqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){ + preserveExpr(pX, pExpr); + pExpr->affExpr = tdsqlite3ExprAffinity(pExpr); + pExpr->op = TK_COLUMN; + pExpr->iTable = pX->iIdxCur; + pExpr->iColumn = pX->iIdxCol; + pExpr->y.pTab = 0; + testcase( ExprHasProperty(pExpr, EP_Skip) ); + testcase( ExprHasProperty(pExpr, EP_Unlikely) ); + ExprClearProperty(pExpr, EP_Skip|EP_Unlikely); + return WRC_Prune; + }else{ + return WRC_Continue; + } +} + +#ifndef SQLITE_OMIT_GENERATED_COLUMNS +/* A walker node callback that translates a column reference to a table +** into a corresponding column reference of an index. +*/ +static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){ + if( pExpr->op==TK_COLUMN ){ + IdxExprTrans *pX = p->u.pIdxTrans; + if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){ + assert( pExpr->y.pTab!=0 ); + preserveExpr(pX, pExpr); + pExpr->affExpr = tdsqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn); + pExpr->iTable = pX->iIdxCur; + pExpr->iColumn = pX->iIdxCol; + pExpr->y.pTab = 0; + } + } + return WRC_Continue; +} +#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ + +/* +** For an indexes on expression X, locate every instance of expression X +** in pExpr and change that subexpression into a reference to the appropriate +** column of the index. +** +** 2019-10-24: Updated to also translate references to a VIRTUAL column in +** the table into references to the corresponding (stored) column of the +** index. +*/ +static void whereIndexExprTrans( + Index *pIdx, /* The Index */ + int iTabCur, /* Cursor of the table that is being indexed */ + int iIdxCur, /* Cursor of the index itself */ + WhereInfo *pWInfo /* Transform expressions in this WHERE clause */ +){ + int iIdxCol; /* Column number of the index */ + ExprList *aColExpr; /* Expressions that are indexed */ + Table *pTab; + Walker w; + IdxExprTrans x; + aColExpr = pIdx->aColExpr; + if( aColExpr==0 && !pIdx->bHasVCol ){ + /* The index does not reference any expressions or virtual columns + ** so no translations are needed. */ + return; + } + pTab = pIdx->pTable; + memset(&w, 0, sizeof(w)); + w.u.pIdxTrans = &x; + x.iTabCur = iTabCur; + x.iIdxCur = iIdxCur; + x.pWInfo = pWInfo; + x.db = pWInfo->pParse->db; + for(iIdxCol=0; iIdxCol<pIdx->nColumn; iIdxCol++){ + i16 iRef = pIdx->aiColumn[iIdxCol]; + if( iRef==XN_EXPR ){ + assert( aColExpr->a[iIdxCol].pExpr!=0 ); + x.pIdxExpr = aColExpr->a[iIdxCol].pExpr; + if( tdsqlite3ExprIsConstant(x.pIdxExpr) ) continue; + w.xExprCallback = whereIndexExprTransNode; +#ifndef SQLITE_OMIT_GENERATED_COLUMNS + }else if( iRef>=0 + && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0 + && (pTab->aCol[iRef].zColl==0 + || tdsqlite3StrICmp(pTab->aCol[iRef].zColl, tdsqlite3StrBINARY)==0) + ){ + /* Check to see if there are direct references to generated columns + ** that are contained in the index. Pulling the generated column + ** out of the index is an optimization only - the main table is always + ** available if the index cannot be used. To avoid unnecessary + ** complication, omit this optimization if the collating sequence for + ** the column is non-standard */ + x.iTabCol = iRef; + w.xExprCallback = whereIndexExprTransColumn; +#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ + }else{ + continue; + } + x.iIdxCol = iIdxCol; + tdsqlite3WalkExpr(&w, pWInfo->pWhere); + tdsqlite3WalkExprList(&w, pWInfo->pOrderBy); + tdsqlite3WalkExprList(&w, pWInfo->pResultSet); + } +} + +/* +** The pTruth expression is always true because it is the WHERE clause +** a partial index that is driving a query loop. Look through all of the +** WHERE clause terms on the query, and if any of those terms must be +** true because pTruth is true, then mark those WHERE clause terms as +** coded. +*/ +static void whereApplyPartialIndexConstraints( + Expr *pTruth, + int iTabCur, + WhereClause *pWC +){ + int i; + WhereTerm *pTerm; + while( pTruth->op==TK_AND ){ + whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC); + pTruth = pTruth->pRight; + } + for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ + Expr *pExpr; + if( pTerm->wtFlags & TERM_CODED ) continue; + pExpr = pTerm->pExpr; + if( tdsqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){ + pTerm->wtFlags |= TERM_CODED; + } } } @@ -128496,42 +144656,54 @@ static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ ** Generate code for the start of the iLevel-th loop in the WHERE clause ** implementation described by pWInfo. */ -SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( +SQLITE_PRIVATE Bitmask tdsqlite3WhereCodeOneLoopStart( + Parse *pParse, /* Parsing context */ + Vdbe *v, /* Prepared statement under construction */ WhereInfo *pWInfo, /* Complete information about the WHERE clause */ int iLevel, /* Which level of pWInfo->a[] should be coded */ + WhereLevel *pLevel, /* The current level pointer */ Bitmask notReady /* Which tables are currently available */ ){ int j, k; /* Loop counters */ int iCur; /* The VDBE cursor for the table */ int addrNxt; /* Where to jump to continue with the next IN case */ - int omitTable; /* True if we use the index only */ int bRev; /* True if we need to scan in reverse order */ - WhereLevel *pLevel; /* The where level to be coded */ WhereLoop *pLoop; /* The WhereLoop object being coded */ WhereClause *pWC; /* Decomposition of the entire WHERE clause */ WhereTerm *pTerm; /* A WHERE clause term */ - Parse *pParse; /* Parsing context */ - sqlite3 *db; /* Database connection */ - Vdbe *v; /* The prepared stmt under constructions */ + tdsqlite3 *db; /* Database connection */ struct SrcList_item *pTabItem; /* FROM clause term being coded */ int addrBrk; /* Jump here to break out of the loop */ + int addrHalt; /* addrBrk for the outermost loop */ int addrCont; /* Jump here to continue with next cycle */ int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ int iReleaseReg = 0; /* Temp register to free before returning */ + Index *pIdx = 0; /* Index used by loop (if any) */ + int iLoop; /* Iteration of constraint generator loop */ - pParse = pWInfo->pParse; - v = pParse->pVdbe; pWC = &pWInfo->sWC; db = pParse->db; - pLevel = &pWInfo->a[iLevel]; pLoop = pLevel->pWLoop; pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; iCur = pTabItem->iCursor; - pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); + pLevel->notReady = notReady & ~tdsqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); bRev = (pWInfo->revMask>>iLevel)&1; - omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 - && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); +#if WHERETRACE_ENABLED /* 0x20800 */ + if( tdsqlite3WhereTrace & 0x800 ){ + tdsqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n", + iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom); + tdsqlite3WhereLoopPrint(pLoop, pWC); + } + if( tdsqlite3WhereTrace & 0x20000 ){ + if( iLevel==0 ){ + tdsqlite3DebugPrintf("WHERE clause being coded:\n"); + tdsqlite3TreeViewExpr(0, pWInfo->pWhere, 0); + } + tdsqlite3DebugPrintf("All WHERE-clause terms before coding:\n"); + tdsqlite3WhereClausePrint(pWC); + } +#endif /* Create labels for the "break" and "continue" instructions ** for the current loop. Jump to addrBrk to break out of a loop. @@ -128543,26 +144715,34 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** there are no IN operators in the constraints, the "addrNxt" label ** is the same as "addrBrk". */ - addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); - addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); + addrBrk = pLevel->addrBrk = pLevel->addrNxt = tdsqlite3VdbeMakeLabel(pParse); + addrCont = pLevel->addrCont = tdsqlite3VdbeMakeLabel(pParse); /* If this is the right table of a LEFT OUTER JOIN, allocate and ** initialize a memory cell that records if this table matches any ** row of the left table of the join. */ + assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) + || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0 + ); if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ pLevel->iLeftJoin = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); VdbeComment((v, "init LEFT JOIN no-match flag")); } + /* Compute a safe address to jump to if we discover that the table for + ** this loop is empty and can never contribute content. */ + for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){} + addrHalt = pWInfo->a[j].addrBrk; + /* Special case of a FROM clause subquery implemented as a co-routine */ if( pTabItem->fg.viaCoroutine ){ int regYield = pTabItem->regReturn; - sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); - pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); + tdsqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); + pLevel->p2 = tdsqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); VdbeCoverage(v); - VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); + VdbeComment((v, "next row of %s", pTabItem->pTab->zName)); pLevel->op = OP_Goto; }else @@ -128576,8 +144756,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( int nConstraint = pLoop->nLTerm; int iIn; /* Counter for IN constraints */ - sqlite3ExprCachePush(pParse); - iReg = sqlite3GetTempRange(pParse, nConstraint+2); + iReg = tdsqlite3GetTempRange(pParse, nConstraint+2); addrNotFound = pLevel->addrBrk; for(j=0; j<nConstraint; j++){ int iTarget = iReg+j+2; @@ -128591,22 +144770,25 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( codeExprOrVector(pParse, pRight, iTarget, 1); } } - sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); - sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); - sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, + tdsqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); + tdsqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); + tdsqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pLoop->u.vtab.idxStr, - pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC); + pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC); VdbeCoverage(v); pLoop->u.vtab.needFree = 0; pLevel->p1 = iCur; pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; - pLevel->p2 = sqlite3VdbeCurrentAddr(v); + pLevel->p2 = tdsqlite3VdbeCurrentAddr(v); iIn = pLevel->u.in.nIn; for(j=nConstraint-1; j>=0; j--){ pTerm = pLoop->aLTerm[j]; + if( (pTerm->eOperator & WO_IN)!=0 ) iIn--; if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ disableTerm(pLevel, pTerm); - }else if( (pTerm->eOperator & WO_IN)!=0 ){ + }else if( (pTerm->eOperator & WO_IN)!=0 + && tdsqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1 + ){ Expr *pCompare; /* The comparison operator */ Expr *pRight; /* RHS of the comparison */ VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ @@ -128617,39 +144799,39 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** encoding of the value in the register, so it *must* be reloaded. */ assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); if( !db->mallocFailed ){ - assert( iIn>0 ); - pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop); + assert( iIn>=0 && iIn<pLevel->u.in.nIn ); + pOp = tdsqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop); assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); testcase( pOp->opcode==OP_Rowid ); - sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); + tdsqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); } /* Generate code that will continue to the next row if ** the IN constraint is not satisfied */ - pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0); + pCompare = tdsqlite3PExpr(pParse, TK_EQ, 0, 0); assert( pCompare!=0 || db->mallocFailed ); if( pCompare ){ pCompare->pLeft = pTerm->pExpr->pLeft; - pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); + pCompare->pRight = pRight = tdsqlite3Expr(db, TK_REGISTER, 0); if( pRight ){ pRight->iTable = iReg+j+2; - sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0); + tdsqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0); } pCompare->pLeft = 0; - sqlite3ExprDelete(db, pCompare); + tdsqlite3ExprDelete(db, pCompare); } } } + assert( iIn==0 || db->mallocFailed ); /* These registers need to be preserved in case there is an IN operator ** loop. So we could deallocate the registers here (and potentially ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems ** simpler and safer to simply not reuse the registers. ** - ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); + ** tdsqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); */ - sqlite3ExprCachePop(pParse); }else #endif /* SQLITE_OMIT_VIRTUALTABLE */ @@ -128665,18 +144847,17 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( pTerm = pLoop->aLTerm[0]; assert( pTerm!=0 ); assert( pTerm->pExpr!=0 ); - assert( omitTable==0 ); testcase( pTerm->wtFlags & TERM_VIRTUAL ); iReleaseReg = ++pParse->nMem; iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); - if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); + if( iRowidReg!=iReleaseReg ) tdsqlite3ReleaseTempReg(pParse, iReleaseReg); addrNxt = pLevel->addrNxt; - sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); + tdsqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); VdbeCoverage(v); - sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); - sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); - VdbeComment((v, "pk")); pLevel->op = OP_Noop; + if( (pTerm->prereqAll & pLevel->notReady)==0 ){ + pTerm->wtFlags |= TERM_CODED; + } }else if( (pLoop->wsFlags & WHERE_IPK)!=0 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 ){ @@ -128687,7 +144868,6 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( int memEndValue = 0; WhereTerm *pStart, *pEnd; - assert( omitTable==0 ); j = 0; pStart = pEnd = 0; if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; @@ -128722,25 +144902,32 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( pX = pStart->pExpr; assert( pX!=0 ); testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ - if( sqlite3ExprIsVector(pX->pRight) ){ - r1 = rTemp = sqlite3GetTempReg(pParse); + if( tdsqlite3ExprIsVector(pX->pRight) ){ + r1 = rTemp = tdsqlite3GetTempReg(pParse); codeExprOrVector(pParse, pX->pRight, r1, 1); - op = aMoveOp[(pX->op - TK_GT) | 0x0001]; + testcase( pX->op==TK_GT ); + testcase( pX->op==TK_GE ); + testcase( pX->op==TK_LT ); + testcase( pX->op==TK_LE ); + op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1]; + assert( pX->op!=TK_GT || op==OP_SeekGE ); + assert( pX->op!=TK_GE || op==OP_SeekGE ); + assert( pX->op!=TK_LT || op==OP_SeekLE ); + assert( pX->op!=TK_LE || op==OP_SeekLE ); }else{ - r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); + r1 = tdsqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); disableTerm(pLevel, pStart); op = aMoveOp[(pX->op - TK_GT)]; } - sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); + tdsqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); VdbeComment((v, "pk")); VdbeCoverageIf(v, pX->op==TK_GT); VdbeCoverageIf(v, pX->op==TK_LE); VdbeCoverageIf(v, pX->op==TK_LT); VdbeCoverageIf(v, pX->op==TK_GE); - sqlite3ExprCacheAffinityChange(pParse, r1, 1); - sqlite3ReleaseTempReg(pParse, rTemp); + tdsqlite3ReleaseTempReg(pParse, rTemp); }else{ - sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); + tdsqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); } @@ -128753,32 +144940,31 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( testcase( pEnd->wtFlags & TERM_VIRTUAL ); memEndValue = ++pParse->nMem; codeExprOrVector(pParse, pX->pRight, memEndValue, 1); - if( 0==sqlite3ExprIsVector(pX->pRight) + if( 0==tdsqlite3ExprIsVector(pX->pRight) && (pX->op==TK_LT || pX->op==TK_GT) ){ testOp = bRev ? OP_Le : OP_Ge; }else{ testOp = bRev ? OP_Lt : OP_Gt; } - if( 0==sqlite3ExprIsVector(pX->pRight) ){ + if( 0==tdsqlite3ExprIsVector(pX->pRight) ){ disableTerm(pLevel, pEnd); } } - start = sqlite3VdbeCurrentAddr(v); + start = tdsqlite3VdbeCurrentAddr(v); pLevel->op = bRev ? OP_Prev : OP_Next; pLevel->p1 = iCur; pLevel->p2 = start; assert( pLevel->p5==0 ); if( testOp!=OP_Noop ){ iRowidReg = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); - sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); - sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); + tdsqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); + tdsqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); VdbeCoverageIf(v, testOp==OP_Le); VdbeCoverageIf(v, testOp==OP_Lt); VdbeCoverageIf(v, testOp==OP_Ge); VdbeCoverageIf(v, testOp==OP_Gt); - sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); + tdsqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); } }else if( pLoop->wsFlags & WHERE_INDEXED ){ /* Case 4: A scan using an index. @@ -128838,7 +145024,6 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( int endEq; /* True if range end uses ==, >= or <= */ int start_constraints; /* Start of range is constrained */ int nConstraint; /* Number of constraint terms */ - Index *pIdx; /* The index we will be using */ int iIdxCur; /* The VDBE cursor for the index */ int nExtraReg = 0; /* Number of extra registers needed */ int op; /* Instruction opcode */ @@ -128846,31 +145031,13 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( char *zEndAff = 0; /* Affinity for end of range constraint */ u8 bSeekPastNull = 0; /* True to seek past initial nulls */ u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ + int omitTable; /* True if we use the index only */ + int regBignull = 0; /* big-null flag register */ pIdx = pLoop->u.btree.pIndex; iIdxCur = pLevel->iIdxCur; assert( nEq>=pLoop->nSkip ); - /* If this loop satisfies a sort order (pOrderBy) request that - ** was passed to this function to implement a "SELECT min(x) ..." - ** query, then the caller will only allow the loop to run for - ** a single iteration. This means that the first row returned - ** should not have a NULL value stored in 'x'. If column 'x' is - ** the first one after the nEq equality constraints in the index, - ** this requires some special handling. - */ - assert( pWInfo->pOrderBy==0 - || pWInfo->pOrderBy->nExpr==1 - || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); - if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 - && pWInfo->nOBSat>0 - && (pIdx->nKeyCol>nEq) - ){ - assert( pLoop->nSkip==0 ); - bSeekPastNull = 1; - nExtraReg = 1; - } - /* Find any inequality constraint terms for the start and end ** of the range. */ @@ -128890,9 +145057,9 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( assert( pRangeStart!=0 ); /* LIKE opt constraints */ assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ pLevel->iLikeRepCntr = (u32)++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); VdbeComment((v, "LIKE loop counter")); - pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); + pLevel->addrLikeRep = tdsqlite3VdbeCurrentAddr(v); /* iLikeRepCntr actually stores 2x the counter register number. The ** bottom bit indicates whether the search order is ASC or DESC. */ testcase( bRev ); @@ -128911,6 +145078,25 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( } assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); + /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses + ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS + ** FIRST). In both cases separate ordered scans are made of those + ** index entries for which the column is null and for those for which + ** it is not. For an ASC sort, the non-NULL entries are scanned first. + ** For DESC, NULL entries are scanned first. + */ + if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0 + && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0 + ){ + assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 ); + assert( pRangeEnd==0 && pRangeStart==0 ); + testcase( pLoop->nSkip>0 ); + nExtraReg = 1; + bSeekPastNull = 1; + pLevel->regBignull = regBignull = ++pParse->nMem; + pLevel->addrBignull = tdsqlite3VdbeMakeLabel(pParse); + } + /* If we are doing a reverse order scan on an ascending index, or ** a forward order scan on a descending index, interchange the ** start and end terms (pRangeStart and pRangeEnd). @@ -128929,11 +145115,11 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( */ codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); - assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); + assert( zStartAff==0 || tdsqlite3Strlen30(zStartAff)>=nEq ); if( zStartAff && nTop ){ - zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]); + zEndAff = tdsqlite3DbStrDup(db, &zStartAff[nEq]); } - addrNxt = pLevel->addrNxt; + addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt); testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); @@ -128950,9 +145136,9 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); if( (pRangeStart->wtFlags & TERM_VNULL)==0 - && sqlite3ExprCanBeNull(pRight) + && tdsqlite3ExprCanBeNull(pRight) ){ - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); + tdsqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); VdbeCoverage(v); } if( zStartAff ){ @@ -128960,17 +145146,21 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( } nConstraint += nBtm; testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); - if( sqlite3ExprIsVector(pRight)==0 ){ + if( tdsqlite3ExprIsVector(pRight)==0 ){ disableTerm(pLevel, pRangeStart); }else{ startEq = 1; } bSeekPastNull = 0; }else if( bSeekPastNull ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); - nConstraint++; startEq = 0; + tdsqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); + start_constraints = 1; + nConstraint++; + }else if( regBignull ){ + tdsqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); start_constraints = 1; + nConstraint++; } codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ @@ -128978,9 +145168,17 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** above has already left the cursor sitting on the correct row, ** so no further seeking is needed */ }else{ + if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){ + tdsqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur); + } + if( regBignull ){ + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull); + VdbeComment((v, "NULL-scan pass ctr")); + } + op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; assert( op!=0 ); - sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); + tdsqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); VdbeCoverage(v); VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); @@ -128988,6 +145186,23 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); + + assert( bSeekPastNull==0 || bStopAtNull==0 ); + if( regBignull ){ + assert( bSeekPastNull==1 || bStopAtNull==1 ); + assert( bSeekPastNull==!bStopAtNull ); + assert( bStopAtNull==startEq ); + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, tdsqlite3VdbeCurrentAddr(v)+2); + op = aStartOp[(nConstraint>1)*4 + 2 + bRev]; + tdsqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, + nConstraint-startEq); + VdbeCoverage(v); + VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); + VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); + VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); + VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); + assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE); + } } /* Load the value for the inequality constraint at the end of the @@ -128996,13 +145211,12 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( nConstraint = nEq; if( pRangeEnd ){ Expr *pRight = pRangeEnd->pExpr->pRight; - sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); codeExprOrVector(pParse, pRight, regBase+nEq, nTop); whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); if( (pRangeEnd->wtFlags & TERM_VNULL)==0 - && sqlite3ExprCanBeNull(pRight) + && tdsqlite3ExprCanBeNull(pRight) ){ - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); + tdsqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); VdbeCoverage(v); } if( zEndAff ){ @@ -129014,56 +145228,129 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( nConstraint += nTop; testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); - if( sqlite3ExprIsVector(pRight)==0 ){ + if( tdsqlite3ExprIsVector(pRight)==0 ){ disableTerm(pLevel, pRangeEnd); }else{ endEq = 1; } }else if( bStopAtNull ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); - endEq = 0; + if( regBignull==0 ){ + tdsqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); + endEq = 0; + } nConstraint++; } - sqlite3DbFree(db, zStartAff); - sqlite3DbFree(db, zEndAff); + tdsqlite3DbFree(db, zStartAff); + tdsqlite3DbFree(db, zEndAff); /* Top of the loop body */ - pLevel->p2 = sqlite3VdbeCurrentAddr(v); + pLevel->p2 = tdsqlite3VdbeCurrentAddr(v); /* Check if the index cursor is past the end of the range. */ if( nConstraint ){ + if( regBignull ){ + /* Except, skip the end-of-range check while doing the NULL-scan */ + tdsqlite3VdbeAddOp2(v, OP_IfNot, regBignull, tdsqlite3VdbeCurrentAddr(v)+3); + VdbeComment((v, "If NULL-scan 2nd pass")); + VdbeCoverage(v); + } op = aEndOp[bRev*2 + endEq]; - sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); + tdsqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); } + if( regBignull ){ + /* During a NULL-scan, check to see if we have reached the end of + ** the NULLs */ + assert( bSeekPastNull==!bStopAtNull ); + assert( bSeekPastNull+bStopAtNull==1 ); + assert( nConstraint+bSeekPastNull>0 ); + tdsqlite3VdbeAddOp2(v, OP_If, regBignull, tdsqlite3VdbeCurrentAddr(v)+2); + VdbeComment((v, "If NULL-scan 1st pass")); + VdbeCoverage(v); + op = aEndOp[bRev*2 + bSeekPastNull]; + tdsqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, + nConstraint+bSeekPastNull); + testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); + testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); + testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); + testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); + } + + if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){ + tdsqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1); + } /* Seek the table cursor, if required */ + omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 + && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; if( omitTable ){ /* pIdx is a covering index. No need to access the main table. */ }else if( HasRowid(pIdx->pTable) ){ - if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){ + if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) + || ( (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)!=0 + && (pWInfo->eOnePass==ONEPASS_SINGLE || pLoop->nLTerm==0) ) + ){ iRowidReg = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); - sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); + tdsqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); + tdsqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); VdbeCoverage(v); }else{ codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); } }else if( iCur!=iIdxCur ){ - Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); - iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); + Index *pPk = tdsqlite3PrimaryKeyIndex(pIdx->pTable); + iRowidReg = tdsqlite3GetTempRange(pParse, pPk->nKeyCol); for(j=0; j<pPk->nKeyCol; j++){ - k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); + k = tdsqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]); + tdsqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); } - sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, + tdsqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, iRowidReg, pPk->nKeyCol); VdbeCoverage(v); } + if( pLevel->iLeftJoin==0 ){ + /* If pIdx is an index on one or more expressions, then look through + ** all the expressions in pWInfo and try to transform matching expressions + ** into reference to index columns. Also attempt to translate references + ** to virtual columns in the table into references to (stored) columns + ** of the index. + ** + ** Do not do this for the RHS of a LEFT JOIN. This is because the + ** expression may be evaluated after OP_NullRow has been executed on + ** the cursor. In this case it is important to do the full evaluation, + ** as the result of the expression may not be NULL, even if all table + ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a + ** + ** Also, do not do this when processing one index an a multi-index + ** OR clause, since the transformation will become invalid once we + ** move forward to the next index. + ** https://sqlite.org/src/info/4e8e4857d32d401f + */ + if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ + whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo); + } + + /* If a partial index is driving the loop, try to eliminate WHERE clause + ** terms from the query that must be true due to the WHERE clause of + ** the partial index. + ** + ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work + ** for a LEFT JOIN. + */ + if( pIdx->pPartIdxWhere ){ + whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC); + } + }else{ + testcase( pIdx->pPartIdxWhere ); + /* The following assert() is not a requirement, merely an observation: + ** The OR-optimization doesn't work for the right hand table of + ** a LEFT JOIN: */ + assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ); + } + /* Record the instruction used to terminate the loop. */ if( pLoop->wsFlags & WHERE_ONEROW ){ pLevel->op = OP_Noop; @@ -129079,6 +145366,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( }else{ assert( pLevel->p5==0 ); } + if( omitTable ) pIdx = 0; }else #ifndef SQLITE_OMIT_OR_OPTIMIZATION @@ -129104,10 +145392,10 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** into the RowSet. If it is already present, control skips the ** Gosub opcode and jumps straight to the code generated by WhereEnd(). ** - ** sqlite3WhereBegin(<term>) + ** tdsqlite3WhereBegin(<term>) ** RowSetTest # Insert rowid into rowset ** Gosub 2 A - ** sqlite3WhereEnd() + ** tdsqlite3WhereEnd() ** ** Following the above, code to terminate the loop. Label A, the target ** of the Gosub above, jumps to the instruction right after the Goto. @@ -129134,7 +145422,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ int regRowset = 0; /* Register for RowSet object */ int regRowid = 0; /* Register holding rowid */ - int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ + int iLoopBody = tdsqlite3VdbeMakeLabel(pParse);/* Start of loop body */ int iRetInit; /* Address of regReturn init */ int untestedTerms = 0; /* Some terms not completely tested */ int ii; /* Loop counter */ @@ -129152,13 +145440,13 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( /* Set up a new SrcList in pOrTab containing the table being scanned ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. - ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). + ** This becomes the SrcList in the recursive call to tdsqlite3WhereBegin(). */ if( pWInfo->nLevel>1 ){ int nNotReady; /* The number of notReady tables */ struct SrcList_item *origSrc; /* Original list of tables */ nNotReady = pWInfo->nLevel - iLevel - 1; - pOrTab = sqlite3StackAllocRaw(db, + pOrTab = tdsqlite3StackAllocRaw(db, sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); if( pOrTab==0 ) return notReady; pOrTab->nAlloc = (u8)(nNotReady + 1); @@ -129187,21 +145475,21 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ if( HasRowid(pTab) ){ regRowset = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); + Index *pPk = tdsqlite3PrimaryKeyIndex(pTab); regRowset = pParse->nTab++; - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); - sqlite3VdbeSetP4KeyInfo(pParse, pPk); + tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); + tdsqlite3VdbeSetP4KeyInfo(pParse, pPk); } regRowid = ++pParse->nMem; } - iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); + iRetInit = tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y ** Then for every term xN, evaluate as the subexpression: xN AND z ** That way, terms in y that are factored into the disjunction will - ** be picked up by the recursive calls to sqlite3WhereBegin() below. + ** be picked up by the recursive calls to tdsqlite3WhereBegin() below. ** ** Actually, each subexpression is converted to "xN AND w" where w is ** the "interesting" terms of z - terms that did not originate in the @@ -129217,17 +145505,21 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ Expr *pExpr = pWC->a[iTerm].pExpr; if( &pWC->a[iTerm] == pTerm ) continue; - if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); - pExpr = sqlite3ExprDup(db, pExpr, 0); - pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); + pExpr = tdsqlite3ExprDup(db, pExpr, 0); + pAndExpr = tdsqlite3ExprAnd(pParse, pAndExpr, pExpr); } if( pAndExpr ){ - pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0); + /* The extra 0x10000 bit on the opcode is masked off and does not + ** become part of the new Expr.op. However, it does make the + ** op==TK_AND comparison inside of tdsqlite3PExpr() false, and this + ** prevents tdsqlite3PExpr() from implementing AND short-circuit + ** optimization, which we do not want here. */ + pAndExpr = tdsqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr); } } @@ -129236,27 +145528,32 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** sub-WHERE clause is to to invoke the main loop body as a subroutine. */ wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE); + ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR")); for(ii=0; ii<pOrWc->nTerm; ii++){ WhereTerm *pOrTerm = &pOrWc->a[ii]; if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ WhereInfo *pSubWInfo; /* Info for single OR-term scan */ Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ int jmp1 = 0; /* Address of jump operation */ - if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ + testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0 + && !ExprHasProperty(pOrExpr, EP_FromJoin) + ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */ + if( pAndExpr ){ pAndExpr->pLeft = pOrExpr; pOrExpr = pAndExpr; } /* Loop through table entries that match term pOrTerm. */ + ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1)); WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); - pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, + pSubWInfo = tdsqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, wctrlFlags, iCovCur); assert( pSubWInfo || pParse->nErr || db->mallocFailed ); if( pSubWInfo ){ WhereLoop *pSubLoop; - int addrExplain = sqlite3WhereExplainOneScan( - pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 + int addrExplain = tdsqlite3WhereExplainOneScan( + pParse, pOrTab, &pSubWInfo->a[0], 0 ); - sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); + tdsqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); /* This is the sub-WHERE clause body. First skip over ** duplicate rows from prior sub-WHERE clauses, and record the @@ -129264,23 +145561,23 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** row will be skipped in subsequent sub-WHERE clauses. */ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ - int r; int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); if( HasRowid(pTab) ){ - r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); - jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, - r,iSet); + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid); + jmp1 = tdsqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, + regRowid, iSet); VdbeCoverage(v); }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); + Index *pPk = tdsqlite3PrimaryKeyIndex(pTab); int nPk = pPk->nKeyCol; int iPk; + int r; /* Read the PK into an array of temp registers. */ - r = sqlite3GetTempRange(pParse, nPk); + r = tdsqlite3GetTempRange(pParse, nPk); for(iPk=0; iPk<nPk; iPk++){ int iCol = pPk->aiColumn[iPk]; - sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk); + tdsqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk); } /* Check if the temp table already contains this key. If so, @@ -129295,26 +145592,27 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** need to insert the key into the temp table, as it will never ** be tested for. */ if( iSet ){ - jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); + jmp1 = tdsqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); VdbeCoverage(v); } if( iSet>=0 ){ - sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); - sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0); - if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); + tdsqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid, + r, nPk); + if( iSet ) tdsqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); } /* Release the array of temp registers */ - sqlite3ReleaseTempRange(pParse, r, nPk); + tdsqlite3ReleaseTempRange(pParse, r, nPk); } } /* Invoke the main loop body as a subroutine */ - sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); + tdsqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); /* Jump here (skipping the main loop body subroutine) if the ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ - if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); + if( jmp1 ) tdsqlite3VdbeJumpHere(v, jmp1); /* The pSubWInfo->untestedTerms flag means that this OR term ** contained one or more AND term from a notReady table. The @@ -129325,10 +145623,10 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( /* If all of the OR-connected terms are optimized using the same ** index, and the index is opened using the same cursor number - ** by each call to sqlite3WhereBegin() made by this loop, it may + ** by each call to tdsqlite3WhereBegin() made by this loop, it may ** be possible to use that index as a covering index. ** - ** If the call to sqlite3WhereBegin() above resulted in a scan that + ** If the call to tdsqlite3WhereBegin() above resulted in a scan that ** uses an index, and this is either the first OR-connected term ** processed or the index is the same as that used by all previous ** terms, set pCov to the candidate covering index. Otherwise, set @@ -129348,21 +145646,23 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( } /* Finish the loop through table entries that match term pOrTerm. */ - sqlite3WhereEnd(pSubWInfo); + tdsqlite3WhereEnd(pSubWInfo); + ExplainQueryPlanPop(pParse); } } } + ExplainQueryPlanPop(pParse); pLevel->u.pCovidx = pCov; if( pCov ) pLevel->iIdxCur = iCovCur; if( pAndExpr ){ pAndExpr->pLeft = 0; - sqlite3ExprDelete(db, pAndExpr); + tdsqlite3ExprDelete(db, pAndExpr); } - sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); - sqlite3VdbeGoto(v, pLevel->addrBrk); - sqlite3VdbeResolveLabel(v, iLoopBody); + tdsqlite3VdbeChangeP1(v, iRetInit, tdsqlite3VdbeCurrentAddr(v)); + tdsqlite3VdbeGoto(v, pLevel->addrBrk); + tdsqlite3VdbeResolveLabel(v, iLoopBody); - if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); + if( pWInfo->nLevel>1 ){ tdsqlite3StackFree(db, pOrTab); } if( !untestedTerms ) disableTerm(pLevel, pTerm); }else #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ @@ -129382,7 +145682,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( codeCursorHint(pTabItem, pWInfo, pLevel, 0); pLevel->op = aStep[bRev]; pLevel->p1 = iCur; - pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); + pLevel->p2 = 1 + tdsqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; @@ -129390,48 +145690,86 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( } #ifdef SQLITE_ENABLE_STMT_SCANSTATUS - pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); + pLevel->addrVisit = tdsqlite3VdbeCurrentAddr(v); #endif /* Insert code to test every subexpression that can be completely ** computed using the current set of tables. + ** + ** This loop may run between one and three times, depending on the + ** constraints to be generated. The value of stack variable iLoop + ** determines the constraints coded by each iteration, as follows: + ** + ** iLoop==1: Code only expressions that are entirely covered by pIdx. + ** iLoop==2: Code remaining expressions that do not contain correlated + ** sub-queries. + ** iLoop==3: Code all remaining expressions. + ** + ** An effort is made to skip unnecessary iterations of the loop. */ - for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ - Expr *pE; - int skipLikeAddr = 0; - testcase( pTerm->wtFlags & TERM_VIRTUAL ); - testcase( pTerm->wtFlags & TERM_CODED ); - if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; - if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ - testcase( pWInfo->untestedTerms==0 - && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); - pWInfo->untestedTerms = 1; - continue; - } - pE = pTerm->pExpr; - assert( pE!=0 ); - if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ - continue; - } - if( pTerm->wtFlags & TERM_LIKECOND ){ - /* If the TERM_LIKECOND flag is set, that means that the range search - ** is sufficient to guarantee that the LIKE operator is true, so we - ** can skip the call to the like(A,B) function. But this only works - ** for strings. So do not skip the call to the function on the pass - ** that compares BLOBs. */ + iLoop = (pIdx ? 1 : 2); + do{ + int iNext = 0; /* Next value for iLoop */ + for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ + Expr *pE; + int skipLikeAddr = 0; + testcase( pTerm->wtFlags & TERM_VIRTUAL ); + testcase( pTerm->wtFlags & TERM_CODED ); + if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; + if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ + testcase( pWInfo->untestedTerms==0 + && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); + pWInfo->untestedTerms = 1; + continue; + } + pE = pTerm->pExpr; + assert( pE!=0 ); + if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){ + continue; + } + + if( iLoop==1 && !tdsqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){ + iNext = 2; + continue; + } + if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){ + if( iNext==0 ) iNext = 3; + continue; + } + + if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){ + /* If the TERM_LIKECOND flag is set, that means that the range search + ** is sufficient to guarantee that the LIKE operator is true, so we + ** can skip the call to the like(A,B) function. But this only works + ** for strings. So do not skip the call to the function on the pass + ** that compares BLOBs. */ #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS - continue; + continue; #else - u32 x = pLevel->iLikeRepCntr; - assert( x>0 ); - skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1)); - VdbeCoverage(v); + u32 x = pLevel->iLikeRepCntr; + if( x>0 ){ + skipLikeAddr = tdsqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1)); + VdbeCoverageIf(v, (x&1)==1); + VdbeCoverageIf(v, (x&1)==0); + } +#endif + } +#ifdef WHERETRACE_ENABLED /* 0xffff */ + if( tdsqlite3WhereTrace ){ + VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d", + pWC->nTerm-j, pTerm, iLoop)); + } + if( tdsqlite3WhereTrace & 0x800 ){ + tdsqlite3DebugPrintf("Coding auxiliary constraint:\n"); + tdsqlite3WhereTermPrint(pTerm, pWC->nTerm-j); + } #endif + tdsqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); + if( skipLikeAddr ) tdsqlite3VdbeJumpHere(v, skipLikeAddr); + pTerm->wtFlags |= TERM_CODED; } - sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); - if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); - pTerm->wtFlags |= TERM_CODED; - } + iLoop = iNext; + }while( iLoop>0 ); /* Insert code to test for implied constraints based on transitivity ** of the "==" operator. @@ -129448,31 +145786,42 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; if( pTerm->leftCursor!=iCur ) continue; - if( pLevel->iLeftJoin ) continue; + if( pTabItem->fg.jointype & JT_LEFT ) continue; pE = pTerm->pExpr; +#ifdef WHERETRACE_ENABLED /* 0x800 */ + if( tdsqlite3WhereTrace & 0x800 ){ + tdsqlite3DebugPrintf("Coding transitive constraint:\n"); + tdsqlite3WhereTermPrint(pTerm, pWC->nTerm-j); + } +#endif assert( !ExprHasProperty(pE, EP_FromJoin) ); assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); - pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, + pAlt = tdsqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN|WO_IS, 0); if( pAlt==0 ) continue; if( pAlt->wtFlags & (TERM_CODED) ) continue; + if( (pAlt->eOperator & WO_IN) + && (pAlt->pExpr->flags & EP_xIsSelect) + && (pAlt->pExpr->x.pSelect->pEList->nExpr>1) + ){ + continue; + } testcase( pAlt->eOperator & WO_EQ ); testcase( pAlt->eOperator & WO_IS ); testcase( pAlt->eOperator & WO_IN ); VdbeModuleComment((v, "begin transitive constraint")); sEAlt = *pAlt->pExpr; sEAlt.pLeft = pE->pLeft; - sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); + tdsqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); } /* For a LEFT OUTER JOIN, generate code that will record the fact that ** at least one row of the right table has matched the left table. */ if( pLevel->iLeftJoin ){ - pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); + pLevel->addrFirst = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); VdbeComment((v, "record LEFT JOIN hit")); - sqlite3ExprCacheClear(pParse); for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ testcase( pTerm->wtFlags & TERM_VIRTUAL ); testcase( pTerm->wtFlags & TERM_CODED ); @@ -129482,11 +145831,22 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( continue; } assert( pTerm->pExpr ); - sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); + tdsqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); pTerm->wtFlags |= TERM_CODED; } } +#if WHERETRACE_ENABLED /* 0x20800 */ + if( tdsqlite3WhereTrace & 0x20000 ){ + tdsqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n", + iLevel); + tdsqlite3WhereClausePrint(pWC); + } + if( tdsqlite3WhereTrace & 0x800 ){ + tdsqlite3DebugPrintf("End Coding level %d: notReady=%llx\n", + iLevel, (u64)pLevel->notReady); + } +#endif return pLevel->notReady; } @@ -129519,17 +145879,17 @@ static void exprAnalyze(SrcList*, WhereClause*, int); /* ** Deallocate all memory associated with a WhereOrInfo object. */ -static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ - sqlite3WhereClauseClear(&p->wc); - sqlite3DbFree(db, p); +static void whereOrInfoDelete(tdsqlite3 *db, WhereOrInfo *p){ + tdsqlite3WhereClauseClear(&p->wc); + tdsqlite3DbFree(db, p); } /* ** Deallocate all memory associated with a WhereAndInfo object. */ -static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ - sqlite3WhereClauseClear(&p->wc); - sqlite3DbFree(db, p); +static void whereAndInfoDelete(tdsqlite3 *db, WhereAndInfo *p){ + tdsqlite3WhereClauseClear(&p->wc); + tdsqlite3DbFree(db, p); } /* @@ -129557,28 +145917,28 @@ static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){ testcase( wtFlags & TERM_VIRTUAL ); if( pWC->nTerm>=pWC->nSlot ){ WhereTerm *pOld = pWC->a; - sqlite3 *db = pWC->pWInfo->pParse->db; - pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); + tdsqlite3 *db = pWC->pWInfo->pParse->db; + pWC->a = tdsqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); if( pWC->a==0 ){ if( wtFlags & TERM_DYNAMIC ){ - sqlite3ExprDelete(db, p); + tdsqlite3ExprDelete(db, p); } pWC->a = pOld; return 0; } memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); if( pOld!=pWC->aStatic ){ - sqlite3DbFree(db, pOld); + tdsqlite3DbFree(db, pOld); } - pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); + pWC->nSlot = tdsqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); } pTerm = &pWC->a[idx = pWC->nTerm++]; if( p && ExprHasProperty(p, EP_Unlikely) ){ - pTerm->truthProb = sqlite3LogEst(p->iTable) - 270; + pTerm->truthProb = tdsqlite3LogEst(p->iTable) - 270; }else{ pTerm->truthProb = 1; } - pTerm->pExpr = sqlite3ExprSkipCollate(p); + pTerm->pExpr = tdsqlite3ExprSkipCollateAndLikely(p); pTerm->wtFlags = wtFlags; pTerm->pWC = pWC; pTerm->iParent = -1; @@ -129603,31 +145963,14 @@ static int allowedOp(int op){ /* ** Commute a comparison operator. Expressions of the form "X op Y" ** are converted into "Y op X". -** -** If left/right precedence rules come into play when determining the -** collating sequence, then COLLATE operators are adjusted to ensure -** that the collating sequence does not change. For example: -** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on -** the left hand side of a comparison overrides any collation sequence -** attached to the right. For the same reason the EP_Collate flag -** is not commuted. -*/ -static void exprCommute(Parse *pParse, Expr *pExpr){ - u16 expRight = (pExpr->pRight->flags & EP_Collate); - u16 expLeft = (pExpr->pLeft->flags & EP_Collate); - assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN ); - if( expRight==expLeft ){ - /* Either X and Y both have COLLATE operator or neither do */ - if( expRight ){ - /* Both X and Y have COLLATE operators. Make sure X is always - ** used by clearing the EP_Collate flag from Y. */ - pExpr->pRight->flags &= ~EP_Collate; - }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){ - /* Neither X nor Y have COLLATE operators, but X has a non-default - ** collating sequence. So add the EP_Collate marker on X to cause - ** it to be searched first. */ - pExpr->pLeft->flags |= EP_Collate; - } +*/ +static u16 exprCommute(Parse *pParse, Expr *pExpr){ + if( pExpr->pLeft->op==TK_VECTOR + || pExpr->pRight->op==TK_VECTOR + || tdsqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) != + tdsqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft) + ){ + pExpr->flags ^= EP_Commuted; } SWAP(Expr*,pExpr->pRight,pExpr->pLeft); if( pExpr->op>=TK_GT ){ @@ -129638,6 +145981,7 @@ static void exprCommute(Parse *pParse, Expr *pExpr){ assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE ); pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; } + return 0; } /* @@ -129688,18 +146032,18 @@ static int isLikeOrGlob( int *pisComplete, /* True if the only wildcard is % in the last character */ int *pnoCase /* True if uppercase is equivalent to lowercase */ ){ - const char *z = 0; /* String on RHS of LIKE operator */ + const u8 *z = 0; /* String on RHS of LIKE operator */ Expr *pRight, *pLeft; /* Right and left size of LIKE operator */ ExprList *pList; /* List of operands to the LIKE operator */ - int c; /* One character in z[] */ + u8 c; /* One character in z[] */ int cnt; /* Number of non-wildcard prefix characters */ - char wc[3]; /* Wildcard characters */ - sqlite3 *db = pParse->db; /* Database connection */ - sqlite3_value *pVal = 0; + u8 wc[4]; /* Wildcard characters */ + tdsqlite3 *db = pParse->db; /* Database connection */ + tdsqlite3_value *pVal = 0; int op; /* Opcode of pRight */ int rc; /* Result code to return */ - if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){ + if( !tdsqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){ return 0; } #ifdef SQLITE_EBCDIC @@ -129707,55 +146051,111 @@ static int isLikeOrGlob( #endif pList = pExpr->x.pList; pLeft = pList->a[1].pExpr; - if( pLeft->op!=TK_COLUMN - || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT - || IsVirtual(pLeft->pTab) /* Value might be numeric */ - ){ - /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must - ** be the name of an indexed column with TEXT affinity. */ - return 0; - } - assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */ - pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr); + pRight = tdsqlite3ExprSkipCollate(pList->a[0].pExpr); op = pRight->op; - if( op==TK_VARIABLE ){ + if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){ Vdbe *pReprepare = pParse->pReprepare; int iCol = pRight->iColumn; - pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB); - if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ - z = (char *)sqlite3_value_text(pVal); + pVal = tdsqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB); + if( pVal && tdsqlite3_value_type(pVal)==SQLITE_TEXT ){ + z = tdsqlite3_value_text(pVal); } - sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); + tdsqlite3VdbeSetVarmask(pParse->pVdbe, iCol); assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); }else if( op==TK_STRING ){ - z = pRight->u.zToken; + z = (u8*)pRight->u.zToken; } if( z ){ + + /* Count the number of prefix characters prior to the first wildcard */ cnt = 0; while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; - } - if( cnt!=0 && 255!=(u8)z[cnt-1] ){ + if( c==wc[3] && z[cnt]!=0 ) cnt++; + } + + /* The optimization is possible only if (1) the pattern does not begin + ** with a wildcard and if (2) the non-wildcard prefix does not end with + ** an (illegal 0xff) character, or (3) the pattern does not consist of + ** a single escape character. The second condition is necessary so + ** that we can increment the prefix key to find an upper bound for the + ** range search. The third is because the caller assumes that the pattern + ** consists of at least one character after all escapes have been + ** removed. */ + if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){ Expr *pPrefix; + + /* A "complete" match if the pattern ends with "*" or "%" */ *pisComplete = c==wc[0] && z[cnt+1]==0; - pPrefix = sqlite3Expr(db, TK_STRING, z); - if( pPrefix ) pPrefix->u.zToken[cnt] = 0; + + /* Get the pattern prefix. Remove all escapes from the prefix. */ + pPrefix = tdsqlite3Expr(db, TK_STRING, (char*)z); + if( pPrefix ){ + int iFrom, iTo; + char *zNew = pPrefix->u.zToken; + zNew[cnt] = 0; + for(iFrom=iTo=0; iFrom<cnt; iFrom++){ + if( zNew[iFrom]==wc[3] ) iFrom++; + zNew[iTo++] = zNew[iFrom]; + } + zNew[iTo] = 0; + assert( iTo>0 ); + + /* If the LHS is not an ordinary column with TEXT affinity, then the + ** pattern prefix boundaries (both the start and end boundaries) must + ** not look like a number. Otherwise the pattern might be treated as + ** a number, which will invalidate the LIKE optimization. + ** + ** Getting this right has been a persistent source of bugs in the + ** LIKE optimization. See, for example: + ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1 + ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28 + ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07 + ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975 + ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a + */ + if( pLeft->op!=TK_COLUMN + || tdsqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT + || IsVirtual(pLeft->y.pTab) /* Value might be numeric */ + ){ + int isNum; + double rDummy; + isNum = tdsqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8); + if( isNum<=0 ){ + if( iTo==1 && zNew[0]=='-' ){ + isNum = +1; + }else{ + zNew[iTo-1]++; + isNum = tdsqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8); + zNew[iTo-1]--; + } + } + if( isNum>0 ){ + tdsqlite3ExprDelete(db, pPrefix); + tdsqlite3ValueFree(pVal); + return 0; + } + } + } *ppPrefix = pPrefix; + + /* If the RHS pattern is a bound parameter, make arrangements to + ** reprepare the statement when that parameter is rebound */ if( op==TK_VARIABLE ){ Vdbe *v = pParse->pVdbe; - sqlite3VdbeSetVarmask(v, pRight->iColumn); + tdsqlite3VdbeSetVarmask(v, pRight->iColumn); if( *pisComplete && pRight->u.zToken[1] ){ /* If the rhs of the LIKE expression is a variable, and the current ** value of the variable means there is no need to invoke the LIKE ** function, then no OP_Variable will be added to the program. - ** This causes problems for the sqlite3_bind_parameter_name() + ** This causes problems for the tdsqlite3_bind_parameter_name() ** API. To work around them, add a dummy OP_Variable here. */ - int r1 = sqlite3GetTempReg(pParse); - sqlite3ExprCodeTarget(pParse, pRight, r1); - sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0); - sqlite3ReleaseTempReg(pParse, r1); + int r1 = tdsqlite3GetTempReg(pParse); + tdsqlite3ExprCodeTarget(pParse, pRight, r1); + tdsqlite3VdbeChangeP3(v, tdsqlite3VdbeCurrentAddr(v)-1, 0); + tdsqlite3ReleaseTempReg(pParse, r1); } } }else{ @@ -129764,7 +146164,7 @@ static int isLikeOrGlob( } rc = (z!=0); - sqlite3ValueFree(pVal); + tdsqlite3ValueFree(pVal); return rc; } #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ @@ -129772,48 +146172,123 @@ static int isLikeOrGlob( #ifndef SQLITE_OMIT_VIRTUALTABLE /* -** Check to see if the given expression is of the form -** -** column OP expr -** -** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a -** column of a virtual table. -** -** If it is then return TRUE. If not, return FALSE. -*/ -static int isMatchOfColumn( +** Check to see if the pExpr expression is a form that needs to be passed +** to the xBestIndex method of virtual tables. Forms of interest include: +** +** Expression Virtual Table Operator +** ----------------------- --------------------------------- +** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH +** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB +** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE +** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP +** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE +** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE +** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT +** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT +** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL +** +** In every case, "column" must be a column of a virtual table. If there +** is a match, set *ppLeft to the "column" expression, set *ppRight to the +** "expr" expression (even though in forms (6) and (8) the column is on the +** right and the expression is on the left). Also set *peOp2 to the +** appropriate virtual table operator. The return value is 1 or 2 if there +** is a match. The usual return is 1, but if the RHS is also a column +** of virtual table in forms (5) or (7) then return 2. +** +** If the expression matches none of the patterns above, return 0. +*/ +static int isAuxiliaryVtabOperator( + tdsqlite3 *db, /* Parsing context */ Expr *pExpr, /* Test this expression */ - unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */ -){ - static const struct Op2 { - const char *zOp; - unsigned char eOp2; - } aOp[] = { - { "match", SQLITE_INDEX_CONSTRAINT_MATCH }, - { "glob", SQLITE_INDEX_CONSTRAINT_GLOB }, - { "like", SQLITE_INDEX_CONSTRAINT_LIKE }, - { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP } - }; - ExprList *pList; - Expr *pCol; /* Column reference */ - int i; + unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */ + Expr **ppLeft, /* Column expression to left of MATCH/op2 */ + Expr **ppRight /* Expression to left of MATCH/op2 */ +){ + if( pExpr->op==TK_FUNCTION ){ + static const struct Op2 { + const char *zOp; + unsigned char eOp2; + } aOp[] = { + { "match", SQLITE_INDEX_CONSTRAINT_MATCH }, + { "glob", SQLITE_INDEX_CONSTRAINT_GLOB }, + { "like", SQLITE_INDEX_CONSTRAINT_LIKE }, + { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP } + }; + ExprList *pList; + Expr *pCol; /* Column reference */ + int i; - if( pExpr->op!=TK_FUNCTION ){ - return 0; - } - pList = pExpr->x.pList; - if( pList==0 || pList->nExpr!=2 ){ - return 0; - } - pCol = pList->a[1].pExpr; - if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){ - return 0; - } - for(i=0; i<ArraySize(aOp); i++){ - if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){ - *peOp2 = aOp[i].eOp2; - return 1; + pList = pExpr->x.pList; + if( pList==0 || pList->nExpr!=2 ){ + return 0; + } + + /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a + ** virtual table on their second argument, which is the same as + ** the left-hand side operand in their in-fix form. + ** + ** vtab_column MATCH expression + ** MATCH(expression,vtab_column) + */ + pCol = pList->a[1].pExpr; + if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){ + for(i=0; i<ArraySize(aOp); i++){ + if( tdsqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){ + *peOp2 = aOp[i].eOp2; + *ppRight = pList->a[0].pExpr; + *ppLeft = pCol; + return 1; + } + } + } + + /* We can also match against the first column of overloaded + ** functions where xFindFunction returns a value of at least + ** SQLITE_INDEX_CONSTRAINT_FUNCTION. + ** + ** OVERLOADED(vtab_column,expression) + ** + ** Historically, xFindFunction expected to see lower-case function + ** names. But for this use case, xFindFunction is expected to deal + ** with function names in an arbitrary case. + */ + pCol = pList->a[0].pExpr; + if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){ + tdsqlite3_vtab *pVtab; + tdsqlite3_module *pMod; + void (*xNotUsed)(tdsqlite3_context*,int,tdsqlite3_value**); + void *pNotUsed; + pVtab = tdsqlite3GetVTable(db, pCol->y.pTab)->pVtab; + assert( pVtab!=0 ); + assert( pVtab->pModule!=0 ); + pMod = (tdsqlite3_module *)pVtab->pModule; + if( pMod->xFindFunction!=0 ){ + i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed); + if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){ + *peOp2 = i; + *ppRight = pList->a[1].pExpr; + *ppLeft = pCol; + return 1; + } + } } + }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){ + int res = 0; + Expr *pLeft = pExpr->pLeft; + Expr *pRight = pExpr->pRight; + if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->y.pTab) ){ + res++; + } + if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->y.pTab) ){ + res++; + SWAP(Expr*, pLeft, pRight); + } + *ppLeft = pLeft; + *ppRight = pRight; + if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE; + if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT; + if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL; + return res; } return 0; } @@ -129881,7 +146356,7 @@ static void whereCombineDisjuncts( WhereTerm *pTwo /* Second disjunct */ ){ u16 eOp = pOne->eOperator | pTwo->eOperator; - sqlite3 *db; /* Database connection (for malloc) */ + tdsqlite3 *db; /* Database connection (for malloc) */ Expr *pNew; /* New virtual expression */ int op; /* Operator for the combined expression */ int idxNew; /* Index in pWC of the next virtual term */ @@ -129892,8 +146367,8 @@ static void whereCombineDisjuncts( && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return; assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 ); assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 ); - if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return; - if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return; + if( tdsqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return; + if( tdsqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return; /* If we reach this point, it means the two subterms can be combined */ if( (eOp & (eOp-1))!=0 ){ if( eOp & (WO_LT|WO_LE) ){ @@ -129904,7 +146379,7 @@ static void whereCombineDisjuncts( } } db = pWC->pWInfo->pParse->db; - pNew = sqlite3ExprDup(db, pOne->pExpr, 0); + pNew = tdsqlite3ExprDup(db, pOne->pExpr, 0); if( pNew==0 ) return; for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); } pNew->op = op; @@ -130007,7 +146482,7 @@ static void exprAnalyzeOrTerm( ){ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ Parse *pParse = pWInfo->pParse; /* Parser context */ - sqlite3 *db = pParse->db; /* Database connection */ + tdsqlite3 *db = pParse->db; /* Database connection */ WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ Expr *pExpr = pTerm->pExpr; /* The expression of the term */ int i; /* Loop counters */ @@ -130024,14 +146499,14 @@ static void exprAnalyzeOrTerm( */ assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); assert( pExpr->op==TK_OR ); - pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); + pTerm->u.pOrInfo = pOrInfo = tdsqlite3DbMallocZero(db, sizeof(*pOrInfo)); if( pOrInfo==0 ) return; pTerm->wtFlags |= TERM_ORINFO; pOrWc = &pOrInfo->wc; memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic)); - sqlite3WhereClauseInit(pOrWc, pWInfo); - sqlite3WhereSplit(pOrWc, pExpr, TK_OR); - sqlite3WhereExprAnalyze(pSrc, pOrWc); + tdsqlite3WhereClauseInit(pOrWc, pWInfo); + tdsqlite3WhereSplit(pOrWc, pExpr, TK_OR); + tdsqlite3WhereExprAnalyze(pSrc, pOrWc); if( db->mallocFailed ) return; assert( pOrWc->nTerm>=2 ); @@ -130045,7 +146520,7 @@ static void exprAnalyzeOrTerm( WhereAndInfo *pAndInfo; assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); chngToIN = 0; - pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo)); + pAndInfo = tdsqlite3DbMallocRawNN(db, sizeof(*pAndInfo)); if( pAndInfo ){ WhereClause *pAndWC; WhereTerm *pAndTerm; @@ -130056,17 +146531,17 @@ static void exprAnalyzeOrTerm( pOrTerm->eOperator = WO_AND; pAndWC = &pAndInfo->wc; memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic)); - sqlite3WhereClauseInit(pAndWC, pWC->pWInfo); - sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND); - sqlite3WhereExprAnalyze(pSrc, pAndWC); + tdsqlite3WhereClauseInit(pAndWC, pWC->pWInfo); + tdsqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND); + tdsqlite3WhereExprAnalyze(pSrc, pAndWC); pAndWC->pOuter = pWC; if( !db->mallocFailed ){ for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){ assert( pAndTerm->pExpr ); if( allowedOp(pAndTerm->pExpr->op) - || pAndTerm->eOperator==WO_MATCH + || pAndTerm->eOperator==WO_AUX ){ - b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); + b |= tdsqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); } } } @@ -130077,10 +146552,10 @@ static void exprAnalyzeOrTerm( ** corresponding TERM_VIRTUAL term */ }else{ Bitmask b; - b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); + b = tdsqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); if( pOrTerm->wtFlags & TERM_VIRTUAL ){ WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; - b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor); + b |= tdsqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor); } indexable &= b; if( (pOrTerm->eOperator & WO_EQ)==0 ){ @@ -130096,7 +146571,12 @@ static void exprAnalyzeOrTerm( ** empty. */ pOrInfo->indexable = indexable; - pTerm->eOperator = indexable==0 ? 0 : WO_OR; + if( indexable ){ + pTerm->eOperator = WO_OR; + pWC->hasOr = 1; + }else{ + pTerm->eOperator = WO_OR; + } /* For a two-way OR, attempt to implementation case 2. */ @@ -130146,6 +146626,7 @@ static void exprAnalyzeOrTerm( ** and column is found but leave okToChngToIN false if not found. */ for(j=0; j<2 && !okToChngToIN; j++){ + Expr *pLeft = 0; pOrTerm = pOrWc->a; for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ assert( pOrTerm->eOperator & WO_EQ ); @@ -130156,7 +146637,7 @@ static void exprAnalyzeOrTerm( assert( j==1 ); continue; } - if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet, + if( (chngToIN & tdsqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){ /* This term must be of the form t1.a==t2.b where t2 is in the ** chngToIN set but t1 is not. This term will be either preceded @@ -130169,6 +146650,7 @@ static void exprAnalyzeOrTerm( } iColumn = pOrTerm->u.leftColumn; iCursor = pOrTerm->leftCursor; + pLeft = pOrTerm->pExpr->pLeft; break; } if( i<0 ){ @@ -130176,7 +146658,7 @@ static void exprAnalyzeOrTerm( ** on the second iteration */ assert( j==1 ); assert( IsPowerOfTwo(chngToIN) ); - assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) ); + assert( chngToIN==tdsqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) ); break; } testcase( j==1 ); @@ -130188,7 +146670,9 @@ static void exprAnalyzeOrTerm( assert( pOrTerm->eOperator & WO_EQ ); if( pOrTerm->leftCursor!=iCursor ){ pOrTerm->wtFlags &= ~TERM_OR_OK; - }else if( pOrTerm->u.leftColumn!=iColumn ){ + }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR + && tdsqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1) + )){ okToChngToIN = 0; }else{ int affLeft, affRight; @@ -130196,8 +146680,8 @@ static void exprAnalyzeOrTerm( ** of both right and left sides must be such that no type ** conversions are required on the right. (Ticket #2249) */ - affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); - affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); + affRight = tdsqlite3ExprAffinity(pOrTerm->pExpr->pRight); + affLeft = tdsqlite3ExprAffinity(pOrTerm->pExpr->pLeft); if( affRight!=0 && affRight!=affLeft ){ okToChngToIN = 0; }else{ @@ -130222,13 +146706,13 @@ static void exprAnalyzeOrTerm( assert( pOrTerm->eOperator & WO_EQ ); assert( pOrTerm->leftCursor==iCursor ); assert( pOrTerm->u.leftColumn==iColumn ); - pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); - pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); + pDup = tdsqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); + pList = tdsqlite3ExprListAppend(pWInfo->pParse, pList, pDup); pLeft = pOrTerm->pExpr->pLeft; } assert( pLeft!=0 ); - pDup = sqlite3ExprDup(db, pLeft, 0); - pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0); + pDup = tdsqlite3ExprDup(db, pLeft, 0); + pNew = tdsqlite3PExpr(pParse, TK_IN, pDup, 0); if( pNew ){ int idxNew; transferJoinMarkings(pNew, pExpr); @@ -130237,12 +146721,11 @@ static void exprAnalyzeOrTerm( idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); testcase( idxNew==0 ); exprAnalyze(pSrc, pWC, idxNew); - pTerm = &pWC->a[idxTerm]; + /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */ markTermAsChild(pWC, idxNew, idxTerm); }else{ - sqlite3ExprListDelete(db, pList); + tdsqlite3ExprListDelete(db, pList); } - pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */ } } } @@ -130266,24 +146749,19 @@ static void exprAnalyzeOrTerm( static int termIsEquivalence(Parse *pParse, Expr *pExpr){ char aff1, aff2; CollSeq *pColl; - const char *zColl1, *zColl2; if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0; - aff1 = sqlite3ExprAffinity(pExpr->pLeft); - aff2 = sqlite3ExprAffinity(pExpr->pRight); + aff1 = tdsqlite3ExprAffinity(pExpr->pLeft); + aff2 = tdsqlite3ExprAffinity(pExpr->pRight); if( aff1!=aff2 - && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2)) + && (!tdsqlite3IsNumericAffinity(aff1) || !tdsqlite3IsNumericAffinity(aff2)) ){ return 0; } - pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight); - if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1; - pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); - zColl1 = pColl ? pColl->zName : 0; - pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight); - zColl2 = pColl ? pColl->zName : 0; - return sqlite3_stricmp(zColl1, zColl2)==0; + pColl = tdsqlite3ExprCompareCollSeq(pParse, pExpr); + if( tdsqlite3IsBinary(pColl) ) return 1; + return tdsqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight); } /* @@ -130295,16 +146773,19 @@ static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){ Bitmask mask = 0; while( pS ){ SrcList *pSrc = pS->pSrc; - mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList); - mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy); - mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy); - mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere); - mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving); + mask |= tdsqlite3WhereExprListUsage(pMaskSet, pS->pEList); + mask |= tdsqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy); + mask |= tdsqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy); + mask |= tdsqlite3WhereExprUsage(pMaskSet, pS->pWhere); + mask |= tdsqlite3WhereExprUsage(pMaskSet, pS->pHaving); if( ALWAYS(pSrc!=0) ){ int i; for(i=0; i<pSrc->nSrc; i++){ mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect); - mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn); + mask |= tdsqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn); + if( pSrc->a[i].fg.isTabFunc ){ + mask |= tdsqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg); + } } } pS = pS->pPrior; @@ -130316,8 +146797,8 @@ static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){ ** Expression pExpr is one operand of a comparison operator that might ** be useful for indexing. This routine checks to see if pExpr appears ** in any index. Return TRUE (1) if pExpr is an indexed term and return -** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor -** number of the table that is indexed and *piColumn to the column number +** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor +** number of the table that is indexed and aiCurCol[1] to the column number ** of the column that is indexed, or XN_EXPR (-2) if an expression is being ** indexed. ** @@ -130325,18 +146806,37 @@ static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){ ** true even if that particular column is not indexed, because the column ** might be added to an automatic index later. */ -static int exprMightBeIndexed( +static SQLITE_NOINLINE int exprMightBeIndexed2( SrcList *pFrom, /* The FROM clause */ - int op, /* The specific comparison operator */ Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ - Expr *pExpr, /* An operand of a comparison operator */ - int *piCur, /* Write the referenced table cursor number here */ - int *piColumn /* Write the referenced table column number here */ + int *aiCurCol, /* Write the referenced table cursor and column here */ + Expr *pExpr /* An operand of a comparison operator */ ){ Index *pIdx; int i; int iCur; - + for(i=0; mPrereq>1; i++, mPrereq>>=1){} + iCur = pFrom->a[i].iCursor; + for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->aColExpr==0 ) continue; + for(i=0; i<pIdx->nKeyCol; i++){ + if( pIdx->aiColumn[i]!=XN_EXPR ) continue; + if( tdsqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){ + aiCurCol[0] = iCur; + aiCurCol[1] = XN_EXPR; + return 1; + } + } + } + return 0; +} +static int exprMightBeIndexed( + SrcList *pFrom, /* The FROM clause */ + Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ + int *aiCurCol, /* Write the referenced table cursor & column here */ + Expr *pExpr, /* An operand of a comparison operator */ + int op /* The specific comparison operator */ +){ /* If this expression is a vector to the left or right of a ** inequality constraint (>, <, >= or <=), perform the processing ** on the first element of the vector. */ @@ -130348,26 +146848,13 @@ static int exprMightBeIndexed( } if( pExpr->op==TK_COLUMN ){ - *piCur = pExpr->iTable; - *piColumn = pExpr->iColumn; + aiCurCol[0] = pExpr->iTable; + aiCurCol[1] = pExpr->iColumn; return 1; } if( mPrereq==0 ) return 0; /* No table references */ if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */ - for(i=0; mPrereq>1; i++, mPrereq>>=1){} - iCur = pFrom->a[i].iCursor; - for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - if( pIdx->aColExpr==0 ) continue; - for(i=0; i<pIdx->nKeyCol; i++){ - if( pIdx->aiColumn[i]!=XN_EXPR ) continue; - if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){ - *piCur = iCur; - *piColumn = XN_EXPR; - return 1; - } - } - } - return 0; + return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr); } /* @@ -130405,8 +146892,9 @@ static void exprAnalyze( int noCase = 0; /* uppercase equivalent to lowercase */ int op; /* Top-level operator. pExpr->op */ Parse *pParse = pWInfo->pParse; /* Parsing context */ - sqlite3 *db = pParse->db; /* Database connection */ - unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */ + tdsqlite3 *db = pParse->db; /* Database connection */ + unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */ + int nLeft; /* Number of elements on left side vector */ if( db->mallocFailed ){ return; @@ -130415,36 +146903,42 @@ static void exprAnalyze( pMaskSet = &pWInfo->sMaskSet; pExpr = pTerm->pExpr; assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); - prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft); + prereqLeft = tdsqlite3WhereExprUsage(pMaskSet, pExpr->pLeft); op = pExpr->op; if( op==TK_IN ){ assert( pExpr->pRight==0 ); - if( sqlite3ExprCheckIN(pParse, pExpr) ) return; + if( tdsqlite3ExprCheckIN(pParse, pExpr) ) return; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect); }else{ - pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList); + pTerm->prereqRight = tdsqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList); } }else if( op==TK_ISNULL ){ pTerm->prereqRight = 0; }else{ - pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight); + pTerm->prereqRight = tdsqlite3WhereExprUsage(pMaskSet, pExpr->pRight); } - prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr); + pMaskSet->bVarSelect = 0; + prereqAll = tdsqlite3WhereExprUsageNN(pMaskSet, pExpr); + if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT; if( ExprHasProperty(pExpr, EP_FromJoin) ){ - Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable); + Bitmask x = tdsqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable); prereqAll |= x; extraRight = x-1; /* ON clause terms may not be used with an index ** on left table of a LEFT JOIN. Ticket #3015 */ + if( (prereqAll>>1)>=x ){ + tdsqlite3ErrorMsg(pParse, "ON clause references tables to its right"); + return; + } } pTerm->prereqAll = prereqAll; pTerm->leftCursor = -1; pTerm->iParent = -1; pTerm->eOperator = 0; if( allowedOp(op) ){ - int iCur, iColumn; - Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); - Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); + int aiCurCol[2]; + Expr *pLeft = tdsqlite3ExprSkipCollate(pExpr->pLeft); + Expr *pRight = tdsqlite3ExprSkipCollate(pExpr->pRight); u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; if( pTerm->iField>0 ){ @@ -130453,14 +146947,14 @@ static void exprAnalyze( pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr; } - if( exprMightBeIndexed(pSrc, op, prereqLeft, pLeft, &iCur, &iColumn) ){ - pTerm->leftCursor = iCur; - pTerm->u.leftColumn = iColumn; + if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){ + pTerm->leftCursor = aiCurCol[0]; + pTerm->u.leftColumn = aiCurCol[1]; pTerm->eOperator = operatorMask(op) & opMask; } if( op==TK_IS ) pTerm->wtFlags |= TERM_IS; if( pRight - && exprMightBeIndexed(pSrc, op, pTerm->prereqRight, pRight, &iCur,&iColumn) + && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op) ){ WhereTerm *pNew; Expr *pDup; @@ -130468,9 +146962,9 @@ static void exprAnalyze( assert( pTerm->iField==0 ); if( pTerm->leftCursor>=0 ){ int idxNew; - pDup = sqlite3ExprDup(db, pExpr, 0); + pDup = tdsqlite3ExprDup(db, pExpr, 0); if( db->mallocFailed ){ - sqlite3ExprDelete(db, pDup); + tdsqlite3ExprDelete(db, pDup); return; } idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); @@ -130489,9 +146983,9 @@ static void exprAnalyze( pDup = pExpr; pNew = pTerm; } - exprCommute(pParse, pDup); - pNew->leftCursor = iCur; - pNew->u.leftColumn = iColumn; + pNew->wtFlags |= exprCommute(pParse, pDup); + pNew->leftCursor = aiCurCol[0]; + pNew->u.leftColumn = aiCurCol[1]; testcase( (prereqLeft | extraRight) != prereqLeft ); pNew->prereqRight = prereqLeft | extraRight; pNew->prereqAll = prereqAll; @@ -130524,9 +147018,9 @@ static void exprAnalyze( for(i=0; i<2; i++){ Expr *pNewExpr; int idxNew; - pNewExpr = sqlite3PExpr(pParse, ops[i], - sqlite3ExprDup(db, pExpr->pLeft, 0), - sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0); + pNewExpr = tdsqlite3PExpr(pParse, ops[i], + tdsqlite3ExprDup(db, pExpr->pLeft, 0), + tdsqlite3ExprDup(db, pList->a[i].pExpr, 0)); transferJoinMarkings(pNewExpr, pExpr); idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); testcase( idxNew==0 ); @@ -130575,7 +147069,7 @@ static void exprAnalyze( const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC; pLeft = pExpr->x.pList->a[1].pExpr; - pStr2 = sqlite3ExprDup(db, pStr1, 0); + pStr2 = tdsqlite3ExprDup(db, pStr1, 0); /* Convert the lower bound to upper-case and the upper bound to ** lower-case (upper-case is less than lower-case in ASCII) so that @@ -130586,14 +147080,14 @@ static void exprAnalyze( char c; pTerm->wtFlags |= TERM_LIKE; for(i=0; (c = pStr1->u.zToken[i])!=0; i++){ - pStr1->u.zToken[i] = sqlite3Toupper(c); - pStr2->u.zToken[i] = sqlite3Tolower(c); + pStr1->u.zToken[i] = tdsqlite3Toupper(c); + pStr2->u.zToken[i] = tdsqlite3Tolower(c); } } if( !db->mallocFailed ){ u8 c, *pC; /* Last character before the first wildcard */ - pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; + pC = (u8*)&pStr2->u.zToken[tdsqlite3Strlen30(pStr2->u.zToken)-1]; c = *pC; if( noCase ){ /* The point is to increment the last character before the first @@ -130603,23 +147097,23 @@ static void exprAnalyze( ** LIKE on all candidate expressions by clearing the isComplete flag */ if( c=='A'-1 ) isComplete = 0; - c = sqlite3UpperToLower[c]; + c = tdsqlite3UpperToLower[c]; } *pC = c + 1; } - zCollSeqName = noCase ? "NOCASE" : "BINARY"; - pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); - pNewExpr1 = sqlite3PExpr(pParse, TK_GE, - sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName), - pStr1, 0); + zCollSeqName = noCase ? "NOCASE" : tdsqlite3StrBINARY; + pNewExpr1 = tdsqlite3ExprDup(db, pLeft, 0); + pNewExpr1 = tdsqlite3PExpr(pParse, TK_GE, + tdsqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName), + pStr1); transferJoinMarkings(pNewExpr1, pExpr); idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags); testcase( idxNew1==0 ); exprAnalyze(pSrc, pWC, idxNew1); - pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); - pNewExpr2 = sqlite3PExpr(pParse, TK_LT, - sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName), - pStr2, 0); + pNewExpr2 = tdsqlite3ExprDup(db, pLeft, 0); + pNewExpr2 = tdsqlite3PExpr(pParse, TK_LT, + tdsqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName), + pStr2); transferJoinMarkings(pNewExpr2, pExpr); idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags); testcase( idxNew2==0 ); @@ -130633,38 +147127,47 @@ static void exprAnalyze( #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ #ifndef SQLITE_OMIT_VIRTUALTABLE - /* Add a WO_MATCH auxiliary term to the constraint set if the - ** current expression is of the form: column MATCH expr. + /* Add a WO_AUX auxiliary term to the constraint set if the + ** current expression is of the form "column OP expr" where OP + ** is an operator that gets passed into virtual tables but which is + ** not normally optimized for ordinary tables. In other words, OP + ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL. ** This information is used by the xBestIndex methods of ** virtual tables. The native query optimizer does not attempt ** to do anything with MATCH functions. */ - if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){ - int idxNew; - Expr *pRight, *pLeft; - WhereTerm *pNewTerm; - Bitmask prereqColumn, prereqExpr; - - pRight = pExpr->x.pList->a[0].pExpr; - pLeft = pExpr->x.pList->a[1].pExpr; - prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight); - prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft); - if( (prereqExpr & prereqColumn)==0 ){ - Expr *pNewExpr; - pNewExpr = sqlite3PExpr(pParse, TK_MATCH, - 0, sqlite3ExprDup(db, pRight, 0), 0); - idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); - testcase( idxNew==0 ); - pNewTerm = &pWC->a[idxNew]; - pNewTerm->prereqRight = prereqExpr; - pNewTerm->leftCursor = pLeft->iTable; - pNewTerm->u.leftColumn = pLeft->iColumn; - pNewTerm->eOperator = WO_MATCH; - pNewTerm->eMatchOp = eOp2; - markTermAsChild(pWC, idxNew, idxTerm); - pTerm = &pWC->a[idxTerm]; - pTerm->wtFlags |= TERM_COPIED; - pNewTerm->prereqAll = pTerm->prereqAll; + if( pWC->op==TK_AND ){ + Expr *pRight = 0, *pLeft = 0; + int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight); + while( res-- > 0 ){ + int idxNew; + WhereTerm *pNewTerm; + Bitmask prereqColumn, prereqExpr; + + prereqExpr = tdsqlite3WhereExprUsage(pMaskSet, pRight); + prereqColumn = tdsqlite3WhereExprUsage(pMaskSet, pLeft); + if( (prereqExpr & prereqColumn)==0 ){ + Expr *pNewExpr; + pNewExpr = tdsqlite3PExpr(pParse, TK_MATCH, + 0, tdsqlite3ExprDup(db, pRight, 0)); + if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){ + ExprSetProperty(pNewExpr, EP_FromJoin); + pNewExpr->iRightJoinTable = pExpr->iRightJoinTable; + } + idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); + testcase( idxNew==0 ); + pNewTerm = &pWC->a[idxNew]; + pNewTerm->prereqRight = prereqExpr; + pNewTerm->leftCursor = pLeft->iTable; + pNewTerm->u.leftColumn = pLeft->iColumn; + pNewTerm->eOperator = WO_AUX; + pNewTerm->eMatchOp = eOp2; + markTermAsChild(pWC, idxNew, idxTerm); + pTerm = &pWC->a[idxTerm]; + pTerm->wtFlags |= TERM_COPIED; + pNewTerm->prereqAll = pTerm->prereqAll; + } + SWAP(Expr*, pLeft, pRight); } } #endif /* SQLITE_OMIT_VIRTUALTABLE */ @@ -130678,26 +147181,25 @@ static void exprAnalyze( ** is not a sub-select. */ if( pWC->op==TK_AND && (pExpr->op==TK_EQ || pExpr->op==TK_IS) - && sqlite3ExprIsVector(pExpr->pLeft) + && (nLeft = tdsqlite3ExprVectorSize(pExpr->pLeft))>1 + && tdsqlite3ExprVectorSize(pExpr->pRight)==nLeft && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 - || (pExpr->pRight->flags & EP_xIsSelect)==0 - )){ - int nLeft = sqlite3ExprVectorSize(pExpr->pLeft); + || (pExpr->pRight->flags & EP_xIsSelect)==0) + ){ int i; - assert( nLeft==sqlite3ExprVectorSize(pExpr->pRight) ); for(i=0; i<nLeft; i++){ int idxNew; Expr *pNew; - Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i); - Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i); + Expr *pLeft = tdsqlite3ExprForVectorField(pParse, pExpr->pLeft, i); + Expr *pRight = tdsqlite3ExprForVectorField(pParse, pExpr->pRight, i); - pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight, 0); + pNew = tdsqlite3PExpr(pParse, pExpr->op, pLeft, pRight); transferJoinMarkings(pNew, pExpr); idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC); exprAnalyze(pSrc, pWC, idxNew); } pTerm = &pWC->a[idxTerm]; - pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */ + pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */ pTerm->eOperator = 0; } @@ -130707,14 +147209,18 @@ static void exprAnalyze( ** expression). The WhereTerm.iField variable identifies the index within ** the vector on the LHS that the virtual term represents. ** - ** This only works if the RHS is a simple SELECT, not a compound + ** This only works if the RHS is a simple SELECT (not a compound) that does + ** not use window functions. */ if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0 && pExpr->pLeft->op==TK_VECTOR && pExpr->x.pSelect->pPrior==0 +#ifndef SQLITE_OMIT_WINDOWFUNC + && pExpr->x.pSelect->pWin==0 +#endif ){ int i; - for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){ + for(i=0; i<tdsqlite3ExprVectorSize(pExpr->pLeft); i++){ int idxNew; idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL); pWC->a[idxNew].iField = i+1; @@ -130723,8 +147229,8 @@ static void exprAnalyze( } } -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - /* When sqlite_stat3 histogram data is available an operator of the +#ifdef SQLITE_ENABLE_STAT4 + /* When sqlite_stat4 histogram data is available an operator of the ** form "x IS NOT NULL" can sometimes be evaluated more efficiently ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a ** virtual term of that form. @@ -130734,16 +147240,17 @@ static void exprAnalyze( if( pExpr->op==TK_NOTNULL && pExpr->pLeft->op==TK_COLUMN && pExpr->pLeft->iColumn>=0 - && OptimizationEnabled(db, SQLITE_Stat34) + && !ExprHasProperty(pExpr, EP_FromJoin) + && OptimizationEnabled(db, SQLITE_Stat4) ){ Expr *pNewExpr; Expr *pLeft = pExpr->pLeft; int idxNew; WhereTerm *pNewTerm; - pNewExpr = sqlite3PExpr(pParse, TK_GT, - sqlite3ExprDup(db, pLeft, 0), - sqlite3ExprAlloc(db, TK_NULL, 0, 0), 0); + pNewExpr = tdsqlite3PExpr(pParse, TK_GT, + tdsqlite3ExprDup(db, pLeft, 0), + tdsqlite3ExprAlloc(db, TK_NULL, 0, 0)); idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL); @@ -130759,7 +147266,7 @@ static void exprAnalyze( pNewTerm->prereqAll = pTerm->prereqAll; } } -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ /* Prevent ON clause terms of a LEFT JOIN from being used to drive ** an index for tables to the left of the join. @@ -130791,26 +147298,27 @@ static void exprAnalyze( ** the WhereClause.a[] array. The slot[] array grows as needed to contain ** all terms of the WHERE clause. */ -SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ - Expr *pE2 = sqlite3ExprSkipCollate(pExpr); +SQLITE_PRIVATE void tdsqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ + Expr *pE2 = tdsqlite3ExprSkipCollateAndLikely(pExpr); pWC->op = op; if( pE2==0 ) return; if( pE2->op!=op ){ whereClauseInsert(pWC, pExpr, 0); }else{ - sqlite3WhereSplit(pWC, pE2->pLeft, op); - sqlite3WhereSplit(pWC, pE2->pRight, op); + tdsqlite3WhereSplit(pWC, pE2->pLeft, op); + tdsqlite3WhereSplit(pWC, pE2->pRight, op); } } /* ** Initialize a preallocated WhereClause structure. */ -SQLITE_PRIVATE void sqlite3WhereClauseInit( +SQLITE_PRIVATE void tdsqlite3WhereClauseInit( WhereClause *pWC, /* The WhereClause to be initialized */ WhereInfo *pWInfo /* The WHERE processing context */ ){ pWC->pWInfo = pWInfo; + pWC->hasOr = 0; pWC->pOuter = 0; pWC->nTerm = 0; pWC->nSlot = ArraySize(pWC->aStatic); @@ -130820,15 +147328,15 @@ SQLITE_PRIVATE void sqlite3WhereClauseInit( /* ** Deallocate a WhereClause structure. The WhereClause structure ** itself is not freed. This routine is the inverse of -** sqlite3WhereClauseInit(). +** tdsqlite3WhereClauseInit(). */ -SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){ +SQLITE_PRIVATE void tdsqlite3WhereClauseClear(WhereClause *pWC){ int i; WhereTerm *a; - sqlite3 *db = pWC->pWInfo->pParse->db; + tdsqlite3 *db = pWC->pWInfo->pParse->db; for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ if( a->wtFlags & TERM_DYNAMIC ){ - sqlite3ExprDelete(db, a->pExpr); + tdsqlite3ExprDelete(db, a->pExpr); } if( a->wtFlags & TERM_ORINFO ){ whereOrInfoDelete(db, a->u.pOrInfo); @@ -130837,7 +147345,7 @@ SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){ } } if( pWC->a!=pWC->aStatic ){ - sqlite3DbFree(db, pWC->a); + tdsqlite3DbFree(db, pWC->a); } } @@ -130847,29 +147355,43 @@ SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){ ** a bitmask indicating which tables are used in that expression ** tree. */ -SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){ +SQLITE_PRIVATE Bitmask tdsqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){ Bitmask mask; - if( p==0 ) return 0; - if( p->op==TK_COLUMN ){ - mask = sqlite3WhereGetMask(pMaskSet, p->iTable); - return mask; + if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){ + return tdsqlite3WhereGetMask(pMaskSet, p->iTable); + }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ + assert( p->op!=TK_IF_NULL_ROW ); + return 0; } - assert( !ExprHasProperty(p, EP_TokenOnly) ); - mask = p->pRight ? sqlite3WhereExprUsage(pMaskSet, p->pRight) : 0; - if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft); - if( ExprHasProperty(p, EP_xIsSelect) ){ + mask = (p->op==TK_IF_NULL_ROW) ? tdsqlite3WhereGetMask(pMaskSet, p->iTable) : 0; + if( p->pLeft ) mask |= tdsqlite3WhereExprUsageNN(pMaskSet, p->pLeft); + if( p->pRight ){ + mask |= tdsqlite3WhereExprUsageNN(pMaskSet, p->pRight); + assert( p->x.pList==0 ); + }else if( ExprHasProperty(p, EP_xIsSelect) ){ + if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1; mask |= exprSelectUsage(pMaskSet, p->x.pSelect); }else if( p->x.pList ){ - mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList); + mask |= tdsqlite3WhereExprListUsage(pMaskSet, p->x.pList); + } +#ifndef SQLITE_OMIT_WINDOWFUNC + if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){ + mask |= tdsqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition); + mask |= tdsqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy); + mask |= tdsqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter); } +#endif return mask; } -SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){ +SQLITE_PRIVATE Bitmask tdsqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){ + return p ? tdsqlite3WhereExprUsageNN(pMaskSet,p) : 0; +} +SQLITE_PRIVATE Bitmask tdsqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){ int i; Bitmask mask = 0; if( pList ){ for(i=0; i<pList->nExpr; i++){ - mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr); + mask |= tdsqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr); } } return mask; @@ -130884,7 +147406,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprLis ** virtual terms, so start analyzing at the end and work forward ** so that the added virtual terms are never processed. */ -SQLITE_PRIVATE void sqlite3WhereExprAnalyze( +SQLITE_PRIVATE void tdsqlite3WhereExprAnalyze( SrcList *pTabList, /* the FROM clause */ WhereClause *pWC /* the WHERE clause to be analyzed */ ){ @@ -130901,7 +147423,7 @@ SQLITE_PRIVATE void sqlite3WhereExprAnalyze( ** Each function argument translates into an equality constraint against ** a HIDDEN column in the table. */ -SQLITE_PRIVATE void sqlite3WhereTabFuncArgs( +SQLITE_PRIVATE void tdsqlite3WhereTabFuncArgs( Parse *pParse, /* Parsing context */ struct SrcList_item *pItem, /* The FROM clause term to process */ WhereClause *pWC /* Xfer function arguments to here */ @@ -130917,19 +147439,24 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs( pArgs = pItem->u1.pFuncArg; if( pArgs==0 ) return; for(j=k=0; j<pArgs->nExpr; j++){ + Expr *pRhs; while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;} if( k>=pTab->nCol ){ - sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d", + tdsqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d", pTab->zName, j); return; } - pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0); + pColRef = tdsqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0); if( pColRef==0 ) return; pColRef->iTable = pItem->iCursor; pColRef->iColumn = k++; - pColRef->pTab = pTab; - pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, - sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0); + pColRef->y.pTab = pTab; + pRhs = tdsqlite3PExpr(pParse, TK_UPLUS, + tdsqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0); + pTerm = tdsqlite3PExpr(pParse, TK_EQ, pColRef, pRhs); + if( pItem->fg.jointype & JT_LEFT ){ + tdsqlite3SetJoinExpr(pTerm, pItem->iCursor); + } whereClauseInsert(pWC, pTerm, TERM_DYNAMIC); } } @@ -130957,19 +147484,34 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs( /* #include "sqliteInt.h" */ /* #include "whereInt.h" */ +/* +** Extra information appended to the end of tdsqlite3_index_info but not +** visible to the xBestIndex function, at least not directly. The +** tdsqlite3_vtab_collation() interface knows how to reach it, however. +** +** This object is not an API and can be changed from one release to the +** next. As long as allocateIndexInfo() and tdsqlite3_vtab_collation() +** agree on the structure, all will be well. +*/ +typedef struct HiddenIndexInfo HiddenIndexInfo; +struct HiddenIndexInfo { + WhereClause *pWC; /* The Where clause being analyzed */ + Parse *pParse; /* The parsing context */ +}; + /* Forward declaration of methods */ -static int whereLoopResize(sqlite3*, WhereLoop*, int); +static int whereLoopResize(tdsqlite3*, WhereLoop*, int); /* Test variable that can be set to enable WHERE tracing */ #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) -/***/ int sqlite3WhereTrace = 0; +/***/ int tdsqlite3WhereTrace = 0; #endif /* ** Return the estimated number of output rows from a WHERE clause */ -SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ +SQLITE_PRIVATE LogEst tdsqlite3WhereOutputRowCount(WhereInfo *pWInfo){ return pWInfo->nRowOut; } @@ -130977,7 +147519,7 @@ SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this ** WHERE clause returns outputs for DISTINCT processing. */ -SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ +SQLITE_PRIVATE int tdsqlite3WhereIsDistinct(WhereInfo *pWInfo){ return pWInfo->eDistinct; } @@ -130985,27 +147527,50 @@ SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ ** Return TRUE if the WHERE clause returns rows in ORDER BY order. ** Return FALSE if the output needs to be sorted. */ -SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ +SQLITE_PRIVATE int tdsqlite3WhereIsOrdered(WhereInfo *pWInfo){ return pWInfo->nOBSat; } /* -** Return TRUE if the innermost loop of the WHERE clause implementation -** returns rows in ORDER BY order for complete run of the inner loop. +** In the ORDER BY LIMIT optimization, if the inner-most loop is known +** to emit rows in increasing order, and if the last row emitted by the +** inner-most loop did not fit within the sorter, then we can skip all +** subsequent rows for the current iteration of the inner loop (because they +** will not fit in the sorter either) and continue with the second inner +** loop - the loop immediately outside the inner-most. +** +** When a row does not fit in the sorter (because the sorter already +** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the +** label returned by this function. +** +** If the ORDER BY LIMIT optimization applies, the jump destination should +** be the continuation for the second-inner-most loop. If the ORDER BY +** LIMIT optimization does not apply, then the jump destination should +** be the continuation for the inner-most loop. ** -** Across multiple iterations of outer loops, the output rows need not be -** sorted. As long as rows are sorted for just the innermost loop, this -** routine can return TRUE. +** It is always safe for this routine to return the continuation of the +** inner-most loop, in the sense that a correct answer will result. +** Returning the continuation the second inner loop is an optimization +** that might make the code run a little faster, but should not change +** the final answer. */ -SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){ - return pWInfo->bOrderedInnerLoop; +SQLITE_PRIVATE int tdsqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){ + WhereLevel *pInner; + if( !pWInfo->bOrderedInnerLoop ){ + /* The ORDER BY LIMIT optimization does not apply. Jump to the + ** continuation of the inner-most loop. */ + return pWInfo->iContinue; + } + pInner = &pWInfo->a[pWInfo->nLevel-1]; + assert( pInner->addrNxt!=0 ); + return pInner->addrNxt; } /* ** Return the VDBE address or label to jump to in order to continue ** immediately with the next row of a WHERE clause. */ -SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ +SQLITE_PRIVATE int tdsqlite3WhereContinueLabel(WhereInfo *pWInfo){ assert( pWInfo->iContinue!=0 ); return pWInfo->iContinue; } @@ -131014,13 +147579,13 @@ SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ ** Return the VDBE address or label to jump to in order to break ** out of a WHERE loop. */ -SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ +SQLITE_PRIVATE int tdsqlite3WhereBreakLabel(WhereInfo *pWInfo){ return pWInfo->iBreak; } /* ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to -** operate directly on the rowis returned by a WHERE clause. Return +** operate directly on the rowids returned by a WHERE clause. Return ** ONEPASS_SINGLE (1) if the statement can operation directly because only ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass ** optimization can be used on multiple @@ -131035,11 +147600,11 @@ SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is ** unable to use the ONEPASS optimization. */ -SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ +SQLITE_PRIVATE int tdsqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); #ifdef WHERETRACE_ENABLED - if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){ - sqlite3DebugPrintf("%s cursors: %d %d\n", + if( tdsqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){ + tdsqlite3DebugPrintf("%s cursors: %d %d\n", pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI", aiCur[0], aiCur[1]); } @@ -131048,6 +147613,14 @@ SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ } /* +** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move +** the data cursor to the row selected by the index cursor. +*/ +SQLITE_PRIVATE int tdsqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){ + return pWInfo->bDeferredSeek; +} + +/* ** Move the content of pSrc into pDest */ static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ @@ -131099,7 +147672,7 @@ whereOrInsert_done: ** Return the bitmask for the given cursor number. Return 0 if ** iCursor is not in the set. */ -SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ +SQLITE_PRIVATE Bitmask tdsqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ int i; assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); for(i=0; i<pMaskSet->n; i++){ @@ -131115,7 +147688,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ ** ** There is one cursor per table in the FROM clause. The number of ** tables in the FROM clause is limited by a test early in the -** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] +** tdsqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] ** array will never overflow. */ static void createMask(WhereMaskSet *pMaskSet, int iCursor){ @@ -131136,21 +147709,25 @@ static WhereTerm *whereScanNext(WhereScan *pScan){ WhereTerm *pTerm; /* The term being tested */ int k = pScan->k; /* Where to start scanning */ - while( pScan->iEquiv<=pScan->nEquiv ){ - iCur = pScan->aiCur[pScan->iEquiv-1]; + assert( pScan->iEquiv<=pScan->nEquiv ); + pWC = pScan->pWC; + while(1){ iColumn = pScan->aiColumn[pScan->iEquiv-1]; - if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0; - while( (pWC = pScan->pWC)!=0 ){ + iCur = pScan->aiCur[pScan->iEquiv-1]; + assert( pWC!=0 ); + do{ for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){ if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn && (iColumn!=XN_EXPR - || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0) + || tdsqlite3ExprCompareSkip(pTerm->pExpr->pLeft, + pScan->pIdxExpr,iCur)==0) && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin)) ){ if( (pTerm->eOperator & WO_EQUIV)!=0 && pScan->nEquiv<ArraySize(pScan->aiCur) - && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN + && (pX = tdsqlite3ExprSkipCollateAndLikely(pTerm->pExpr->pRight))->op + ==TK_COLUMN ){ int j; for(j=0; j<pScan->nEquiv; j++){ @@ -131171,14 +147748,13 @@ static WhereTerm *whereScanNext(WhereScan *pScan){ CollSeq *pColl; Parse *pParse = pWC->pWInfo->pParse; pX = pTerm->pExpr; - if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ + if( !tdsqlite3IndexAffinityOk(pX, pScan->idxaff) ){ continue; } assert(pX->pLeft); - pColl = sqlite3BinaryCompareCollSeq(pParse, - pX->pLeft, pX->pRight); + pColl = tdsqlite3ExprCompareCollSeq(pParse, pX); if( pColl==0 ) pColl = pParse->db->pDfltColl; - if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ + if( tdsqlite3StrICmp(pColl->zName, pScan->zCollName) ){ continue; } } @@ -131190,15 +147766,17 @@ static WhereTerm *whereScanNext(WhereScan *pScan){ testcase( pTerm->eOperator & WO_IS ); continue; } + pScan->pWC = pWC; pScan->k = k+1; return pTerm; } } } - pScan->pWC = pScan->pWC->pOuter; + pWC = pWC->pOuter; k = 0; - } - pScan->pWC = pScan->pOrigWC; + }while( pWC!=0 ); + if( pScan->iEquiv>=pScan->nEquiv ) break; + pWC = pScan->pOrigWC; k = 0; pScan->iEquiv++; } @@ -131206,6 +147784,17 @@ static WhereTerm *whereScanNext(WhereScan *pScan){ } /* +** This is whereScanInit() for the case of an index on an expression. +** It is factored out into a separate tail-recursion subroutine so that +** the normal whereScanInit() routine, which is a high-runner, does not +** need to push registers onto the stack as part of its prologue. +*/ +static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){ + pScan->idxaff = tdsqlite3ExprAffinity(pScan->pIdxExpr); + return whereScanNext(pScan); +} + +/* ** Initialize a WHERE clause scanner object. Return a pointer to the ** first match. Return NULL if there are no matches. ** @@ -131232,31 +147821,34 @@ static WhereTerm *whereScanInit( u32 opMask, /* Operator(s) to scan for */ Index *pIdx /* Must be compatible with this index */ ){ - int j = 0; - - /* memset(pScan, 0, sizeof(*pScan)); */ pScan->pOrigWC = pWC; pScan->pWC = pWC; pScan->pIdxExpr = 0; - if( pIdx ){ - j = iColumn; - iColumn = pIdx->aiColumn[j]; - if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr; - if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID; - } - if( pIdx && iColumn>=0 ){ - pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; - pScan->zCollName = pIdx->azColl[j]; - }else{ - pScan->idxaff = 0; - pScan->zCollName = 0; - } + pScan->idxaff = 0; + pScan->zCollName = 0; pScan->opMask = opMask; pScan->k = 0; pScan->aiCur[0] = iCur; - pScan->aiColumn[0] = iColumn; pScan->nEquiv = 1; pScan->iEquiv = 1; + if( pIdx ){ + int j = iColumn; + iColumn = pIdx->aiColumn[j]; + if( iColumn==XN_EXPR ){ + pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr; + pScan->zCollName = pIdx->azColl[j]; + pScan->aiColumn[0] = XN_EXPR; + return whereScanInitIndexExpr(pScan); + }else if( iColumn==pIdx->pTable->iPKey ){ + iColumn = XN_ROWID; + }else if( iColumn>=0 ){ + pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; + pScan->zCollName = pIdx->azColl[j]; + } + }else if( iColumn==XN_EXPR ){ + return 0; + } + pScan->aiColumn[0] = iColumn; return whereScanNext(pScan); } @@ -131285,7 +147877,7 @@ static WhereTerm *whereScanInit( ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS ** exist, try to return a term that does not use WO_EQUIV. */ -SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( +SQLITE_PRIVATE WhereTerm *tdsqlite3WhereFindTerm( WhereClause *pWC, /* The WHERE clause to be searched */ int iCur, /* Cursor number of LHS */ int iColumn, /* Column number of LHS */ @@ -131330,13 +147922,13 @@ static int findIndexCol( const char *zColl = pIdx->azColl[iCol]; for(i=0; i<pList->nExpr; i++){ - Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr); + Expr *p = tdsqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr); if( p->op==TK_COLUMN && p->iColumn==pIdx->aiColumn[iCol] && p->iTable==iBase ){ - CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr); - if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){ + CollSeq *pColl = tdsqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr); + if( 0==tdsqlite3StrICmp(pColl->zName, zColl) ){ return i; } } @@ -131394,7 +147986,7 @@ static int isDistinctRedundant( ** current SELECT is a correlated sub-query. */ for(i=0; i<pDistinct->nExpr; i++){ - Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr); + Expr *p = tdsqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr); if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1; } @@ -131414,7 +148006,7 @@ static int isDistinctRedundant( for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( !IsUniqueIndex(pIdx) ) continue; for(i=0; i<pIdx->nKeyCol; i++){ - if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){ + if( 0==tdsqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){ if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break; if( indexColumnNotNull(pIdx, i)==0 ) break; } @@ -131433,7 +148025,7 @@ static int isDistinctRedundant( ** Estimate the logarithm of the input value to base 2. */ static LogEst estLog(LogEst N){ - return N<=10 ? 0 : sqlite3LogEst(N) - 33; + return N<=10 ? 0 : tdsqlite3LogEst(N) - 33; } /* @@ -131443,20 +148035,22 @@ static LogEst estLog(LogEst N){ ** opcodes into OP_Copy when the table is being accessed via co-routine ** instead of via table lookup. ** -** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on -** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero, -** then each OP_Rowid is transformed into an instruction to increment the -** value stored in its output register. +** If the iAutoidxCur is not zero, then any OP_Rowid instructions on +** cursor iTabCur are transformed into OP_Sequence opcode for the +** iAutoidxCur cursor, in order to generate unique rowids for the +** automatic index being generated. */ static void translateColumnToCopy( - Vdbe *v, /* The VDBE containing code to translate */ + Parse *pParse, /* Parsing context */ int iStart, /* Translate from this opcode to the end */ int iTabCur, /* OP_Column/OP_Rowid references to this table */ int iRegister, /* The first column is in this register */ - int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */ + int iAutoidxCur /* If non-zero, cursor of autoindex being generated */ ){ - VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart); - int iEnd = sqlite3VdbeCurrentAddr(v); + Vdbe *v = pParse->pVdbe; + VdbeOp *pOp = tdsqlite3VdbeGetOp(v, iStart); + int iEnd = tdsqlite3VdbeCurrentAddr(v); + if( pParse->db->mallocFailed ) return; for(; iStart<iEnd; iStart++, pOp++){ if( pOp->p1!=iTabCur ) continue; if( pOp->opcode==OP_Column ){ @@ -131465,11 +148059,9 @@ static void translateColumnToCopy( pOp->p2 = pOp->p3; pOp->p3 = 0; }else if( pOp->opcode==OP_Rowid ){ - if( bIncrRowid ){ - /* Increment the value stored in the P2 operand of the OP_Rowid. */ - pOp->opcode = OP_AddImm; - pOp->p1 = pOp->p2; - pOp->p2 = 1; + if( iAutoidxCur ){ + pOp->opcode = OP_Sequence; + pOp->p1 = iAutoidxCur; }else{ pOp->opcode = OP_Null; pOp->p1 = 0; @@ -131480,17 +148072,17 @@ static void translateColumnToCopy( } /* -** Two routines for printing the content of an sqlite3_index_info +** Two routines for printing the content of an tdsqlite3_index_info ** structure. Used for testing and debugging only. If neither ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines ** are no-ops. */ #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) -static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ +static void whereTraceIndexInfoInputs(tdsqlite3_index_info *p){ int i; - if( !sqlite3WhereTrace ) return; + if( !tdsqlite3WhereTrace ) return; for(i=0; i<p->nConstraint; i++){ - sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", + tdsqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", i, p->aConstraint[i].iColumn, p->aConstraint[i].iTermOffset, @@ -131498,30 +148090,30 @@ static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ p->aConstraint[i].usable); } for(i=0; i<p->nOrderBy; i++){ - sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", + tdsqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", i, p->aOrderBy[i].iColumn, p->aOrderBy[i].desc); } } -static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ +static void whereTraceIndexInfoOutputs(tdsqlite3_index_info *p){ int i; - if( !sqlite3WhereTrace ) return; + if( !tdsqlite3WhereTrace ) return; for(i=0; i<p->nConstraint; i++){ - sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", + tdsqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", i, p->aConstraintUsage[i].argvIndex, p->aConstraintUsage[i].omit); } - sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); - sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); - sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); - sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); - sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows); + tdsqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); + tdsqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); + tdsqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); + tdsqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); + tdsqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows); } #else -#define TRACE_IDX_INPUTS(A) -#define TRACE_IDX_OUTPUTS(A) +#define whereTraceIndexInfoInputs(A) +#define whereTraceIndexInfoOutputs(A) #endif #ifndef SQLITE_OMIT_AUTOMATIC_INDEX @@ -131538,10 +148130,19 @@ static int termCanDriveIndex( char aff; if( pTerm->leftCursor!=pSrc->iCursor ) return 0; if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0; + if( (pSrc->fg.jointype & JT_LEFT) + && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) + && (pTerm->eOperator & WO_IS) + ){ + /* Cannot use an IS term from the WHERE clause as an index driver for + ** the RHS of a LEFT JOIN. Such a term can only be used if it is from + ** the ON clause. */ + return 0; + } if( (pTerm->prereqRight & notReady)!=0 ) return 0; if( pTerm->u.leftColumn<0 ) return 0; aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity; - if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; + if( !tdsqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; testcase( pTerm->pExpr->op==TK_IS ); return 1; } @@ -131589,7 +148190,7 @@ static void constructAutomaticIndex( ** transient index on 2nd and subsequent iterations of the loop. */ v = pParse->pVdbe; assert( v!=0 ); - addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); + addrInit = tdsqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); /* Count the number of columns that will be added to the index ** and used to match WHERE clause constraints */ @@ -131606,9 +148207,9 @@ static void constructAutomaticIndex( if( pLoop->prereq==0 && (pTerm->wtFlags & TERM_VIRTUAL)==0 && !ExprHasProperty(pExpr, EP_FromJoin) - && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){ - pPartial = sqlite3ExprAnd(pParse->db, pPartial, - sqlite3ExprDup(pParse->db, pExpr, 0)); + && tdsqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){ + pPartial = tdsqlite3ExprAnd(pParse, pPartial, + tdsqlite3ExprDup(pParse->db, pExpr, 0)); } if( termCanDriveIndex(pTerm, pSrc, notReady) ){ int iCol = pTerm->u.leftColumn; @@ -131616,7 +148217,7 @@ static void constructAutomaticIndex( testcase( iCol==BMS ); testcase( iCol==BMS-1 ); if( !sentWarning ){ - sqlite3_log(SQLITE_WARNING_AUTOINDEX, + tdsqlite3_log(SQLITE_WARNING_AUTOINDEX, "automatic index on %s(%s)", pTable->zName, pTable->aCol[iCol].zName); sentWarning = 1; @@ -131655,7 +148256,7 @@ static void constructAutomaticIndex( } /* Construct the Index object to describe this index */ - pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); + pIdx = tdsqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); if( pIdx==0 ) goto end_auto_index_create; pLoop->u.btree.pIndex = pIdx; pIdx->zName = "auto-index"; @@ -131672,8 +148273,9 @@ static void constructAutomaticIndex( Expr *pX = pTerm->pExpr; idxCols |= cMask; pIdx->aiColumn[n] = pTerm->u.leftColumn; - pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); - pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY; + pColl = tdsqlite3ExprCompareCollSeq(pParse, pX); + assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */ + pIdx->azColl[n] = pColl ? pColl->zName : tdsqlite3StrBINARY; n++; } } @@ -131685,96 +148287,98 @@ static void constructAutomaticIndex( for(i=0; i<mxBitCol; i++){ if( extraCols & MASKBIT(i) ){ pIdx->aiColumn[n] = i; - pIdx->azColl[n] = sqlite3StrBINARY; + pIdx->azColl[n] = tdsqlite3StrBINARY; n++; } } if( pSrc->colUsed & MASKBIT(BMS-1) ){ for(i=BMS-1; i<pTable->nCol; i++){ pIdx->aiColumn[n] = i; - pIdx->azColl[n] = sqlite3StrBINARY; + pIdx->azColl[n] = tdsqlite3StrBINARY; n++; } } assert( n==nKeyCol ); pIdx->aiColumn[n] = XN_ROWID; - pIdx->azColl[n] = sqlite3StrBINARY; + pIdx->azColl[n] = tdsqlite3StrBINARY; /* Create the automatic index */ assert( pLevel->iIdxCur>=0 ); pLevel->iIdxCur = pParse->nTab++; - sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); + tdsqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); + tdsqlite3VdbeSetP4KeyInfo(pParse, pIdx); VdbeComment((v, "for %s", pTable->zName)); /* Fill the automatic index with content */ - sqlite3ExprCachePush(pParse); pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom]; if( pTabItem->fg.viaCoroutine ){ int regYield = pTabItem->regReturn; - addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0); - sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); - addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield); + addrCounter = tdsqlite3VdbeAddOp2(v, OP_Integer, 0, 0); + tdsqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); + addrTop = tdsqlite3VdbeAddOp1(v, OP_Yield, regYield); VdbeCoverage(v); - VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); + VdbeComment((v, "next row of %s", pTabItem->pTab->zName)); }else{ - addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v); + addrTop = tdsqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v); } if( pPartial ){ - iContinue = sqlite3VdbeMakeLabel(v); - sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL); + iContinue = tdsqlite3VdbeMakeLabel(pParse); + tdsqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL); pLoop->wsFlags |= WHERE_PARTIALIDX; } - regRecord = sqlite3GetTempReg(pParse); - regBase = sqlite3GenerateIndexKey( + regRecord = tdsqlite3GetTempReg(pParse); + regBase = tdsqlite3GenerateIndexKey( pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0 ); - sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); - sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); - if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue); + tdsqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); + tdsqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + if( pPartial ) tdsqlite3VdbeResolveLabel(v, iContinue); if( pTabItem->fg.viaCoroutine ){ - sqlite3VdbeChangeP2(v, addrCounter, regBase+n); - translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1); - sqlite3VdbeGoto(v, addrTop); + tdsqlite3VdbeChangeP2(v, addrCounter, regBase+n); + testcase( pParse->db->mallocFailed ); + assert( pLevel->iIdxCur>0 ); + translateColumnToCopy(pParse, addrTop, pLevel->iTabCur, + pTabItem->regResult, pLevel->iIdxCur); + tdsqlite3VdbeGoto(v, addrTop); pTabItem->fg.viaCoroutine = 0; }else{ - sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); + tdsqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); + tdsqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); } - sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); - sqlite3VdbeJumpHere(v, addrTop); - sqlite3ReleaseTempReg(pParse, regRecord); - sqlite3ExprCachePop(pParse); + tdsqlite3VdbeJumpHere(v, addrTop); + tdsqlite3ReleaseTempReg(pParse, regRecord); /* Jump here when skipping the initialization */ - sqlite3VdbeJumpHere(v, addrInit); + tdsqlite3VdbeJumpHere(v, addrInit); end_auto_index_create: - sqlite3ExprDelete(pParse->db, pPartial); + tdsqlite3ExprDelete(pParse->db, pPartial); } #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* -** Allocate and populate an sqlite3_index_info structure. It is the +** Allocate and populate an tdsqlite3_index_info structure. It is the ** responsibility of the caller to eventually release the structure -** by passing the pointer returned by this function to sqlite3_free(). +** by passing the pointer returned by this function to tdsqlite3_free(). */ -static sqlite3_index_info *allocateIndexInfo( - Parse *pParse, - WhereClause *pWC, +static tdsqlite3_index_info *allocateIndexInfo( + Parse *pParse, /* The parsing context */ + WhereClause *pWC, /* The WHERE clause being analyzed */ Bitmask mUnusable, /* Ignore terms with these prereqs */ - struct SrcList_item *pSrc, - ExprList *pOrderBy, + struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */ + ExprList *pOrderBy, /* The ORDER BY clause */ u16 *pmNoOmit /* Mask of terms not to omit */ ){ int i, j; int nTerm; - struct sqlite3_index_constraint *pIdxCons; - struct sqlite3_index_orderby *pIdxOrderBy; - struct sqlite3_index_constraint_usage *pUsage; + struct tdsqlite3_index_constraint *pIdxCons; + struct tdsqlite3_index_orderby *pIdxOrderBy; + struct tdsqlite3_index_constraint_usage *pUsage; + struct HiddenIndexInfo *pHidden; WhereTerm *pTerm; int nOrderBy; - sqlite3_index_info *pIdxInfo; + tdsqlite3_index_info *pIdxInfo; u16 mNoOmit = 0; /* Count the number of possible WHERE clause constraints referring @@ -131787,7 +148391,7 @@ static sqlite3_index_info *allocateIndexInfo( testcase( pTerm->eOperator & WO_ISNULL ); testcase( pTerm->eOperator & WO_IS ); testcase( pTerm->eOperator & WO_ALL ); - if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue; + if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue; if( pTerm->wtFlags & TERM_VNULL ) continue; assert( pTerm->u.leftColumn>=(-1) ); nTerm++; @@ -131795,7 +148399,7 @@ static sqlite3_index_info *allocateIndexInfo( /* If the ORDER BY clause contains only columns in the current ** virtual table then allocate space for the aOrderBy part of - ** the sqlite3_index_info structure. + ** the tdsqlite3_index_info structure. */ nOrderBy = 0; if( pOrderBy ){ @@ -131803,39 +148407,34 @@ static sqlite3_index_info *allocateIndexInfo( for(i=0; i<n; i++){ Expr *pExpr = pOrderBy->a[i].pExpr; if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; + if( pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL ) break; } if( i==n){ nOrderBy = n; } } - /* Allocate the sqlite3_index_info structure + /* Allocate the tdsqlite3_index_info structure */ - pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) + pIdxInfo = tdsqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm - + sizeof(*pIdxOrderBy)*nOrderBy ); + + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) ); if( pIdxInfo==0 ){ - sqlite3ErrorMsg(pParse, "out of memory"); + tdsqlite3ErrorMsg(pParse, "out of memory"); return 0; } - - /* Initialize the structure. The sqlite3_index_info structure contains - ** many fields that are declared "const" to prevent xBestIndex from - ** changing them. We have to do some funky casting in order to - ** initialize those fields. - */ - pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1]; - pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; - pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; - *(int*)&pIdxInfo->nConstraint = nTerm; - *(int*)&pIdxInfo->nOrderBy = nOrderBy; - *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; - *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; - *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = - pUsage; - + pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1]; + pIdxCons = (struct tdsqlite3_index_constraint*)&pHidden[1]; + pIdxOrderBy = (struct tdsqlite3_index_orderby*)&pIdxCons[nTerm]; + pUsage = (struct tdsqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; + pIdxInfo->nOrderBy = nOrderBy; + pIdxInfo->aConstraint = pIdxCons; + pIdxInfo->aOrderBy = pIdxOrderBy; + pIdxInfo->aConstraintUsage = pUsage; + pHidden->pWC = pWC; + pHidden->pParse = pParse; for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ - u8 op; + u16 op; if( pTerm->leftCursor != pSrc->iCursor ) continue; if( pTerm->prereqRight & mUnusable ) continue; assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); @@ -131843,42 +148442,59 @@ static sqlite3_index_info *allocateIndexInfo( testcase( pTerm->eOperator & WO_IS ); testcase( pTerm->eOperator & WO_ISNULL ); testcase( pTerm->eOperator & WO_ALL ); - if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue; + if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue; if( pTerm->wtFlags & TERM_VNULL ) continue; + + /* tag-20191211-002: WHERE-clause constraints are not useful to the + ** right-hand table of a LEFT JOIN. See tag-20191211-001 for the + ** equivalent restriction for ordinary tables. */ + if( (pSrc->fg.jointype & JT_LEFT)!=0 + && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) + ){ + continue; + } assert( pTerm->u.leftColumn>=(-1) ); pIdxCons[j].iColumn = pTerm->u.leftColumn; pIdxCons[j].iTermOffset = i; - op = (u8)pTerm->eOperator & WO_ALL; + op = pTerm->eOperator & WO_ALL; if( op==WO_IN ) op = WO_EQ; - if( op==WO_MATCH ){ - op = pTerm->eMatchOp; - } - pIdxCons[j].op = op; - /* The direct assignment in the previous line is possible only because - ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The - ** following asserts verify this fact. */ - assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); - assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); - assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); - assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); - assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); - assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); - assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) ); - - if( op & (WO_LT|WO_LE|WO_GT|WO_GE) - && sqlite3ExprIsVector(pTerm->pExpr->pRight) - ){ - if( i<16 ) mNoOmit |= (1 << i); - if( op==WO_LT ) pIdxCons[j].op = WO_LE; - if( op==WO_GT ) pIdxCons[j].op = WO_GE; + if( op==WO_AUX ){ + pIdxCons[j].op = pTerm->eMatchOp; + }else if( op & (WO_ISNULL|WO_IS) ){ + if( op==WO_ISNULL ){ + pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL; + }else{ + pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS; + } + }else{ + pIdxCons[j].op = (u8)op; + /* The direct assignment in the previous line is possible only because + ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The + ** following asserts verify this fact. */ + assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); + assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); + assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); + assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); + assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); + assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) ); + + if( op & (WO_LT|WO_LE|WO_GT|WO_GE) + && tdsqlite3ExprIsVector(pTerm->pExpr->pRight) + ){ + testcase( j!=i ); + if( j<16 ) mNoOmit |= (1 << j); + if( op==WO_LT ) pIdxCons[j].op = WO_LE; + if( op==WO_GT ) pIdxCons[j].op = WO_GE; + } } j++; } + pIdxInfo->nConstraint = j; for(i=0; i<nOrderBy; i++){ Expr *pExpr = pOrderBy->a[i].pExpr; pIdxOrderBy[i].iColumn = pExpr->iColumn; - pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder; + pIdxOrderBy[i].desc = pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC; } *pmNoOmit = mNoOmit; @@ -131888,53 +148504,43 @@ static sqlite3_index_info *allocateIndexInfo( /* ** The table object reference passed as the second argument to this function ** must represent a virtual table. This function invokes the xBestIndex() -** method of the virtual table with the sqlite3_index_info object that +** method of the virtual table with the tdsqlite3_index_info object that ** comes in as the 3rd argument to this function. ** -** If an error occurs, pParse is populated with an error message and a -** non-zero value is returned. Otherwise, 0 is returned and the output -** part of the sqlite3_index_info structure is left populated. +** If an error occurs, pParse is populated with an error message and an +** appropriate error code is returned. A return of SQLITE_CONSTRAINT from +** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that +** the current configuration of "unusable" flags in tdsqlite3_index_info can +** not result in a valid plan. ** ** Whether or not an error is returned, it is the responsibility of the ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates ** that this is required. */ -static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ - sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; +static int vtabBestIndex(Parse *pParse, Table *pTab, tdsqlite3_index_info *p){ + tdsqlite3_vtab *pVtab = tdsqlite3GetVTable(pParse->db, pTab)->pVtab; int rc; - TRACE_IDX_INPUTS(p); + whereTraceIndexInfoInputs(p); rc = pVtab->pModule->xBestIndex(pVtab, p); - TRACE_IDX_OUTPUTS(p); + whereTraceIndexInfoOutputs(p); - if( rc!=SQLITE_OK ){ + if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){ if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(pParse->db); + tdsqlite3OomFault(pParse->db); }else if( !pVtab->zErrMsg ){ - sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); + tdsqlite3ErrorMsg(pParse, "%s", tdsqlite3ErrStr(rc)); }else{ - sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); + tdsqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); } } - sqlite3_free(pVtab->zErrMsg); + tdsqlite3_free(pVtab->zErrMsg); pVtab->zErrMsg = 0; - -#if 0 - /* This error is now caught by the caller. - ** Search for "xBestIndex malfunction" below */ - for(i=0; i<p->nConstraint; i++){ - if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ - sqlite3ErrorMsg(pParse, - "table %s: xBestIndex returned an invalid plan", pTab->zName); - } - } -#endif - - return pParse->nErr; + return rc; } #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 /* ** Estimate the location of a particular key among all keys in an ** index. Store the results in aStat as follows: @@ -132037,7 +148643,7 @@ static int whereKeyStats( } pRec->nField = n; - res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec); + res = tdsqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec); if( res<0 ){ iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1]; iMin = iTest+1; @@ -132062,7 +148668,7 @@ static int whereKeyStats( assert( i<pIdx->nSample ); assert( iCol==nField-1 ); pRec->nField = nField; - assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) + assert( 0==tdsqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) || pParse->db->mallocFailed ); }else{ @@ -132072,7 +148678,7 @@ static int whereKeyStats( assert( i<=pIdx->nSample && i>=0 ); pRec->nField = iCol+1; assert( i==pIdx->nSample - || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 + || tdsqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 || pParse->db->mallocFailed ); /* if i==0 and iCol==0, then record pRec is smaller than all samples @@ -132081,12 +148687,12 @@ static int whereKeyStats( ** If (i>0), then pRec must also be greater than sample (i-1). */ if( iCol>0 ){ pRec->nField = iCol; - assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0 + assert( tdsqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0 || pParse->db->mallocFailed ); } if( i>0 ){ pRec->nField = nField; - assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 + assert( tdsqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 || pParse->db->mallocFailed ); } } @@ -132104,7 +148710,7 @@ static int whereKeyStats( ** is larger than all samples in the array. */ tRowcnt iUpper, iGap; if( i>=pIdx->nSample ){ - iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]); + iUpper = tdsqlite3LogEstToInt(pIdx->aiRowLogEst[0]); }else{ iUpper = aSample[i].anLt[iCol]; } @@ -132120,14 +148726,14 @@ static int whereKeyStats( iGap = iGap/3; } aStat[0] = iLower + iGap; - aStat[1] = pIdx->aAvgEq[iCol]; + aStat[1] = pIdx->aAvgEq[nField-1]; } /* Restore the pRec->nField value before returning. */ pRec->nField = nField; return i; } -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ /* ** If it is not NULL, pTerm is a term that provides an upper or lower @@ -132146,28 +148752,29 @@ static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){ if( pTerm->truthProb<=0 ){ nRet += pTerm->truthProb; }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){ - nRet -= 20; assert( 20==sqlite3LogEst(4) ); + nRet -= 20; assert( 20==tdsqlite3LogEst(4) ); } } return nRet; } -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 /* ** Return the affinity for a single column of an index. */ -SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){ +SQLITE_PRIVATE char tdsqlite3IndexColumnAffinity(tdsqlite3 *db, Index *pIdx, int iCol){ assert( iCol>=0 && iCol<pIdx->nColumn ); if( !pIdx->zColAff ){ - if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB; + if( tdsqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB; } + assert( pIdx->zColAff[iCol]!=0 ); return pIdx->zColAff[iCol]; } #endif -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 /* ** This function is called to estimate the number of rows visited by a ** range-scan on a skip-scan index. For example: @@ -132212,24 +148819,24 @@ static int whereRangeSkipScanEst( ){ Index *p = pLoop->u.btree.pIndex; int nEq = pLoop->u.btree.nEq; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; int nLower = -1; int nUpper = p->nSample+1; int rc = SQLITE_OK; - u8 aff = sqlite3IndexColumnAffinity(db, p, nEq); + u8 aff = tdsqlite3IndexColumnAffinity(db, p, nEq); CollSeq *pColl; - sqlite3_value *p1 = 0; /* Value extracted from pLower */ - sqlite3_value *p2 = 0; /* Value extracted from pUpper */ - sqlite3_value *pVal = 0; /* Value extracted from record */ + tdsqlite3_value *p1 = 0; /* Value extracted from pLower */ + tdsqlite3_value *p2 = 0; /* Value extracted from pUpper */ + tdsqlite3_value *pVal = 0; /* Value extracted from record */ - pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); + pColl = tdsqlite3LocateCollSeq(pParse, p->azColl[nEq]); if( pLower ){ - rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); + rc = tdsqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); nLower = 0; } if( pUpper && rc==SQLITE_OK ){ - rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2); + rc = tdsqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2); nUpper = p2 ? 0 : p->nSample; } @@ -132237,13 +148844,13 @@ static int whereRangeSkipScanEst( int i; int nDiff; for(i=0; rc==SQLITE_OK && i<p->nSample; i++){ - rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal); + rc = tdsqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal); if( rc==SQLITE_OK && p1 ){ - int res = sqlite3MemCompare(p1, pVal, pColl); + int res = tdsqlite3MemCompare(p1, pVal, pColl); if( res>=0 ) nLower++; } if( rc==SQLITE_OK && p2 ){ - int res = sqlite3MemCompare(p2, pVal, pColl); + int res = tdsqlite3MemCompare(p2, pVal, pColl); if( res>=0 ) nUpper++; } } @@ -132256,7 +148863,7 @@ static int whereRangeSkipScanEst( ** the number of rows visited. Otherwise, estimate the number of rows ** using the method described in the header comment for this function. */ if( nDiff!=1 || pUpper==0 || pLower==0 ){ - int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff)); + int nAdjust = (tdsqlite3LogEst(p->nSample) - tdsqlite3LogEst(nDiff)); pLoop->nOut -= nAdjust; *pbDone = 1; WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n", @@ -132267,13 +148874,13 @@ static int whereRangeSkipScanEst( assert( *pbDone==0 ); } - sqlite3ValueFree(p1); - sqlite3ValueFree(p2); - sqlite3ValueFree(pVal); + tdsqlite3ValueFree(p1); + tdsqlite3ValueFree(p2); + tdsqlite3ValueFree(pVal); return rc; } -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ /* ** This function is used to estimate the number of rows that will be visited @@ -132304,7 +148911,7 @@ static int whereRangeSkipScanEst( ** ** then nEq is set to 0. ** -** When this function is called, *pnOut is set to the sqlite3LogEst() of the +** When this function is called, *pnOut is set to the tdsqlite3LogEst() of the ** number of rows that the index scan is expected to visit without ** considering the range constraints. If nEq is 0, then *pnOut is the number of ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) @@ -132326,11 +148933,13 @@ static int whereRangeScanEst( int nOut = pLoop->nOut; LogEst nNew; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 Index *p = pLoop->u.btree.pIndex; int nEq = pLoop->u.btree.nEq; - if( p->nSample>0 && nEq<p->nSampleCol ){ + if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol) + && OptimizationEnabled(pParse->db, SQLITE_Stat4) + ){ if( nEq==pBuilder->nRecValid ){ UnpackedRecord *pRec = pBuilder->pRec; tRowcnt a[2]; @@ -132390,11 +148999,11 @@ static int whereRangeScanEst( if( pLower ){ int n; /* Values extracted from pExpr */ Expr *pExpr = pLower->pExpr->pRight; - rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n); + rc = tdsqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n); if( rc==SQLITE_OK && n ){ tRowcnt iNew; u16 mask = WO_GT|WO_LE; - if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); + if( tdsqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a); iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0); if( iNew>iLower ) iLower = iNew; @@ -132407,11 +149016,11 @@ static int whereRangeScanEst( if( pUpper ){ int n; /* Values extracted from pExpr */ Expr *pExpr = pUpper->pExpr->pRight; - rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n); + rc = tdsqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n); if( rc==SQLITE_OK && n ){ tRowcnt iNew; u16 mask = WO_GT|WO_LE; - if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); + if( tdsqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); iUprIdx = whereKeyStats(pParse, p, pRec, 1, a); iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0); if( iNew<iUpper ) iUpper = iNew; @@ -132423,14 +149032,14 @@ static int whereRangeScanEst( pBuilder->pRec = pRec; if( rc==SQLITE_OK ){ if( iUpper>iLower ){ - nNew = sqlite3LogEst(iUpper - iLower); + nNew = tdsqlite3LogEst(iUpper - iLower); /* TUNING: If both iUpper and iLower are derived from the same ** sample, then assume they are 4x more selective. This brings ** the estimated selectivity more in line with what it would be - ** if estimated without the use of STAT3/4 tables. */ - if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) ); + ** if estimated without the use of STAT4 tables. */ + if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==tdsqlite3LogEst(4) ); }else{ - nNew = 10; assert( 10==sqlite3LogEst(2) ); + nNew = 10; assert( 10==tdsqlite3LogEst(2) ); } if( nNew<nOut ){ nOut = nNew; @@ -132476,12 +149085,12 @@ static int whereRangeScanEst( return rc; } -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 /* ** Estimate the number of rows that will be returned based on ** an equality constraint x=VALUE and where that VALUE occurs in ** the histogram data. This only works when x is the left-most -** column of an index and sqlite_stat3 histogram data is available +** column of an index and sqlite_stat4 histogram data is available ** for that index. When pExpr==NULL that means the constraint is ** "x IS NULL" instead of "x=VALUE". ** @@ -132519,14 +149128,14 @@ static int whereEqualScanEst( return SQLITE_NOTFOUND; } - /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() + /* This is an optimization only. The call to tdsqlite3Stat4ProbeSetValue() ** below would return the same value. */ if( nEq>=p->nColumn ){ *pnRow = 1; return SQLITE_OK; } - rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk); + rc = tdsqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk); pBuilder->pRec = pRec; if( rc!=SQLITE_OK ) return rc; if( bOk==0 ) return SQLITE_NOTFOUND; @@ -132539,9 +149148,9 @@ static int whereEqualScanEst( return rc; } -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 /* ** Estimate the number of rows that will be returned based on ** an IN constraint where the right-hand side of the IN operator @@ -132565,7 +149174,7 @@ static int whereInScanEst( tRowcnt *pnRow /* Write the revised row estimate here */ ){ Index *p = pBuilder->pNew->u.btree.pIndex; - i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]); + i64 nRow0 = tdsqlite3LogEstToInt(p->aiRowLogEst[0]); int nRecValid = pBuilder->nRecValid; int rc = SQLITE_OK; /* Subfunction return code */ tRowcnt nEst; /* Number of rows for a single term */ @@ -132588,42 +149197,50 @@ static int whereInScanEst( assert( pBuilder->nRecValid==nRecValid ); return rc; } -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ +#endif /* SQLITE_ENABLE_STAT4 */ #ifdef WHERETRACE_ENABLED /* ** Print the content of a WhereTerm object */ -static void whereTermPrint(WhereTerm *pTerm, int iTerm){ +SQLITE_PRIVATE void tdsqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){ if( pTerm==0 ){ - sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); + tdsqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); }else{ - char zType[4]; + char zType[8]; char zLeft[50]; - memcpy(zType, "...", 4); + memcpy(zType, "....", 5); if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L'; + if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C'; if( pTerm->eOperator & WO_SINGLE ){ - sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}", + tdsqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}", pTerm->leftCursor, pTerm->u.leftColumn); }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){ - sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", + tdsqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", pTerm->u.pOrInfo->indexable); }else{ - sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor); + tdsqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor); + } + tdsqlite3DebugPrintf( + "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x", + iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags); + /* The 0x10000 .wheretrace flag causes extra information to be + ** shown about each Term */ + if( tdsqlite3WhereTrace & 0x10000 ){ + tdsqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx", + pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight); } - sqlite3DebugPrintf( - "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x", - iTerm, pTerm, zType, zLeft, pTerm->truthProb, - pTerm->eOperator, pTerm->wtFlags); if( pTerm->iField ){ - sqlite3DebugPrintf(" iField=%d\n", pTerm->iField); - }else{ - sqlite3DebugPrintf("\n"); + tdsqlite3DebugPrintf(" iField=%d", pTerm->iField); } - sqlite3TreeViewExpr(0, pTerm->pExpr, 0); + if( pTerm->iParent>=0 ){ + tdsqlite3DebugPrintf(" iParent=%d", pTerm->iParent); + } + tdsqlite3DebugPrintf("\n"); + tdsqlite3TreeViewExpr(0, pTerm->pExpr, 0); } } #endif @@ -132632,10 +149249,10 @@ static void whereTermPrint(WhereTerm *pTerm, int iTerm){ /* ** Show the complete content of a WhereClause */ -SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){ +SQLITE_PRIVATE void tdsqlite3WhereClausePrint(WhereClause *pWC){ int i; for(i=0; i<pWC->nTerm; i++){ - whereTermPrint(&pWC->a[i], i); + tdsqlite3WhereTermPrint(&pWC->a[i], i); } } #endif @@ -132644,49 +149261,49 @@ SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){ /* ** Print a WhereLoop object for debugging purposes */ -static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){ +SQLITE_PRIVATE void tdsqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){ WhereInfo *pWInfo = pWC->pWInfo; int nb = 1+(pWInfo->pTabList->nSrc+3)/4; struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab; Table *pTab = pItem->pTab; Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1; - sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, + tdsqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, p->iTab, nb, p->maskSelf, nb, p->prereq & mAll); - sqlite3DebugPrintf(" %12s", + tdsqlite3DebugPrintf(" %12s", pItem->zAlias ? pItem->zAlias : pTab->zName); if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ const char *zName; if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){ if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ - int i = sqlite3Strlen30(zName) - 1; + int i = tdsqlite3Strlen30(zName) - 1; while( zName[i]!='_' ) i--; zName += i; } - sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); + tdsqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); }else{ - sqlite3DebugPrintf("%20s",""); + tdsqlite3DebugPrintf("%20s",""); } }else{ char *z; if( p->u.vtab.idxStr ){ - z = sqlite3_mprintf("(%d,\"%s\",%x)", + z = tdsqlite3_mprintf("(%d,\"%s\",%#x)", p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); }else{ - z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); + z = tdsqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); } - sqlite3DebugPrintf(" %-19s", z); - sqlite3_free(z); + tdsqlite3DebugPrintf(" %-19s", z); + tdsqlite3_free(z); } if( p->wsFlags & WHERE_SKIPSCAN ){ - sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip); + tdsqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip); }else{ - sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); + tdsqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); } - sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); - if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ + tdsqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); + if( p->nLTerm && (tdsqlite3WhereTrace & 0x100)!=0 ){ int i; for(i=0; i<p->nLTerm; i++){ - whereTermPrint(p->aLTerm[i], i); + tdsqlite3WhereTermPrint(p->aLTerm[i], i); } } } @@ -132706,15 +149323,15 @@ static void whereLoopInit(WhereLoop *p){ /* ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. */ -static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ +static void whereLoopClearUnion(tdsqlite3 *db, WhereLoop *p){ if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ - sqlite3_free(p->u.vtab.idxStr); + tdsqlite3_free(p->u.vtab.idxStr); p->u.vtab.needFree = 0; p->u.vtab.idxStr = 0; }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ - sqlite3DbFree(db, p->u.btree.pIndex->zColAff); - sqlite3DbFree(db, p->u.btree.pIndex); + tdsqlite3DbFree(db, p->u.btree.pIndex->zColAff); + tdsqlite3DbFreeNN(db, p->u.btree.pIndex); p->u.btree.pIndex = 0; } } @@ -132723,8 +149340,8 @@ static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ /* ** Deallocate internal memory used by a WhereLoop object */ -static void whereLoopClear(sqlite3 *db, WhereLoop *p){ - if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); +static void whereLoopClear(tdsqlite3 *db, WhereLoop *p){ + if( p->aLTerm!=p->aLTermSpace ) tdsqlite3DbFreeNN(db, p->aLTerm); whereLoopClearUnion(db, p); whereLoopInit(p); } @@ -132732,14 +149349,14 @@ static void whereLoopClear(sqlite3 *db, WhereLoop *p){ /* ** Increase the memory allocation for pLoop->aLTerm[] to be at least n. */ -static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ +static int whereLoopResize(tdsqlite3 *db, WhereLoop *p, int n){ WhereTerm **paNew; if( p->nLSlot>=n ) return SQLITE_OK; n = (n+7)&~7; - paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n); + paNew = tdsqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n); if( paNew==0 ) return SQLITE_NOMEM_BKPT; memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); - if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); + if( p->aLTerm!=p->aLTermSpace ) tdsqlite3DbFreeNN(db, p->aLTerm); p->aLTerm = paNew; p->nLSlot = n; return SQLITE_OK; @@ -132748,7 +149365,7 @@ static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ /* ** Transfer content from the second pLoop into the first. */ -static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ +static int whereLoopXfer(tdsqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ whereLoopClearUnion(db, pTo); if( whereLoopResize(db, pTo, pFrom->nLTerm) ){ memset(&pTo->u, 0, sizeof(pTo->u)); @@ -132767,49 +149384,50 @@ static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ /* ** Delete a WhereLoop object */ -static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ +static void whereLoopDelete(tdsqlite3 *db, WhereLoop *p){ whereLoopClear(db, p); - sqlite3DbFree(db, p); + tdsqlite3DbFreeNN(db, p); } /* ** Free a WhereInfo structure */ -static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ - if( ALWAYS(pWInfo) ){ - int i; - for(i=0; i<pWInfo->nLevel; i++){ - WhereLevel *pLevel = &pWInfo->a[i]; - if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){ - sqlite3DbFree(db, pLevel->u.in.aInLoop); - } - } - sqlite3WhereClauseClear(&pWInfo->sWC); - while( pWInfo->pLoops ){ - WhereLoop *p = pWInfo->pLoops; - pWInfo->pLoops = p->pNextLoop; - whereLoopDelete(db, p); +static void whereInfoFree(tdsqlite3 *db, WhereInfo *pWInfo){ + int i; + assert( pWInfo!=0 ); + for(i=0; i<pWInfo->nLevel; i++){ + WhereLevel *pLevel = &pWInfo->a[i]; + if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){ + tdsqlite3DbFree(db, pLevel->u.in.aInLoop); } - sqlite3DbFree(db, pWInfo); } + tdsqlite3WhereClauseClear(&pWInfo->sWC); + while( pWInfo->pLoops ){ + WhereLoop *p = pWInfo->pLoops; + pWInfo->pLoops = p->pNextLoop; + whereLoopDelete(db, p); + } + assert( pWInfo->pExprMods==0 ); + tdsqlite3DbFreeNN(db, pWInfo); } /* ** Return TRUE if all of the following are true: ** ** (1) X has the same or lower cost that Y -** (2) X is a proper subset of Y -** (3) X skips at least as many columns as Y -** -** By "proper subset" we mean that X uses fewer WHERE clause terms -** than Y and that every WHERE clause term used by X is also used -** by Y. +** (2) X uses fewer WHERE clause terms than Y +** (3) Every WHERE clause term used by X is also used by Y +** (4) X skips at least as many columns as Y +** (5) If X is a covering index, than Y is too ** +** Conditions (2) and (3) mean that X is a "proper subset" of Y. ** If X is a proper subset of Y then Y is a better choice and ought ** to have a lower cost. This routine returns TRUE when that cost -** relationship is inverted and needs to be adjusted. The third rule +** relationship is inverted and needs to be adjusted. Constraint (4) ** was added because if X uses skip-scan less than Y it still might -** deserve a lower cost even if it is a proper subset of Y. +** deserve a lower cost even if it is a proper subset of Y. Constraint (5) +** was added because a covering index probably deserves to have a lower cost +** than a non-covering index even if it is a proper subset. */ static int whereLoopCheaperProperSubset( const WhereLoop *pX, /* First WhereLoop to compare */ @@ -132831,6 +149449,10 @@ static int whereLoopCheaperProperSubset( } if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */ } + if( (pX->wsFlags&WHERE_IDX_ONLY)!=0 + && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){ + return 0; /* Constraint (5) */ + } return 1; /* All conditions meet */ } @@ -132873,16 +149495,17 @@ static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ /* ** Search the list of WhereLoops in *ppPrev looking for one that can be -** supplanted by pTemplate. +** replaced by pTemplate. ** -** Return NULL if the WhereLoop list contains an entry that can supplant -** pTemplate, in other words if pTemplate does not belong on the list. +** Return NULL if pTemplate does not belong on the WhereLoop list. +** In other words if pTemplate ought to be dropped from further consideration. ** -** If pX is a WhereLoop that pTemplate can supplant, then return the +** If pX is a WhereLoop that pTemplate can replace, then return the ** link that points to pX. ** -** If pTemplate cannot supplant any existing element of the list but needs -** to be added to the list, then return a pointer to the tail of the list. +** If pTemplate cannot replace any existing element of the list but needs +** to be added to the list as a new entry, then return a pointer to the +** tail of the list. */ static WhereLoop **whereLoopFindLesser( WhereLoop **ppPrev, @@ -132975,9 +149598,19 @@ static WhereLoop **whereLoopFindLesser( static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ WhereLoop **ppPrev, *p; WhereInfo *pWInfo = pBuilder->pWInfo; - sqlite3 *db = pWInfo->pParse->db; + tdsqlite3 *db = pWInfo->pParse->db; int rc; + /* Stop the search once we hit the query planner search limit */ + if( pBuilder->iPlanLimit==0 ){ + WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n")); + if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0; + return SQLITE_DONE; + } + pBuilder->iPlanLimit--; + + whereLoopAdjustCost(pWInfo->pLoops, pTemplate); + /* If pBuilder->pOrSet is defined, then only keep track of the costs ** and prereqs. */ @@ -132990,9 +149623,9 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, pTemplate->nOut); #if WHERETRACE_ENABLED /* 0x8 */ - if( sqlite3WhereTrace & 0x8 ){ - sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); - whereLoopPrint(pTemplate, pBuilder->pWC); + if( tdsqlite3WhereTrace & 0x8 ){ + tdsqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); + tdsqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); } #endif } @@ -133001,16 +149634,15 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ /* Look for an existing WhereLoop to replace with pTemplate */ - whereLoopAdjustCost(pWInfo->pLoops, pTemplate); ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); if( ppPrev==0 ){ /* There already exists a WhereLoop on the list that is better ** than pTemplate, so just ignore pTemplate */ #if WHERETRACE_ENABLED /* 0x8 */ - if( sqlite3WhereTrace & 0x8 ){ - sqlite3DebugPrintf(" skip: "); - whereLoopPrint(pTemplate, pBuilder->pWC); + if( tdsqlite3WhereTrace & 0x8 ){ + tdsqlite3DebugPrintf(" skip: "); + tdsqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); } #endif return SQLITE_OK; @@ -133023,18 +149655,20 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ ** WhereLoop and insert it. */ #if WHERETRACE_ENABLED /* 0x8 */ - if( sqlite3WhereTrace & 0x8 ){ + if( tdsqlite3WhereTrace & 0x8 ){ if( p!=0 ){ - sqlite3DebugPrintf("replace: "); - whereLoopPrint(p, pBuilder->pWC); + tdsqlite3DebugPrintf("replace: "); + tdsqlite3WhereLoopPrint(p, pBuilder->pWC); + tdsqlite3DebugPrintf(" with: "); + }else{ + tdsqlite3DebugPrintf(" add: "); } - sqlite3DebugPrintf(" add: "); - whereLoopPrint(pTemplate, pBuilder->pWC); + tdsqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); } #endif if( p==0 ){ /* Allocate a new WhereLoop to add to the end of the list */ - *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop)); + *ppPrev = p = tdsqlite3DbMallocRawNN(db, sizeof(WhereLoop)); if( p==0 ) return SQLITE_NOMEM_BKPT; whereLoopInit(p); p->pNextLoop = 0; @@ -133051,9 +149685,9 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ if( pToDel==0 ) break; *ppTail = pToDel->pNextLoop; #if WHERETRACE_ENABLED /* 0x8 */ - if( sqlite3WhereTrace & 0x8 ){ - sqlite3DebugPrintf(" delete: "); - whereLoopPrint(pToDel, pBuilder->pWC); + if( tdsqlite3WhereTrace & 0x8 ){ + tdsqlite3DebugPrintf(" delete: "); + tdsqlite3WhereLoopPrint(pToDel, pBuilder->pWC); } #endif whereLoopDelete(db, pToDel); @@ -133062,7 +149696,7 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ rc = whereLoopXfer(db, p, pTemplate); if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ Index *pIndex = p->u.btree.pIndex; - if( pIndex && pIndex->tnum==0 ){ + if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){ p->u.btree.pIndex = 0; } } @@ -133105,11 +149739,12 @@ static void whereLoopOutputAdjust( ){ WhereTerm *pTerm, *pX; Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); - int i, j, k; + int i, j; LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */ assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ + assert( pTerm!=0 ); if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; if( (pTerm->prereqAll & notAllowed)!=0 ) continue; @@ -133130,8 +149765,9 @@ static void whereLoopOutputAdjust( pLoop->nOut--; if( pTerm->eOperator&(WO_EQ|WO_IS) ){ Expr *pRight = pTerm->pExpr->pRight; + int k = 0; testcase( pTerm->pExpr->op==TK_IS ); - if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){ + if( tdsqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){ k = 10; }else{ k = 20; @@ -133168,7 +149804,7 @@ static int whereRangeVectorLen( int nEq, /* Number of prior equality constraints on same index */ WhereTerm *pTerm /* The vector inequality constraint */ ){ - int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft); + int nCmp = tdsqlite3ExprVectorSize(pTerm->pExpr->pLeft); int i; nCmp = MIN(nCmp, (pIdx->nColumn - nEq)); @@ -133199,13 +149835,13 @@ static int whereRangeVectorLen( } testcase( pLhs->iColumn==XN_ROWID ); - aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs)); - idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); + aff = tdsqlite3CompareAffinity(pRhs, tdsqlite3ExprAffinity(pLhs)); + idxaff = tdsqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); if( aff!=idxaff ) break; - pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); + pColl = tdsqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); if( pColl==0 ) break; - if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; + if( tdsqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; } return i; } @@ -133229,8 +149865,8 @@ static int whereRangeVectorLen( ** terms only. If it is modified, this value is restored before this ** function returns. ** -** If pProbe->tnum==0, that means pIndex is a fake index used for the -** INTEGER PRIMARY KEY. +** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is +** a fake index used for the INTEGER PRIMARY KEY. */ static int whereLoopAddBtreeIndex( WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ @@ -133240,7 +149876,7 @@ static int whereLoopAddBtreeIndex( ){ WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ Parse *pParse = pWInfo->pParse; /* Parsing context */ - sqlite3 *db = pParse->db; /* Database connection malloc context */ + tdsqlite3 *db = pParse->db; /* Database connection malloc context */ WhereLoop *pNew; /* Template WhereLoop under construction */ WhereTerm *pTerm; /* A WhereTerm under consideration */ int opMask; /* Valid operators for constraints */ @@ -133260,8 +149896,9 @@ static int whereLoopAddBtreeIndex( pNew = pBuilder->pNew; if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; - WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n", - pProbe->zName, pNew->u.btree.nEq)); + WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d\n", + pProbe->pTable->zName,pProbe->zName, + pNew->u.btree.nEq, pNew->nSkip)); assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); @@ -133293,7 +149930,7 @@ static int whereLoopAddBtreeIndex( LogEst rCostIdx; LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ int nIn = 0; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 int nRecValid = pBuilder->nRecValid; #endif if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) @@ -133307,18 +149944,20 @@ static int whereLoopAddBtreeIndex( ** to mix with a lower range bound from some other source */ if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue; - /* Do not allow IS constraints from the WHERE clause to be used by the - ** right table of a LEFT JOIN. Only constraints in the ON clause are - ** allowed */ + /* tag-20191211-001: Do not allow constraints from the WHERE clause to + ** be used by the right table of a LEFT JOIN. Only constraints in the + ** ON clause are allowed. See tag-20191211-002 for the vtab equivalent. */ if( (pSrc->fg.jointype & JT_LEFT)!=0 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) - && (eOp & (WO_IS|WO_ISNULL))!=0 ){ - testcase( eOp & WO_IS ); - testcase( eOp & WO_ISNULL ); continue; } + if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){ + pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE; + }else{ + pBuilder->bldFlags |= SQLITE_BLDF_INDEXED; + } pNew->wsFlags = saved_wsFlags; pNew->u.btree.nEq = saved_nEq; pNew->u.btree.nBtm = saved_nBtm; @@ -133336,11 +149975,10 @@ static int whereLoopAddBtreeIndex( if( eOp & WO_IN ){ Expr *pExpr = pTerm->pExpr; - pNew->wsFlags |= WHERE_COLUMN_IN; if( ExprHasProperty(pExpr, EP_xIsSelect) ){ /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ int i; - nIn = 46; assert( 46==sqlite3LogEst(25) ); + nIn = 46; assert( 46==tdsqlite3LogEst(25) ); /* The expression may actually be of the form (x, y) IN (SELECT...). ** In this case there is a separate term for each of (x) and (y). @@ -133352,21 +149990,57 @@ static int whereLoopAddBtreeIndex( } }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ /* "x IN (value, value, ...)" */ - nIn = sqlite3LogEst(pExpr->x.pList->nExpr); - assert( nIn>0 ); /* RHS always has 2 or more terms... The parser - ** changes "x IN (?)" into "x=?". */ + nIn = tdsqlite3LogEst(pExpr->x.pList->nExpr); + } + if( pProbe->hasStat1 ){ + LogEst M, logK, safetyMargin; + /* Let: + ** N = the total number of rows in the table + ** K = the number of entries on the RHS of the IN operator + ** M = the number of rows in the table that match terms to the + ** to the left in the same index. If the IN operator is on + ** the left-most index column, M==N. + ** + ** Given the definitions above, it is better to omit the IN operator + ** from the index lookup and instead do a scan of the M elements, + ** testing each scanned row against the IN operator separately, if: + ** + ** M*log(K) < K*log(N) + ** + ** Our estimates for M, K, and N might be inaccurate, so we build in + ** a safety margin of 2 (LogEst: 10) that favors using the IN operator + ** with the index, as using an index has better worst-case behavior. + ** If we do not have real sqlite_stat1 data, always prefer to use + ** the index. + */ + M = pProbe->aiRowLogEst[saved_nEq]; + logK = estLog(nIn); + safetyMargin = 10; /* TUNING: extra weight for indexed IN */ + if( M + logK + safetyMargin < nIn + rLogSize ){ + WHERETRACE(0x40, + ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n", + saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize)); + continue; + }else{ + WHERETRACE(0x40, + ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n", + saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize)); + } } + pNew->wsFlags |= WHERE_COLUMN_IN; }else if( eOp & (WO_EQ|WO_IS) ){ int iCol = pProbe->aiColumn[saved_nEq]; pNew->wsFlags |= WHERE_COLUMN_EQ; assert( saved_nEq==pNew->u.btree.nEq ); if( iCol==XN_ROWID - || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1) + || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1) ){ - if( iCol>=0 && pProbe->uniqNotNull==0 ){ - pNew->wsFlags |= WHERE_UNQ_WANTED; - }else{ + if( iCol==XN_ROWID || pProbe->uniqNotNull + || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ) + ){ pNew->wsFlags |= WHERE_ONEROW; + }else{ + pNew->wsFlags |= WHERE_UNQ_WANTED; } } }else if( eOp & WO_ISNULL ){ @@ -133412,7 +150086,7 @@ static int whereLoopAddBtreeIndex( ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ assert( pNew->nOut==saved_nOut ); if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ - /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4 + /* Adjust nOut using stat4 data. Or, if there is no stat4 ** data, using some other estimate. */ whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); }else{ @@ -133426,12 +150100,13 @@ static int whereLoopAddBtreeIndex( pNew->nOut += pTerm->truthProb; pNew->nOut -= nIn; }else{ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 tRowcnt nOut = 0; if( nInMul==0 && pProbe->nSample && pNew->u.btree.nEq<=pProbe->nSampleCol && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) + && OptimizationEnabled(db, SQLITE_Stat4) ){ Expr *pExpr = pTerm->pExpr; if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){ @@ -133445,7 +150120,7 @@ static int whereLoopAddBtreeIndex( if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ if( nOut ){ - pNew->nOut = sqlite3LogEst(nOut); + pNew->nOut = tdsqlite3LogEst(nOut); if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; pNew->nOut -= nIn; } @@ -133468,10 +150143,11 @@ static int whereLoopAddBtreeIndex( ** it to pNew->rRun, which is currently set to the cost of the index ** seek only. Then, if this is a non-covering index, add the cost of ** visiting the rows in the main table. */ + assert( pSrc->pTab->szTabRow>0 ); rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow; - pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx); + pNew->rRun = tdsqlite3LogEstAdd(rLogSize, rCostIdx); if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){ - pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16); + pNew->rRun = tdsqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16); } ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult); @@ -133493,7 +150169,7 @@ static int whereLoopAddBtreeIndex( whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); } pNew->nOut = saved_nOut; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 +#ifdef SQLITE_ENABLE_STAT4 pBuilder->nRecValid = nRecValid; #endif } @@ -133516,10 +150192,12 @@ static int whereLoopAddBtreeIndex( ** the code). And, even if it is not, it should not be too much slower. ** On the other hand, the extra seeks could end up being significantly ** more expensive. */ - assert( 42==sqlite3LogEst(18) ); + assert( 42==tdsqlite3LogEst(18) ); if( saved_nEq==saved_nSkip && saved_nEq+1<pProbe->nKeyCol + && saved_nEq==pNew->nLTerm && pProbe->noSkipScan==0 + && OptimizationEnabled(db, SQLITE_SkipScan) && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK ){ @@ -133540,8 +150218,8 @@ static int whereLoopAddBtreeIndex( pNew->wsFlags = saved_wsFlags; } - WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n", - pProbe->zName, saved_nEq, rc)); + WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n", + pProbe->pTable->zName, pProbe->zName, saved_nEq, rc)); return rc; } @@ -133565,7 +150243,7 @@ static int indexMightHelpWithOrderBy( if( pIndex->bUnordered ) return 0; if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; for(ii=0; ii<pOB->nExpr; ii++){ - Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr); + Expr *pExpr = tdsqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr); if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){ if( pExpr->iColumn<0 ) return 1; for(jj=0; jj<pIndex->nKeyCol; jj++){ @@ -133574,7 +150252,7 @@ static int indexMightHelpWithOrderBy( }else if( (aColExpr = pIndex->aColExpr)!=0 ){ for(jj=0; jj<pIndex->nKeyCol; jj++){ if( pIndex->aiColumn[jj]!=XN_EXPR ) continue; - if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){ + if( tdsqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){ return 1; } } @@ -133583,38 +150261,29 @@ static int indexMightHelpWithOrderBy( return 0; } -/* -** Return a bitmask where 1s indicate that the corresponding column of -** the table is used by an index. Only the first 63 columns are considered. -*/ -static Bitmask columnsInIndex(Index *pIdx){ - Bitmask m = 0; - int j; - for(j=pIdx->nColumn-1; j>=0; j--){ - int x = pIdx->aiColumn[j]; - if( x>=0 ){ - testcase( x==BMS-1 ); - testcase( x==BMS-2 ); - if( x<BMS-1 ) m |= MASKBIT(x); - } - } - return m; -} - /* Check to see if a partial index with pPartIndexWhere can be used ** in the current query. Return true if it can be and false if not. */ -static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){ +static int whereUsablePartialIndex( + int iTab, /* The table for which we want an index */ + int isLeft, /* True if iTab is the right table of a LEFT JOIN */ + WhereClause *pWC, /* The WHERE clause of the query */ + Expr *pWhere /* The WHERE clause from the partial index */ +){ int i; WhereTerm *pTerm; + Parse *pParse = pWC->pWInfo->pParse; while( pWhere->op==TK_AND ){ - if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0; + if( !whereUsablePartialIndex(iTab,isLeft,pWC,pWhere->pLeft) ) return 0; pWhere = pWhere->pRight; } + if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0; for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ - Expr *pExpr = pTerm->pExpr; - if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab) - && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab) + Expr *pExpr; + pExpr = pTerm->pExpr; + if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab) + && (isLeft==0 || ExprHasProperty(pExpr, EP_FromJoin)) + && tdsqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab) ){ return 1; } @@ -133705,6 +150374,7 @@ static int whereLoopAddBtree( sPk.onError = OE_Replace; sPk.pTable = pTab; sPk.szIdxRow = pTab->szTabRow; + sPk.idxType = SQLITE_IDXTYPE_IPK; aiRowEstPk[0] = pTab->nRowLogEst; aiRowEstPk[1] = 0; pFirst = pSrc->pTab->pIndex; @@ -133743,14 +150413,16 @@ static int whereLoopAddBtree( /* TUNING: One-time cost for computing the automatic index is ** estimated to be X*N*log2(N) where N is the number of rows in ** the table being indexed and where X is 7 (LogEst=28) for normal - ** tables or 1.375 (LogEst=4) for views and subqueries. The value + ** tables or 0.5 (LogEst=-10) for views and subqueries. The value ** of X is smaller for views and subqueries so that the query planner ** will be more aggressive about generating automatic indexes for ** those objects, since there is no opportunity to add schema ** indexes on subqueries and views. */ - pNew->rSetup = rLogSize + rSize + 4; + pNew->rSetup = rLogSize + rSize; if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){ - pNew->rSetup += 24; + pNew->rSetup += 28; + }else{ + pNew->rSetup -= 10; } ApplyCostMultiplier(pNew->rSetup, pTab->costMult); if( pNew->rSetup<0 ) pNew->rSetup = 0; @@ -133758,8 +150430,8 @@ static int whereLoopAddBtree( ** is more than the usual guess of 10 rows, since we have no way ** of knowing how selective the index will ultimately be. It would ** not be unreasonable to make this value much larger. */ - pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); - pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); + pNew->nOut = 43; assert( 43==tdsqlite3LogEst(20) ); + pNew->rRun = tdsqlite3LogEstAdd(rLogSize,pNew->nOut); pNew->wsFlags = WHERE_AUTO_INDEX; pNew->prereq = mPrereq | pTerm->prereqRight; rc = whereLoopInsert(pBuilder, pNew); @@ -133768,14 +150440,20 @@ static int whereLoopAddBtree( } #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ - /* Loop over all indices - */ - for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ + /* Loop over all indices. If there was an INDEXED BY clause, then only + ** consider index pProbe. */ + for(; rc==SQLITE_OK && pProbe; + pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++ + ){ + int isLeft = (pSrc->fg.jointype & JT_OUTER)!=0; if( pProbe->pPartIdxWhere!=0 - && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){ + && !whereUsablePartialIndex(pSrc->iCursor, isLeft, pWC, + pProbe->pPartIdxWhere) + ){ testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */ continue; /* Partial index inappropriate for this query */ } + if( pProbe->bNoQuery ) continue; rSize = pProbe->aiRowLogEst[0]; pNew->u.btree.nEq = 0; pNew->u.btree.nBtm = 0; @@ -133790,7 +150468,7 @@ static int whereLoopAddBtree( b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); - if( pProbe->tnum<=0 ){ + if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){ /* Integer primary key index */ pNew->wsFlags = WHERE_IPK; @@ -133809,7 +150487,7 @@ static int whereLoopAddBtree( pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; m = 0; }else{ - m = pSrc->colUsed & ~columnsInIndex(pProbe); + m = pSrc->colUsed & pProbe->colNotIdxed; pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; } @@ -133821,7 +150499,7 @@ static int whereLoopAddBtree( && pProbe->bUnordered==0 && (pProbe->szIdxRow<pTab->szTabRow) && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 - && sqlite3GlobalConfig.bUseCis + && tdsqlite3GlobalConfig.bUseCis && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) ) ){ @@ -133843,7 +150521,7 @@ static int whereLoopAddBtree( WhereClause *pWC2 = &pWInfo->sWC; for(ii=0; ii<pWC2->nTerm; ii++){ WhereTerm *pTerm = &pWC2->a[ii]; - if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){ + if( !tdsqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){ break; } /* pTerm can be evaluated using just the index. So reduce @@ -133856,7 +150534,7 @@ static int whereLoopAddBtree( } } - pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup); + pNew->rRun = tdsqlite3LogEstAdd(pNew->rRun, nLookup); } ApplyCostMultiplier(pNew->rRun, pTab->costMult); whereLoopOutputAdjust(pWC, pNew, rSize); @@ -133866,16 +150544,20 @@ static int whereLoopAddBtree( } } + pBuilder->bldFlags = 0; rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - sqlite3Stat4ProbeFree(pBuilder->pRec); + if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){ + /* If a non-unique index is used, or if a prefix of the key for + ** unique index is used (making the index functionally non-unique) + ** then the sqlite_stat1 data becomes important for scoring the + ** plan */ + pTab->tabFlags |= TF_StatsUsed; + } +#ifdef SQLITE_ENABLE_STAT4 + tdsqlite3Stat4ProbeFree(pBuilder->pRec); pBuilder->nRecValid = 0; pBuilder->pRec = 0; #endif - - /* If there was an INDEXED BY clause, then only that one index is - ** considered. */ - if( pSrc->pIBIndex ) break; } return rc; } @@ -133907,13 +150589,13 @@ static int whereLoopAddVirtualOne( Bitmask mPrereq, /* Mask of tables that must be used. */ Bitmask mUsable, /* Mask of usable tables */ u16 mExclude, /* Exclude terms using these operators */ - sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */ + tdsqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */ u16 mNoOmit, /* Do not omit these constraints */ int *pbIn /* OUT: True if plan uses an IN(...) op */ ){ WhereClause *pWC = pBuilder->pWC; - struct sqlite3_index_constraint *pIdxCons; - struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage; + struct tdsqlite3_index_constraint *pIdxCons; + struct tdsqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage; int i; int mxTerm; int rc = SQLITE_OK; @@ -133928,7 +150610,7 @@ static int whereLoopAddVirtualOne( /* Set the usable flag on the subset of constraints identified by ** arguments mUsable and mExclude. */ - pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; + pIdxCons = *(struct tdsqlite3_index_constraint**)&pIdxInfo->aConstraint; for(i=0; i<nConstraint; i++, pIdxCons++){ WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset]; pIdxCons->usable = 0; @@ -133939,7 +150621,7 @@ static int whereLoopAddVirtualOne( } } - /* Initialize the output fields of the sqlite3_index_info structure */ + /* Initialize the output fields of the tdsqlite3_index_info structure */ memset(pUsage, 0, sizeof(pUsage[0])*nConstraint); assert( pIdxInfo->needToFreeIdxStr==0 ); pIdxInfo->idxStr = 0; @@ -133948,17 +150630,27 @@ static int whereLoopAddVirtualOne( pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; pIdxInfo->estimatedRows = 25; pIdxInfo->idxFlags = 0; - pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed; + pIdxInfo->colUsed = (tdsqlite3_int64)pSrc->colUsed; /* Invoke the virtual table xBestIndex() method */ rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo); - if( rc ) return rc; + if( rc ){ + if( rc==SQLITE_CONSTRAINT ){ + /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means + ** that the particular combination of parameters provided is unusable. + ** Make no entries in the loop table. + */ + WHERETRACE(0xffff, (" ^^^^--- non-viable plan rejected!\n")); + return SQLITE_OK; + } + return rc; + } mxTerm = -1; assert( pNew->nLSlot>=nConstraint ); for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0; pNew->u.vtab.omitMask = 0; - pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; + pIdxCons = *(struct tdsqlite3_index_constraint**)&pIdxInfo->aConstraint; for(i=0; i<nConstraint; i++, pIdxCons++){ int iTerm; if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){ @@ -133970,9 +150662,9 @@ static int whereLoopAddVirtualOne( || pNew->aLTerm[iTerm]!=0 || pIdxCons->usable==0 ){ - rc = SQLITE_ERROR; - sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); - return rc; + tdsqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); + testcase( pIdxInfo->needToFreeIdxStr ); + return SQLITE_ERROR; } testcase( iTerm==nConstraint-1 ); testcase( j==0 ); @@ -133984,7 +150676,14 @@ static int whereLoopAddVirtualOne( if( iTerm>mxTerm ) mxTerm = iTerm; testcase( iTerm==15 ); testcase( iTerm==16 ); - if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm; + if( pUsage[i].omit ){ + if( i<16 && ((1<<i)&mNoOmit)==0 ){ + testcase( i!=iTerm ); + pNew->u.vtab.omitMask |= 1<<iTerm; + }else{ + testcase( i!=iTerm ); + } + } if( (pTerm->eOperator & WO_IN)!=0 ){ /* A virtual table that is constrained by an IN clause may not ** consume the ORDER BY clause because (1) the order of IN terms @@ -133997,9 +150696,17 @@ static int whereLoopAddVirtualOne( } } } - pNew->u.vtab.omitMask &= ~mNoOmit; pNew->nLTerm = mxTerm+1; + for(i=0; i<=mxTerm; i++){ + if( pNew->aLTerm[i]==0 ){ + /* The non-zero argvIdx values must be contiguous. Raise an + ** error if they are not */ + tdsqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); + testcase( pIdxInfo->needToFreeIdxStr ); + return SQLITE_ERROR; + } + } assert( pNew->nLTerm<=pNew->nLSlot ); pNew->u.vtab.idxNum = pIdxInfo->idxNum; pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; @@ -134008,8 +150715,8 @@ static int whereLoopAddVirtualOne( pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? pIdxInfo->nOrderBy : 0); pNew->rSetup = 0; - pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); - pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); + pNew->rRun = tdsqlite3LogEstFromDouble(pIdxInfo->estimatedCost); + pNew->nOut = tdsqlite3LogEst(pIdxInfo->estimatedRows); /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated ** that the scan will visit at most one row. Clear it otherwise. */ @@ -134020,16 +150727,37 @@ static int whereLoopAddVirtualOne( } rc = whereLoopInsert(pBuilder, pNew); if( pNew->u.vtab.needFree ){ - sqlite3_free(pNew->u.vtab.idxStr); + tdsqlite3_free(pNew->u.vtab.idxStr); pNew->u.vtab.needFree = 0; } WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n", - *pbIn, (sqlite3_uint64)mPrereq, - (sqlite3_uint64)(pNew->prereq & ~mPrereq))); + *pbIn, (tdsqlite3_uint64)mPrereq, + (tdsqlite3_uint64)(pNew->prereq & ~mPrereq))); return rc; } +/* +** If this function is invoked from within an xBestIndex() callback, it +** returns a pointer to a buffer containing the name of the collation +** sequence associated with element iCons of the tdsqlite3_index_info.aConstraint +** array. Or, if iCons is out of range or there is no active xBestIndex +** call, return NULL. +*/ +SQLITE_API const char *tdsqlite3_vtab_collation(tdsqlite3_index_info *pIdxInfo, int iCons){ + HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1]; + const char *zRet = 0; + if( iCons>=0 && iCons<pIdxInfo->nConstraint ){ + CollSeq *pC = 0; + int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset; + Expr *pX = pHidden->pWC->a[iTerm].pExpr; + if( pX->pLeft ){ + pC = tdsqlite3ExprCompareCollSeq(pHidden->pParse, pX); + } + zRet = (pC ? pC->zName : tdsqlite3StrBINARY); + } + return zRet; +} /* ** Add all WhereLoop objects for a table of the join identified by @@ -134066,7 +150794,7 @@ static int whereLoopAddVirtual( Parse *pParse; /* The parsing context */ WhereClause *pWC; /* The WHERE clause */ struct SrcList_item *pSrc; /* The FROM clause term to search */ - sqlite3_index_info *p; /* Object to pass to xBestIndex() */ + tdsqlite3_index_info *p; /* Object to pass to xBestIndex() */ int nConstraint; /* Number of constraints in p */ int bIn; /* True if plan uses IN(...) operator */ WhereLoop *pNew; @@ -134089,20 +150817,21 @@ static int whereLoopAddVirtual( pNew->u.vtab.needFree = 0; nConstraint = p->nConstraint; if( whereLoopResize(pParse->db, pNew, nConstraint) ){ - sqlite3DbFree(pParse->db, p); + tdsqlite3DbFree(pParse->db, p); return SQLITE_NOMEM_BKPT; } /* First call xBestIndex() with all constraints usable. */ + WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName)); WHERETRACE(0x40, (" VirtualOne: all usable\n")); rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn); /* If the call to xBestIndex() with all terms enabled produced a plan - ** that does not require any source tables (IOW: a plan with mBest==0), - ** then there is no point in making any further calls to xBestIndex() - ** since they will all return the same result (if the xBestIndex() - ** implementation is sane). */ - if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){ + ** that does not require any source tables (IOW: a plan with mBest==0) + ** and does not use an IN(...) operator, then there is no point in making + ** any further calls to xBestIndex() since they will all return the same + ** result (if the xBestIndex() implementation is sane). */ + if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){ int seenZero = 0; /* True if a plan with no prereqs seen */ int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */ Bitmask mPrev = 0; @@ -134138,7 +150867,7 @@ static int whereLoopAddVirtual( if( mNext==ALLBITS ) break; if( mNext==mBest || mNext==mBestNoIn ) continue; WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n", - (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext)); + (tdsqlite3_uint64)mPrev, (tdsqlite3_uint64)mNext)); rc = whereLoopAddVirtualOne( pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn); if( pNew->prereq==mPrereq ){ @@ -134167,8 +150896,9 @@ static int whereLoopAddVirtual( } } - if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr); - sqlite3DbFree(pParse->db, p); + if( p->needToFreeIdxStr ) tdsqlite3_free(p->idxStr); + tdsqlite3DbFreeNN(pParse->db, p); + WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc)); return rc; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ @@ -134232,8 +150962,8 @@ static int whereLoopAddOr( #ifdef WHERETRACE_ENABLED WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm)); - if( sqlite3WhereTrace & 0x400 ){ - sqlite3WhereClausePrint(sSubBuild.pWC); + if( tdsqlite3WhereTrace & 0x400 ){ + tdsqlite3WhereClausePrint(sSubBuild.pWC); } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -134247,7 +150977,8 @@ static int whereLoopAddOr( if( rc==SQLITE_OK ){ rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable); } - assert( rc==SQLITE_OK || sCur.n==0 ); + assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0 ); + testcase( rc==SQLITE_DONE ); if( sCur.n==0 ){ sSum.n = 0; break; @@ -134261,8 +150992,8 @@ static int whereLoopAddOr( for(i=0; i<sPrev.n; i++){ for(j=0; j<sCur.n; j++){ whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq, - sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun), - sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut)); + tdsqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun), + tdsqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut)); } } } @@ -134308,7 +151039,7 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ SrcList *pTabList = pWInfo->pTabList; struct SrcList_item *pItem; struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel]; - sqlite3 *db = pWInfo->pParse->db; + tdsqlite3 *db = pWInfo->pParse->db; int rc = SQLITE_OK; WhereLoop *pNew; u8 priorJointype = 0; @@ -134316,10 +151047,12 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ /* Loop over the tables in the join, from left to right */ pNew = pBuilder->pNew; whereLoopInit(pNew); + pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT; for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){ Bitmask mUnusable = 0; pNew->iTab = iTab; - pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor); + pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR; + pNew->maskSelf = tdsqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor); if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){ /* This condition is true when pItem is the FROM clause term on the ** right-hand-side of a LEFT or CROSS JOIN. */ @@ -134331,7 +151064,7 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ struct SrcList_item *p; for(p=&pItem[1]; p<pEnd; p++){ if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){ - mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor); + mUnusable |= tdsqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor); } } rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable); @@ -134340,11 +151073,19 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ { rc = whereLoopAddBtree(pBuilder, mPrereq); } - if( rc==SQLITE_OK ){ + if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){ rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable); } mPrior |= pNew->maskSelf; - if( rc || db->mallocFailed ) break; + if( rc || db->mallocFailed ){ + if( rc==SQLITE_DONE ){ + /* We hit the query planner search limit set by iPlanLimit */ + tdsqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search"); + rc = SQLITE_OK; + }else{ + break; + } + } } whereLoopClear(db, pNew); @@ -134352,7 +151093,7 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ } /* -** Examine a WherePath (with the addition of the extra WhereLoop of the 5th +** Examine a WherePath (with the addition of the extra WhereLoop of the 6th ** parameters) to see if it outputs rows in the requested ORDER BY ** (or GROUP BY) without requiring a separate sort operation. Return N: ** @@ -134396,7 +151137,7 @@ static i8 wherePathSatisfiesOrderBy( Expr *pOBExpr; /* An expression from the ORDER BY clause */ CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ Index *pIndex; /* The index associated with pLoop */ - sqlite3 *db = pWInfo->pParse->db; /* Database connection */ + tdsqlite3 *db = pWInfo->pParse->db; /* Database connection */ Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ Bitmask obDone; /* Mask of all ORDER BY terms */ Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ @@ -134445,8 +151186,12 @@ static i8 wherePathSatisfiesOrderBy( pLoop = pLast; } if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){ - if( pLoop->u.vtab.isOrdered ) obSat = obDone; + if( pLoop->u.vtab.isOrdered && (wctrlFlags & WHERE_DISTINCTBY)==0 ){ + obSat = obDone; + } break; + }else if( wctrlFlags & WHERE_DISTINCTBY ){ + pLoop->u.btree.nDistinctCol = 0; } iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; @@ -134457,10 +151202,10 @@ static i8 wherePathSatisfiesOrderBy( */ for(i=0; i<nOrderBy; i++){ if( MASKBIT(i) & obSat ) continue; - pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); + pOBExpr = tdsqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr); if( pOBExpr->op!=TK_COLUMN ) continue; if( pOBExpr->iTable!=iCur ) continue; - pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, + pTerm = tdsqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, ~ready, eqOpMask, 0); if( pTerm==0 ) continue; if( pTerm->eOperator==WO_IN ){ @@ -134472,14 +151217,10 @@ static i8 wherePathSatisfiesOrderBy( if( j>=pLoop->nLTerm ) continue; } if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){ - const char *z1, *z2; - pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); - if( !pColl ) pColl = db->pDfltColl; - z1 = pColl->zName; - pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr); - if( !pColl ) pColl = db->pDfltColl; - z2 = pColl->zName; - if( sqlite3StrICmp(z1, z2)!=0 ) continue; + if( tdsqlite3ExprCollSeqMatch(pWInfo->pParse, + pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){ + continue; + } testcase( pTerm->pExpr->op==TK_IS ); } obSat |= MASKBIT(i); @@ -134498,7 +151239,8 @@ static i8 wherePathSatisfiesOrderBy( assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); assert( pIndex->aiColumn[nColumn-1]==XN_ROWID || !HasRowid(pIndex->pTable)); - isOrderDistinct = IsUniqueIndex(pIndex); + isOrderDistinct = IsUniqueIndex(pIndex) + && (pLoop->wsFlags & WHERE_SKIPSCAN)==0; } /* Loop through all columns of the index and deal with the ones @@ -134516,15 +151258,21 @@ static i8 wherePathSatisfiesOrderBy( u16 eOp = pLoop->aLTerm[j]->eOperator; /* Skip over == and IS and ISNULL terms. (Also skip IN terms when - ** doing WHERE_ORDERBY_LIMIT processing). + ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL + ** terms imply that the index is not UNIQUE NOT NULL in which case + ** the loop need to be marked as not order-distinct because it can + ** have repeated NULL rows. ** ** If the current term is a column of an ((?,?) IN (SELECT...)) ** expression for which the SELECT returns more than one column, ** check that it is the only column used by this loop. Otherwise, ** if it is one of two or more, none of the columns can be - ** considered to match an ORDER BY term. */ + ** considered to match an ORDER BY term. + */ if( (eOp & eqOpMask)!=0 ){ - if( eOp & WO_ISNULL ){ + if( eOp & (WO_ISNULL|WO_IS) ){ + testcase( eOp & WO_ISNULL ); + testcase( eOp & WO_IS ); testcase( isOrderDistinct ); isOrderDistinct = 0; } @@ -134550,8 +151298,8 @@ static i8 wherePathSatisfiesOrderBy( */ if( pIndex ){ iColumn = pIndex->aiColumn[j]; - revIdx = pIndex->aSortOrder[j]; - if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; + revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC; + if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID; }else{ iColumn = XN_ROWID; revIdx = 0; @@ -134574,23 +151322,26 @@ static i8 wherePathSatisfiesOrderBy( isMatch = 0; for(i=0; bOnce && i<nOrderBy; i++){ if( MASKBIT(i) & obSat ) continue; - pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); + pOBExpr = tdsqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr); testcase( wctrlFlags & WHERE_GROUPBY ); testcase( wctrlFlags & WHERE_DISTINCTBY ); if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; - if( iColumn>=(-1) ){ + if( iColumn>=XN_ROWID ){ if( pOBExpr->op!=TK_COLUMN ) continue; if( pOBExpr->iTable!=iCur ) continue; if( pOBExpr->iColumn!=iColumn ) continue; }else{ - if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){ + Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr; + if( tdsqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){ continue; } } - if( iColumn>=0 ){ - pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); - if( !pColl ) pColl = db->pDfltColl; - if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; + if( iColumn!=XN_ROWID ){ + pColl = tdsqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); + if( tdsqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; + } + if( wctrlFlags & WHERE_DISTINCTBY ){ + pLoop->u.btree.nDistinctCol = j+1; } isMatch = 1; break; @@ -134599,13 +151350,22 @@ static i8 wherePathSatisfiesOrderBy( /* Make sure the sort order is compatible in an ORDER BY clause. ** Sort order is irrelevant for a GROUP BY clause. */ if( revSet ){ - if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0; + if( (rev ^ revIdx)!=(pOrderBy->a[i].sortFlags&KEYINFO_ORDER_DESC) ){ + isMatch = 0; + } }else{ - rev = revIdx ^ pOrderBy->a[i].sortOrder; + rev = revIdx ^ (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC); if( rev ) *pRevMask |= MASKBIT(iLoop); revSet = 1; } } + if( isMatch && (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL) ){ + if( j==pLoop->u.btree.nEq ){ + pLoop->wsFlags |= WHERE_BIGNULL_SORT; + }else{ + isMatch = 0; + } + } if( isMatch ){ if( iColumn==XN_ROWID ){ testcase( distinctColumns==0 ); @@ -134635,8 +151395,8 @@ static i8 wherePathSatisfiesOrderBy( Bitmask mTerm; if( MASKBIT(i) & obSat ) continue; p = pOrderBy->a[i].pExpr; - mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p); - if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue; + mTerm = tdsqlite3WhereExprUsage(&pWInfo->sMaskSet,p); + if( mTerm==0 && !tdsqlite3ExprIsConstant(p) ) continue; if( (mTerm&~orderDistinctMask)==0 ){ obSat |= MASKBIT(i); } @@ -134656,7 +151416,7 @@ static i8 wherePathSatisfiesOrderBy( /* -** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(), +** If the WHERE_GROUPBY flag is set in the mask passed to tdsqlite3WhereBegin(), ** the planner assumes that the specified pOrderBy list is actually a GROUP ** BY clause - and so any order that groups rows as required satisfies the ** request. @@ -134664,7 +151424,7 @@ static i8 wherePathSatisfiesOrderBy( ** Normally, in this case it is not possible for the caller to determine ** whether or not the rows are really being delivered in sorted order, or ** just in some other order that provides the required grouping. However, -** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then +** if the WHERE_SORTBYGROUP flag is also passed to tdsqlite3WhereBegin(), then ** this function may be called on the returned WhereInfo object. It returns ** true if the rows really will be sorted in the specified order, or false ** otherwise. @@ -134678,7 +151438,7 @@ static i8 wherePathSatisfiesOrderBy( ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0 */ -SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){ +SQLITE_PRIVATE int tdsqlite3WhereIsSorted(WhereInfo *pWInfo){ assert( pWInfo->wctrlFlags & WHERE_GROUPBY ); assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP ); return pWInfo->sorted; @@ -134721,8 +151481,8 @@ static LogEst whereSortingCost( ** The (Y/X) term is implemented using stack variable rScale ** below. */ LogEst rScale, rSortCost; - assert( nOrderBy>0 && 66==sqlite3LogEst(100) ); - rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66; + assert( nOrderBy>0 && 66==tdsqlite3LogEst(100) ); + rScale = tdsqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66; rSortCost = nRow + rScale + 16; /* Multiple by log(M) where M is the number of output rows. @@ -134750,7 +151510,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ int mxChoice; /* Maximum number of simultaneous paths tracked */ int nLoop; /* Number of terms in the join */ Parse *pParse; /* Parsing context */ - sqlite3 *db; /* The database connection */ + tdsqlite3 *db; /* The database connection */ int iLoop; /* Loop counter over the terms of the join */ int ii, jj; /* Loop counters */ int mxI = 0; /* Index of next entry to replace */ @@ -134792,7 +151552,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ /* Allocate and initialize space for aTo, aFrom and aSortCost[] */ nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; nSpace += sizeof(LogEst) * nOrderBy; - pSpace = sqlite3DbMallocRawNN(db, nSpace); + pSpace = tdsqlite3DbMallocRawNN(db, nSpace); if( pSpace==0 ) return SQLITE_NOMEM_BKPT; aTo = (WherePath*)pSpace; aFrom = aTo+mxChoice; @@ -134819,7 +151579,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ ** TUNING: Do not let the number of iterations go above 28. If the cost ** of computing an automatic index is not paid back within the first 28 ** rows, then do not use the automatic index. */ - aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) ); + aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==tdsqlite3LogEst(28) ); nFrom = 1; assert( aFrom[0].isOrdered==0 ); if( nOrderBy ){ @@ -134848,16 +151608,19 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; - if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){ + if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){ /* Do not use an automatic index if the this loop is expected - ** to run less than 2 times. */ - assert( 10==sqlite3LogEst(2) ); + ** to run less than 1.25 times. It is tempting to also exclude + ** automatic index usage on an outer loop, but sometimes an automatic + ** index is useful in the outer loop of a correlated subquery. */ + assert( 10==tdsqlite3LogEst(2) ); continue; } + /* At this point, pWLoop is a candidate to be the next loop. ** Compute its cost */ - rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); - rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted); + rUnsorted = tdsqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); + rUnsorted = tdsqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted); nOut = pFrom->nRow + pWLoop->nOut; maskNew = pFrom->maskLoop | pWLoop->maskSelf; if( isOrdered<0 ){ @@ -134873,7 +151636,11 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ pWInfo, nRowEst, nOrderBy, isOrdered ); } - rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]); + /* TUNING: Add a small extra penalty (5) to sorting as an + ** extra encouragment to the query planner to select a plan + ** where the rows emerge in the correct order without any sorting + ** required. */ + rCost = tdsqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5; WHERETRACE(0x002, ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n", @@ -134881,6 +151648,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ rUnsorted, rCost)); }else{ rCost = rUnsorted; + rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */ } /* Check to see if pWLoop should be added to the set of @@ -134911,9 +151679,9 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ ** paths currently in the best-so-far buffer. So discard ** this candidate as not viable. */ #ifdef WHERETRACE_ENABLED /* 0x4 */ - if( sqlite3WhereTrace&0x4 ){ - sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + if( tdsqlite3WhereTrace&0x4 ){ + tdsqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, isOrdered>=0 ? isOrdered+'0' : '?'); } #endif @@ -134930,27 +151698,37 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ } pTo = &aTo[jj]; #ifdef WHERETRACE_ENABLED /* 0x4 */ - if( sqlite3WhereTrace&0x4 ){ - sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + if( tdsqlite3WhereTrace&0x4 ){ + tdsqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, isOrdered>=0 ? isOrdered+'0' : '?'); } #endif }else{ /* Control reaches here if best-so-far path pTo=aTo[jj] covers the - ** same set of loops and has the sam isOrdered setting as the + ** same set of loops and has the same isOrdered setting as the ** candidate path. Check to see if the candidate should replace - ** pTo or if the candidate should be skipped */ - if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){ + ** pTo or if the candidate should be skipped. + ** + ** The conditional is an expanded vector comparison equivalent to: + ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted) + */ + if( pTo->rCost<rCost + || (pTo->rCost==rCost + && (pTo->nRow<nOut + || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted) + ) + ) + ){ #ifdef WHERETRACE_ENABLED /* 0x4 */ - if( sqlite3WhereTrace&0x4 ){ - sqlite3DebugPrintf( - "Skip %s cost=%-3d,%3d order=%c", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + if( tdsqlite3WhereTrace&0x4 ){ + tdsqlite3DebugPrintf( + "Skip %s cost=%-3d,%3d,%3d order=%c", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, isOrdered>=0 ? isOrdered+'0' : '?'); - sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n", + tdsqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, - pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); + pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); } #endif /* Discard the candidate path from further consideration */ @@ -134961,14 +151739,14 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ /* Control reaches here if the candidate path is better than the ** pTo path. Replace pTo with the candidate. */ #ifdef WHERETRACE_ENABLED /* 0x4 */ - if( sqlite3WhereTrace&0x4 ){ - sqlite3DebugPrintf( - "Update %s cost=%-3d,%3d order=%c", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, + if( tdsqlite3WhereTrace&0x4 ){ + tdsqlite3DebugPrintf( + "Update %s cost=%-3d,%3d,%3d order=%c", + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, isOrdered>=0 ? isOrdered+'0' : '?'); - sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n", + tdsqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, - pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); + pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); } #endif } @@ -134999,16 +151777,16 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ } #ifdef WHERETRACE_ENABLED /* >=2 */ - if( sqlite3WhereTrace & 0x02 ){ - sqlite3DebugPrintf("---- after round %d ----\n", iLoop); + if( tdsqlite3WhereTrace & 0x02 ){ + tdsqlite3DebugPrintf("---- after round %d ----\n", iLoop); for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){ - sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c", + tdsqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); if( pTo->isOrdered>0 ){ - sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); + tdsqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); }else{ - sqlite3DebugPrintf("\n"); + tdsqlite3DebugPrintf("\n"); } } } @@ -135022,8 +151800,8 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ } if( nFrom==0 ){ - sqlite3ErrorMsg(pParse, "no query solution"); - sqlite3DbFree(db, pSpace); + tdsqlite3ErrorMsg(pParse, "no query solution"); + tdsqlite3DbFreeNN(db, pSpace); return SQLITE_ERROR; } @@ -135046,12 +151824,13 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ && nRowEst ){ Bitmask notUsed; - int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom, + int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom, WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used); - if( rc==pWInfo->pDistinctSet->nExpr ){ + if( rc==pWInfo->pResultSet->nExpr ){ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; } } + pWInfo->bOrderedInnerLoop = 0; if( pWInfo->pOrderBy ){ if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ @@ -135099,7 +151878,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ pWInfo->nRowOut = pFrom->nRow; /* Free temporary memory and return success */ - sqlite3DbFree(db, pSpace); + tdsqlite3DbFreeNN(db, pSpace); return SQLITE_OK; } @@ -135107,7 +151886,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ ** Most queries use only a single table (they are not joins) and have ** simple == constraints against indexed fields. This routine attempts ** to plan those simple cases using much less ceremony than the -** general-purpose query planner, and thereby yield faster sqlite3_prepare() +** general-purpose query planner, and thereby yield faster tdsqlite3_prepare() ** times for the common case. ** ** Return non-zero on success, if this query can be handled by this @@ -135137,7 +151916,7 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){ pLoop = pBuilder->pNew; pLoop->wsFlags = 0; pLoop->nSkip = 0; - pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0); + pTerm = tdsqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0); if( pTerm ){ testcase( pTerm->eOperator & WO_IS ); pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; @@ -135145,7 +151924,7 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){ pLoop->nLTerm = 1; pLoop->u.btree.nEq = 1; /* TUNING: Cost of a rowid lookup is 10 */ - pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ + pLoop->rRun = 33; /* 33==tdsqlite3LogEst(10) */ }else{ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int opMask; @@ -135156,28 +151935,29 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){ ) continue; opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ; for(j=0; j<pIdx->nKeyCol; j++){ - pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx); + pTerm = tdsqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx); if( pTerm==0 ) break; testcase( pTerm->eOperator & WO_IS ); pLoop->aLTerm[j] = pTerm; } if( j!=pIdx->nKeyCol ) continue; pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; - if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ + if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){ pLoop->wsFlags |= WHERE_IDX_ONLY; } pLoop->nLTerm = j; pLoop->u.btree.nEq = j; pLoop->u.btree.pIndex = pIdx; /* TUNING: Cost of a unique index lookup is 15 */ - pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ + pLoop->rRun = 39; /* 39==tdsqlite3LogEst(15) */ break; } } if( pLoop->wsFlags ){ pLoop->nOut = (LogEst)1; pWInfo->a[0].pWLoop = pLoop; - pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); + assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] ); + pLoop->maskSelf = 1; /* tdsqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */ pWInfo->a[0].iTabCur = iCur; pWInfo->nRowOut = 1; if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; @@ -135193,10 +151973,36 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){ } /* +** Helper function for exprIsDeterministic(). +*/ +static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){ + if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){ + pWalker->eCode = 0; + return WRC_Abort; + } + return WRC_Continue; +} + +/* +** Return true if the expression contains no non-deterministic SQL +** functions. Do not consider non-deterministic SQL functions that are +** part of sub-select statements. +*/ +static int exprIsDeterministic(Expr *p){ + Walker w; + memset(&w, 0, sizeof(w)); + w.eCode = 1; + w.xExprCallback = exprNodeIsDeterministic; + w.xSelectCallback = tdsqlite3SelectWalkFail; + tdsqlite3WalkExpr(&w, p); + return w.eCode; +} + +/* ** Generate the beginning of the loop used for WHERE clause processing. ** The return value is a pointer to an opaque structure that contains ** information needed to terminate the loop. Later, the calling routine -** should invoke sqlite3WhereEnd() with the return value of this function +** should invoke tdsqlite3WhereEnd() with the return value of this function ** in order to complete the WHERE clause processing. ** ** If an error occurs, this routine returns NULL. @@ -135211,11 +152017,11 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){ ** Then the code generated is conceptually like the following: ** ** foreach row1 in t1 do \ Code generated -** foreach row2 in t2 do |-- by sqlite3WhereBegin() +** foreach row2 in t2 do |-- by tdsqlite3WhereBegin() ** foreach row3 in t3 do / ** ... ** end \ Code generated -** end |-- by sqlite3WhereEnd() +** end |-- by tdsqlite3WhereEnd() ** end / ** ** Note that the loops might not be nested in the order in which they @@ -135227,9 +152033,9 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){ ** There are Btree cursors associated with each table. t1 uses cursor ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. ** And so forth. This routine generates code to open those VDBE cursors -** and sqlite3WhereEnd() generates the code to close them. +** and tdsqlite3WhereEnd() generates the code to close them. ** -** The code that sqlite3WhereBegin() generates leaves the cursors named +** The code that tdsqlite3WhereBegin() generates leaves the cursors named ** in pTabList pointing at their appropriate entries. The [...] code ** can use OP_Column and OP_Rowid opcodes on these cursors to extract ** data from the various tables of the loop. @@ -135280,12 +152086,12 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){ ** be used to compute the appropriate cursor depending on which index is ** used. */ -SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( +SQLITE_PRIVATE WhereInfo *tdsqlite3WhereBegin( Parse *pParse, /* The parser context */ SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ Expr *pWhere, /* The WHERE clause */ ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */ - ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */ + ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */ u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */ int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number ** If WHERE_USE_LIMIT, then the limit amount */ @@ -135300,7 +152106,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( WhereLevel *pLevel; /* A single level in pWInfo->a[] */ WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ int ii; /* Loop counter */ - sqlite3 *db; /* Database connection */ + tdsqlite3 *db; /* Database connection */ int rc; /* Return code */ u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */ @@ -135323,7 +152129,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( sWLB.pOrderBy = pOrderBy; /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via - ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ + ** tdsqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ wctrlFlags &= ~WHERE_WANT_DISTINCT; } @@ -135333,7 +152139,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( */ testcase( pTabList->nSrc==BMS ); if( pTabList->nSrc>BMS ){ - sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); + tdsqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); return 0; } @@ -135352,19 +152158,20 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( ** some architectures. Hence the ROUND8() below. */ nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); - pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop)); + pWInfo = tdsqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop)); if( db->mallocFailed ){ - sqlite3DbFree(db, pWInfo); + tdsqlite3DbFree(db, pWInfo); pWInfo = 0; goto whereBeginError; } pWInfo->pParse = pParse; pWInfo->pTabList = pTabList; pWInfo->pOrderBy = pOrderBy; - pWInfo->pDistinctSet = pDistinctSet; + pWInfo->pWhere = pWhere; + pWInfo->pResultSet = pResultSet; pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; pWInfo->nLevel = nTabList; - pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v); + pWInfo->iBreak = pWInfo->iContinue = tdsqlite3VdbeMakeLabel(pParse); pWInfo->wctrlFlags = wctrlFlags; pWInfo->iLimit = iAuxArg; pWInfo->savedNQueryLoop = pParse->nQueryLoop; @@ -135386,20 +152193,9 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( ** subexpression is separated by an AND operator. */ initMaskSet(pMaskSet); - sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo); - sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND); + tdsqlite3WhereClauseInit(&pWInfo->sWC, pWInfo); + tdsqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND); - /* Special case: a WHERE clause that is constant. Evaluate the - ** expression and either jump over all of the code or fall thru. - */ - for(ii=0; ii<sWLB.pWC->nTerm; ii++){ - if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){ - sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak, - SQLITE_JUMPIFNULL); - sWLB.pWC->a[ii].wtFlags |= TERM_CODED; - } - } - /* Special case: No FROM clause */ if( nTabList==0 ){ @@ -135407,59 +152203,96 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( if( wctrlFlags & WHERE_WANT_DISTINCT ){ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; } + ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW")); + }else{ + /* Assign a bit from the bitmask to every term in the FROM clause. + ** + ** The N-th term of the FROM clause is assigned a bitmask of 1<<N. + ** + ** The rule of the previous sentence ensures thta if X is the bitmask for + ** a table T, then X-1 is the bitmask for all other tables to the left of T. + ** Knowing the bitmask for all tables to the left of a left join is + ** important. Ticket #3015. + ** + ** Note that bitmasks are created for all pTabList->nSrc tables in + ** pTabList, not just the first nTabList tables. nTabList is normally + ** equal to pTabList->nSrc but might be shortened to 1 if the + ** WHERE_OR_SUBCLAUSE flag is set. + */ + ii = 0; + do{ + createMask(pMaskSet, pTabList->a[ii].iCursor); + tdsqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC); + }while( (++ii)<pTabList->nSrc ); + #ifdef SQLITE_DEBUG + { + Bitmask mx = 0; + for(ii=0; ii<pTabList->nSrc; ii++){ + Bitmask m = tdsqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor); + assert( m>=mx ); + mx = m; + } + } + #endif } + + /* Analyze all of the subexpressions. */ + tdsqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC); + if( db->mallocFailed ) goto whereBeginError; - /* Assign a bit from the bitmask to every term in the FROM clause. + /* Special case: WHERE terms that do not refer to any tables in the join + ** (constant expressions). Evaluate each such term, and jump over all the + ** generated code if the result is not true. ** - ** The N-th term of the FROM clause is assigned a bitmask of 1<<N. + ** Do not do this if the expression contains non-deterministic functions + ** that are not within a sub-select. This is not strictly required, but + ** preserves SQLite's legacy behaviour in the following two cases: ** - ** The rule of the previous sentence ensures thta if X is the bitmask for - ** a table T, then X-1 is the bitmask for all other tables to the left of T. - ** Knowing the bitmask for all tables to the left of a left join is - ** important. Ticket #3015. - ** - ** Note that bitmasks are created for all pTabList->nSrc tables in - ** pTabList, not just the first nTabList tables. nTabList is normally - ** equal to pTabList->nSrc but might be shortened to 1 if the - ** WHERE_OR_SUBCLAUSE flag is set. + ** FROM ... WHERE random()>0; -- eval random() once per row + ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall */ - for(ii=0; ii<pTabList->nSrc; ii++){ - createMask(pMaskSet, pTabList->a[ii].iCursor); - sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC); - } -#ifdef SQLITE_DEBUG - for(ii=0; ii<pTabList->nSrc; ii++){ - Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor); - assert( m==MASKBIT(ii) ); + for(ii=0; ii<sWLB.pWC->nTerm; ii++){ + WhereTerm *pT = &sWLB.pWC->a[ii]; + if( pT->wtFlags & TERM_VIRTUAL ) continue; + if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){ + tdsqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL); + pT->wtFlags |= TERM_CODED; + } } -#endif - - /* Analyze all of the subexpressions. */ - sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC); - if( db->mallocFailed ) goto whereBeginError; if( wctrlFlags & WHERE_WANT_DISTINCT ){ - if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){ + if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){ /* The DISTINCT marking is pointless. Ignore it. */ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; }else if( pOrderBy==0 ){ /* Try to ORDER BY the result set to make distinct processing easier */ pWInfo->wctrlFlags |= WHERE_DISTINCTBY; - pWInfo->pOrderBy = pDistinctSet; + pWInfo->pOrderBy = pResultSet; } } /* Construct the WhereLoop objects */ #if defined(WHERETRACE_ENABLED) - if( sqlite3WhereTrace & 0xffff ){ - sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags); + if( tdsqlite3WhereTrace & 0xffff ){ + tdsqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags); if( wctrlFlags & WHERE_USE_LIMIT ){ - sqlite3DebugPrintf(", limit: %d", iAuxArg); + tdsqlite3DebugPrintf(", limit: %d", iAuxArg); + } + tdsqlite3DebugPrintf(")\n"); + if( tdsqlite3WhereTrace & 0x100 ){ + Select sSelect; + memset(&sSelect, 0, sizeof(sSelect)); + sSelect.selFlags = SF_WhereBegin; + sSelect.pSrc = pTabList; + sSelect.pWhere = pWhere; + sSelect.pOrderBy = pOrderBy; + sSelect.pEList = pResultSet; + tdsqlite3TreeViewSelect(0, &sSelect, 0); } - sqlite3DebugPrintf(")\n"); } - if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ - sqlite3WhereClausePrint(sWLB.pWC); + if( tdsqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ + tdsqlite3DebugPrintf("---- WHERE clause at start of analysis:\n"); + tdsqlite3WhereClausePrint(sWLB.pWC); } #endif @@ -135468,14 +152301,14 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( if( rc ) goto whereBeginError; #ifdef WHERETRACE_ENABLED - if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */ + if( tdsqlite3WhereTrace ){ /* Display all of the WhereLoop objects */ WhereLoop *p; int i; static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ - p->cId = zLabel[i%sizeof(zLabel)]; - whereLoopPrint(p, sWLB.pWC); + p->cId = zLabel[i%(sizeof(zLabel)-1)]; + tdsqlite3WhereLoopPrint(p, sWLB.pWC); } } #endif @@ -135494,78 +152327,147 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( goto whereBeginError; } #ifdef WHERETRACE_ENABLED - if( sqlite3WhereTrace ){ - sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); + if( tdsqlite3WhereTrace ){ + tdsqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); if( pWInfo->nOBSat>0 ){ - sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); + tdsqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); } switch( pWInfo->eDistinct ){ case WHERE_DISTINCT_UNIQUE: { - sqlite3DebugPrintf(" DISTINCT=unique"); + tdsqlite3DebugPrintf(" DISTINCT=unique"); break; } case WHERE_DISTINCT_ORDERED: { - sqlite3DebugPrintf(" DISTINCT=ordered"); + tdsqlite3DebugPrintf(" DISTINCT=ordered"); break; } case WHERE_DISTINCT_UNORDERED: { - sqlite3DebugPrintf(" DISTINCT=unordered"); + tdsqlite3DebugPrintf(" DISTINCT=unordered"); break; } } - sqlite3DebugPrintf("\n"); + tdsqlite3DebugPrintf("\n"); for(ii=0; ii<pWInfo->nLevel; ii++){ - whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); + tdsqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); } } #endif - /* Attempt to omit tables from the join that do not effect the result */ + + /* Attempt to omit tables from the join that do not affect the result. + ** For a table to not affect the result, the following must be true: + ** + ** 1) The query must not be an aggregate. + ** 2) The table must be the RHS of a LEFT JOIN. + ** 3) Either the query must be DISTINCT, or else the ON or USING clause + ** must contain a constraint that limits the scan of the table to + ** at most a single row. + ** 4) The table must not be referenced by any part of the query apart + ** from its own USING or ON clause. + ** + ** For example, given: + ** + ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1); + ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2); + ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3); + ** + ** then table t2 can be omitted from the following: + ** + ** SELECT v1, v3 FROM t1 + ** LEFT JOIN t2 ON (t1.ipk=t2.ipk) + ** LEFT JOIN t3 ON (t1.ipk=t3.ipk) + ** + ** or from: + ** + ** SELECT DISTINCT v1, v3 FROM t1 + ** LEFT JOIN t2 + ** LEFT JOIN t3 ON (t1.ipk=t3.ipk) + */ + notReady = ~(Bitmask)0; if( pWInfo->nLevel>=2 - && pDistinctSet!=0 + && pResultSet!=0 /* guarantees condition (1) above */ && OptimizationEnabled(db, SQLITE_OmitNoopJoin) ){ - Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet); + int i; + Bitmask tabUsed = tdsqlite3WhereExprListUsage(pMaskSet, pResultSet); if( sWLB.pOrderBy ){ - tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy); + tabUsed |= tdsqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy); } - while( pWInfo->nLevel>=2 ){ + for(i=pWInfo->nLevel-1; i>=1; i--){ WhereTerm *pTerm, *pEnd; - pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop; - if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break; + struct SrcList_item *pItem; + pLoop = pWInfo->a[i].pWLoop; + pItem = &pWInfo->pTabList->a[pLoop->iTab]; + if( (pItem->fg.jointype & JT_LEFT)==0 ) continue; if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 && (pLoop->wsFlags & WHERE_ONEROW)==0 ){ - break; + continue; } - if( (tabUsed & pLoop->maskSelf)!=0 ) break; + if( (tabUsed & pLoop->maskSelf)!=0 ) continue; pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){ - if( (pTerm->prereqAll & pLoop->maskSelf)!=0 - && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) - ){ - break; + if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){ + if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin) + || pTerm->pExpr->iRightJoinTable!=pItem->iCursor + ){ + break; + } } } - if( pTerm<pEnd ) break; + if( pTerm<pEnd ) continue; WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId)); + notReady &= ~pLoop->maskSelf; + for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){ + if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){ + pTerm->wtFlags |= TERM_CODED; + } + } + if( i!=pWInfo->nLevel-1 ){ + int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel); + memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte); + } pWInfo->nLevel--; nTabList--; } } +#if defined(WHERETRACE_ENABLED) + if( tdsqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ + tdsqlite3DebugPrintf("---- WHERE clause at end of analysis:\n"); + tdsqlite3WhereClausePrint(sWLB.pWC); + } WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); +#endif pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; /* If the caller is an UPDATE or DELETE statement that is requesting ** to use a one-pass algorithm, determine if this is appropriate. + ** + ** A one-pass approach can be used if the caller has requested one + ** and either (a) the scan visits at most one row or (b) each + ** of the following are true: + ** + ** * the caller has indicated that a one-pass approach can be used + ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and + ** * the table is not a virtual table, and + ** * either the scan does not use the OR optimization or the caller + ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified + ** for DELETE). + ** + ** The last qualification is because an UPDATE statement uses + ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can + ** use a one-pass approach, and this is not set accurately for scans + ** that use the OR optimization. */ assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){ int wsFlags = pWInfo->a[0].pWLoop->wsFlags; int bOnerow = (wsFlags & WHERE_ONEROW)!=0; - if( bOnerow - || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0 - && 0==(wsFlags & WHERE_VIRTUALTABLE)) - ){ + assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) ); + if( bOnerow || ( + 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW) + && !IsVirtual(pTabList->a[0].pTab) + && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK)) + )){ pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI; if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){ if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){ @@ -135586,16 +152488,16 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( pTabItem = &pTabList->a[pLevel->iFrom]; pTab = pTabItem->pTab; - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + iDb = tdsqlite3SchemaToIndex(db, pTab->pSchema); pLoop = pLevel->pWLoop; if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ /* Do nothing */ }else #ifndef SQLITE_OMIT_VIRTUALTABLE if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ - const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); + const char *pVTab = (const char *)tdsqlite3GetVTable(db, pTab); int iCur = pTabItem->iCursor; - sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); + tdsqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); }else if( IsVirtual(pTab) ){ /* noop */ }else @@ -135607,37 +152509,43 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( op = OP_OpenWrite; pWInfo->aiCurOnePass[0] = pTabItem->iCursor; }; - sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); + tdsqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); assert( pTabItem->iCursor==pLevel->iTabCur ); testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 ); testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS ); - if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){ + if( pWInfo->eOnePass==ONEPASS_OFF + && pTab->nCol<BMS + && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0 + ){ + /* If we know that only a prefix of the record will be used, + ** it is advantageous to reduce the "column count" field in + ** the P4 operand of the OP_OpenRead/Write opcode. */ Bitmask b = pTabItem->colUsed; int n = 0; for(; b; b=b>>1, n++){} - sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32); + tdsqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32); assert( n<=pTab->nCol ); } #ifdef SQLITE_ENABLE_CURSOR_HINTS if( pLoop->u.btree.pIndex!=0 ){ - sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete); + tdsqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete); }else #endif { - sqlite3VdbeChangeP5(v, bFordelete); + tdsqlite3VdbeChangeP5(v, bFordelete); } #ifdef SQLITE_ENABLE_COLUMN_USED_MASK - sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0, + tdsqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0, (const u8*)&pTabItem->colUsed, P4_INT64); #endif }else{ - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + tdsqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); } if( pLoop->wsFlags & WHERE_INDEXED ){ Index *pIx = pLoop->u.btree.pIndex; int iIndexCur; int op = OP_OpenRead; - /* iAuxArg is always set if to a positive value if ONEPASS is possible */ + /* iAuxArg is always set to a positive value if ONEPASS is possible */ assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 @@ -135666,13 +152574,15 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( assert( pIx->pSchema==pTab->pSchema ); assert( iIndexCur>=0 ); if( op ){ - sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIx); + tdsqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); + tdsqlite3VdbeSetP4KeyInfo(pParse, pIx); if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0 + && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 + && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED ){ - sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */ + tdsqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */ } VdbeComment((v, "%s", pIx->zName)); #ifdef SQLITE_ENABLE_COLUMN_USED_MASK @@ -135686,22 +152596,21 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue; colUsed |= ((u64)1)<<(ii<63 ? ii : 63); } - sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0, + tdsqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0, (u8*)&colUsed, P4_INT64); } #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */ } } - if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); + if( iDb>=0 ) tdsqlite3CodeVerifySchema(pParse, iDb); } - pWInfo->iTop = sqlite3VdbeCurrentAddr(v); + pWInfo->iTop = tdsqlite3VdbeCurrentAddr(v); if( db->mallocFailed ) goto whereBeginError; /* Generate the code to do the search. Each iteration of the for ** loop below generates code for a single nested loop of the VM ** program. */ - notReady = ~(Bitmask)0; for(ii=0; ii<nTabList; ii++){ int addrExplain; int wsFlags; @@ -135714,14 +152623,14 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( if( db->mallocFailed ) goto whereBeginError; } #endif - addrExplain = sqlite3WhereExplainOneScan( - pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags + addrExplain = tdsqlite3WhereExplainOneScan( + pParse, pTabList, pLevel, wctrlFlags ); - pLevel->addrBody = sqlite3VdbeCurrentAddr(v); - notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady); + pLevel->addrBody = tdsqlite3VdbeCurrentAddr(v); + notReady = tdsqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady); pWInfo->iContinue = pLevel->addrCont; if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){ - sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain); + tdsqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain); } } @@ -135739,82 +152648,160 @@ whereBeginError: } /* +** Part of tdsqlite3WhereEnd() will rewrite opcodes to reference the +** index rather than the main table. In SQLITE_DEBUG mode, we want +** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine +** does that. +*/ +#ifndef SQLITE_DEBUG +# define OpcodeRewriteTrace(D,K,P) /* no-op */ +#else +# define OpcodeRewriteTrace(D,K,P) tdsqlite3WhereOpcodeRewriteTrace(D,K,P) + static void tdsqlite3WhereOpcodeRewriteTrace( + tdsqlite3 *db, + int pc, + VdbeOp *pOp + ){ + if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return; + tdsqlite3VdbePrintOp(0, pc, pOp); + } +#endif + +/* ** Generate the end of the WHERE loop. See comments on -** sqlite3WhereBegin() for additional information. +** tdsqlite3WhereBegin() for additional information. */ -SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ +SQLITE_PRIVATE void tdsqlite3WhereEnd(WhereInfo *pWInfo){ Parse *pParse = pWInfo->pParse; Vdbe *v = pParse->pVdbe; int i; WhereLevel *pLevel; WhereLoop *pLoop; SrcList *pTabList = pWInfo->pTabList; - sqlite3 *db = pParse->db; + tdsqlite3 *db = pParse->db; /* Generate loop termination code. */ VdbeModuleComment((v, "End WHERE-core")); - sqlite3ExprCacheClear(pParse); for(i=pWInfo->nLevel-1; i>=0; i--){ int addr; pLevel = &pWInfo->a[i]; pLoop = pLevel->pWLoop; - sqlite3VdbeResolveLabel(v, pLevel->addrCont); if( pLevel->op!=OP_Noop ){ - sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); - sqlite3VdbeChangeP5(v, pLevel->p5); +#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT + int addrSeek = 0; + Index *pIdx; + int n; + if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED + && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */ + && (pLoop->wsFlags & WHERE_INDEXED)!=0 + && (pIdx = pLoop->u.btree.pIndex)->hasStat1 + && (n = pLoop->u.btree.nDistinctCol)>0 + && pIdx->aiRowLogEst[n]>=36 + ){ + int r1 = pParse->nMem+1; + int j, op; + for(j=0; j<n; j++){ + tdsqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j); + } + pParse->nMem += n+1; + op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT; + addrSeek = tdsqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n); + VdbeCoverageIf(v, op==OP_SeekLT); + VdbeCoverageIf(v, op==OP_SeekGT); + tdsqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2); + } +#endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */ + /* The common case: Advance to the next row */ + tdsqlite3VdbeResolveLabel(v, pLevel->addrCont); + tdsqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); + tdsqlite3VdbeChangeP5(v, pLevel->p5); VdbeCoverage(v); VdbeCoverageIf(v, pLevel->op==OP_Next); VdbeCoverageIf(v, pLevel->op==OP_Prev); VdbeCoverageIf(v, pLevel->op==OP_VNext); + if( pLevel->regBignull ){ + tdsqlite3VdbeResolveLabel(v, pLevel->addrBignull); + tdsqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1); + VdbeCoverage(v); + } +#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT + if( addrSeek ) tdsqlite3VdbeJumpHere(v, addrSeek); +#endif + }else{ + tdsqlite3VdbeResolveLabel(v, pLevel->addrCont); } if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ struct InLoop *pIn; int j; - sqlite3VdbeResolveLabel(v, pLevel->addrNxt); + tdsqlite3VdbeResolveLabel(v, pLevel->addrNxt); for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ - sqlite3VdbeJumpHere(v, pIn->addrInTop+1); + tdsqlite3VdbeJumpHere(v, pIn->addrInTop+1); if( pIn->eEndLoopOp!=OP_Noop ){ - sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); + if( pIn->nPrefix ){ + assert( pLoop->wsFlags & WHERE_IN_EARLYOUT ); + if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){ + tdsqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur, + tdsqlite3VdbeCurrentAddr(v)+2+(pLevel->iLeftJoin!=0), + pIn->iBase, pIn->nPrefix); + VdbeCoverage(v); + } + if( pLevel->iLeftJoin ){ + /* For LEFT JOIN queries, cursor pIn->iCur may not have been + ** opened yet. This occurs for WHERE clauses such as + ** "a = ? AND b IN (...)", where the index is on (a, b). If + ** the RHS of the (a=?) is NULL, then the "b IN (...)" may + ** never have been coded, but the body of the loop run to + ** return the null-row. So, if the cursor is not open yet, + ** jump over the OP_Next or OP_Prev instruction about to + ** be coded. */ + tdsqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur, + tdsqlite3VdbeCurrentAddr(v) + 2 + ); + VdbeCoverage(v); + } + } + tdsqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); VdbeCoverage(v); - VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen); - VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen); + VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev); + VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next); } - sqlite3VdbeJumpHere(v, pIn->addrInTop-1); + tdsqlite3VdbeJumpHere(v, pIn->addrInTop-1); } } - sqlite3VdbeResolveLabel(v, pLevel->addrBrk); + tdsqlite3VdbeResolveLabel(v, pLevel->addrBrk); if( pLevel->addrSkip ){ - sqlite3VdbeGoto(v, pLevel->addrSkip); + tdsqlite3VdbeGoto(v, pLevel->addrSkip); VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName)); - sqlite3VdbeJumpHere(v, pLevel->addrSkip); - sqlite3VdbeJumpHere(v, pLevel->addrSkip-2); + tdsqlite3VdbeJumpHere(v, pLevel->addrSkip); + tdsqlite3VdbeJumpHere(v, pLevel->addrSkip-2); } #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS if( pLevel->addrLikeRep ){ - sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1), + tdsqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1), pLevel->addrLikeRep); VdbeCoverage(v); } #endif if( pLevel->iLeftJoin ){ int ws = pLoop->wsFlags; - addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); + addr = tdsqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 ); if( (ws & WHERE_IDX_ONLY)==0 ){ - sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); + assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor ); + tdsqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur); } if( (ws & WHERE_INDEXED) || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) ){ - sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); + tdsqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); } if( pLevel->op==OP_Return ){ - sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); + tdsqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); }else{ - sqlite3VdbeGoto(v, pLevel->addrFirst); + tdsqlite3VdbeGoto(v, pLevel->addrFirst); } - sqlite3VdbeJumpHere(v, addr); + tdsqlite3VdbeJumpHere(v, addr); } VdbeModuleComment((v, "End WHERE-loop%d: %s", i, pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); @@ -135823,7 +152810,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ /* The "break" point is here, just past the end of the outer loop. ** Set it. */ - sqlite3VdbeResolveLabel(v, pWInfo->iBreak); + tdsqlite3VdbeResolveLabel(v, pWInfo->iBreak); assert( pWInfo->nLevel<=pTabList->nSrc ); for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){ @@ -135839,13 +152826,15 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ ** the co-routine into OP_Copy of result contained in a register. ** OP_Rowid becomes OP_Null. */ - if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){ - translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur, + if( pTabItem->fg.viaCoroutine ){ + testcase( pParse->db->mallocFailed ); + translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur, pTabItem->regResult, 0); continue; } - /* Close all of the cursors that were opened by sqlite3WhereBegin. +#ifdef SQLITE_ENABLE_EARLY_CURSOR_CLOSE + /* Close all of the cursors that were opened by tdsqlite3WhereBegin. ** Except, do not close cursors that will be reused by the OR optimization ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors ** created for the ONEPASS optimization. @@ -135856,23 +152845,24 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ ){ int ws = pLoop->wsFlags; if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){ - sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); + tdsqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); } if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1] ){ - sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); + tdsqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); } } +#endif /* If this scan uses an index, make VDBE code substitutions to read data ** from the index instead of from the table where possible. In some cases ** this optimization prevents the table from ever being read, which can ** yield a significant performance boost. ** - ** Calls to the code generator in between sqlite3WhereBegin and - ** sqlite3WhereEnd will have created code that references the table + ** Calls to the code generator in between tdsqlite3WhereBegin and + ** tdsqlite3WhereEnd will have created code that references the table ** directly. This loop scans all that code looking for opcodes ** that reference the table and converts them into opcodes that ** reference the index. @@ -135886,33 +152876,62 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable)) && !db->mallocFailed ){ - last = sqlite3VdbeCurrentAddr(v); + last = tdsqlite3VdbeCurrentAddr(v); k = pLevel->addrBody; - pOp = sqlite3VdbeGetOp(v, k); +#ifdef SQLITE_DEBUG + if( db->flags & SQLITE_VdbeAddopTrace ){ + printf("TRANSLATE opcodes in range %d..%d\n", k, last-1); + } +#endif + pOp = tdsqlite3VdbeGetOp(v, k); for(; k<last; k++, pOp++){ if( pOp->p1!=pLevel->iTabCur ) continue; - if( pOp->opcode==OP_Column ){ + if( pOp->opcode==OP_Column +#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC + || pOp->opcode==OP_Offset +#endif + ){ int x = pOp->p2; assert( pIdx->pTable==pTab ); if( !HasRowid(pTab) ){ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); + Index *pPk = tdsqlite3PrimaryKeyIndex(pTab); x = pPk->aiColumn[x]; assert( x>=0 ); + }else{ + testcase( x!=tdsqlite3StorageColumnToTable(pTab,x) ); + x = tdsqlite3StorageColumnToTable(pTab,x); } - x = sqlite3ColumnOfIndex(pIdx, x); + x = tdsqlite3TableColumnToIndex(pIdx, x); if( x>=0 ){ pOp->p2 = x; pOp->p1 = pLevel->iIdxCur; + OpcodeRewriteTrace(db, k, pOp); } - assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 ); + assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 + || pWInfo->eOnePass ); }else if( pOp->opcode==OP_Rowid ){ pOp->p1 = pLevel->iIdxCur; pOp->opcode = OP_IdxRowid; + OpcodeRewriteTrace(db, k, pOp); + }else if( pOp->opcode==OP_IfNullRow ){ + pOp->p1 = pLevel->iIdxCur; + OpcodeRewriteTrace(db, k, pOp); } } +#ifdef SQLITE_DEBUG + if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n"); +#endif } } + /* Undo all Expr node modifications */ + while( pWInfo->pExprMods ){ + WhereExprMod *p = pWInfo->pExprMods; + pWInfo->pExprMods = p->pNext; + memcpy(p->pExpr, &p->orig, sizeof(p->orig)); + tdsqlite3DbFree(db, p); + } + /* Final cleanup */ pParse->nQueryLoop = pWInfo->savedNQueryLoop; @@ -135921,6 +152940,3008 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ } /************** End of where.c ***********************************************/ +/************** Begin file window.c ******************************************/ +/* +** 2018 May 08 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ +/* #include "sqliteInt.h" */ + +#ifndef SQLITE_OMIT_WINDOWFUNC + +/* +** SELECT REWRITING +** +** Any SELECT statement that contains one or more window functions in +** either the select list or ORDER BY clause (the only two places window +** functions may be used) is transformed by function tdsqlite3WindowRewrite() +** in order to support window function processing. For example, with the +** schema: +** +** CREATE TABLE t1(a, b, c, d, e, f, g); +** +** the statement: +** +** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e; +** +** is transformed to: +** +** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM ( +** SELECT a, e, c, d, b FROM t1 ORDER BY c, d +** ) ORDER BY e; +** +** The flattening optimization is disabled when processing this transformed +** SELECT statement. This allows the implementation of the window function +** (in this case max()) to process rows sorted in order of (c, d), which +** makes things easier for obvious reasons. More generally: +** +** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to +** the sub-query. +** +** * ORDER BY, LIMIT and OFFSET remain part of the parent query. +** +** * Terminals from each of the expression trees that make up the +** select-list and ORDER BY expressions in the parent query are +** selected by the sub-query. For the purposes of the transformation, +** terminals are column references and aggregate functions. +** +** If there is more than one window function in the SELECT that uses +** the same window declaration (the OVER bit), then a single scan may +** be used to process more than one window function. For example: +** +** SELECT max(b) OVER (PARTITION BY c ORDER BY d), +** min(e) OVER (PARTITION BY c ORDER BY d) +** FROM t1; +** +** is transformed in the same way as the example above. However: +** +** SELECT max(b) OVER (PARTITION BY c ORDER BY d), +** min(e) OVER (PARTITION BY a ORDER BY b) +** FROM t1; +** +** Must be transformed to: +** +** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM ( +** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM +** SELECT a, e, c, d, b FROM t1 ORDER BY a, b +** ) ORDER BY c, d +** ) ORDER BY e; +** +** so that both min() and max() may process rows in the order defined by +** their respective window declarations. +** +** INTERFACE WITH SELECT.C +** +** When processing the rewritten SELECT statement, code in select.c calls +** tdsqlite3WhereBegin() to begin iterating through the results of the +** sub-query, which is always implemented as a co-routine. It then calls +** tdsqlite3WindowCodeStep() to process rows and finish the scan by calling +** tdsqlite3WhereEnd(). +** +** tdsqlite3WindowCodeStep() generates VM code so that, for each row returned +** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked. +** When the sub-routine is invoked: +** +** * The results of all window-functions for the row are stored +** in the associated Window.regResult registers. +** +** * The required terminal values are stored in the current row of +** temp table Window.iEphCsr. +** +** In some cases, depending on the window frame and the specific window +** functions invoked, tdsqlite3WindowCodeStep() caches each entire partition +** in a temp table before returning any rows. In other cases it does not. +** This detail is encapsulated within this file, the code generated by +** select.c is the same in either case. +** +** BUILT-IN WINDOW FUNCTIONS +** +** This implementation features the following built-in window functions: +** +** row_number() +** rank() +** dense_rank() +** percent_rank() +** cume_dist() +** ntile(N) +** lead(expr [, offset [, default]]) +** lag(expr [, offset [, default]]) +** first_value(expr) +** last_value(expr) +** nth_value(expr, N) +** +** These are the same built-in window functions supported by Postgres. +** Although the behaviour of aggregate window functions (functions that +** can be used as either aggregates or window funtions) allows them to +** be implemented using an API, built-in window functions are much more +** esoteric. Additionally, some window functions (e.g. nth_value()) +** may only be implemented by caching the entire partition in memory. +** As such, some built-in window functions use the same API as aggregate +** window functions and some are implemented directly using VDBE +** instructions. Additionally, for those functions that use the API, the +** window frame is sometimes modified before the SELECT statement is +** rewritten. For example, regardless of the specified window frame, the +** row_number() function always uses: +** +** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW +** +** See tdsqlite3WindowUpdate() for details. +** +** As well as some of the built-in window functions, aggregate window +** functions min() and max() are implemented using VDBE instructions if +** the start of the window frame is declared as anything other than +** UNBOUNDED PRECEDING. +*/ + +/* +** Implementation of built-in window function row_number(). Assumes that the +** window frame has been coerced to: +** +** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW +*/ +static void row_numberStepFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + i64 *p = (i64*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ) (*p)++; + UNUSED_PARAMETER(nArg); + UNUSED_PARAMETER(apArg); +} +static void row_numberValueFunc(tdsqlite3_context *pCtx){ + i64 *p = (i64*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + tdsqlite3_result_int64(pCtx, (p ? *p : 0)); +} + +/* +** Context object type used by rank(), dense_rank(), percent_rank() and +** cume_dist(). +*/ +struct CallCount { + i64 nValue; + i64 nStep; + i64 nTotal; +}; + +/* +** Implementation of built-in window function dense_rank(). Assumes that +** the window frame has been set to: +** +** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW +*/ +static void dense_rankStepFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct CallCount *p; + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ) p->nStep = 1; + UNUSED_PARAMETER(nArg); + UNUSED_PARAMETER(apArg); +} +static void dense_rankValueFunc(tdsqlite3_context *pCtx){ + struct CallCount *p; + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ){ + if( p->nStep ){ + p->nValue++; + p->nStep = 0; + } + tdsqlite3_result_int64(pCtx, p->nValue); + } +} + +/* +** Implementation of built-in window function nth_value(). This +** implementation is used in "slow mode" only - when the EXCLUDE clause +** is not set to the default value "NO OTHERS". +*/ +struct NthValueCtx { + i64 nStep; + tdsqlite3_value *pValue; +}; +static void nth_valueStepFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct NthValueCtx *p; + p = (struct NthValueCtx*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ){ + i64 iVal; + switch( tdsqlite3_value_numeric_type(apArg[1]) ){ + case SQLITE_INTEGER: + iVal = tdsqlite3_value_int64(apArg[1]); + break; + case SQLITE_FLOAT: { + double fVal = tdsqlite3_value_double(apArg[1]); + if( ((i64)fVal)!=fVal ) goto error_out; + iVal = (i64)fVal; + break; + } + default: + goto error_out; + } + if( iVal<=0 ) goto error_out; + + p->nStep++; + if( iVal==p->nStep ){ + p->pValue = tdsqlite3_value_dup(apArg[0]); + if( !p->pValue ){ + tdsqlite3_result_error_nomem(pCtx); + } + } + } + UNUSED_PARAMETER(nArg); + UNUSED_PARAMETER(apArg); + return; + + error_out: + tdsqlite3_result_error( + pCtx, "second argument to nth_value must be a positive integer", -1 + ); +} +static void nth_valueFinalizeFunc(tdsqlite3_context *pCtx){ + struct NthValueCtx *p; + p = (struct NthValueCtx*)tdsqlite3_aggregate_context(pCtx, 0); + if( p && p->pValue ){ + tdsqlite3_result_value(pCtx, p->pValue); + tdsqlite3_value_free(p->pValue); + p->pValue = 0; + } +} +#define nth_valueInvFunc noopStepFunc +#define nth_valueValueFunc noopValueFunc + +static void first_valueStepFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct NthValueCtx *p; + p = (struct NthValueCtx*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p && p->pValue==0 ){ + p->pValue = tdsqlite3_value_dup(apArg[0]); + if( !p->pValue ){ + tdsqlite3_result_error_nomem(pCtx); + } + } + UNUSED_PARAMETER(nArg); + UNUSED_PARAMETER(apArg); +} +static void first_valueFinalizeFunc(tdsqlite3_context *pCtx){ + struct NthValueCtx *p; + p = (struct NthValueCtx*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p && p->pValue ){ + tdsqlite3_result_value(pCtx, p->pValue); + tdsqlite3_value_free(p->pValue); + p->pValue = 0; + } +} +#define first_valueInvFunc noopStepFunc +#define first_valueValueFunc noopValueFunc + +/* +** Implementation of built-in window function rank(). Assumes that +** the window frame has been set to: +** +** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW +*/ +static void rankStepFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct CallCount *p; + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ){ + p->nStep++; + if( p->nValue==0 ){ + p->nValue = p->nStep; + } + } + UNUSED_PARAMETER(nArg); + UNUSED_PARAMETER(apArg); +} +static void rankValueFunc(tdsqlite3_context *pCtx){ + struct CallCount *p; + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ){ + tdsqlite3_result_int64(pCtx, p->nValue); + p->nValue = 0; + } +} + +/* +** Implementation of built-in window function percent_rank(). Assumes that +** the window frame has been set to: +** +** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING +*/ +static void percent_rankStepFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct CallCount *p; + UNUSED_PARAMETER(nArg); assert( nArg==0 ); + UNUSED_PARAMETER(apArg); + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ){ + p->nTotal++; + } +} +static void percent_rankInvFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct CallCount *p; + UNUSED_PARAMETER(nArg); assert( nArg==0 ); + UNUSED_PARAMETER(apArg); + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + p->nStep++; +} +static void percent_rankValueFunc(tdsqlite3_context *pCtx){ + struct CallCount *p; + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ){ + p->nValue = p->nStep; + if( p->nTotal>1 ){ + double r = (double)p->nValue / (double)(p->nTotal-1); + tdsqlite3_result_double(pCtx, r); + }else{ + tdsqlite3_result_double(pCtx, 0.0); + } + } +} +#define percent_rankFinalizeFunc percent_rankValueFunc + +/* +** Implementation of built-in window function cume_dist(). Assumes that +** the window frame has been set to: +** +** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING +*/ +static void cume_distStepFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct CallCount *p; + UNUSED_PARAMETER(nArg); assert( nArg==0 ); + UNUSED_PARAMETER(apArg); + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ){ + p->nTotal++; + } +} +static void cume_distInvFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct CallCount *p; + UNUSED_PARAMETER(nArg); assert( nArg==0 ); + UNUSED_PARAMETER(apArg); + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + p->nStep++; +} +static void cume_distValueFunc(tdsqlite3_context *pCtx){ + struct CallCount *p; + p = (struct CallCount*)tdsqlite3_aggregate_context(pCtx, 0); + if( p ){ + double r = (double)(p->nStep) / (double)(p->nTotal); + tdsqlite3_result_double(pCtx, r); + } +} +#define cume_distFinalizeFunc cume_distValueFunc + +/* +** Context object for ntile() window function. +*/ +struct NtileCtx { + i64 nTotal; /* Total rows in partition */ + i64 nParam; /* Parameter passed to ntile(N) */ + i64 iRow; /* Current row */ +}; + +/* +** Implementation of ntile(). This assumes that the window frame has +** been coerced to: +** +** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING +*/ +static void ntileStepFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct NtileCtx *p; + assert( nArg==1 ); UNUSED_PARAMETER(nArg); + p = (struct NtileCtx*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ){ + if( p->nTotal==0 ){ + p->nParam = tdsqlite3_value_int64(apArg[0]); + if( p->nParam<=0 ){ + tdsqlite3_result_error( + pCtx, "argument of ntile must be a positive integer", -1 + ); + } + } + p->nTotal++; + } +} +static void ntileInvFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct NtileCtx *p; + assert( nArg==1 ); UNUSED_PARAMETER(nArg); + UNUSED_PARAMETER(apArg); + p = (struct NtileCtx*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + p->iRow++; +} +static void ntileValueFunc(tdsqlite3_context *pCtx){ + struct NtileCtx *p; + p = (struct NtileCtx*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p && p->nParam>0 ){ + int nSize = (p->nTotal / p->nParam); + if( nSize==0 ){ + tdsqlite3_result_int64(pCtx, p->iRow+1); + }else{ + i64 nLarge = p->nTotal - p->nParam*nSize; + i64 iSmall = nLarge*(nSize+1); + i64 iRow = p->iRow; + + assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal ); + + if( iRow<iSmall ){ + tdsqlite3_result_int64(pCtx, 1 + iRow/(nSize+1)); + }else{ + tdsqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize); + } + } + } +} +#define ntileFinalizeFunc ntileValueFunc + +/* +** Context object for last_value() window function. +*/ +struct LastValueCtx { + tdsqlite3_value *pVal; + int nVal; +}; + +/* +** Implementation of last_value(). +*/ +static void last_valueStepFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct LastValueCtx *p; + UNUSED_PARAMETER(nArg); + p = (struct LastValueCtx*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p ){ + tdsqlite3_value_free(p->pVal); + p->pVal = tdsqlite3_value_dup(apArg[0]); + if( p->pVal==0 ){ + tdsqlite3_result_error_nomem(pCtx); + }else{ + p->nVal++; + } + } +} +static void last_valueInvFunc( + tdsqlite3_context *pCtx, + int nArg, + tdsqlite3_value **apArg +){ + struct LastValueCtx *p; + UNUSED_PARAMETER(nArg); + UNUSED_PARAMETER(apArg); + p = (struct LastValueCtx*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( ALWAYS(p) ){ + p->nVal--; + if( p->nVal==0 ){ + tdsqlite3_value_free(p->pVal); + p->pVal = 0; + } + } +} +static void last_valueValueFunc(tdsqlite3_context *pCtx){ + struct LastValueCtx *p; + p = (struct LastValueCtx*)tdsqlite3_aggregate_context(pCtx, 0); + if( p && p->pVal ){ + tdsqlite3_result_value(pCtx, p->pVal); + } +} +static void last_valueFinalizeFunc(tdsqlite3_context *pCtx){ + struct LastValueCtx *p; + p = (struct LastValueCtx*)tdsqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p && p->pVal ){ + tdsqlite3_result_value(pCtx, p->pVal); + tdsqlite3_value_free(p->pVal); + p->pVal = 0; + } +} + +/* +** Static names for the built-in window function names. These static +** names are used, rather than string literals, so that FuncDef objects +** can be associated with a particular window function by direct +** comparison of the zName pointer. Example: +** +** if( pFuncDef->zName==row_valueName ){ ... } +*/ +static const char row_numberName[] = "row_number"; +static const char dense_rankName[] = "dense_rank"; +static const char rankName[] = "rank"; +static const char percent_rankName[] = "percent_rank"; +static const char cume_distName[] = "cume_dist"; +static const char ntileName[] = "ntile"; +static const char last_valueName[] = "last_value"; +static const char nth_valueName[] = "nth_value"; +static const char first_valueName[] = "first_value"; +static const char leadName[] = "lead"; +static const char lagName[] = "lag"; + +/* +** No-op implementations of xStep() and xFinalize(). Used as place-holders +** for built-in window functions that never call those interfaces. +** +** The noopValueFunc() is called but is expected to do nothing. The +** noopStepFunc() is never called, and so it is marked with NO_TEST to +** let the test coverage routine know not to expect this function to be +** invoked. +*/ +static void noopStepFunc( /*NO_TEST*/ + tdsqlite3_context *p, /*NO_TEST*/ + int n, /*NO_TEST*/ + tdsqlite3_value **a /*NO_TEST*/ +){ /*NO_TEST*/ + UNUSED_PARAMETER(p); /*NO_TEST*/ + UNUSED_PARAMETER(n); /*NO_TEST*/ + UNUSED_PARAMETER(a); /*NO_TEST*/ + assert(0); /*NO_TEST*/ +} /*NO_TEST*/ +static void noopValueFunc(tdsqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ } + +/* Window functions that use all window interfaces: xStep, xFinal, +** xValue, and xInverse */ +#define WINDOWFUNCALL(name,nArg,extra) { \ + nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ + name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \ + name ## InvFunc, name ## Name, {0} \ +} + +/* Window functions that are implemented using bytecode and thus have +** no-op routines for their methods */ +#define WINDOWFUNCNOOP(name,nArg,extra) { \ + nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ + noopStepFunc, noopValueFunc, noopValueFunc, \ + noopStepFunc, name ## Name, {0} \ +} + +/* Window functions that use all window interfaces: xStep, the +** same routine for xFinalize and xValue and which never call +** xInverse. */ +#define WINDOWFUNCX(name,nArg,extra) { \ + nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ + name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \ + noopStepFunc, name ## Name, {0} \ +} + + +/* +** Register those built-in window functions that are not also aggregates. +*/ +SQLITE_PRIVATE void tdsqlite3WindowFunctions(void){ + static FuncDef aWindowFuncs[] = { + WINDOWFUNCX(row_number, 0, 0), + WINDOWFUNCX(dense_rank, 0, 0), + WINDOWFUNCX(rank, 0, 0), + WINDOWFUNCALL(percent_rank, 0, 0), + WINDOWFUNCALL(cume_dist, 0, 0), + WINDOWFUNCALL(ntile, 1, 0), + WINDOWFUNCALL(last_value, 1, 0), + WINDOWFUNCALL(nth_value, 2, 0), + WINDOWFUNCALL(first_value, 1, 0), + WINDOWFUNCNOOP(lead, 1, 0), + WINDOWFUNCNOOP(lead, 2, 0), + WINDOWFUNCNOOP(lead, 3, 0), + WINDOWFUNCNOOP(lag, 1, 0), + WINDOWFUNCNOOP(lag, 2, 0), + WINDOWFUNCNOOP(lag, 3, 0), + }; + tdsqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs)); +} + +static Window *windowFind(Parse *pParse, Window *pList, const char *zName){ + Window *p; + for(p=pList; p; p=p->pNextWin){ + if( tdsqlite3StrICmp(p->zName, zName)==0 ) break; + } + if( p==0 ){ + tdsqlite3ErrorMsg(pParse, "no such window: %s", zName); + } + return p; +} + +/* +** This function is called immediately after resolving the function name +** for a window function within a SELECT statement. Argument pList is a +** linked list of WINDOW definitions for the current SELECT statement. +** Argument pFunc is the function definition just resolved and pWin +** is the Window object representing the associated OVER clause. This +** function updates the contents of pWin as follows: +** +** * If the OVER clause refered to a named window (as in "max(x) OVER win"), +** search list pList for a matching WINDOW definition, and update pWin +** accordingly. If no such WINDOW clause can be found, leave an error +** in pParse. +** +** * If the function is a built-in window function that requires the +** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top +** of this file), pWin is updated here. +*/ +SQLITE_PRIVATE void tdsqlite3WindowUpdate( + Parse *pParse, + Window *pList, /* List of named windows for this SELECT */ + Window *pWin, /* Window frame to update */ + FuncDef *pFunc /* Window function definition */ +){ + if( pWin->zName && pWin->eFrmType==0 ){ + Window *p = windowFind(pParse, pList, pWin->zName); + if( p==0 ) return; + pWin->pPartition = tdsqlite3ExprListDup(pParse->db, p->pPartition, 0); + pWin->pOrderBy = tdsqlite3ExprListDup(pParse->db, p->pOrderBy, 0); + pWin->pStart = tdsqlite3ExprDup(pParse->db, p->pStart, 0); + pWin->pEnd = tdsqlite3ExprDup(pParse->db, p->pEnd, 0); + pWin->eStart = p->eStart; + pWin->eEnd = p->eEnd; + pWin->eFrmType = p->eFrmType; + pWin->eExclude = p->eExclude; + }else{ + tdsqlite3WindowChain(pParse, pWin, pList); + } + if( (pWin->eFrmType==TK_RANGE) + && (pWin->pStart || pWin->pEnd) + && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1) + ){ + tdsqlite3ErrorMsg(pParse, + "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression" + ); + }else + if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){ + tdsqlite3 *db = pParse->db; + if( pWin->pFilter ){ + tdsqlite3ErrorMsg(pParse, + "FILTER clause may only be used with aggregate window functions" + ); + }else{ + struct WindowUpdate { + const char *zFunc; + int eFrmType; + int eStart; + int eEnd; + } aUp[] = { + { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT }, + { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT }, + { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT }, + { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED }, + { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED }, + { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED }, + { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED }, + { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT }, + }; + int i; + for(i=0; i<ArraySize(aUp); i++){ + if( pFunc->zName==aUp[i].zFunc ){ + tdsqlite3ExprDelete(db, pWin->pStart); + tdsqlite3ExprDelete(db, pWin->pEnd); + pWin->pEnd = pWin->pStart = 0; + pWin->eFrmType = aUp[i].eFrmType; + pWin->eStart = aUp[i].eStart; + pWin->eEnd = aUp[i].eEnd; + pWin->eExclude = 0; + if( pWin->eStart==TK_FOLLOWING ){ + pWin->pStart = tdsqlite3Expr(db, TK_INTEGER, "1"); + } + break; + } + } + } + } + pWin->pFunc = pFunc; +} + +/* +** Context object passed through tdsqlite3WalkExprList() to +** selectWindowRewriteExprCb() by selectWindowRewriteEList(). +*/ +typedef struct WindowRewrite WindowRewrite; +struct WindowRewrite { + Window *pWin; + SrcList *pSrc; + ExprList *pSub; + Table *pTab; + Select *pSubSelect; /* Current sub-select, if any */ +}; + +/* +** Callback function used by selectWindowRewriteEList(). If necessary, +** this function appends to the output expression-list and updates +** expression (*ppExpr) in place. +*/ +static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){ + struct WindowRewrite *p = pWalker->u.pRewrite; + Parse *pParse = pWalker->pParse; + assert( p!=0 ); + assert( p->pWin!=0 ); + + /* If this function is being called from within a scalar sub-select + ** that used by the SELECT statement being processed, only process + ** TK_COLUMN expressions that refer to it (the outer SELECT). Do + ** not process aggregates or window functions at all, as they belong + ** to the scalar sub-select. */ + if( p->pSubSelect ){ + if( pExpr->op!=TK_COLUMN ){ + return WRC_Continue; + }else{ + int nSrc = p->pSrc->nSrc; + int i; + for(i=0; i<nSrc; i++){ + if( pExpr->iTable==p->pSrc->a[i].iCursor ) break; + } + if( i==nSrc ) return WRC_Continue; + } + } + + switch( pExpr->op ){ + + case TK_FUNCTION: + if( !ExprHasProperty(pExpr, EP_WinFunc) ){ + break; + }else{ + Window *pWin; + for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){ + if( pExpr->y.pWin==pWin ){ + assert( pWin->pOwner==pExpr ); + return WRC_Prune; + } + } + } + /* Fall through. */ + + case TK_AGG_FUNCTION: + case TK_COLUMN: { + int iCol = -1; + if( p->pSub ){ + int i; + for(i=0; i<p->pSub->nExpr; i++){ + if( 0==tdsqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){ + iCol = i; + break; + } + } + } + if( iCol<0 ){ + Expr *pDup = tdsqlite3ExprDup(pParse->db, pExpr, 0); + if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION; + p->pSub = tdsqlite3ExprListAppend(pParse, p->pSub, pDup); + } + if( p->pSub ){ + assert( ExprHasProperty(pExpr, EP_Static)==0 ); + ExprSetProperty(pExpr, EP_Static); + tdsqlite3ExprDelete(pParse->db, pExpr); + ExprClearProperty(pExpr, EP_Static); + memset(pExpr, 0, sizeof(Expr)); + + pExpr->op = TK_COLUMN; + pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol); + pExpr->iTable = p->pWin->iEphCsr; + pExpr->y.pTab = p->pTab; + } + if( pParse->db->mallocFailed ) return WRC_Abort; + break; + } + + default: /* no-op */ + break; + } + + return WRC_Continue; +} +static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){ + struct WindowRewrite *p = pWalker->u.pRewrite; + Select *pSave = p->pSubSelect; + if( pSave==pSelect ){ + return WRC_Continue; + }else{ + p->pSubSelect = pSelect; + tdsqlite3WalkSelect(pWalker, pSelect); + p->pSubSelect = pSave; + } + return WRC_Prune; +} + + +/* +** Iterate through each expression in expression-list pEList. For each: +** +** * TK_COLUMN, +** * aggregate function, or +** * window function with a Window object that is not a member of the +** Window list passed as the second argument (pWin). +** +** Append the node to output expression-list (*ppSub). And replace it +** with a TK_COLUMN that reads the (N-1)th element of table +** pWin->iEphCsr, where N is the number of elements in (*ppSub) after +** appending the new one. +*/ +static void selectWindowRewriteEList( + Parse *pParse, + Window *pWin, + SrcList *pSrc, + ExprList *pEList, /* Rewrite expressions in this list */ + Table *pTab, + ExprList **ppSub /* IN/OUT: Sub-select expression-list */ +){ + Walker sWalker; + WindowRewrite sRewrite; + + assert( pWin!=0 ); + memset(&sWalker, 0, sizeof(Walker)); + memset(&sRewrite, 0, sizeof(WindowRewrite)); + + sRewrite.pSub = *ppSub; + sRewrite.pWin = pWin; + sRewrite.pSrc = pSrc; + sRewrite.pTab = pTab; + + sWalker.pParse = pParse; + sWalker.xExprCallback = selectWindowRewriteExprCb; + sWalker.xSelectCallback = selectWindowRewriteSelectCb; + sWalker.u.pRewrite = &sRewrite; + + (void)tdsqlite3WalkExprList(&sWalker, pEList); + + *ppSub = sRewrite.pSub; +} + +/* +** Append a copy of each expression in expression-list pAppend to +** expression list pList. Return a pointer to the result list. +*/ +static ExprList *exprListAppendList( + Parse *pParse, /* Parsing context */ + ExprList *pList, /* List to which to append. Might be NULL */ + ExprList *pAppend, /* List of values to append. Might be NULL */ + int bIntToNull +){ + if( pAppend ){ + int i; + int nInit = pList ? pList->nExpr : 0; + for(i=0; i<pAppend->nExpr; i++){ + int iDummy; + Expr *pDup = tdsqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0); + assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) ); + if( bIntToNull && pDup && tdsqlite3ExprIsInteger(pDup, &iDummy) ){ + pDup->op = TK_NULL; + pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse); + pDup->u.zToken = 0; + } + pList = tdsqlite3ExprListAppend(pParse, pList, pDup); + if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags; + } + } + return pList; +} + +/* +** If the SELECT statement passed as the second argument does not invoke +** any SQL window functions, this function is a no-op. Otherwise, it +** rewrites the SELECT statement so that window function xStep functions +** are invoked in the correct order as described under "SELECT REWRITING" +** at the top of this file. +*/ +SQLITE_PRIVATE int tdsqlite3WindowRewrite(Parse *pParse, Select *p){ + int rc = SQLITE_OK; + if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){ + Vdbe *v = tdsqlite3GetVdbe(pParse); + tdsqlite3 *db = pParse->db; + Select *pSub = 0; /* The subquery */ + SrcList *pSrc = p->pSrc; + Expr *pWhere = p->pWhere; + ExprList *pGroupBy = p->pGroupBy; + Expr *pHaving = p->pHaving; + ExprList *pSort = 0; + + ExprList *pSublist = 0; /* Expression list for sub-query */ + Window *pMWin = p->pWin; /* Master window object */ + Window *pWin; /* Window object iterator */ + Table *pTab; + + pTab = tdsqlite3DbMallocZero(db, sizeof(Table)); + if( pTab==0 ){ + return tdsqlite3ErrorToParser(db, SQLITE_NOMEM); + } + + p->pSrc = 0; + p->pWhere = 0; + p->pGroupBy = 0; + p->pHaving = 0; + p->selFlags &= ~SF_Aggregate; + p->selFlags |= SF_WinRewrite; + + /* Create the ORDER BY clause for the sub-select. This is the concatenation + ** of the window PARTITION and ORDER BY clauses. Then, if this makes it + ** redundant, remove the ORDER BY from the parent SELECT. */ + pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1); + pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1); + if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){ + int nSave = pSort->nExpr; + pSort->nExpr = p->pOrderBy->nExpr; + if( tdsqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){ + tdsqlite3ExprListDelete(db, p->pOrderBy); + p->pOrderBy = 0; + } + pSort->nExpr = nSave; + } + + /* Assign a cursor number for the ephemeral table used to buffer rows. + ** The OpenEphemeral instruction is coded later, after it is known how + ** many columns the table will have. */ + pMWin->iEphCsr = pParse->nTab++; + pParse->nTab += 3; + + selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist); + selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist); + pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0); + + /* Append the PARTITION BY and ORDER BY expressions to the to the + ** sub-select expression list. They are required to figure out where + ** boundaries for partitions and sets of peer rows lie. */ + pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0); + pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0); + + /* Append the arguments passed to each window function to the + ** sub-select expression list. Also allocate two registers for each + ** window function - one for the accumulator, another for interim + ** results. */ + for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ + ExprList *pArgs = pWin->pOwner->x.pList; + if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){ + selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist); + pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); + pWin->bExprArgs = 1; + }else{ + pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); + pSublist = exprListAppendList(pParse, pSublist, pArgs, 0); + } + if( pWin->pFilter ){ + Expr *pFilter = tdsqlite3ExprDup(db, pWin->pFilter, 0); + pSublist = tdsqlite3ExprListAppend(pParse, pSublist, pFilter); + } + pWin->regAccum = ++pParse->nMem; + pWin->regResult = ++pParse->nMem; + tdsqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); + } + + /* If there is no ORDER BY or PARTITION BY clause, and the window + ** function accepts zero arguments, and there are no other columns + ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible + ** that pSublist is still NULL here. Add a constant expression here to + ** keep everything legal in this case. + */ + if( pSublist==0 ){ + pSublist = tdsqlite3ExprListAppend(pParse, 0, + tdsqlite3Expr(db, TK_INTEGER, "0") + ); + } + + pSub = tdsqlite3SelectNew( + pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0 + ); + p->pSrc = tdsqlite3SrcListAppend(pParse, 0, 0, 0); + if( p->pSrc ){ + Table *pTab2; + p->pSrc->a[0].pSelect = pSub; + tdsqlite3SrcListAssignCursors(pParse, p->pSrc); + pSub->selFlags |= SF_Expanded; + pTab2 = tdsqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE); + if( pTab2==0 ){ + /* Might actually be some other kind of error, but in that case + ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get + ** the correct error message regardless. */ + rc = SQLITE_NOMEM; + }else{ + memcpy(pTab, pTab2, sizeof(Table)); + pTab->tabFlags |= TF_Ephemeral; + p->pSrc->a[0].pTab = pTab; + pTab = pTab2; + } + }else{ + tdsqlite3SelectDelete(db, pSub); + } + if( db->mallocFailed ) rc = SQLITE_NOMEM; + tdsqlite3DbFree(db, pTab); + } + + if( rc ){ + if( pParse->nErr==0 ){ + assert( pParse->db->mallocFailed ); + tdsqlite3ErrorToParser(pParse->db, SQLITE_NOMEM); + } + tdsqlite3SelectReset(pParse, p); + } + return rc; +} + +/* +** Unlink the Window object from the Select to which it is attached, +** if it is attached. +*/ +SQLITE_PRIVATE void tdsqlite3WindowUnlinkFromSelect(Window *p){ + if( p->ppThis ){ + *p->ppThis = p->pNextWin; + if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis; + p->ppThis = 0; + } +} + +/* +** Free the Window object passed as the second argument. +*/ +SQLITE_PRIVATE void tdsqlite3WindowDelete(tdsqlite3 *db, Window *p){ + if( p ){ + tdsqlite3WindowUnlinkFromSelect(p); + tdsqlite3ExprDelete(db, p->pFilter); + tdsqlite3ExprListDelete(db, p->pPartition); + tdsqlite3ExprListDelete(db, p->pOrderBy); + tdsqlite3ExprDelete(db, p->pEnd); + tdsqlite3ExprDelete(db, p->pStart); + tdsqlite3DbFree(db, p->zName); + tdsqlite3DbFree(db, p->zBase); + tdsqlite3DbFree(db, p); + } +} + +/* +** Free the linked list of Window objects starting at the second argument. +*/ +SQLITE_PRIVATE void tdsqlite3WindowListDelete(tdsqlite3 *db, Window *p){ + while( p ){ + Window *pNext = p->pNextWin; + tdsqlite3WindowDelete(db, p); + p = pNext; + } +} + +/* +** The argument expression is an PRECEDING or FOLLOWING offset. The +** value should be a non-negative integer. If the value is not a +** constant, change it to NULL. The fact that it is then a non-negative +** integer will be caught later. But it is important not to leave +** variable values in the expression tree. +*/ +static Expr *tdsqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){ + if( 0==tdsqlite3ExprIsConstant(pExpr) ){ + if( IN_RENAME_OBJECT ) tdsqlite3RenameExprUnmap(pParse, pExpr); + tdsqlite3ExprDelete(pParse->db, pExpr); + pExpr = tdsqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0); + } + return pExpr; +} + +/* +** Allocate and return a new Window object describing a Window Definition. +*/ +SQLITE_PRIVATE Window *tdsqlite3WindowAlloc( + Parse *pParse, /* Parsing context */ + int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */ + int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */ + Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */ + int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */ + Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */ + u8 eExclude /* EXCLUDE clause */ +){ + Window *pWin = 0; + int bImplicitFrame = 0; + + /* Parser assures the following: */ + assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS ); + assert( eStart==TK_CURRENT || eStart==TK_PRECEDING + || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING ); + assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING + || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING ); + assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) ); + assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) ); + + if( eType==0 ){ + bImplicitFrame = 1; + eType = TK_RANGE; + } + + /* Additionally, the + ** starting boundary type may not occur earlier in the following list than + ** the ending boundary type: + ** + ** UNBOUNDED PRECEDING + ** <expr> PRECEDING + ** CURRENT ROW + ** <expr> FOLLOWING + ** UNBOUNDED FOLLOWING + ** + ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending + ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting + ** frame boundary. + */ + if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING) + || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT)) + ){ + tdsqlite3ErrorMsg(pParse, "unsupported frame specification"); + goto windowAllocErr; + } + + pWin = (Window*)tdsqlite3DbMallocZero(pParse->db, sizeof(Window)); + if( pWin==0 ) goto windowAllocErr; + pWin->eFrmType = eType; + pWin->eStart = eStart; + pWin->eEnd = eEnd; + if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){ + eExclude = TK_NO; + } + pWin->eExclude = eExclude; + pWin->bImplicitFrame = bImplicitFrame; + pWin->pEnd = tdsqlite3WindowOffsetExpr(pParse, pEnd); + pWin->pStart = tdsqlite3WindowOffsetExpr(pParse, pStart); + return pWin; + +windowAllocErr: + tdsqlite3ExprDelete(pParse->db, pEnd); + tdsqlite3ExprDelete(pParse->db, pStart); + return 0; +} + +/* +** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window +** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the +** equivalent nul-terminated string. +*/ +SQLITE_PRIVATE Window *tdsqlite3WindowAssemble( + Parse *pParse, + Window *pWin, + ExprList *pPartition, + ExprList *pOrderBy, + Token *pBase +){ + if( pWin ){ + pWin->pPartition = pPartition; + pWin->pOrderBy = pOrderBy; + if( pBase ){ + pWin->zBase = tdsqlite3DbStrNDup(pParse->db, pBase->z, pBase->n); + } + }else{ + tdsqlite3ExprListDelete(pParse->db, pPartition); + tdsqlite3ExprListDelete(pParse->db, pOrderBy); + } + return pWin; +} + +/* +** Window *pWin has just been created from a WINDOW clause. Tokne pBase +** is the base window. Earlier windows from the same WINDOW clause are +** stored in the linked list starting at pWin->pNextWin. This function +** either updates *pWin according to the base specification, or else +** leaves an error in pParse. +*/ +SQLITE_PRIVATE void tdsqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){ + if( pWin->zBase ){ + tdsqlite3 *db = pParse->db; + Window *pExist = windowFind(pParse, pList, pWin->zBase); + if( pExist ){ + const char *zErr = 0; + /* Check for errors */ + if( pWin->pPartition ){ + zErr = "PARTITION clause"; + }else if( pExist->pOrderBy && pWin->pOrderBy ){ + zErr = "ORDER BY clause"; + }else if( pExist->bImplicitFrame==0 ){ + zErr = "frame specification"; + } + if( zErr ){ + tdsqlite3ErrorMsg(pParse, + "cannot override %s of window: %s", zErr, pWin->zBase + ); + }else{ + pWin->pPartition = tdsqlite3ExprListDup(db, pExist->pPartition, 0); + if( pExist->pOrderBy ){ + assert( pWin->pOrderBy==0 ); + pWin->pOrderBy = tdsqlite3ExprListDup(db, pExist->pOrderBy, 0); + } + tdsqlite3DbFree(db, pWin->zBase); + pWin->zBase = 0; + } + } + } +} + +/* +** Attach window object pWin to expression p. +*/ +SQLITE_PRIVATE void tdsqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){ + if( p ){ + assert( p->op==TK_FUNCTION ); + assert( pWin ); + p->y.pWin = pWin; + ExprSetProperty(p, EP_WinFunc); + pWin->pOwner = p; + if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){ + tdsqlite3ErrorMsg(pParse, + "DISTINCT is not supported for window functions" + ); + } + }else{ + tdsqlite3WindowDelete(pParse->db, pWin); + } +} + +/* +** Possibly link window pWin into the list at pSel->pWin (window functions +** to be processed as part of SELECT statement pSel). The window is linked +** in if either (a) there are no other windows already linked to this +** SELECT, or (b) the windows already linked use a compatible window frame. +*/ +SQLITE_PRIVATE void tdsqlite3WindowLink(Select *pSel, Window *pWin){ + if( pSel!=0 + && (0==pSel->pWin || 0==tdsqlite3WindowCompare(0, pSel->pWin, pWin, 0)) + ){ + pWin->pNextWin = pSel->pWin; + if( pSel->pWin ){ + pSel->pWin->ppThis = &pWin->pNextWin; + } + pSel->pWin = pWin; + pWin->ppThis = &pSel->pWin; + } +} + +/* +** Return 0 if the two window objects are identical, 1 if they are +** different, or 2 if it cannot be determined if the objects are identical +** or not. Identical window objects can be processed in a single scan. +*/ +SQLITE_PRIVATE int tdsqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){ + int res; + if( NEVER(p1==0) || NEVER(p2==0) ) return 1; + if( p1->eFrmType!=p2->eFrmType ) return 1; + if( p1->eStart!=p2->eStart ) return 1; + if( p1->eEnd!=p2->eEnd ) return 1; + if( p1->eExclude!=p2->eExclude ) return 1; + if( tdsqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1; + if( tdsqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1; + if( (res = tdsqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){ + return res; + } + if( (res = tdsqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){ + return res; + } + if( bFilter ){ + if( (res = tdsqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){ + return res; + } + } + return 0; +} + + +/* +** This is called by code in select.c before it calls tdsqlite3WhereBegin() +** to begin iterating through the sub-query results. It is used to allocate +** and initialize registers and cursors used by tdsqlite3WindowCodeStep(). +*/ +SQLITE_PRIVATE void tdsqlite3WindowCodeInit(Parse *pParse, Select *pSelect){ + int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr; + Window *pMWin = pSelect->pWin; + Window *pWin; + Vdbe *v = tdsqlite3GetVdbe(pParse); + + tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr); + tdsqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr); + tdsqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr); + tdsqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr); + + /* Allocate registers to use for PARTITION BY values, if any. Initialize + ** said registers to NULL. */ + if( pMWin->pPartition ){ + int nExpr = pMWin->pPartition->nExpr; + pMWin->regPart = pParse->nMem+1; + pParse->nMem += nExpr; + tdsqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1); + } + + pMWin->regOne = ++pParse->nMem; + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne); + + if( pMWin->eExclude ){ + pMWin->regStartRowid = ++pParse->nMem; + pMWin->regEndRowid = ++pParse->nMem; + pMWin->csrApp = pParse->nTab++; + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid); + tdsqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr); + return; + } + + for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ + FuncDef *p = pWin->pFunc; + if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){ + /* The inline versions of min() and max() require a single ephemeral + ** table and 3 registers. The registers are used as follows: + ** + ** regApp+0: slot to copy min()/max() argument to for MakeRecord + ** regApp+1: integer value used to ensure keys are unique + ** regApp+2: output of MakeRecord + */ + ExprList *pList = pWin->pOwner->x.pList; + KeyInfo *pKeyInfo = tdsqlite3KeyInfoFromExprList(pParse, pList, 0, 0); + pWin->csrApp = pParse->nTab++; + pWin->regApp = pParse->nMem+1; + pParse->nMem += 3; + if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){ + assert( pKeyInfo->aSortFlags[0]==0 ); + pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC; + } + tdsqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2); + tdsqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); + } + else if( p->zName==nth_valueName || p->zName==first_valueName ){ + /* Allocate two registers at pWin->regApp. These will be used to + ** store the start and end index of the current frame. */ + pWin->regApp = pParse->nMem+1; + pWin->csrApp = pParse->nTab++; + pParse->nMem += 2; + tdsqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); + } + else if( p->zName==leadName || p->zName==lagName ){ + pWin->csrApp = pParse->nTab++; + tdsqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); + } + } +} + +#define WINDOW_STARTING_INT 0 +#define WINDOW_ENDING_INT 1 +#define WINDOW_NTH_VALUE_INT 2 +#define WINDOW_STARTING_NUM 3 +#define WINDOW_ENDING_NUM 4 + +/* +** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the +** value of the second argument to nth_value() (eCond==2) has just been +** evaluated and the result left in register reg. This function generates VM +** code to check that the value is a non-negative integer and throws an +** exception if it is not. +*/ +static void windowCheckValue(Parse *pParse, int reg, int eCond){ + static const char *azErr[] = { + "frame starting offset must be a non-negative integer", + "frame ending offset must be a non-negative integer", + "second argument to nth_value must be a positive integer", + "frame starting offset must be a non-negative number", + "frame ending offset must be a non-negative number", + }; + static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge }; + Vdbe *v = tdsqlite3GetVdbe(pParse); + int regZero = tdsqlite3GetTempReg(pParse); + assert( eCond>=0 && eCond<ArraySize(azErr) ); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regZero); + if( eCond>=WINDOW_STARTING_NUM ){ + int regString = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC); + tdsqlite3VdbeAddOp3(v, OP_Ge, regString, tdsqlite3VdbeCurrentAddr(v)+2, reg); + tdsqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL); + VdbeCoverage(v); + assert( eCond==3 || eCond==4 ); + VdbeCoverageIf(v, eCond==3); + VdbeCoverageIf(v, eCond==4); + }else{ + tdsqlite3VdbeAddOp2(v, OP_MustBeInt, reg, tdsqlite3VdbeCurrentAddr(v)+2); + VdbeCoverage(v); + assert( eCond==0 || eCond==1 || eCond==2 ); + VdbeCoverageIf(v, eCond==0); + VdbeCoverageIf(v, eCond==1); + VdbeCoverageIf(v, eCond==2); + } + tdsqlite3VdbeAddOp3(v, aOp[eCond], regZero, tdsqlite3VdbeCurrentAddr(v)+2, reg); + VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */ + VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */ + VdbeCoverageNeverNullIf(v, eCond==2); + VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */ + VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */ + tdsqlite3MayAbort(pParse); + tdsqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort); + tdsqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC); + tdsqlite3ReleaseTempReg(pParse, regZero); +} + +/* +** Return the number of arguments passed to the window-function associated +** with the object passed as the only argument to this function. +*/ +static int windowArgCount(Window *pWin){ + ExprList *pList = pWin->pOwner->x.pList; + return (pList ? pList->nExpr : 0); +} + +typedef struct WindowCodeArg WindowCodeArg; +typedef struct WindowCsrAndReg WindowCsrAndReg; + +/* +** See comments above struct WindowCodeArg. +*/ +struct WindowCsrAndReg { + int csr; /* Cursor number */ + int reg; /* First in array of peer values */ +}; + +/* +** A single instance of this structure is allocated on the stack by +** tdsqlite3WindowCodeStep() and a pointer to it passed to the various helper +** routines. This is to reduce the number of arguments required by each +** helper function. +** +** regArg: +** Each window function requires an accumulator register (just as an +** ordinary aggregate function does). This variable is set to the first +** in an array of accumulator registers - one for each window function +** in the WindowCodeArg.pMWin list. +** +** eDelete: +** The window functions implementation sometimes caches the input rows +** that it processes in a temporary table. If it is not zero, this +** variable indicates when rows may be removed from the temp table (in +** order to reduce memory requirements - it would always be safe just +** to leave them there). Possible values for eDelete are: +** +** WINDOW_RETURN_ROW: +** An input row can be discarded after it is returned to the caller. +** +** WINDOW_AGGINVERSE: +** An input row can be discarded after the window functions xInverse() +** callbacks have been invoked in it. +** +** WINDOW_AGGSTEP: +** An input row can be discarded after the window functions xStep() +** callbacks have been invoked in it. +** +** start,current,end +** Consider a window-frame similar to the following: +** +** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING) +** +** The windows functions implmentation caches the input rows in a temp +** table, sorted by "a, b" (it actually populates the cache lazily, and +** aggressively removes rows once they are no longer required, but that's +** a mere detail). It keeps three cursors open on the temp table. One +** (current) that points to the next row to return to the query engine +** once its window function values have been calculated. Another (end) +** points to the next row to call the xStep() method of each window function +** on (so that it is 2 groups ahead of current). And a third (start) that +** points to the next row to call the xInverse() method of each window +** function on. +** +** Each cursor (start, current and end) consists of a VDBE cursor +** (WindowCsrAndReg.csr) and an array of registers (starting at +** WindowCodeArg.reg) that always contains a copy of the peer values +** read from the corresponding cursor. +** +** Depending on the window-frame in question, all three cursors may not +** be required. In this case both WindowCodeArg.csr and reg are set to +** 0. +*/ +struct WindowCodeArg { + Parse *pParse; /* Parse context */ + Window *pMWin; /* First in list of functions being processed */ + Vdbe *pVdbe; /* VDBE object */ + int addrGosub; /* OP_Gosub to this address to return one row */ + int regGosub; /* Register used with OP_Gosub(addrGosub) */ + int regArg; /* First in array of accumulator registers */ + int eDelete; /* See above */ + + WindowCsrAndReg start; + WindowCsrAndReg current; + WindowCsrAndReg end; +}; + +/* +** Generate VM code to read the window frames peer values from cursor csr into +** an array of registers starting at reg. +*/ +static void windowReadPeerValues( + WindowCodeArg *p, + int csr, + int reg +){ + Window *pMWin = p->pMWin; + ExprList *pOrderBy = pMWin->pOrderBy; + if( pOrderBy ){ + Vdbe *v = tdsqlite3GetVdbe(p->pParse); + ExprList *pPart = pMWin->pPartition; + int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0); + int i; + for(i=0; i<pOrderBy->nExpr; i++){ + tdsqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i); + } + } +} + +/* +** Generate VM code to invoke either xStep() (if bInverse is 0) or +** xInverse (if bInverse is non-zero) for each window function in the +** linked list starting at pMWin. Or, for built-in window functions +** that do not use the standard function API, generate the required +** inline VM code. +** +** If argument csr is greater than or equal to 0, then argument reg is +** the first register in an array of registers guaranteed to be large +** enough to hold the array of arguments for each function. In this case +** the arguments are extracted from the current row of csr into the +** array of registers before invoking OP_AggStep or OP_AggInverse +** +** Or, if csr is less than zero, then the array of registers at reg is +** already populated with all columns from the current row of the sub-query. +** +** If argument regPartSize is non-zero, then it is a register containing the +** number of rows in the current partition. +*/ +static void windowAggStep( + WindowCodeArg *p, + Window *pMWin, /* Linked list of window functions */ + int csr, /* Read arguments from this cursor */ + int bInverse, /* True to invoke xInverse instead of xStep */ + int reg /* Array of registers */ +){ + Parse *pParse = p->pParse; + Vdbe *v = tdsqlite3GetVdbe(pParse); + Window *pWin; + for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ + FuncDef *pFunc = pWin->pFunc; + int regArg; + int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin); + int i; + + assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED ); + + /* All OVER clauses in the same window function aggregate step must + ** be the same. */ + assert( pWin==pMWin || tdsqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 ); + + for(i=0; i<nArg; i++){ + if( i!=1 || pFunc->zName!=nth_valueName ){ + tdsqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i); + }else{ + tdsqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i); + } + } + regArg = reg; + + if( pMWin->regStartRowid==0 + && (pFunc->funcFlags & SQLITE_FUNC_MINMAX) + && (pWin->eStart!=TK_UNBOUNDED) + ){ + int addrIsNull = tdsqlite3VdbeAddOp1(v, OP_IsNull, regArg); + VdbeCoverage(v); + if( bInverse==0 ){ + tdsqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1); + tdsqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp); + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2); + tdsqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2); + }else{ + tdsqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1); + VdbeCoverageNeverTaken(v); + tdsqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp); + tdsqlite3VdbeJumpHere(v, tdsqlite3VdbeCurrentAddr(v)-2); + } + tdsqlite3VdbeJumpHere(v, addrIsNull); + }else if( pWin->regApp ){ + assert( pFunc->zName==nth_valueName + || pFunc->zName==first_valueName + ); + assert( bInverse==0 || bInverse==1 ); + tdsqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1); + }else if( pFunc->xSFunc!=noopStepFunc ){ + int addrIf = 0; + if( pWin->pFilter ){ + int regTmp; + assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr ); + assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 ); + regTmp = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp); + addrIf = tdsqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1); + VdbeCoverage(v); + tdsqlite3ReleaseTempReg(pParse, regTmp); + } + + if( pWin->bExprArgs ){ + int iStart = tdsqlite3VdbeCurrentAddr(v); + VdbeOp *pOp, *pEnd; + + nArg = pWin->pOwner->x.pList->nExpr; + regArg = tdsqlite3GetTempRange(pParse, nArg); + tdsqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0); + + pEnd = tdsqlite3VdbeGetOp(v, -1); + for(pOp=tdsqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){ + if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){ + pOp->p1 = csr; + } + } + } + if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ + CollSeq *pColl; + assert( nArg>0 ); + pColl = tdsqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr); + tdsqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ); + } + tdsqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep, + bInverse, regArg, pWin->regAccum); + tdsqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF); + tdsqlite3VdbeChangeP5(v, (u8)nArg); + if( pWin->bExprArgs ){ + tdsqlite3ReleaseTempRange(pParse, regArg, nArg); + } + if( addrIf ) tdsqlite3VdbeJumpHere(v, addrIf); + } + } +} + +/* +** Values that may be passed as the second argument to windowCodeOp(). +*/ +#define WINDOW_RETURN_ROW 1 +#define WINDOW_AGGINVERSE 2 +#define WINDOW_AGGSTEP 3 + +/* +** Generate VM code to invoke either xValue() (bFin==0) or xFinalize() +** (bFin==1) for each window function in the linked list starting at +** pMWin. Or, for built-in window-functions that do not use the standard +** API, generate the equivalent VM code. +*/ +static void windowAggFinal(WindowCodeArg *p, int bFin){ + Parse *pParse = p->pParse; + Window *pMWin = p->pMWin; + Vdbe *v = tdsqlite3GetVdbe(pParse); + Window *pWin; + + for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ + if( pMWin->regStartRowid==0 + && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX) + && (pWin->eStart!=TK_UNBOUNDED) + ){ + tdsqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); + tdsqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp); + VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult); + tdsqlite3VdbeJumpHere(v, tdsqlite3VdbeCurrentAddr(v)-2); + }else if( pWin->regApp ){ + assert( pMWin->regStartRowid==0 ); + }else{ + int nArg = windowArgCount(pWin); + if( bFin ){ + tdsqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg); + tdsqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF); + tdsqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); + }else{ + tdsqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult); + tdsqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF); + } + } + } +} + +/* +** Generate code to calculate the current values of all window functions in the +** p->pMWin list by doing a full scan of the current window frame. Store the +** results in the Window.regResult registers, ready to return the upper +** layer. +*/ +static void windowFullScan(WindowCodeArg *p){ + Window *pWin; + Parse *pParse = p->pParse; + Window *pMWin = p->pMWin; + Vdbe *v = p->pVdbe; + + int regCRowid = 0; /* Current rowid value */ + int regCPeer = 0; /* Current peer values */ + int regRowid = 0; /* AggStep rowid value */ + int regPeer = 0; /* AggStep peer values */ + + int nPeer; + int lblNext; + int lblBrk; + int addrNext; + int csr; + + VdbeModuleComment((v, "windowFullScan begin")); + + assert( pMWin!=0 ); + csr = pMWin->csrApp; + nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0); + + lblNext = tdsqlite3VdbeMakeLabel(pParse); + lblBrk = tdsqlite3VdbeMakeLabel(pParse); + + regCRowid = tdsqlite3GetTempReg(pParse); + regRowid = tdsqlite3GetTempReg(pParse); + if( nPeer ){ + regCPeer = tdsqlite3GetTempRange(pParse, nPeer); + regPeer = tdsqlite3GetTempRange(pParse, nPeer); + } + + tdsqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid); + windowReadPeerValues(p, pMWin->iEphCsr, regCPeer); + + for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ + tdsqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); + } + + tdsqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid); + VdbeCoverage(v); + addrNext = tdsqlite3VdbeCurrentAddr(v); + tdsqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid); + tdsqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid); + VdbeCoverageNeverNull(v); + + if( pMWin->eExclude==TK_CURRENT ){ + tdsqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid); + VdbeCoverageNeverNull(v); + }else if( pMWin->eExclude!=TK_NO ){ + int addr; + int addrEq = 0; + KeyInfo *pKeyInfo = 0; + + if( pMWin->pOrderBy ){ + pKeyInfo = tdsqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0); + } + if( pMWin->eExclude==TK_TIES ){ + addrEq = tdsqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid); + VdbeCoverageNeverNull(v); + } + if( pKeyInfo ){ + windowReadPeerValues(p, csr, regPeer); + tdsqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer); + tdsqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); + addr = tdsqlite3VdbeCurrentAddr(v)+1; + tdsqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr); + VdbeCoverageEqNe(v); + }else{ + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext); + } + if( addrEq ) tdsqlite3VdbeJumpHere(v, addrEq); + } + + windowAggStep(p, pMWin, csr, 0, p->regArg); + + tdsqlite3VdbeResolveLabel(v, lblNext); + tdsqlite3VdbeAddOp2(v, OP_Next, csr, addrNext); + VdbeCoverage(v); + tdsqlite3VdbeJumpHere(v, addrNext-1); + tdsqlite3VdbeJumpHere(v, addrNext+1); + tdsqlite3ReleaseTempReg(pParse, regRowid); + tdsqlite3ReleaseTempReg(pParse, regCRowid); + if( nPeer ){ + tdsqlite3ReleaseTempRange(pParse, regPeer, nPeer); + tdsqlite3ReleaseTempRange(pParse, regCPeer, nPeer); + } + + windowAggFinal(p, 1); + VdbeModuleComment((v, "windowFullScan end")); +} + +/* +** Invoke the sub-routine at regGosub (generated by code in select.c) to +** return the current row of Window.iEphCsr. If all window functions are +** aggregate window functions that use the standard API, a single +** OP_Gosub instruction is all that this routine generates. Extra VM code +** for per-row processing is only generated for the following built-in window +** functions: +** +** nth_value() +** first_value() +** lag() +** lead() +*/ +static void windowReturnOneRow(WindowCodeArg *p){ + Window *pMWin = p->pMWin; + Vdbe *v = p->pVdbe; + + if( pMWin->regStartRowid ){ + windowFullScan(p); + }else{ + Parse *pParse = p->pParse; + Window *pWin; + + for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ + FuncDef *pFunc = pWin->pFunc; + if( pFunc->zName==nth_valueName + || pFunc->zName==first_valueName + ){ + int csr = pWin->csrApp; + int lbl = tdsqlite3VdbeMakeLabel(pParse); + int tmpReg = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); + + if( pFunc->zName==nth_valueName ){ + tdsqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg); + windowCheckValue(pParse, tmpReg, 2); + }else{ + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg); + } + tdsqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg); + tdsqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg); + VdbeCoverageNeverNull(v); + tdsqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg); + VdbeCoverageNeverTaken(v); + tdsqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); + tdsqlite3VdbeResolveLabel(v, lbl); + tdsqlite3ReleaseTempReg(pParse, tmpReg); + } + else if( pFunc->zName==leadName || pFunc->zName==lagName ){ + int nArg = pWin->pOwner->x.pList->nExpr; + int csr = pWin->csrApp; + int lbl = tdsqlite3VdbeMakeLabel(pParse); + int tmpReg = tdsqlite3GetTempReg(pParse); + int iEph = pMWin->iEphCsr; + + if( nArg<3 ){ + tdsqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); + }else{ + tdsqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult); + } + tdsqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg); + if( nArg<2 ){ + int val = (pFunc->zName==leadName ? 1 : -1); + tdsqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val); + }else{ + int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract); + int tmpReg2 = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2); + tdsqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg); + tdsqlite3ReleaseTempReg(pParse, tmpReg2); + } + + tdsqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg); + VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); + tdsqlite3VdbeResolveLabel(v, lbl); + tdsqlite3ReleaseTempReg(pParse, tmpReg); + } + } + } + tdsqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub); +} + +/* +** Generate code to set the accumulator register for each window function +** in the linked list passed as the second argument to NULL. And perform +** any equivalent initialization required by any built-in window functions +** in the list. +*/ +static int windowInitAccum(Parse *pParse, Window *pMWin){ + Vdbe *v = tdsqlite3GetVdbe(pParse); + int regArg; + int nArg = 0; + Window *pWin; + for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ + FuncDef *pFunc = pWin->pFunc; + tdsqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); + nArg = MAX(nArg, windowArgCount(pWin)); + if( pMWin->regStartRowid==0 ){ + if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){ + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); + } + + if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){ + assert( pWin->eStart!=TK_UNBOUNDED ); + tdsqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); + } + } + } + regArg = pParse->nMem+1; + pParse->nMem += nArg; + return regArg; +} + +/* +** Return true if the current frame should be cached in the ephemeral table, +** even if there are no xInverse() calls required. +*/ +static int windowCacheFrame(Window *pMWin){ + Window *pWin; + if( pMWin->regStartRowid ) return 1; + for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ + FuncDef *pFunc = pWin->pFunc; + if( (pFunc->zName==nth_valueName) + || (pFunc->zName==first_valueName) + || (pFunc->zName==leadName) + || (pFunc->zName==lagName) + ){ + return 1; + } + } + return 0; +} + +/* +** regOld and regNew are each the first register in an array of size +** pOrderBy->nExpr. This function generates code to compare the two +** arrays of registers using the collation sequences and other comparison +** parameters specified by pOrderBy. +** +** If the two arrays are not equal, the contents of regNew is copied to +** regOld and control falls through. Otherwise, if the contents of the arrays +** are equal, an OP_Goto is executed. The address of the OP_Goto is returned. +*/ +static void windowIfNewPeer( + Parse *pParse, + ExprList *pOrderBy, + int regNew, /* First in array of new values */ + int regOld, /* First in array of old values */ + int addr /* Jump here */ +){ + Vdbe *v = tdsqlite3GetVdbe(pParse); + if( pOrderBy ){ + int nVal = pOrderBy->nExpr; + KeyInfo *pKeyInfo = tdsqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0); + tdsqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal); + tdsqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); + tdsqlite3VdbeAddOp3(v, OP_Jump, + tdsqlite3VdbeCurrentAddr(v)+1, addr, tdsqlite3VdbeCurrentAddr(v)+1 + ); + VdbeCoverageEqNe(v); + tdsqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1); + }else{ + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, addr); + } +} + +/* +** This function is called as part of generating VM programs for RANGE +** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for +** the ORDER BY term in the window, and that argument op is OP_Ge, it generates +** code equivalent to: +** +** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl; +** +** The value of parameter op may also be OP_Gt or OP_Le. In these cases the +** operator in the above pseudo-code is replaced with ">" or "<=", respectively. +** +** If the sort-order for the ORDER BY term in the window is DESC, then the +** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is +** subtracted. And the comparison operator is inverted to - ">=" becomes "<=", +** ">" becomes "<", and so on. So, with DESC sort order, if the argument op +** is OP_Ge, the generated code is equivalent to: +** +** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl; +** +** A special type of arithmetic is used such that if csr1.peerVal is not +** a numeric type (real or integer), then the result of the addition addition +** or subtraction is a a copy of csr1.peerVal. +*/ +static void windowCodeRangeTest( + WindowCodeArg *p, + int op, /* OP_Ge, OP_Gt, or OP_Le */ + int csr1, /* Cursor number for cursor 1 */ + int regVal, /* Register containing non-negative number */ + int csr2, /* Cursor number for cursor 2 */ + int lbl /* Jump destination if condition is true */ +){ + Parse *pParse = p->pParse; + Vdbe *v = tdsqlite3GetVdbe(pParse); + ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */ + int reg1 = tdsqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */ + int reg2 = tdsqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */ + int regString = ++pParse->nMem; /* Reg. for constant value '' */ + int arith = OP_Add; /* OP_Add or OP_Subtract */ + int addrGe; /* Jump destination */ + + assert( op==OP_Ge || op==OP_Gt || op==OP_Le ); + assert( pOrderBy && pOrderBy->nExpr==1 ); + if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){ + switch( op ){ + case OP_Ge: op = OP_Le; break; + case OP_Gt: op = OP_Lt; break; + default: assert( op==OP_Le ); op = OP_Ge; break; + } + arith = OP_Subtract; + } + + /* Read the peer-value from each cursor into a register */ + windowReadPeerValues(p, csr1, reg1); + windowReadPeerValues(p, csr2, reg2); + + VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl", + reg1, (arith==OP_Add ? "+" : "-"), regVal, + ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2 + )); + + /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1). + ** This block adds (or subtracts for DESC) the numeric value in regVal + ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob), + ** then leave reg1 as it is. In pseudo-code, this is implemented as: + ** + ** if( reg1>='' ) goto addrGe; + ** reg1 = reg1 +/- regVal + ** addrGe: + ** + ** Since all strings and blobs are greater-than-or-equal-to an empty string, + ** the add/subtract is skipped for these, as required. If reg1 is a NULL, + ** then the arithmetic is performed, but since adding or subtracting from + ** NULL is always NULL anyway, this case is handled as required too. */ + tdsqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC); + addrGe = tdsqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1); + VdbeCoverage(v); + tdsqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1); + tdsqlite3VdbeJumpHere(v, addrGe); + + /* If the BIGNULL flag is set for the ORDER BY, then it is required to + ** consider NULL values to be larger than all other values, instead of + ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this + ** (and adding that capability causes a performance regression), so + ** instead if the BIGNULL flag is set then cases where either reg1 or + ** reg2 are NULL are handled separately in the following block. The code + ** generated is equivalent to: + ** + ** if( reg1 IS NULL ){ + ** if( op==OP_Ge ) goto lbl; + ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl; + ** if( op==OP_Le && reg2 IS NULL ) goto lbl; + ** }else if( reg2 IS NULL ){ + ** if( op==OP_Le ) goto lbl; + ** } + ** + ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is + ** not taken, control jumps over the comparison operator coded below this + ** block. */ + if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){ + /* This block runs if reg1 contains a NULL. */ + int addr = tdsqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v); + switch( op ){ + case OP_Ge: + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, lbl); + break; + case OP_Gt: + tdsqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl); + VdbeCoverage(v); + break; + case OP_Le: + tdsqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); + VdbeCoverage(v); + break; + default: assert( op==OP_Lt ); /* no-op */ break; + } + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, tdsqlite3VdbeCurrentAddr(v)+3); + + /* This block runs if reg1 is not NULL, but reg2 is. */ + tdsqlite3VdbeJumpHere(v, addr); + tdsqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v); + if( op==OP_Gt || op==OP_Ge ){ + tdsqlite3VdbeChangeP2(v, -1, tdsqlite3VdbeCurrentAddr(v)+1); + } + } + + /* Compare registers reg2 and reg1, taking the jump if required. Note that + ** control skips over this test if the BIGNULL flag is set and either + ** reg1 or reg2 contain a NULL value. */ + tdsqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v); + tdsqlite3VdbeChangeP5(v, SQLITE_NULLEQ); + + assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le ); + testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge); + testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt); + testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le); + testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt); + tdsqlite3ReleaseTempReg(pParse, reg1); + tdsqlite3ReleaseTempReg(pParse, reg2); + + VdbeModuleComment((v, "CodeRangeTest: end")); +} + +/* +** Helper function for tdsqlite3WindowCodeStep(). Each call to this function +** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE +** operation. Refer to the header comment for tdsqlite3WindowCodeStep() for +** details. +*/ +static int windowCodeOp( + WindowCodeArg *p, /* Context object */ + int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */ + int regCountdown, /* Register for OP_IfPos countdown */ + int jumpOnEof /* Jump here if stepped cursor reaches EOF */ +){ + int csr, reg; + Parse *pParse = p->pParse; + Window *pMWin = p->pMWin; + int ret = 0; + Vdbe *v = p->pVdbe; + int addrContinue = 0; + int bPeer = (pMWin->eFrmType!=TK_ROWS); + + int lblDone = tdsqlite3VdbeMakeLabel(pParse); + int addrNextRange = 0; + + /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame + ** starts with UNBOUNDED PRECEDING. */ + if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){ + assert( regCountdown==0 && jumpOnEof==0 ); + return 0; + } + + if( regCountdown>0 ){ + if( pMWin->eFrmType==TK_RANGE ){ + addrNextRange = tdsqlite3VdbeCurrentAddr(v); + assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP ); + if( op==WINDOW_AGGINVERSE ){ + if( pMWin->eStart==TK_FOLLOWING ){ + windowCodeRangeTest( + p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone + ); + }else{ + windowCodeRangeTest( + p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone + ); + } + }else{ + windowCodeRangeTest( + p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone + ); + } + }else{ + tdsqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1); + VdbeCoverage(v); + } + } + + if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){ + windowAggFinal(p, 0); + } + addrContinue = tdsqlite3VdbeCurrentAddr(v); + + /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or + ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the + ** start cursor does not advance past the end cursor within the + ** temporary table. It otherwise might, if (a>b). */ + if( pMWin->eStart==pMWin->eEnd && regCountdown + && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE + ){ + int regRowid1 = tdsqlite3GetTempReg(pParse); + int regRowid2 = tdsqlite3GetTempReg(pParse); + tdsqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1); + tdsqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2); + tdsqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1); + VdbeCoverage(v); + tdsqlite3ReleaseTempReg(pParse, regRowid1); + tdsqlite3ReleaseTempReg(pParse, regRowid2); + assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ); + } + + switch( op ){ + case WINDOW_RETURN_ROW: + csr = p->current.csr; + reg = p->current.reg; + windowReturnOneRow(p); + break; + + case WINDOW_AGGINVERSE: + csr = p->start.csr; + reg = p->start.reg; + if( pMWin->regStartRowid ){ + assert( pMWin->regEndRowid ); + tdsqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1); + }else{ + windowAggStep(p, pMWin, csr, 1, p->regArg); + } + break; + + default: + assert( op==WINDOW_AGGSTEP ); + csr = p->end.csr; + reg = p->end.reg; + if( pMWin->regStartRowid ){ + assert( pMWin->regEndRowid ); + tdsqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1); + }else{ + windowAggStep(p, pMWin, csr, 0, p->regArg); + } + break; + } + + if( op==p->eDelete ){ + tdsqlite3VdbeAddOp1(v, OP_Delete, csr); + tdsqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); + } + + if( jumpOnEof ){ + tdsqlite3VdbeAddOp2(v, OP_Next, csr, tdsqlite3VdbeCurrentAddr(v)+2); + VdbeCoverage(v); + ret = tdsqlite3VdbeAddOp0(v, OP_Goto); + }else{ + tdsqlite3VdbeAddOp2(v, OP_Next, csr, tdsqlite3VdbeCurrentAddr(v)+1+bPeer); + VdbeCoverage(v); + if( bPeer ){ + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone); + } + } + + if( bPeer ){ + int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0); + int regTmp = (nReg ? tdsqlite3GetTempRange(pParse, nReg) : 0); + windowReadPeerValues(p, csr, regTmp); + windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue); + tdsqlite3ReleaseTempRange(pParse, regTmp, nReg); + } + + if( addrNextRange ){ + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange); + } + tdsqlite3VdbeResolveLabel(v, lblDone); + return ret; +} + + +/* +** Allocate and return a duplicate of the Window object indicated by the +** third argument. Set the Window.pOwner field of the new object to +** pOwner. +*/ +SQLITE_PRIVATE Window *tdsqlite3WindowDup(tdsqlite3 *db, Expr *pOwner, Window *p){ + Window *pNew = 0; + if( ALWAYS(p) ){ + pNew = tdsqlite3DbMallocZero(db, sizeof(Window)); + if( pNew ){ + pNew->zName = tdsqlite3DbStrDup(db, p->zName); + pNew->zBase = tdsqlite3DbStrDup(db, p->zBase); + pNew->pFilter = tdsqlite3ExprDup(db, p->pFilter, 0); + pNew->pFunc = p->pFunc; + pNew->pPartition = tdsqlite3ExprListDup(db, p->pPartition, 0); + pNew->pOrderBy = tdsqlite3ExprListDup(db, p->pOrderBy, 0); + pNew->eFrmType = p->eFrmType; + pNew->eEnd = p->eEnd; + pNew->eStart = p->eStart; + pNew->eExclude = p->eExclude; + pNew->regResult = p->regResult; + pNew->pStart = tdsqlite3ExprDup(db, p->pStart, 0); + pNew->pEnd = tdsqlite3ExprDup(db, p->pEnd, 0); + pNew->pOwner = pOwner; + pNew->bImplicitFrame = p->bImplicitFrame; + } + } + return pNew; +} + +/* +** Return a copy of the linked list of Window objects passed as the +** second argument. +*/ +SQLITE_PRIVATE Window *tdsqlite3WindowListDup(tdsqlite3 *db, Window *p){ + Window *pWin; + Window *pRet = 0; + Window **pp = &pRet; + + for(pWin=p; pWin; pWin=pWin->pNextWin){ + *pp = tdsqlite3WindowDup(db, 0, pWin); + if( *pp==0 ) break; + pp = &((*pp)->pNextWin); + } + + return pRet; +} + +/* +** Return true if it can be determined at compile time that expression +** pExpr evaluates to a value that, when cast to an integer, is greater +** than zero. False otherwise. +** +** If an OOM error occurs, this function sets the Parse.db.mallocFailed +** flag and returns zero. +*/ +static int windowExprGtZero(Parse *pParse, Expr *pExpr){ + int ret = 0; + tdsqlite3 *db = pParse->db; + tdsqlite3_value *pVal = 0; + tdsqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal); + if( pVal && tdsqlite3_value_int(pVal)>0 ){ + ret = 1; + } + tdsqlite3ValueFree(pVal); + return ret; +} + +/* +** tdsqlite3WhereBegin() has already been called for the SELECT statement +** passed as the second argument when this function is invoked. It generates +** code to populate the Window.regResult register for each window function +** and invoke the sub-routine at instruction addrGosub once for each row. +** tdsqlite3WhereEnd() is always called before returning. +** +** This function handles several different types of window frames, which +** require slightly different processing. The following pseudo code is +** used to implement window frames of the form: +** +** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING +** +** Other window frame types use variants of the following: +** +** ... loop started by tdsqlite3WhereBegin() ... +** if( new partition ){ +** Gosub flush +** } +** Insert new row into eph table. +** +** if( first row of partition ){ +** // Rewind three cursors, all open on the eph table. +** Rewind(csrEnd); +** Rewind(csrStart); +** Rewind(csrCurrent); +** +** regEnd = <expr2> // FOLLOWING expression +** regStart = <expr1> // PRECEDING expression +** }else{ +** // First time this branch is taken, the eph table contains two +** // rows. The first row in the partition, which all three cursors +** // currently point to, and the following row. +** AGGSTEP +** if( (regEnd--)<=0 ){ +** RETURN_ROW +** if( (regStart--)<=0 ){ +** AGGINVERSE +** } +** } +** } +** } +** flush: +** AGGSTEP +** while( 1 ){ +** RETURN ROW +** if( csrCurrent is EOF ) break; +** if( (regStart--)<=0 ){ +** AggInverse(csrStart) +** Next(csrStart) +** } +** } +** +** The pseudo-code above uses the following shorthand: +** +** AGGSTEP: invoke the aggregate xStep() function for each window function +** with arguments read from the current row of cursor csrEnd, then +** step cursor csrEnd forward one row (i.e. tdsqlite3BtreeNext()). +** +** RETURN_ROW: return a row to the caller based on the contents of the +** current row of csrCurrent and the current state of all +** aggregates. Then step cursor csrCurrent forward one row. +** +** AGGINVERSE: invoke the aggregate xInverse() function for each window +** functions with arguments read from the current row of cursor +** csrStart. Then step csrStart forward one row. +** +** There are two other ROWS window frames that are handled significantly +** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING" +** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special +** cases because they change the order in which the three cursors (csrStart, +** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that +** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these +** three. +** +** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING +** +** ... loop started by tdsqlite3WhereBegin() ... +** if( new partition ){ +** Gosub flush +** } +** Insert new row into eph table. +** if( first row of partition ){ +** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) +** regEnd = <expr2> +** regStart = <expr1> +** }else{ +** if( (regEnd--)<=0 ){ +** AGGSTEP +** } +** RETURN_ROW +** if( (regStart--)<=0 ){ +** AGGINVERSE +** } +** } +** } +** flush: +** if( (regEnd--)<=0 ){ +** AGGSTEP +** } +** RETURN_ROW +** +** +** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING +** +** ... loop started by tdsqlite3WhereBegin() ... +** if( new partition ){ +** Gosub flush +** } +** Insert new row into eph table. +** if( first row of partition ){ +** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) +** regEnd = <expr2> +** regStart = regEnd - <expr1> +** }else{ +** AGGSTEP +** if( (regEnd--)<=0 ){ +** RETURN_ROW +** } +** if( (regStart--)<=0 ){ +** AGGINVERSE +** } +** } +** } +** flush: +** AGGSTEP +** while( 1 ){ +** if( (regEnd--)<=0 ){ +** RETURN_ROW +** if( eof ) break; +** } +** if( (regStart--)<=0 ){ +** AGGINVERSE +** if( eof ) break +** } +** } +** while( !eof csrCurrent ){ +** RETURN_ROW +** } +** +** For the most part, the patterns above are adapted to support UNBOUNDED by +** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and +** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING". +** This is optimized of course - branches that will never be taken and +** conditions that are always true are omitted from the VM code. The only +** exceptional case is: +** +** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING +** +** ... loop started by tdsqlite3WhereBegin() ... +** if( new partition ){ +** Gosub flush +** } +** Insert new row into eph table. +** if( first row of partition ){ +** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) +** regStart = <expr1> +** }else{ +** AGGSTEP +** } +** } +** flush: +** AGGSTEP +** while( 1 ){ +** if( (regStart--)<=0 ){ +** AGGINVERSE +** if( eof ) break +** } +** RETURN_ROW +** } +** while( !eof csrCurrent ){ +** RETURN_ROW +** } +** +** Also requiring special handling are the cases: +** +** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING +** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING +** +** when (expr1 < expr2). This is detected at runtime, not by this function. +** To handle this case, the pseudo-code programs depicted above are modified +** slightly to be: +** +** ... loop started by tdsqlite3WhereBegin() ... +** if( new partition ){ +** Gosub flush +** } +** Insert new row into eph table. +** if( first row of partition ){ +** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) +** regEnd = <expr2> +** regStart = <expr1> +** if( regEnd < regStart ){ +** RETURN_ROW +** delete eph table contents +** continue +** } +** ... +** +** The new "continue" statement in the above jumps to the next iteration +** of the outer loop - the one started by tdsqlite3WhereBegin(). +** +** The various GROUPS cases are implemented using the same patterns as +** ROWS. The VM code is modified slightly so that: +** +** 1. The else branch in the main loop is only taken if the row just +** added to the ephemeral table is the start of a new group. In +** other words, it becomes: +** +** ... loop started by tdsqlite3WhereBegin() ... +** if( new partition ){ +** Gosub flush +** } +** Insert new row into eph table. +** if( first row of partition ){ +** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) +** regEnd = <expr2> +** regStart = <expr1> +** }else if( new group ){ +** ... +** } +** } +** +** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or +** AGGINVERSE step processes the current row of the relevant cursor and +** all subsequent rows belonging to the same group. +** +** RANGE window frames are a little different again. As for GROUPS, the +** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE +** deal in groups instead of rows. As for ROWS and GROUPS, there are three +** basic cases: +** +** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING +** +** ... loop started by tdsqlite3WhereBegin() ... +** if( new partition ){ +** Gosub flush +** } +** Insert new row into eph table. +** if( first row of partition ){ +** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) +** regEnd = <expr2> +** regStart = <expr1> +** }else{ +** AGGSTEP +** while( (csrCurrent.key + regEnd) < csrEnd.key ){ +** RETURN_ROW +** while( csrStart.key + regStart) < csrCurrent.key ){ +** AGGINVERSE +** } +** } +** } +** } +** flush: +** AGGSTEP +** while( 1 ){ +** RETURN ROW +** if( csrCurrent is EOF ) break; +** while( csrStart.key + regStart) < csrCurrent.key ){ +** AGGINVERSE +** } +** } +** } +** +** In the above notation, "csr.key" means the current value of the ORDER BY +** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING +** or <expr PRECEDING) read from cursor csr. +** +** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING +** +** ... loop started by tdsqlite3WhereBegin() ... +** if( new partition ){ +** Gosub flush +** } +** Insert new row into eph table. +** if( first row of partition ){ +** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) +** regEnd = <expr2> +** regStart = <expr1> +** }else{ +** while( (csrEnd.key + regEnd) <= csrCurrent.key ){ +** AGGSTEP +** } +** while( (csrStart.key + regStart) < csrCurrent.key ){ +** AGGINVERSE +** } +** RETURN_ROW +** } +** } +** flush: +** while( (csrEnd.key + regEnd) <= csrCurrent.key ){ +** AGGSTEP +** } +** while( (csrStart.key + regStart) < csrCurrent.key ){ +** AGGINVERSE +** } +** RETURN_ROW +** +** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING +** +** ... loop started by tdsqlite3WhereBegin() ... +** if( new partition ){ +** Gosub flush +** } +** Insert new row into eph table. +** if( first row of partition ){ +** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) +** regEnd = <expr2> +** regStart = <expr1> +** }else{ +** AGGSTEP +** while( (csrCurrent.key + regEnd) < csrEnd.key ){ +** while( (csrCurrent.key + regStart) > csrStart.key ){ +** AGGINVERSE +** } +** RETURN_ROW +** } +** } +** } +** flush: +** AGGSTEP +** while( 1 ){ +** while( (csrCurrent.key + regStart) > csrStart.key ){ +** AGGINVERSE +** if( eof ) break "while( 1 )" loop. +** } +** RETURN_ROW +** } +** while( !eof csrCurrent ){ +** RETURN_ROW +** } +** +** The text above leaves out many details. Refer to the code and comments +** below for a more complete picture. +*/ +SQLITE_PRIVATE void tdsqlite3WindowCodeStep( + Parse *pParse, /* Parse context */ + Select *p, /* Rewritten SELECT statement */ + WhereInfo *pWInfo, /* Context returned by tdsqlite3WhereBegin() */ + int regGosub, /* Register for OP_Gosub */ + int addrGosub /* OP_Gosub here to return each row */ +){ + Window *pMWin = p->pWin; + ExprList *pOrderBy = pMWin->pOrderBy; + Vdbe *v = tdsqlite3GetVdbe(pParse); + int csrWrite; /* Cursor used to write to eph. table */ + int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */ + int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */ + int iInput; /* To iterate through sub cols */ + int addrNe; /* Address of OP_Ne */ + int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */ + int addrInteger = 0; /* Address of OP_Integer */ + int addrEmpty; /* Address of OP_Rewind in flush: */ + int regNew; /* Array of registers holding new input row */ + int regRecord; /* regNew array in record form */ + int regRowid; /* Rowid for regRecord in eph table */ + int regNewPeer = 0; /* Peer values for new row (part of regNew) */ + int regPeer = 0; /* Peer values for current row */ + int regFlushPart = 0; /* Register for "Gosub flush_partition" */ + WindowCodeArg s; /* Context object for sub-routines */ + int lblWhereEnd; /* Label just before tdsqlite3WhereEnd() code */ + int regStart = 0; /* Value of <expr> PRECEDING */ + int regEnd = 0; /* Value of <expr> FOLLOWING */ + + assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT + || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED + ); + assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT + || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING + ); + assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT + || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES + || pMWin->eExclude==TK_NO + ); + + lblWhereEnd = tdsqlite3VdbeMakeLabel(pParse); + + /* Fill in the context object */ + memset(&s, 0, sizeof(WindowCodeArg)); + s.pParse = pParse; + s.pMWin = pMWin; + s.pVdbe = v; + s.regGosub = regGosub; + s.addrGosub = addrGosub; + s.current.csr = pMWin->iEphCsr; + csrWrite = s.current.csr+1; + s.start.csr = s.current.csr+2; + s.end.csr = s.current.csr+3; + + /* Figure out when rows may be deleted from the ephemeral table. There + ** are four options - they may never be deleted (eDelete==0), they may + ** be deleted as soon as they are no longer part of the window frame + ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row + ** has been returned to the caller (WINDOW_RETURN_ROW), or they may + ** be deleted after they enter the frame (WINDOW_AGGSTEP). */ + switch( pMWin->eStart ){ + case TK_FOLLOWING: + if( pMWin->eFrmType!=TK_RANGE + && windowExprGtZero(pParse, pMWin->pStart) + ){ + s.eDelete = WINDOW_RETURN_ROW; + } + break; + case TK_UNBOUNDED: + if( windowCacheFrame(pMWin)==0 ){ + if( pMWin->eEnd==TK_PRECEDING ){ + if( pMWin->eFrmType!=TK_RANGE + && windowExprGtZero(pParse, pMWin->pEnd) + ){ + s.eDelete = WINDOW_AGGSTEP; + } + }else{ + s.eDelete = WINDOW_RETURN_ROW; + } + } + break; + default: + s.eDelete = WINDOW_AGGINVERSE; + break; + } + + /* Allocate registers for the array of values from the sub-query, the + ** samve values in record form, and the rowid used to insert said record + ** into the ephemeral table. */ + regNew = pParse->nMem+1; + pParse->nMem += nInput; + regRecord = ++pParse->nMem; + regRowid = ++pParse->nMem; + + /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING" + ** clause, allocate registers to store the results of evaluating each + ** <expr>. */ + if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){ + regStart = ++pParse->nMem; + } + if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){ + regEnd = ++pParse->nMem; + } + + /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of + ** registers to store copies of the ORDER BY expressions (peer values) + ** for the main loop, and for each cursor (start, current and end). */ + if( pMWin->eFrmType!=TK_ROWS ){ + int nPeer = (pOrderBy ? pOrderBy->nExpr : 0); + regNewPeer = regNew + pMWin->nBufferCol; + if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr; + regPeer = pParse->nMem+1; pParse->nMem += nPeer; + s.start.reg = pParse->nMem+1; pParse->nMem += nPeer; + s.current.reg = pParse->nMem+1; pParse->nMem += nPeer; + s.end.reg = pParse->nMem+1; pParse->nMem += nPeer; + } + + /* Load the column values for the row returned by the sub-select + ** into an array of registers starting at regNew. Assemble them into + ** a record in register regRecord. */ + for(iInput=0; iInput<nInput; iInput++){ + tdsqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput); + } + tdsqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord); + + /* An input row has just been read into an array of registers starting + ** at regNew. If the window has a PARTITION clause, this block generates + ** VM code to check if the input row is the start of a new partition. + ** If so, it does an OP_Gosub to an address to be filled in later. The + ** address of the OP_Gosub is stored in local variable addrGosubFlush. */ + if( pMWin->pPartition ){ + int addr; + ExprList *pPart = pMWin->pPartition; + int nPart = pPart->nExpr; + int regNewPart = regNew + pMWin->nBufferCol; + KeyInfo *pKeyInfo = tdsqlite3KeyInfoFromExprList(pParse, pPart, 0, 0); + + regFlushPart = ++pParse->nMem; + addr = tdsqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart); + tdsqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); + tdsqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2); + VdbeCoverageEqNe(v); + addrGosubFlush = tdsqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart); + VdbeComment((v, "call flush_partition")); + tdsqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1); + } + + /* Insert the new row into the ephemeral table */ + tdsqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid); + tdsqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid); + addrNe = tdsqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid); + VdbeCoverageNeverNull(v); + + /* This block is run for the first row of each partition */ + s.regArg = windowInitAccum(pParse, pMWin); + + if( regStart ){ + tdsqlite3ExprCode(pParse, pMWin->pStart, regStart); + windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0)); + } + if( regEnd ){ + tdsqlite3ExprCode(pParse, pMWin->pEnd, regEnd); + windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0)); + } + + if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){ + int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le); + int addrGe = tdsqlite3VdbeAddOp3(v, op, regStart, 0, regEnd); + VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */ + VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */ + windowAggFinal(&s, 0); + tdsqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1); + VdbeCoverageNeverTaken(v); + windowReturnOneRow(&s); + tdsqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr); + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd); + tdsqlite3VdbeJumpHere(v, addrGe); + } + if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){ + assert( pMWin->eEnd==TK_FOLLOWING ); + tdsqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart); + } + + if( pMWin->eStart!=TK_UNBOUNDED ){ + tdsqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1); + VdbeCoverageNeverTaken(v); + } + tdsqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1); + VdbeCoverageNeverTaken(v); + tdsqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1); + VdbeCoverageNeverTaken(v); + if( regPeer && pOrderBy ){ + tdsqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1); + tdsqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1); + tdsqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1); + tdsqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1); + } + + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd); + + tdsqlite3VdbeJumpHere(v, addrNe); + + /* Beginning of the block executed for the second and subsequent rows. */ + if( regPeer ){ + windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd); + } + if( pMWin->eStart==TK_FOLLOWING ){ + windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); + if( pMWin->eEnd!=TK_UNBOUNDED ){ + if( pMWin->eFrmType==TK_RANGE ){ + int lbl = tdsqlite3VdbeMakeLabel(pParse); + int addrNext = tdsqlite3VdbeCurrentAddr(v); + windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl); + windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); + windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext); + tdsqlite3VdbeResolveLabel(v, lbl); + }else{ + windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0); + windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); + } + } + }else + if( pMWin->eEnd==TK_PRECEDING ){ + int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE); + windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0); + if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); + windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); + if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); + }else{ + int addr = 0; + windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); + if( pMWin->eEnd!=TK_UNBOUNDED ){ + if( pMWin->eFrmType==TK_RANGE ){ + int lbl = 0; + addr = tdsqlite3VdbeCurrentAddr(v); + if( regEnd ){ + lbl = tdsqlite3VdbeMakeLabel(pParse); + windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl); + } + windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); + windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); + if( regEnd ){ + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, addr); + tdsqlite3VdbeResolveLabel(v, lbl); + } + }else{ + if( regEnd ){ + addr = tdsqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1); + VdbeCoverage(v); + } + windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); + windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); + if( regEnd ) tdsqlite3VdbeJumpHere(v, addr); + } + } + } + + /* End of the main input loop */ + tdsqlite3VdbeResolveLabel(v, lblWhereEnd); + tdsqlite3WhereEnd(pWInfo); + + /* Fall through */ + if( pMWin->pPartition ){ + addrInteger = tdsqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart); + tdsqlite3VdbeJumpHere(v, addrGosubFlush); + } + + addrEmpty = tdsqlite3VdbeAddOp1(v, OP_Rewind, csrWrite); + VdbeCoverage(v); + if( pMWin->eEnd==TK_PRECEDING ){ + int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE); + windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0); + if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); + windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); + }else if( pMWin->eStart==TK_FOLLOWING ){ + int addrStart; + int addrBreak1; + int addrBreak2; + int addrBreak3; + windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); + if( pMWin->eFrmType==TK_RANGE ){ + addrStart = tdsqlite3VdbeCurrentAddr(v); + addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1); + addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); + }else + if( pMWin->eEnd==TK_UNBOUNDED ){ + addrStart = tdsqlite3VdbeCurrentAddr(v); + addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1); + addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1); + }else{ + assert( pMWin->eEnd==TK_FOLLOWING ); + addrStart = tdsqlite3VdbeCurrentAddr(v); + addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1); + addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1); + } + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); + tdsqlite3VdbeJumpHere(v, addrBreak2); + addrStart = tdsqlite3VdbeCurrentAddr(v); + addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); + tdsqlite3VdbeJumpHere(v, addrBreak1); + tdsqlite3VdbeJumpHere(v, addrBreak3); + }else{ + int addrBreak; + int addrStart; + windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); + addrStart = tdsqlite3VdbeCurrentAddr(v); + addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); + windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); + tdsqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); + tdsqlite3VdbeJumpHere(v, addrBreak); + } + tdsqlite3VdbeJumpHere(v, addrEmpty); + + tdsqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr); + if( pMWin->pPartition ){ + if( pMWin->regStartRowid ){ + tdsqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid); + tdsqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid); + } + tdsqlite3VdbeChangeP1(v, addrInteger, tdsqlite3VdbeCurrentAddr(v)); + tdsqlite3VdbeAddOp1(v, OP_Return, regFlushPart); + } +} + +#endif /* SQLITE_OMIT_WINDOWFUNC */ + +/************** End of window.c **********************************************/ /************** Begin file parse.c *******************************************/ /* ** 2000-05-29 @@ -135947,6 +155968,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ ** input grammar file: */ /* #include <stdio.h> */ +/* #include <assert.h> */ /************ Begin %include sections from the grammar ************************/ /* #include "sqliteInt.h" */ @@ -135963,25 +155985,29 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ #define yytestcase(X) testcase(X) /* -** Indicate that sqlite3ParserFree() will never be called with a null +** Indicate that tdsqlite3ParserFree() will never be called with a null ** pointer. */ #define YYPARSEFREENEVERNULL 1 /* -** Alternative datatype for the argument to the malloc() routine passed -** into sqlite3ParserAlloc(). The default is size_t. +** In the amalgamation, the parse.c file generated by lemon and the +** tokenize.c file are concatenated. In that case, tdsqlite3RunParser() +** has access to the the size of the yyParser object and so the parser +** engine can be allocated from stack. In that case, only the +** tdsqlite3ParserInit() and tdsqlite3ParserFinalize() routines are invoked +** and the tdsqlite3ParserAlloc() and tdsqlite3ParserFree() routines can be +** omitted. */ -#define YYMALLOCARGTYPE u64 +#ifdef SQLITE_AMALGAMATION +# define tdsqlite3Parser_ENGINEALWAYSONSTACK 1 +#endif /* -** An instance of this structure holds information about the -** LIMIT clause of a SELECT statement. +** Alternative datatype for the argument to the malloc() routine passed +** into tdsqlite3ParserAlloc(). The default is size_t. */ -struct LimitVal { - Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */ - Expr *pOffset; /* The OFFSET expression. NULL if there is none */ -}; +#define YYMALLOCARGTYPE u64 /* ** An instance of the following structure describes the event of a @@ -135994,13 +156020,16 @@ struct LimitVal { */ struct TrigEvent { int a; IdList * b; }; +struct FrameBound { int eType; Expr *pExpr; }; + /* ** Disable lookaside memory allocation for objects that might be ** shared across database connections. */ static void disableLookaside(Parse *pParse){ + tdsqlite3 *db = pParse->db; pParse->disableLookaside++; - pParse->db->lookaside.bDisable++; + DisableLookaside; } @@ -136010,6 +156039,7 @@ static void disableLookaside(Parse *pParse){ ** SQLITE_LIMIT_COMPOUND_SELECT. */ static void parserDoubleLinkSelect(Parse *pParse, Select *p){ + assert( p!=0 ); if( p->pPrior ){ Select *pNext = 0, *pLoop; int mxSelect, cnt = 0; @@ -136021,106 +156051,59 @@ static void disableLookaside(Parse *pParse){ (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 && cnt>mxSelect ){ - sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); + tdsqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); } } } - /* This is a utility routine used to set the ExprSpan.zStart and - ** ExprSpan.zEnd values of pOut so that the span covers the complete - ** range of text beginning with pStart and going to the end of pEnd. - */ - static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){ - pOut->zStart = pStart->z; - pOut->zEnd = &pEnd->z[pEnd->n]; - } /* Construct a new Expr object from a single identifier. Use the ** new Expr to populate pOut. Set the span of pOut to be the identifier ** that created the expression. */ - static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){ - Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1); + static Expr *tokenExpr(Parse *pParse, int op, Token t){ + Expr *p = tdsqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1); if( p ){ - memset(p, 0, sizeof(Expr)); + /* memset(p, 0, sizeof(Expr)); */ p->op = (u8)op; + p->affExpr = 0; p->flags = EP_Leaf; p->iAgg = -1; + p->pLeft = p->pRight = 0; + p->x.pList = 0; + p->pAggInfo = 0; + p->y.pTab = 0; + p->op2 = 0; + p->iTable = 0; + p->iColumn = 0; p->u.zToken = (char*)&p[1]; memcpy(p->u.zToken, t.z, t.n); p->u.zToken[t.n] = 0; - if( sqlite3Isquote(p->u.zToken[0]) ){ - if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted; - sqlite3Dequote(p->u.zToken); + if( tdsqlite3Isquote(p->u.zToken[0]) ){ + tdsqlite3DequoteExpr(p); } #if SQLITE_MAX_EXPR_DEPTH>0 p->nHeight = 1; #endif + if( IN_RENAME_OBJECT ){ + return (Expr*)tdsqlite3RenameTokenMap(pParse, (void*)p, &t); + } } - pOut->pExpr = p; - pOut->zStart = t.z; - pOut->zEnd = &t.z[t.n]; - } - - /* This routine constructs a binary expression node out of two ExprSpan - ** objects and uses the result to populate a new ExprSpan object. - */ - static void spanBinaryExpr( - Parse *pParse, /* The parsing context. Errors accumulate here */ - int op, /* The binary operation */ - ExprSpan *pLeft, /* The left operand, and output */ - ExprSpan *pRight /* The right operand */ - ){ - pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0); - pLeft->zEnd = pRight->zEnd; - } - - /* If doNot is true, then add a TK_NOT Expr-node wrapper around the - ** outside of *ppExpr. - */ - static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){ - if( doNot ){ - pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0, 0); - } + return p; } - /* Construct an expression node for a unary postfix operator - */ - static void spanUnaryPostfix( - Parse *pParse, /* Parsing context to record errors */ - int op, /* The operator */ - ExprSpan *pOperand, /* The operand, and output */ - Token *pPostOp /* The operand token for setting the span */ - ){ - pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0); - pOperand->zEnd = &pPostOp->z[pPostOp->n]; - } /* A routine to convert a binary TK_IS or TK_ISNOT expression into a ** unary TK_ISNULL or TK_NOTNULL expression. */ static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){ - sqlite3 *db = pParse->db; - if( pA && pY && pY->op==TK_NULL ){ + tdsqlite3 *db = pParse->db; + if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){ pA->op = (u8)op; - sqlite3ExprDelete(db, pA->pRight); + tdsqlite3ExprDelete(db, pA->pRight); pA->pRight = 0; } } - /* Construct an expression node for a unary prefix operator - */ - static void spanUnaryPrefix( - ExprSpan *pOut, /* Write the new expression node here */ - Parse *pParse, /* Parsing context to record errors */ - int op, /* The operator */ - ExprSpan *pOperand, /* The operand */ - Token *pPreOp /* The operand token for setting the span */ - ){ - pOut->zStart = pPreOp->z; - pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0); - pOut->zEnd = pOperand->zEnd; - } - /* Add a single new term to an ExprList that is used to store a ** list of identifiers. Report an error if the ID list contains ** a COLLATE clause or an ASC or DESC keyword, except ignore the @@ -136133,16 +156116,20 @@ static void disableLookaside(Parse *pParse){ int hasCollate, int sortOrder ){ - ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0); + ExprList *p = tdsqlite3ExprListAppend(pParse, pPrior, 0); if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED) && pParse->db->init.busy==0 ){ - sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"", + tdsqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"", pIdToken->n, pIdToken->z); } - sqlite3ExprListSetName(pParse, p, pIdToken, 1); + tdsqlite3ExprListSetName(pParse, p, pIdToken, 1); return p; } + +#if TK_SPAN>255 +# error too many tokens in the grammar +#endif /**************** End of %include directives **********************************/ /* These constants specify the various numeric values for terminal symbols ** in a format understandable to "makeheaders". This section is blank unless @@ -136166,7 +156153,7 @@ static void disableLookaside(Parse *pParse){ ** YYACTIONTYPE is the data type used for "action codes" - numbers ** that indicate what to do in response to the next ** token. -** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal +** tdsqlite3ParserTOKENTYPE is the data type used for minor type for terminal ** symbols. Background: A "minor type" is a semantic ** value associated with a terminal or non-terminal ** symbols. For example, for an "ID" terminal symbol, @@ -136177,70 +156164,86 @@ static void disableLookaside(Parse *pParse){ ** symbols. ** YYMINORTYPE is the data type used for all minor types. ** This is typically a union of many types, one of -** which is sqlite3ParserTOKENTYPE. The entry in the union +** which is tdsqlite3ParserTOKENTYPE. The entry in the union ** for terminal symbols is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. If ** zero the stack is dynamically sized using realloc() -** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument -** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument -** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser -** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser +** tdsqlite3ParserARG_SDECL A static variable declaration for the %extra_argument +** tdsqlite3ParserARG_PDECL A parameter declaration for the %extra_argument +** tdsqlite3ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter +** tdsqlite3ParserARG_STORE Code to store %extra_argument into yypParser +** tdsqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser +** tdsqlite3ParserCTX_* As tdsqlite3ParserARG_ except for %extra_context ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar +** YYNTOKEN Number of terminal symbols ** YY_MAX_SHIFT Maximum value for shift actions ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions -** YY_MIN_REDUCE Maximum value for reduce actions ** YY_ERROR_ACTION The yy_action[] code for syntax error ** YY_ACCEPT_ACTION The yy_action[] code for accept ** YY_NO_ACTION The yy_action[] code for no-op +** YY_MIN_REDUCE Minimum value for reduce actions +** YY_MAX_REDUCE Maximum value for reduce actions */ #ifndef INTERFACE # define INTERFACE 1 #endif /************* Begin control #defines *****************************************/ -#define YYCODETYPE unsigned char -#define YYNOCODE 252 +#define YYCODETYPE unsigned short int +#define YYNOCODE 310 #define YYACTIONTYPE unsigned short int -#define YYWILDCARD 96 -#define sqlite3ParserTOKENTYPE Token +#define YYWILDCARD 100 +#define tdsqlite3ParserTOKENTYPE Token typedef union { int yyinit; - sqlite3ParserTOKENTYPE yy0; - Expr* yy72; - TriggerStep* yy145; - ExprList* yy148; - SrcList* yy185; - ExprSpan yy190; - int yy194; - Select* yy243; - IdList* yy254; - With* yy285; - struct TrigEvent yy332; - struct LimitVal yy354; - struct {int value; int mask;} yy497; + tdsqlite3ParserTOKENTYPE yy0; + SrcList* yy47; + u8 yy58; + struct FrameBound yy77; + With* yy131; + int yy192; + Expr* yy202; + struct {int value; int mask;} yy207; + struct TrigEvent yy230; + ExprList* yy242; + Window* yy303; + Upsert* yy318; + const char* yy436; + TriggerStep* yy447; + Select* yy539; + IdList* yy600; } YYMINORTYPE; #ifndef YYSTACKDEPTH #define YYSTACKDEPTH 100 #endif -#define sqlite3ParserARG_SDECL Parse *pParse; -#define sqlite3ParserARG_PDECL ,Parse *pParse -#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse -#define sqlite3ParserARG_STORE yypParser->pParse = pParse +#define tdsqlite3ParserARG_SDECL +#define tdsqlite3ParserARG_PDECL +#define tdsqlite3ParserARG_PARAM +#define tdsqlite3ParserARG_FETCH +#define tdsqlite3ParserARG_STORE +#define tdsqlite3ParserCTX_SDECL Parse *pParse; +#define tdsqlite3ParserCTX_PDECL ,Parse *pParse +#define tdsqlite3ParserCTX_PARAM ,pParse +#define tdsqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse; +#define tdsqlite3ParserCTX_STORE yypParser->pParse=pParse; #define YYFALLBACK 1 -#define YYNSTATE 456 -#define YYNRULE 332 -#define YY_MAX_SHIFT 455 -#define YY_MIN_SHIFTREDUCE 668 -#define YY_MAX_SHIFTREDUCE 999 -#define YY_MIN_REDUCE 1000 -#define YY_MAX_REDUCE 1331 -#define YY_ERROR_ACTION 1332 -#define YY_ACCEPT_ACTION 1333 -#define YY_NO_ACTION 1334 +#define YYNSTATE 551 +#define YYNRULE 385 +#define YYNRULE_WITH_ACTION 325 +#define YYNTOKEN 181 +#define YY_MAX_SHIFT 550 +#define YY_MIN_SHIFTREDUCE 801 +#define YY_MAX_SHIFTREDUCE 1185 +#define YY_ERROR_ACTION 1186 +#define YY_ACCEPT_ACTION 1187 +#define YY_NO_ACTION 1188 +#define YY_MIN_REDUCE 1189 +#define YY_MAX_REDUCE 1573 /************* End control #defines *******************************************/ +#define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0]))) /* Define the yytestcase() macro to be a no-op if is not already defined ** otherwise. @@ -136269,9 +156272,6 @@ typedef union { ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE. ** -** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE -** and YY_MAX_REDUCE -** ** N == YY_ERROR_ACTION A syntax error has occurred. ** ** N == YY_ACCEPT_ACTION The parser accepts its input. @@ -136279,25 +156279,22 @@ typedef union { ** N == YY_NO_ACTION No such action. Denotes unused ** slots in the yy_action[] table. ** +** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE +** and YY_MAX_REDUCE +** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as either: ** ** (A) N = yy_action[ yy_shift_ofst[S] + X ] ** (B) N = yy_default[S] ** -** The (A) formula is preferred. The B formula is used instead if: -** (1) The yy_shift_ofst[S]+X value is out of range, or -** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or -** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT. -** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that -** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X. -** Hence only tests (1) and (2) need to be evaluated.) +** The (A) formula is preferred. The B formula is used instead if +** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X. ** ** The formulas above are for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of -** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of -** YY_SHIFT_USE_DFLT. +** the yy_shift_ofst[] array. ** ** The following are the tables generated in this section: ** @@ -136311,463 +156308,583 @@ typedef union { ** yy_default[] Default action for each state. ** *********** Begin parsing tables **********************************************/ -#define YY_ACTTAB_COUNT (1567) +#define YY_ACTTAB_COUNT (1958) static const YYACTIONTYPE yy_action[] = { - /* 0 */ 325, 832, 351, 825, 5, 203, 203, 819, 99, 100, - /* 10 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98, - /* 20 */ 98, 98, 98, 301, 96, 96, 96, 96, 95, 95, - /* 30 */ 94, 94, 94, 93, 351, 325, 977, 977, 824, 824, - /* 40 */ 826, 947, 354, 99, 100, 90, 842, 842, 854, 857, - /* 50 */ 846, 846, 97, 97, 98, 98, 98, 98, 338, 96, - /* 60 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351, - /* 70 */ 95, 95, 94, 94, 94, 93, 351, 791, 977, 977, - /* 80 */ 325, 94, 94, 94, 93, 351, 792, 75, 99, 100, - /* 90 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98, - /* 100 */ 98, 98, 98, 450, 96, 96, 96, 96, 95, 95, - /* 110 */ 94, 94, 94, 93, 351, 1333, 155, 155, 2, 325, - /* 120 */ 275, 146, 132, 52, 52, 93, 351, 99, 100, 90, - /* 130 */ 842, 842, 854, 857, 846, 846, 97, 97, 98, 98, - /* 140 */ 98, 98, 101, 96, 96, 96, 96, 95, 95, 94, - /* 150 */ 94, 94, 93, 351, 958, 958, 325, 268, 428, 413, - /* 160 */ 411, 61, 752, 752, 99, 100, 90, 842, 842, 854, - /* 170 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 60, - /* 180 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, - /* 190 */ 351, 325, 270, 329, 273, 277, 959, 960, 250, 99, - /* 200 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, - /* 210 */ 98, 98, 98, 98, 301, 96, 96, 96, 96, 95, - /* 220 */ 95, 94, 94, 94, 93, 351, 325, 938, 1326, 698, - /* 230 */ 706, 1326, 242, 412, 99, 100, 90, 842, 842, 854, - /* 240 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 347, - /* 250 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, - /* 260 */ 351, 325, 938, 1327, 384, 699, 1327, 381, 379, 99, - /* 270 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, - /* 280 */ 98, 98, 98, 98, 701, 96, 96, 96, 96, 95, - /* 290 */ 95, 94, 94, 94, 93, 351, 325, 92, 89, 178, - /* 300 */ 833, 936, 373, 700, 99, 100, 90, 842, 842, 854, - /* 310 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 375, - /* 320 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, - /* 330 */ 351, 325, 1276, 947, 354, 818, 936, 739, 739, 99, - /* 340 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, - /* 350 */ 98, 98, 98, 98, 230, 96, 96, 96, 96, 95, - /* 360 */ 95, 94, 94, 94, 93, 351, 325, 969, 227, 92, - /* 370 */ 89, 178, 373, 300, 99, 100, 90, 842, 842, 854, - /* 380 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 921, - /* 390 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, - /* 400 */ 351, 325, 449, 447, 447, 447, 147, 737, 737, 99, - /* 410 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97, - /* 420 */ 98, 98, 98, 98, 296, 96, 96, 96, 96, 95, - /* 430 */ 95, 94, 94, 94, 93, 351, 325, 419, 231, 958, - /* 440 */ 958, 158, 25, 422, 99, 100, 90, 842, 842, 854, - /* 450 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 450, - /* 460 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, - /* 470 */ 351, 443, 224, 224, 420, 958, 958, 962, 325, 52, - /* 480 */ 52, 959, 960, 176, 415, 78, 99, 100, 90, 842, - /* 490 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98, - /* 500 */ 98, 379, 96, 96, 96, 96, 95, 95, 94, 94, - /* 510 */ 94, 93, 351, 325, 428, 418, 298, 959, 960, 962, - /* 520 */ 81, 99, 88, 90, 842, 842, 854, 857, 846, 846, - /* 530 */ 97, 97, 98, 98, 98, 98, 717, 96, 96, 96, - /* 540 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 843, - /* 550 */ 843, 855, 858, 996, 318, 343, 379, 100, 90, 842, - /* 560 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98, - /* 570 */ 98, 450, 96, 96, 96, 96, 95, 95, 94, 94, - /* 580 */ 94, 93, 351, 325, 350, 350, 350, 260, 377, 340, - /* 590 */ 929, 52, 52, 90, 842, 842, 854, 857, 846, 846, - /* 600 */ 97, 97, 98, 98, 98, 98, 361, 96, 96, 96, - /* 610 */ 96, 95, 95, 94, 94, 94, 93, 351, 86, 445, - /* 620 */ 847, 3, 1203, 361, 360, 378, 344, 813, 958, 958, - /* 630 */ 1300, 86, 445, 729, 3, 212, 169, 287, 405, 282, - /* 640 */ 404, 199, 232, 450, 300, 760, 83, 84, 280, 245, - /* 650 */ 262, 365, 251, 85, 352, 352, 92, 89, 178, 83, - /* 660 */ 84, 242, 412, 52, 52, 448, 85, 352, 352, 246, - /* 670 */ 959, 960, 194, 455, 670, 402, 399, 398, 448, 243, - /* 680 */ 221, 114, 434, 776, 361, 450, 397, 268, 747, 224, - /* 690 */ 224, 132, 132, 198, 832, 434, 452, 451, 428, 427, - /* 700 */ 819, 415, 734, 713, 132, 52, 52, 832, 268, 452, - /* 710 */ 451, 734, 194, 819, 363, 402, 399, 398, 450, 1271, - /* 720 */ 1271, 23, 958, 958, 86, 445, 397, 3, 228, 429, - /* 730 */ 895, 824, 824, 826, 827, 19, 203, 720, 52, 52, - /* 740 */ 428, 408, 439, 249, 824, 824, 826, 827, 19, 229, - /* 750 */ 403, 153, 83, 84, 761, 177, 241, 450, 721, 85, - /* 760 */ 352, 352, 120, 157, 959, 960, 58, 977, 409, 355, - /* 770 */ 330, 448, 268, 428, 430, 320, 790, 32, 32, 86, - /* 780 */ 445, 776, 3, 341, 98, 98, 98, 98, 434, 96, - /* 790 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351, - /* 800 */ 832, 120, 452, 451, 813, 887, 819, 83, 84, 977, - /* 810 */ 813, 132, 410, 920, 85, 352, 352, 132, 407, 789, - /* 820 */ 958, 958, 92, 89, 178, 917, 448, 262, 370, 261, - /* 830 */ 82, 914, 80, 262, 370, 261, 776, 824, 824, 826, - /* 840 */ 827, 19, 934, 434, 96, 96, 96, 96, 95, 95, - /* 850 */ 94, 94, 94, 93, 351, 832, 74, 452, 451, 958, - /* 860 */ 958, 819, 959, 960, 120, 92, 89, 178, 945, 2, - /* 870 */ 918, 965, 268, 1, 976, 76, 445, 762, 3, 708, - /* 880 */ 901, 901, 387, 958, 958, 757, 919, 371, 740, 778, - /* 890 */ 756, 257, 824, 824, 826, 827, 19, 417, 741, 450, - /* 900 */ 24, 959, 960, 83, 84, 369, 958, 958, 177, 226, - /* 910 */ 85, 352, 352, 885, 315, 314, 313, 215, 311, 10, - /* 920 */ 10, 683, 448, 349, 348, 959, 960, 909, 777, 157, - /* 930 */ 120, 958, 958, 337, 776, 416, 711, 310, 450, 434, - /* 940 */ 450, 321, 450, 791, 103, 200, 175, 450, 959, 960, - /* 950 */ 908, 832, 792, 452, 451, 9, 9, 819, 10, 10, - /* 960 */ 52, 52, 51, 51, 180, 716, 248, 10, 10, 171, - /* 970 */ 170, 167, 339, 959, 960, 247, 984, 702, 702, 450, - /* 980 */ 715, 233, 686, 982, 889, 983, 182, 914, 824, 824, - /* 990 */ 826, 827, 19, 183, 256, 423, 132, 181, 394, 10, - /* 1000 */ 10, 889, 891, 749, 958, 958, 917, 268, 985, 198, - /* 1010 */ 985, 349, 348, 425, 415, 299, 817, 832, 326, 825, - /* 1020 */ 120, 332, 133, 819, 268, 98, 98, 98, 98, 91, - /* 1030 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, - /* 1040 */ 351, 157, 810, 371, 382, 359, 959, 960, 358, 268, - /* 1050 */ 450, 918, 368, 324, 824, 824, 826, 450, 709, 450, - /* 1060 */ 264, 380, 889, 450, 877, 746, 253, 919, 255, 433, - /* 1070 */ 36, 36, 234, 450, 234, 120, 269, 37, 37, 12, - /* 1080 */ 12, 334, 272, 27, 27, 450, 330, 118, 450, 162, - /* 1090 */ 742, 280, 450, 38, 38, 450, 985, 356, 985, 450, - /* 1100 */ 709, 1210, 450, 132, 450, 39, 39, 450, 40, 40, - /* 1110 */ 450, 362, 41, 41, 450, 42, 42, 450, 254, 28, - /* 1120 */ 28, 450, 29, 29, 31, 31, 450, 43, 43, 450, - /* 1130 */ 44, 44, 450, 714, 45, 45, 450, 11, 11, 767, - /* 1140 */ 450, 46, 46, 450, 268, 450, 105, 105, 450, 47, - /* 1150 */ 47, 450, 48, 48, 450, 237, 33, 33, 450, 172, - /* 1160 */ 49, 49, 450, 50, 50, 34, 34, 274, 122, 122, - /* 1170 */ 450, 123, 123, 450, 124, 124, 450, 898, 56, 56, - /* 1180 */ 450, 897, 35, 35, 450, 267, 450, 817, 450, 817, - /* 1190 */ 106, 106, 450, 53, 53, 385, 107, 107, 450, 817, - /* 1200 */ 108, 108, 817, 450, 104, 104, 121, 121, 119, 119, - /* 1210 */ 450, 117, 112, 112, 450, 276, 450, 225, 111, 111, - /* 1220 */ 450, 730, 450, 109, 109, 450, 673, 674, 675, 912, - /* 1230 */ 110, 110, 317, 998, 55, 55, 57, 57, 692, 331, - /* 1240 */ 54, 54, 26, 26, 696, 30, 30, 317, 937, 197, - /* 1250 */ 196, 195, 335, 281, 336, 446, 331, 745, 689, 436, - /* 1260 */ 440, 444, 120, 72, 386, 223, 175, 345, 757, 933, - /* 1270 */ 20, 286, 319, 756, 815, 372, 374, 202, 202, 202, - /* 1280 */ 263, 395, 285, 74, 208, 21, 696, 719, 718, 884, - /* 1290 */ 120, 120, 120, 120, 120, 754, 278, 828, 77, 74, - /* 1300 */ 726, 727, 785, 783, 880, 202, 999, 208, 894, 893, - /* 1310 */ 894, 893, 694, 816, 763, 116, 774, 1290, 431, 432, - /* 1320 */ 302, 999, 390, 303, 823, 697, 691, 680, 159, 289, - /* 1330 */ 679, 884, 681, 952, 291, 218, 293, 7, 316, 828, - /* 1340 */ 173, 805, 259, 364, 252, 911, 376, 713, 295, 435, - /* 1350 */ 308, 168, 955, 993, 135, 400, 990, 284, 882, 881, - /* 1360 */ 205, 928, 926, 59, 333, 62, 144, 156, 130, 72, - /* 1370 */ 802, 366, 367, 393, 137, 185, 189, 160, 139, 383, - /* 1380 */ 67, 896, 140, 141, 142, 148, 389, 812, 775, 266, - /* 1390 */ 219, 190, 154, 391, 913, 876, 271, 406, 191, 322, - /* 1400 */ 682, 733, 192, 342, 732, 724, 731, 711, 723, 421, - /* 1410 */ 705, 71, 323, 6, 204, 771, 288, 79, 297, 346, - /* 1420 */ 772, 704, 290, 283, 703, 770, 292, 294, 967, 239, - /* 1430 */ 769, 102, 862, 438, 426, 240, 424, 442, 73, 213, - /* 1440 */ 688, 238, 22, 453, 953, 214, 217, 216, 454, 677, - /* 1450 */ 676, 671, 753, 125, 115, 235, 126, 669, 353, 166, - /* 1460 */ 127, 244, 179, 357, 306, 304, 305, 307, 113, 892, - /* 1470 */ 327, 890, 811, 328, 134, 128, 136, 138, 743, 258, - /* 1480 */ 907, 184, 143, 129, 910, 186, 63, 64, 145, 187, - /* 1490 */ 906, 65, 8, 66, 13, 188, 202, 899, 265, 149, - /* 1500 */ 987, 388, 150, 685, 161, 392, 285, 193, 279, 396, - /* 1510 */ 151, 401, 68, 14, 15, 722, 69, 236, 831, 131, - /* 1520 */ 830, 860, 70, 751, 16, 414, 755, 4, 174, 220, - /* 1530 */ 222, 784, 201, 152, 779, 77, 74, 17, 18, 875, - /* 1540 */ 861, 859, 916, 864, 915, 207, 206, 942, 163, 437, - /* 1550 */ 948, 943, 164, 209, 1002, 441, 863, 165, 210, 829, - /* 1560 */ 695, 87, 312, 211, 1292, 1291, 309, + /* 0 */ 544, 1220, 544, 449, 1258, 544, 1237, 544, 114, 111, + /* 10 */ 211, 544, 1535, 544, 1258, 521, 114, 111, 211, 390, + /* 20 */ 1230, 342, 42, 42, 42, 42, 1223, 42, 42, 71, + /* 30 */ 71, 935, 1222, 71, 71, 71, 71, 1460, 1491, 936, + /* 40 */ 818, 451, 6, 121, 122, 112, 1163, 1163, 1004, 1007, + /* 50 */ 997, 997, 119, 119, 120, 120, 120, 120, 1541, 390, + /* 60 */ 1356, 1515, 550, 2, 1191, 194, 526, 434, 143, 291, + /* 70 */ 526, 136, 526, 369, 261, 502, 272, 383, 1271, 525, + /* 80 */ 501, 491, 164, 121, 122, 112, 1163, 1163, 1004, 1007, + /* 90 */ 997, 997, 119, 119, 120, 120, 120, 120, 1356, 440, + /* 100 */ 1512, 118, 118, 118, 118, 117, 117, 116, 116, 116, + /* 110 */ 115, 422, 266, 266, 266, 266, 1496, 356, 1498, 433, + /* 120 */ 355, 1496, 515, 522, 1483, 541, 1112, 541, 1112, 390, + /* 130 */ 403, 241, 208, 114, 111, 211, 98, 290, 535, 221, + /* 140 */ 1027, 118, 118, 118, 118, 117, 117, 116, 116, 116, + /* 150 */ 115, 422, 1140, 121, 122, 112, 1163, 1163, 1004, 1007, + /* 160 */ 997, 997, 119, 119, 120, 120, 120, 120, 404, 426, + /* 170 */ 117, 117, 116, 116, 116, 115, 422, 1416, 466, 123, + /* 180 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115, + /* 190 */ 422, 116, 116, 116, 115, 422, 538, 538, 538, 390, + /* 200 */ 503, 120, 120, 120, 120, 113, 1049, 1140, 1141, 1142, + /* 210 */ 1049, 118, 118, 118, 118, 117, 117, 116, 116, 116, + /* 220 */ 115, 422, 1459, 121, 122, 112, 1163, 1163, 1004, 1007, + /* 230 */ 997, 997, 119, 119, 120, 120, 120, 120, 390, 442, + /* 240 */ 314, 83, 461, 81, 357, 380, 1140, 80, 118, 118, + /* 250 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 179, + /* 260 */ 432, 422, 121, 122, 112, 1163, 1163, 1004, 1007, 997, + /* 270 */ 997, 119, 119, 120, 120, 120, 120, 432, 431, 266, + /* 280 */ 266, 118, 118, 118, 118, 117, 117, 116, 116, 116, + /* 290 */ 115, 422, 541, 1107, 901, 504, 1140, 114, 111, 211, + /* 300 */ 1429, 1140, 1141, 1142, 206, 489, 1107, 390, 447, 1107, + /* 310 */ 543, 328, 120, 120, 120, 120, 298, 1429, 1431, 17, + /* 320 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115, + /* 330 */ 422, 121, 122, 112, 1163, 1163, 1004, 1007, 997, 997, + /* 340 */ 119, 119, 120, 120, 120, 120, 390, 1356, 432, 1140, + /* 350 */ 480, 1140, 1141, 1142, 994, 994, 1005, 1008, 443, 118, + /* 360 */ 118, 118, 118, 117, 117, 116, 116, 116, 115, 422, + /* 370 */ 121, 122, 112, 1163, 1163, 1004, 1007, 997, 997, 119, + /* 380 */ 119, 120, 120, 120, 120, 1052, 1052, 463, 1429, 118, + /* 390 */ 118, 118, 118, 117, 117, 116, 116, 116, 115, 422, + /* 400 */ 1140, 449, 544, 1424, 1140, 1141, 1142, 233, 964, 1140, + /* 410 */ 479, 476, 475, 171, 358, 390, 164, 405, 412, 840, + /* 420 */ 474, 164, 185, 332, 71, 71, 1241, 998, 118, 118, + /* 430 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 121, + /* 440 */ 122, 112, 1163, 1163, 1004, 1007, 997, 997, 119, 119, + /* 450 */ 120, 120, 120, 120, 390, 1140, 1141, 1142, 833, 12, + /* 460 */ 313, 507, 163, 354, 1140, 1141, 1142, 114, 111, 211, + /* 470 */ 506, 290, 535, 544, 276, 180, 290, 535, 121, 122, + /* 480 */ 112, 1163, 1163, 1004, 1007, 997, 997, 119, 119, 120, + /* 490 */ 120, 120, 120, 343, 482, 71, 71, 118, 118, 118, + /* 500 */ 118, 117, 117, 116, 116, 116, 115, 422, 1140, 209, + /* 510 */ 409, 521, 1140, 1107, 1569, 376, 252, 269, 340, 485, + /* 520 */ 335, 484, 238, 390, 511, 362, 1107, 1125, 331, 1107, + /* 530 */ 191, 407, 286, 32, 455, 441, 118, 118, 118, 118, + /* 540 */ 117, 117, 116, 116, 116, 115, 422, 121, 122, 112, + /* 550 */ 1163, 1163, 1004, 1007, 997, 997, 119, 119, 120, 120, + /* 560 */ 120, 120, 390, 1140, 1141, 1142, 985, 1140, 1141, 1142, + /* 570 */ 1140, 233, 490, 1490, 479, 476, 475, 6, 163, 544, + /* 580 */ 510, 544, 115, 422, 474, 5, 121, 122, 112, 1163, + /* 590 */ 1163, 1004, 1007, 997, 997, 119, 119, 120, 120, 120, + /* 600 */ 120, 13, 13, 13, 13, 118, 118, 118, 118, 117, + /* 610 */ 117, 116, 116, 116, 115, 422, 401, 500, 406, 544, + /* 620 */ 1484, 542, 1140, 890, 890, 1140, 1141, 1142, 1471, 1140, + /* 630 */ 275, 390, 806, 807, 808, 969, 420, 420, 420, 16, + /* 640 */ 16, 55, 55, 1240, 118, 118, 118, 118, 117, 117, + /* 650 */ 116, 116, 116, 115, 422, 121, 122, 112, 1163, 1163, + /* 660 */ 1004, 1007, 997, 997, 119, 119, 120, 120, 120, 120, + /* 670 */ 390, 1187, 1, 1, 550, 2, 1191, 1140, 1141, 1142, + /* 680 */ 194, 291, 896, 136, 1140, 1141, 1142, 895, 519, 1490, + /* 690 */ 1271, 3, 378, 6, 121, 122, 112, 1163, 1163, 1004, + /* 700 */ 1007, 997, 997, 119, 119, 120, 120, 120, 120, 856, + /* 710 */ 544, 922, 544, 118, 118, 118, 118, 117, 117, 116, + /* 720 */ 116, 116, 115, 422, 266, 266, 1090, 1567, 1140, 549, + /* 730 */ 1567, 1191, 13, 13, 13, 13, 291, 541, 136, 390, + /* 740 */ 483, 419, 418, 964, 342, 1271, 466, 408, 857, 279, + /* 750 */ 140, 221, 118, 118, 118, 118, 117, 117, 116, 116, + /* 760 */ 116, 115, 422, 121, 122, 112, 1163, 1163, 1004, 1007, + /* 770 */ 997, 997, 119, 119, 120, 120, 120, 120, 544, 266, + /* 780 */ 266, 426, 390, 1140, 1141, 1142, 1170, 828, 1170, 466, + /* 790 */ 429, 145, 541, 1144, 399, 313, 437, 301, 836, 1488, + /* 800 */ 71, 71, 410, 6, 1088, 471, 221, 100, 112, 1163, + /* 810 */ 1163, 1004, 1007, 997, 997, 119, 119, 120, 120, 120, + /* 820 */ 120, 118, 118, 118, 118, 117, 117, 116, 116, 116, + /* 830 */ 115, 422, 237, 1423, 544, 449, 426, 287, 984, 544, + /* 840 */ 236, 235, 234, 828, 97, 527, 427, 1263, 1263, 1144, + /* 850 */ 492, 306, 428, 836, 975, 544, 71, 71, 974, 1239, + /* 860 */ 544, 51, 51, 300, 118, 118, 118, 118, 117, 117, + /* 870 */ 116, 116, 116, 115, 422, 194, 103, 70, 70, 266, + /* 880 */ 266, 544, 71, 71, 266, 266, 30, 389, 342, 974, + /* 890 */ 974, 976, 541, 526, 1107, 326, 390, 541, 493, 395, + /* 900 */ 1468, 195, 528, 13, 13, 1356, 240, 1107, 277, 280, + /* 910 */ 1107, 280, 303, 455, 305, 331, 390, 31, 188, 417, + /* 920 */ 121, 122, 112, 1163, 1163, 1004, 1007, 997, 997, 119, + /* 930 */ 119, 120, 120, 120, 120, 142, 390, 363, 455, 984, + /* 940 */ 121, 122, 112, 1163, 1163, 1004, 1007, 997, 997, 119, + /* 950 */ 119, 120, 120, 120, 120, 975, 321, 1140, 324, 974, + /* 960 */ 121, 110, 112, 1163, 1163, 1004, 1007, 997, 997, 119, + /* 970 */ 119, 120, 120, 120, 120, 462, 375, 1183, 118, 118, + /* 980 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 1140, + /* 990 */ 974, 974, 976, 304, 9, 364, 244, 360, 118, 118, + /* 1000 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 312, + /* 1010 */ 544, 342, 1140, 1141, 1142, 299, 290, 535, 118, 118, + /* 1020 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 1261, + /* 1030 */ 1261, 1161, 13, 13, 278, 419, 418, 466, 390, 921, + /* 1040 */ 260, 260, 289, 1167, 1140, 1141, 1142, 189, 1169, 266, + /* 1050 */ 266, 466, 388, 541, 1184, 544, 1168, 263, 144, 487, + /* 1060 */ 920, 544, 541, 122, 112, 1163, 1163, 1004, 1007, 997, + /* 1070 */ 997, 119, 119, 120, 120, 120, 120, 71, 71, 1140, + /* 1080 */ 1170, 1270, 1170, 13, 13, 896, 1068, 1161, 544, 466, + /* 1090 */ 895, 107, 536, 1489, 4, 1266, 1107, 6, 523, 1047, + /* 1100 */ 12, 1069, 1090, 1568, 311, 453, 1568, 518, 539, 1107, + /* 1110 */ 56, 56, 1107, 1487, 421, 1356, 1070, 6, 343, 285, + /* 1120 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115, + /* 1130 */ 422, 423, 1269, 319, 1140, 1141, 1142, 876, 266, 266, + /* 1140 */ 1275, 107, 536, 533, 4, 1486, 293, 877, 1209, 6, + /* 1150 */ 210, 541, 541, 164, 1540, 494, 414, 865, 539, 267, + /* 1160 */ 267, 1212, 396, 509, 497, 204, 266, 266, 394, 529, + /* 1170 */ 8, 984, 541, 517, 544, 920, 456, 105, 105, 541, + /* 1180 */ 1088, 423, 266, 266, 106, 415, 423, 546, 545, 266, + /* 1190 */ 266, 974, 516, 533, 1371, 541, 15, 15, 266, 266, + /* 1200 */ 454, 1118, 541, 266, 266, 1068, 1370, 513, 290, 535, + /* 1210 */ 544, 541, 512, 97, 442, 314, 541, 544, 920, 125, + /* 1220 */ 1069, 984, 974, 974, 976, 977, 27, 105, 105, 399, + /* 1230 */ 341, 1509, 44, 44, 106, 1070, 423, 546, 545, 57, + /* 1240 */ 57, 974, 341, 1509, 107, 536, 544, 4, 460, 399, + /* 1250 */ 214, 1118, 457, 294, 375, 1089, 532, 297, 544, 537, + /* 1260 */ 396, 539, 290, 535, 104, 244, 102, 524, 58, 58, + /* 1270 */ 544, 109, 974, 974, 976, 977, 27, 1514, 1129, 425, + /* 1280 */ 59, 59, 270, 237, 423, 138, 95, 373, 373, 372, + /* 1290 */ 255, 370, 60, 60, 815, 1178, 533, 544, 273, 544, + /* 1300 */ 1161, 843, 387, 386, 544, 1307, 544, 215, 210, 296, + /* 1310 */ 513, 847, 544, 265, 208, 514, 1306, 295, 274, 61, + /* 1320 */ 61, 62, 62, 436, 984, 1160, 45, 45, 46, 46, + /* 1330 */ 105, 105, 1184, 920, 47, 47, 1474, 106, 544, 423, + /* 1340 */ 546, 545, 218, 544, 974, 935, 1085, 217, 544, 377, + /* 1350 */ 395, 107, 536, 936, 4, 156, 1161, 843, 158, 544, + /* 1360 */ 49, 49, 141, 544, 38, 50, 50, 544, 539, 307, + /* 1370 */ 63, 63, 544, 1448, 216, 974, 974, 976, 977, 27, + /* 1380 */ 444, 64, 64, 544, 1447, 65, 65, 544, 524, 14, + /* 1390 */ 14, 423, 458, 544, 66, 66, 310, 544, 316, 97, + /* 1400 */ 1034, 544, 961, 533, 268, 127, 127, 544, 391, 67, + /* 1410 */ 67, 544, 978, 290, 535, 52, 52, 513, 544, 68, + /* 1420 */ 68, 1294, 512, 69, 69, 397, 165, 855, 854, 53, + /* 1430 */ 53, 984, 966, 151, 151, 243, 430, 105, 105, 199, + /* 1440 */ 152, 152, 448, 1303, 106, 243, 423, 546, 545, 1129, + /* 1450 */ 425, 974, 320, 270, 862, 863, 1034, 220, 373, 373, + /* 1460 */ 372, 255, 370, 450, 323, 815, 243, 544, 978, 544, + /* 1470 */ 107, 536, 544, 4, 544, 938, 939, 325, 215, 1046, + /* 1480 */ 296, 1046, 974, 974, 976, 977, 27, 539, 295, 76, + /* 1490 */ 76, 54, 54, 327, 72, 72, 128, 128, 1503, 1254, + /* 1500 */ 107, 536, 544, 4, 1045, 544, 1045, 531, 1238, 544, + /* 1510 */ 423, 544, 315, 334, 544, 97, 544, 539, 217, 544, + /* 1520 */ 472, 1528, 533, 239, 73, 73, 156, 129, 129, 158, + /* 1530 */ 467, 130, 130, 126, 126, 344, 150, 150, 149, 149, + /* 1540 */ 423, 134, 134, 329, 1030, 216, 97, 239, 929, 345, + /* 1550 */ 984, 243, 533, 1315, 339, 544, 105, 105, 900, 1355, + /* 1560 */ 544, 1290, 258, 106, 338, 423, 546, 545, 544, 1301, + /* 1570 */ 974, 893, 99, 536, 109, 4, 544, 133, 133, 391, + /* 1580 */ 984, 197, 131, 131, 290, 535, 105, 105, 530, 539, + /* 1590 */ 132, 132, 1361, 106, 1219, 423, 546, 545, 75, 75, + /* 1600 */ 974, 974, 974, 976, 977, 27, 544, 430, 826, 1211, + /* 1610 */ 894, 139, 423, 109, 544, 1200, 1199, 1201, 1522, 544, + /* 1620 */ 201, 544, 11, 374, 533, 1287, 347, 349, 77, 77, + /* 1630 */ 1340, 974, 974, 976, 977, 27, 74, 74, 351, 213, + /* 1640 */ 435, 43, 43, 48, 48, 302, 477, 309, 1348, 382, + /* 1650 */ 353, 452, 984, 337, 1237, 1420, 1419, 205, 105, 105, + /* 1660 */ 192, 367, 193, 534, 1525, 106, 1178, 423, 546, 545, + /* 1670 */ 247, 167, 974, 270, 1467, 200, 1465, 1175, 373, 373, + /* 1680 */ 372, 255, 370, 398, 79, 815, 83, 82, 1425, 446, + /* 1690 */ 161, 177, 169, 95, 1337, 438, 172, 173, 215, 174, + /* 1700 */ 296, 175, 35, 974, 974, 976, 977, 27, 295, 1345, + /* 1710 */ 439, 470, 223, 36, 379, 445, 1414, 381, 459, 1351, + /* 1720 */ 181, 227, 88, 465, 259, 229, 1436, 318, 186, 468, + /* 1730 */ 322, 230, 384, 1202, 231, 486, 1257, 1256, 217, 411, + /* 1740 */ 1255, 1248, 90, 847, 206, 413, 156, 505, 1539, 158, + /* 1750 */ 1226, 1538, 283, 1508, 1227, 336, 385, 284, 1225, 496, + /* 1760 */ 1537, 1298, 94, 346, 348, 216, 1247, 499, 1299, 245, + /* 1770 */ 246, 1297, 416, 350, 1494, 124, 1493, 10, 524, 361, + /* 1780 */ 1400, 101, 96, 288, 508, 253, 1135, 1208, 34, 1296, + /* 1790 */ 547, 254, 256, 257, 392, 548, 1197, 1192, 359, 391, + /* 1800 */ 1280, 1279, 196, 365, 290, 535, 366, 352, 1452, 1322, + /* 1810 */ 1321, 1453, 153, 137, 281, 154, 802, 424, 155, 1451, + /* 1820 */ 1450, 198, 292, 202, 203, 78, 212, 430, 271, 135, + /* 1830 */ 1044, 1042, 958, 168, 219, 157, 170, 879, 308, 222, + /* 1840 */ 1058, 176, 159, 962, 400, 84, 402, 178, 85, 86, + /* 1850 */ 87, 166, 160, 393, 1061, 224, 225, 1057, 146, 18, + /* 1860 */ 226, 317, 1050, 1172, 243, 464, 182, 228, 37, 183, + /* 1870 */ 817, 469, 338, 232, 330, 481, 184, 89, 845, 19, + /* 1880 */ 20, 92, 473, 478, 333, 91, 162, 858, 147, 488, + /* 1890 */ 282, 1123, 148, 1010, 928, 1093, 39, 93, 40, 495, + /* 1900 */ 1094, 187, 498, 207, 262, 264, 923, 242, 1109, 109, + /* 1910 */ 1113, 1111, 1097, 33, 21, 1117, 520, 1025, 22, 23, + /* 1920 */ 24, 1116, 25, 190, 97, 1011, 1009, 26, 1013, 1067, + /* 1930 */ 248, 7, 1066, 249, 1014, 28, 41, 889, 979, 827, + /* 1940 */ 108, 29, 250, 540, 251, 1530, 371, 368, 1131, 1130, + /* 1950 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1529, }; static const YYCODETYPE yy_lookahead[] = { - /* 0 */ 19, 95, 53, 97, 22, 24, 24, 101, 27, 28, - /* 10 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, - /* 20 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48, - /* 30 */ 49, 50, 51, 52, 53, 19, 55, 55, 132, 133, - /* 40 */ 134, 1, 2, 27, 28, 29, 30, 31, 32, 33, - /* 50 */ 34, 35, 36, 37, 38, 39, 40, 41, 187, 43, - /* 60 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - /* 70 */ 47, 48, 49, 50, 51, 52, 53, 61, 97, 97, - /* 80 */ 19, 49, 50, 51, 52, 53, 70, 26, 27, 28, - /* 90 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, - /* 100 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48, - /* 110 */ 49, 50, 51, 52, 53, 144, 145, 146, 147, 19, - /* 120 */ 16, 22, 92, 172, 173, 52, 53, 27, 28, 29, - /* 130 */ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, - /* 140 */ 40, 41, 81, 43, 44, 45, 46, 47, 48, 49, - /* 150 */ 50, 51, 52, 53, 55, 56, 19, 152, 207, 208, - /* 160 */ 115, 24, 117, 118, 27, 28, 29, 30, 31, 32, - /* 170 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 79, - /* 180 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 190 */ 53, 19, 88, 157, 90, 23, 97, 98, 193, 27, - /* 200 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, - /* 210 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47, - /* 220 */ 48, 49, 50, 51, 52, 53, 19, 22, 23, 172, - /* 230 */ 23, 26, 119, 120, 27, 28, 29, 30, 31, 32, - /* 240 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187, - /* 250 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 260 */ 53, 19, 22, 23, 228, 23, 26, 231, 152, 27, - /* 270 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, - /* 280 */ 38, 39, 40, 41, 172, 43, 44, 45, 46, 47, - /* 290 */ 48, 49, 50, 51, 52, 53, 19, 221, 222, 223, - /* 300 */ 23, 96, 152, 172, 27, 28, 29, 30, 31, 32, - /* 310 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152, - /* 320 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 330 */ 53, 19, 0, 1, 2, 23, 96, 190, 191, 27, - /* 340 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, - /* 350 */ 38, 39, 40, 41, 238, 43, 44, 45, 46, 47, - /* 360 */ 48, 49, 50, 51, 52, 53, 19, 185, 218, 221, - /* 370 */ 222, 223, 152, 152, 27, 28, 29, 30, 31, 32, - /* 380 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 241, - /* 390 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 400 */ 53, 19, 152, 168, 169, 170, 22, 190, 191, 27, - /* 410 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, - /* 420 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47, - /* 430 */ 48, 49, 50, 51, 52, 53, 19, 19, 218, 55, - /* 440 */ 56, 24, 22, 152, 27, 28, 29, 30, 31, 32, - /* 450 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152, - /* 460 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 470 */ 53, 250, 194, 195, 56, 55, 56, 55, 19, 172, - /* 480 */ 173, 97, 98, 152, 206, 138, 27, 28, 29, 30, - /* 490 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - /* 500 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50, - /* 510 */ 51, 52, 53, 19, 207, 208, 152, 97, 98, 97, - /* 520 */ 138, 27, 28, 29, 30, 31, 32, 33, 34, 35, - /* 530 */ 36, 37, 38, 39, 40, 41, 181, 43, 44, 45, - /* 540 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 30, - /* 550 */ 31, 32, 33, 247, 248, 19, 152, 28, 29, 30, - /* 560 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - /* 570 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50, - /* 580 */ 51, 52, 53, 19, 168, 169, 170, 238, 19, 53, - /* 590 */ 152, 172, 173, 29, 30, 31, 32, 33, 34, 35, - /* 600 */ 36, 37, 38, 39, 40, 41, 152, 43, 44, 45, - /* 610 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 20, - /* 620 */ 101, 22, 23, 169, 170, 56, 207, 85, 55, 56, - /* 630 */ 23, 19, 20, 26, 22, 99, 100, 101, 102, 103, - /* 640 */ 104, 105, 238, 152, 152, 210, 47, 48, 112, 152, - /* 650 */ 108, 109, 110, 54, 55, 56, 221, 222, 223, 47, - /* 660 */ 48, 119, 120, 172, 173, 66, 54, 55, 56, 152, - /* 670 */ 97, 98, 99, 148, 149, 102, 103, 104, 66, 154, - /* 680 */ 23, 156, 83, 26, 230, 152, 113, 152, 163, 194, - /* 690 */ 195, 92, 92, 30, 95, 83, 97, 98, 207, 208, - /* 700 */ 101, 206, 179, 180, 92, 172, 173, 95, 152, 97, - /* 710 */ 98, 188, 99, 101, 219, 102, 103, 104, 152, 119, - /* 720 */ 120, 196, 55, 56, 19, 20, 113, 22, 193, 163, - /* 730 */ 11, 132, 133, 134, 135, 136, 24, 65, 172, 173, - /* 740 */ 207, 208, 250, 152, 132, 133, 134, 135, 136, 193, - /* 750 */ 78, 84, 47, 48, 49, 98, 199, 152, 86, 54, - /* 760 */ 55, 56, 196, 152, 97, 98, 209, 55, 163, 244, - /* 770 */ 107, 66, 152, 207, 208, 164, 175, 172, 173, 19, - /* 780 */ 20, 124, 22, 111, 38, 39, 40, 41, 83, 43, - /* 790 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - /* 800 */ 95, 196, 97, 98, 85, 152, 101, 47, 48, 97, - /* 810 */ 85, 92, 207, 193, 54, 55, 56, 92, 49, 175, - /* 820 */ 55, 56, 221, 222, 223, 12, 66, 108, 109, 110, - /* 830 */ 137, 163, 139, 108, 109, 110, 26, 132, 133, 134, - /* 840 */ 135, 136, 152, 83, 43, 44, 45, 46, 47, 48, - /* 850 */ 49, 50, 51, 52, 53, 95, 26, 97, 98, 55, - /* 860 */ 56, 101, 97, 98, 196, 221, 222, 223, 146, 147, - /* 870 */ 57, 171, 152, 22, 26, 19, 20, 49, 22, 179, - /* 880 */ 108, 109, 110, 55, 56, 116, 73, 219, 75, 124, - /* 890 */ 121, 152, 132, 133, 134, 135, 136, 163, 85, 152, - /* 900 */ 232, 97, 98, 47, 48, 237, 55, 56, 98, 5, - /* 910 */ 54, 55, 56, 193, 10, 11, 12, 13, 14, 172, - /* 920 */ 173, 17, 66, 47, 48, 97, 98, 152, 124, 152, - /* 930 */ 196, 55, 56, 186, 124, 152, 106, 160, 152, 83, - /* 940 */ 152, 164, 152, 61, 22, 211, 212, 152, 97, 98, - /* 950 */ 152, 95, 70, 97, 98, 172, 173, 101, 172, 173, - /* 960 */ 172, 173, 172, 173, 60, 181, 62, 172, 173, 47, - /* 970 */ 48, 123, 186, 97, 98, 71, 100, 55, 56, 152, - /* 980 */ 181, 186, 21, 107, 152, 109, 82, 163, 132, 133, - /* 990 */ 134, 135, 136, 89, 16, 207, 92, 93, 19, 172, - /* 1000 */ 173, 169, 170, 195, 55, 56, 12, 152, 132, 30, - /* 1010 */ 134, 47, 48, 186, 206, 225, 152, 95, 114, 97, - /* 1020 */ 196, 245, 246, 101, 152, 38, 39, 40, 41, 42, - /* 1030 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 1040 */ 53, 152, 163, 219, 152, 141, 97, 98, 193, 152, - /* 1050 */ 152, 57, 91, 164, 132, 133, 134, 152, 55, 152, - /* 1060 */ 152, 237, 230, 152, 103, 193, 88, 73, 90, 75, - /* 1070 */ 172, 173, 183, 152, 185, 196, 152, 172, 173, 172, - /* 1080 */ 173, 217, 152, 172, 173, 152, 107, 22, 152, 24, - /* 1090 */ 193, 112, 152, 172, 173, 152, 132, 242, 134, 152, - /* 1100 */ 97, 140, 152, 92, 152, 172, 173, 152, 172, 173, - /* 1110 */ 152, 100, 172, 173, 152, 172, 173, 152, 140, 172, - /* 1120 */ 173, 152, 172, 173, 172, 173, 152, 172, 173, 152, - /* 1130 */ 172, 173, 152, 152, 172, 173, 152, 172, 173, 213, - /* 1140 */ 152, 172, 173, 152, 152, 152, 172, 173, 152, 172, - /* 1150 */ 173, 152, 172, 173, 152, 210, 172, 173, 152, 26, - /* 1160 */ 172, 173, 152, 172, 173, 172, 173, 152, 172, 173, - /* 1170 */ 152, 172, 173, 152, 172, 173, 152, 59, 172, 173, - /* 1180 */ 152, 63, 172, 173, 152, 193, 152, 152, 152, 152, - /* 1190 */ 172, 173, 152, 172, 173, 77, 172, 173, 152, 152, - /* 1200 */ 172, 173, 152, 152, 172, 173, 172, 173, 172, 173, - /* 1210 */ 152, 22, 172, 173, 152, 152, 152, 22, 172, 173, - /* 1220 */ 152, 152, 152, 172, 173, 152, 7, 8, 9, 163, - /* 1230 */ 172, 173, 22, 23, 172, 173, 172, 173, 166, 167, - /* 1240 */ 172, 173, 172, 173, 55, 172, 173, 22, 23, 108, - /* 1250 */ 109, 110, 217, 152, 217, 166, 167, 163, 163, 163, - /* 1260 */ 163, 163, 196, 130, 217, 211, 212, 217, 116, 23, - /* 1270 */ 22, 101, 26, 121, 23, 23, 23, 26, 26, 26, - /* 1280 */ 23, 23, 112, 26, 26, 37, 97, 100, 101, 55, - /* 1290 */ 196, 196, 196, 196, 196, 23, 23, 55, 26, 26, - /* 1300 */ 7, 8, 23, 152, 23, 26, 96, 26, 132, 132, - /* 1310 */ 134, 134, 23, 152, 152, 26, 152, 122, 152, 191, - /* 1320 */ 152, 96, 234, 152, 152, 152, 152, 152, 197, 210, - /* 1330 */ 152, 97, 152, 152, 210, 233, 210, 198, 150, 97, - /* 1340 */ 184, 201, 239, 214, 214, 201, 239, 180, 214, 227, - /* 1350 */ 200, 198, 155, 67, 243, 176, 69, 175, 175, 175, - /* 1360 */ 122, 159, 159, 240, 159, 240, 22, 220, 27, 130, - /* 1370 */ 201, 18, 159, 18, 189, 158, 158, 220, 192, 159, - /* 1380 */ 137, 236, 192, 192, 192, 189, 74, 189, 159, 235, - /* 1390 */ 159, 158, 22, 177, 201, 201, 159, 107, 158, 177, - /* 1400 */ 159, 174, 158, 76, 174, 182, 174, 106, 182, 125, - /* 1410 */ 174, 107, 177, 22, 159, 216, 215, 137, 159, 53, - /* 1420 */ 216, 176, 215, 174, 174, 216, 215, 215, 174, 229, - /* 1430 */ 216, 129, 224, 177, 126, 229, 127, 177, 128, 25, - /* 1440 */ 162, 226, 26, 161, 13, 153, 6, 153, 151, 151, - /* 1450 */ 151, 151, 205, 165, 178, 178, 165, 4, 3, 22, - /* 1460 */ 165, 142, 15, 94, 202, 204, 203, 201, 16, 23, - /* 1470 */ 249, 23, 120, 249, 246, 111, 131, 123, 20, 16, - /* 1480 */ 1, 125, 123, 111, 56, 64, 37, 37, 131, 122, - /* 1490 */ 1, 37, 5, 37, 22, 107, 26, 80, 140, 80, - /* 1500 */ 87, 72, 107, 20, 24, 19, 112, 105, 23, 79, - /* 1510 */ 22, 79, 22, 22, 22, 58, 22, 79, 23, 68, - /* 1520 */ 23, 23, 26, 116, 22, 26, 23, 22, 122, 23, - /* 1530 */ 23, 56, 64, 22, 124, 26, 26, 64, 64, 23, - /* 1540 */ 23, 23, 23, 11, 23, 22, 26, 23, 22, 24, - /* 1550 */ 1, 23, 22, 26, 251, 24, 23, 22, 122, 23, - /* 1560 */ 23, 22, 15, 122, 122, 122, 23, + /* 0 */ 189, 211, 189, 189, 218, 189, 220, 189, 267, 268, + /* 10 */ 269, 189, 210, 189, 228, 189, 267, 268, 269, 19, + /* 20 */ 218, 189, 211, 212, 211, 212, 211, 211, 212, 211, + /* 30 */ 212, 31, 211, 211, 212, 211, 212, 288, 300, 39, + /* 40 */ 21, 189, 304, 43, 44, 45, 46, 47, 48, 49, + /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 225, 19, + /* 60 */ 189, 183, 184, 185, 186, 189, 248, 263, 236, 191, + /* 70 */ 248, 193, 248, 197, 208, 257, 262, 201, 200, 257, + /* 80 */ 200, 257, 81, 43, 44, 45, 46, 47, 48, 49, + /* 90 */ 50, 51, 52, 53, 54, 55, 56, 57, 189, 80, + /* 100 */ 189, 101, 102, 103, 104, 105, 106, 107, 108, 109, + /* 110 */ 110, 111, 234, 235, 234, 235, 305, 306, 305, 118, + /* 120 */ 307, 305, 306, 297, 298, 247, 86, 247, 88, 19, + /* 130 */ 259, 251, 252, 267, 268, 269, 26, 136, 137, 261, + /* 140 */ 121, 101, 102, 103, 104, 105, 106, 107, 108, 109, + /* 150 */ 110, 111, 59, 43, 44, 45, 46, 47, 48, 49, + /* 160 */ 50, 51, 52, 53, 54, 55, 56, 57, 259, 291, + /* 170 */ 105, 106, 107, 108, 109, 110, 111, 158, 189, 69, + /* 180 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + /* 190 */ 111, 107, 108, 109, 110, 111, 205, 206, 207, 19, + /* 200 */ 19, 54, 55, 56, 57, 58, 29, 114, 115, 116, + /* 210 */ 33, 101, 102, 103, 104, 105, 106, 107, 108, 109, + /* 220 */ 110, 111, 233, 43, 44, 45, 46, 47, 48, 49, + /* 230 */ 50, 51, 52, 53, 54, 55, 56, 57, 19, 126, + /* 240 */ 127, 148, 65, 24, 214, 200, 59, 67, 101, 102, + /* 250 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 22, + /* 260 */ 189, 111, 43, 44, 45, 46, 47, 48, 49, 50, + /* 270 */ 51, 52, 53, 54, 55, 56, 57, 206, 207, 234, + /* 280 */ 235, 101, 102, 103, 104, 105, 106, 107, 108, 109, + /* 290 */ 110, 111, 247, 76, 107, 114, 59, 267, 268, 269, + /* 300 */ 189, 114, 115, 116, 162, 163, 89, 19, 263, 92, + /* 310 */ 189, 23, 54, 55, 56, 57, 189, 206, 207, 22, + /* 320 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + /* 330 */ 111, 43, 44, 45, 46, 47, 48, 49, 50, 51, + /* 340 */ 52, 53, 54, 55, 56, 57, 19, 189, 277, 59, + /* 350 */ 23, 114, 115, 116, 46, 47, 48, 49, 61, 101, + /* 360 */ 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, + /* 370 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + /* 380 */ 53, 54, 55, 56, 57, 125, 126, 127, 277, 101, + /* 390 */ 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, + /* 400 */ 59, 189, 189, 276, 114, 115, 116, 117, 73, 59, + /* 410 */ 120, 121, 122, 72, 214, 19, 81, 259, 19, 23, + /* 420 */ 130, 81, 72, 24, 211, 212, 221, 119, 101, 102, + /* 430 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 43, + /* 440 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, + /* 450 */ 54, 55, 56, 57, 19, 114, 115, 116, 23, 208, + /* 460 */ 125, 248, 189, 189, 114, 115, 116, 267, 268, 269, + /* 470 */ 189, 136, 137, 189, 262, 22, 136, 137, 43, 44, + /* 480 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, + /* 490 */ 55, 56, 57, 189, 95, 211, 212, 101, 102, 103, + /* 500 */ 104, 105, 106, 107, 108, 109, 110, 111, 59, 189, + /* 510 */ 111, 189, 59, 76, 294, 295, 117, 118, 119, 120, + /* 520 */ 121, 122, 123, 19, 87, 189, 89, 23, 129, 92, + /* 530 */ 279, 227, 248, 22, 189, 284, 101, 102, 103, 104, + /* 540 */ 105, 106, 107, 108, 109, 110, 111, 43, 44, 45, + /* 550 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, + /* 560 */ 56, 57, 19, 114, 115, 116, 23, 114, 115, 116, + /* 570 */ 59, 117, 299, 300, 120, 121, 122, 304, 189, 189, + /* 580 */ 143, 189, 110, 111, 130, 22, 43, 44, 45, 46, + /* 590 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, + /* 600 */ 57, 211, 212, 211, 212, 101, 102, 103, 104, 105, + /* 610 */ 106, 107, 108, 109, 110, 111, 226, 189, 226, 189, + /* 620 */ 298, 132, 59, 134, 135, 114, 115, 116, 189, 59, + /* 630 */ 285, 19, 7, 8, 9, 23, 205, 206, 207, 211, + /* 640 */ 212, 211, 212, 221, 101, 102, 103, 104, 105, 106, + /* 650 */ 107, 108, 109, 110, 111, 43, 44, 45, 46, 47, + /* 660 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + /* 670 */ 19, 181, 182, 183, 184, 185, 186, 114, 115, 116, + /* 680 */ 189, 191, 133, 193, 114, 115, 116, 138, 299, 300, + /* 690 */ 200, 22, 201, 304, 43, 44, 45, 46, 47, 48, + /* 700 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, + /* 710 */ 189, 141, 189, 101, 102, 103, 104, 105, 106, 107, + /* 720 */ 108, 109, 110, 111, 234, 235, 22, 23, 59, 184, + /* 730 */ 26, 186, 211, 212, 211, 212, 191, 247, 193, 19, + /* 740 */ 66, 105, 106, 73, 189, 200, 189, 226, 74, 226, + /* 750 */ 22, 261, 101, 102, 103, 104, 105, 106, 107, 108, + /* 760 */ 109, 110, 111, 43, 44, 45, 46, 47, 48, 49, + /* 770 */ 50, 51, 52, 53, 54, 55, 56, 57, 189, 234, + /* 780 */ 235, 291, 19, 114, 115, 116, 150, 59, 152, 189, + /* 790 */ 233, 236, 247, 59, 189, 125, 126, 127, 59, 300, + /* 800 */ 211, 212, 128, 304, 100, 19, 261, 156, 45, 46, + /* 810 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, + /* 820 */ 57, 101, 102, 103, 104, 105, 106, 107, 108, 109, + /* 830 */ 110, 111, 46, 233, 189, 189, 291, 248, 99, 189, + /* 840 */ 125, 126, 127, 115, 26, 200, 289, 230, 231, 115, + /* 850 */ 200, 16, 189, 114, 115, 189, 211, 212, 119, 221, + /* 860 */ 189, 211, 212, 258, 101, 102, 103, 104, 105, 106, + /* 870 */ 107, 108, 109, 110, 111, 189, 156, 211, 212, 234, + /* 880 */ 235, 189, 211, 212, 234, 235, 22, 201, 189, 150, + /* 890 */ 151, 152, 247, 248, 76, 16, 19, 247, 248, 113, + /* 900 */ 189, 24, 257, 211, 212, 189, 26, 89, 262, 223, + /* 910 */ 92, 225, 77, 189, 79, 129, 19, 53, 226, 248, + /* 920 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + /* 930 */ 53, 54, 55, 56, 57, 236, 19, 271, 189, 99, + /* 940 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + /* 950 */ 53, 54, 55, 56, 57, 115, 77, 59, 79, 119, + /* 960 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + /* 970 */ 53, 54, 55, 56, 57, 259, 22, 23, 101, 102, + /* 980 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 59, + /* 990 */ 150, 151, 152, 158, 22, 244, 24, 246, 101, 102, + /* 1000 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 285, + /* 1010 */ 189, 189, 114, 115, 116, 200, 136, 137, 101, 102, + /* 1020 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 230, + /* 1030 */ 231, 59, 211, 212, 285, 105, 106, 189, 19, 141, + /* 1040 */ 234, 235, 239, 113, 114, 115, 116, 226, 118, 234, + /* 1050 */ 235, 189, 249, 247, 100, 189, 126, 23, 236, 107, + /* 1060 */ 26, 189, 247, 44, 45, 46, 47, 48, 49, 50, + /* 1070 */ 51, 52, 53, 54, 55, 56, 57, 211, 212, 59, + /* 1080 */ 150, 233, 152, 211, 212, 133, 12, 115, 189, 189, + /* 1090 */ 138, 19, 20, 300, 22, 233, 76, 304, 226, 11, + /* 1100 */ 208, 27, 22, 23, 200, 19, 26, 87, 36, 89, + /* 1110 */ 211, 212, 92, 300, 248, 189, 42, 304, 189, 250, + /* 1120 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + /* 1130 */ 111, 59, 200, 233, 114, 115, 116, 63, 234, 235, + /* 1140 */ 235, 19, 20, 71, 22, 300, 189, 73, 200, 304, + /* 1150 */ 116, 247, 247, 81, 23, 200, 227, 26, 36, 234, + /* 1160 */ 235, 203, 204, 143, 200, 26, 234, 235, 194, 200, + /* 1170 */ 48, 99, 247, 66, 189, 141, 284, 105, 106, 247, + /* 1180 */ 100, 59, 234, 235, 112, 259, 114, 115, 116, 234, + /* 1190 */ 235, 119, 85, 71, 266, 247, 211, 212, 234, 235, + /* 1200 */ 114, 94, 247, 234, 235, 12, 266, 85, 136, 137, + /* 1210 */ 189, 247, 90, 26, 126, 127, 247, 189, 26, 22, + /* 1220 */ 27, 99, 150, 151, 152, 153, 154, 105, 106, 189, + /* 1230 */ 302, 303, 211, 212, 112, 42, 114, 115, 116, 211, + /* 1240 */ 212, 119, 302, 303, 19, 20, 189, 22, 274, 189, + /* 1250 */ 15, 144, 278, 189, 22, 23, 63, 189, 189, 203, + /* 1260 */ 204, 36, 136, 137, 155, 24, 157, 143, 211, 212, + /* 1270 */ 189, 26, 150, 151, 152, 153, 154, 0, 1, 2, + /* 1280 */ 211, 212, 5, 46, 59, 161, 147, 10, 11, 12, + /* 1290 */ 13, 14, 211, 212, 17, 60, 71, 189, 258, 189, + /* 1300 */ 59, 59, 105, 106, 189, 189, 189, 30, 116, 32, + /* 1310 */ 85, 124, 189, 251, 252, 90, 189, 40, 258, 211, + /* 1320 */ 212, 211, 212, 189, 99, 26, 211, 212, 211, 212, + /* 1330 */ 105, 106, 100, 141, 211, 212, 189, 112, 189, 114, + /* 1340 */ 115, 116, 24, 189, 119, 31, 23, 70, 189, 26, + /* 1350 */ 113, 19, 20, 39, 22, 78, 115, 115, 81, 189, + /* 1360 */ 211, 212, 22, 189, 24, 211, 212, 189, 36, 189, + /* 1370 */ 211, 212, 189, 189, 97, 150, 151, 152, 153, 154, + /* 1380 */ 127, 211, 212, 189, 189, 211, 212, 189, 143, 211, + /* 1390 */ 212, 59, 189, 189, 211, 212, 23, 189, 189, 26, + /* 1400 */ 59, 189, 149, 71, 22, 211, 212, 189, 131, 211, + /* 1410 */ 212, 189, 59, 136, 137, 211, 212, 85, 189, 211, + /* 1420 */ 212, 253, 90, 211, 212, 292, 293, 118, 119, 211, + /* 1430 */ 212, 99, 23, 211, 212, 26, 159, 105, 106, 140, + /* 1440 */ 211, 212, 23, 189, 112, 26, 114, 115, 116, 1, + /* 1450 */ 2, 119, 189, 5, 7, 8, 115, 139, 10, 11, + /* 1460 */ 12, 13, 14, 23, 189, 17, 26, 189, 115, 189, + /* 1470 */ 19, 20, 189, 22, 189, 83, 84, 189, 30, 150, + /* 1480 */ 32, 152, 150, 151, 152, 153, 154, 36, 40, 211, + /* 1490 */ 212, 211, 212, 189, 211, 212, 211, 212, 309, 189, + /* 1500 */ 19, 20, 189, 22, 150, 189, 152, 231, 189, 189, + /* 1510 */ 59, 189, 23, 189, 189, 26, 189, 36, 70, 189, + /* 1520 */ 23, 139, 71, 26, 211, 212, 78, 211, 212, 81, + /* 1530 */ 281, 211, 212, 211, 212, 189, 211, 212, 211, 212, + /* 1540 */ 59, 211, 212, 23, 23, 97, 26, 26, 23, 189, + /* 1550 */ 99, 26, 71, 189, 119, 189, 105, 106, 107, 189, + /* 1560 */ 189, 189, 280, 112, 129, 114, 115, 116, 189, 189, + /* 1570 */ 119, 23, 19, 20, 26, 22, 189, 211, 212, 131, + /* 1580 */ 99, 237, 211, 212, 136, 137, 105, 106, 189, 36, + /* 1590 */ 211, 212, 189, 112, 189, 114, 115, 116, 211, 212, + /* 1600 */ 119, 150, 151, 152, 153, 154, 189, 159, 23, 189, + /* 1610 */ 23, 26, 59, 26, 189, 189, 189, 189, 189, 189, + /* 1620 */ 209, 189, 238, 187, 71, 250, 250, 250, 211, 212, + /* 1630 */ 241, 150, 151, 152, 153, 154, 211, 212, 250, 290, + /* 1640 */ 254, 211, 212, 211, 212, 254, 215, 286, 241, 241, + /* 1650 */ 254, 286, 99, 214, 220, 214, 214, 224, 105, 106, + /* 1660 */ 244, 240, 244, 273, 192, 112, 60, 114, 115, 116, + /* 1670 */ 139, 290, 119, 5, 196, 238, 196, 38, 10, 11, + /* 1680 */ 12, 13, 14, 196, 287, 17, 148, 287, 276, 113, + /* 1690 */ 43, 22, 229, 147, 241, 18, 232, 232, 30, 232, + /* 1700 */ 32, 232, 264, 150, 151, 152, 153, 154, 40, 265, + /* 1710 */ 196, 18, 195, 264, 241, 241, 241, 265, 196, 229, + /* 1720 */ 229, 195, 155, 62, 196, 195, 283, 282, 22, 216, + /* 1730 */ 196, 195, 216, 196, 195, 113, 213, 213, 70, 64, + /* 1740 */ 213, 222, 22, 124, 162, 111, 78, 142, 219, 81, + /* 1750 */ 215, 219, 275, 303, 213, 213, 216, 275, 213, 216, + /* 1760 */ 213, 256, 113, 255, 255, 97, 222, 216, 256, 196, + /* 1770 */ 91, 256, 82, 255, 308, 146, 308, 22, 143, 196, + /* 1780 */ 270, 155, 145, 272, 144, 25, 13, 199, 26, 256, + /* 1790 */ 198, 190, 190, 6, 296, 188, 188, 188, 244, 131, + /* 1800 */ 245, 245, 243, 242, 136, 137, 241, 255, 208, 260, + /* 1810 */ 260, 208, 202, 217, 217, 202, 4, 3, 202, 208, + /* 1820 */ 208, 22, 160, 209, 209, 208, 15, 159, 98, 16, + /* 1830 */ 23, 23, 137, 148, 24, 128, 140, 20, 16, 142, + /* 1840 */ 1, 140, 128, 149, 61, 53, 37, 148, 53, 53, + /* 1850 */ 53, 293, 128, 296, 114, 34, 139, 1, 5, 22, + /* 1860 */ 113, 158, 68, 75, 26, 41, 68, 139, 24, 113, + /* 1870 */ 20, 19, 129, 123, 23, 96, 22, 22, 59, 22, + /* 1880 */ 22, 147, 67, 67, 24, 22, 37, 28, 23, 22, + /* 1890 */ 67, 23, 23, 23, 114, 23, 22, 26, 22, 24, + /* 1900 */ 23, 22, 24, 139, 23, 23, 141, 34, 88, 26, + /* 1910 */ 75, 86, 23, 22, 34, 75, 24, 23, 34, 34, + /* 1920 */ 34, 93, 34, 26, 26, 23, 23, 34, 23, 23, + /* 1930 */ 26, 44, 23, 22, 11, 22, 22, 133, 23, 23, + /* 1940 */ 22, 22, 139, 26, 139, 139, 15, 23, 1, 1, + /* 1950 */ 310, 310, 310, 310, 310, 310, 310, 139, 310, 310, + /* 1960 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 1970 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 1980 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 1990 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2000 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2010 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2020 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2030 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2040 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2050 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2060 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2070 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2080 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2090 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2100 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2110 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2120 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, + /* 2130 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, }; -#define YY_SHIFT_USE_DFLT (1567) -#define YY_SHIFT_COUNT (455) -#define YY_SHIFT_MIN (-94) -#define YY_SHIFT_MAX (1549) -static const short yy_shift_ofst[] = { - /* 0 */ 40, 599, 904, 612, 760, 760, 760, 760, 725, -19, - /* 10 */ 16, 16, 100, 760, 760, 760, 760, 760, 760, 760, - /* 20 */ 876, 876, 573, 542, 719, 600, 61, 137, 172, 207, - /* 30 */ 242, 277, 312, 347, 382, 417, 459, 459, 459, 459, - /* 40 */ 459, 459, 459, 459, 459, 459, 459, 459, 459, 459, - /* 50 */ 459, 459, 459, 494, 459, 529, 564, 564, 705, 760, - /* 60 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, - /* 70 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, - /* 80 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760, - /* 90 */ 856, 760, 760, 760, 760, 760, 760, 760, 760, 760, - /* 100 */ 760, 760, 760, 760, 987, 746, 746, 746, 746, 746, - /* 110 */ 801, 23, 32, 949, 961, 979, 964, 964, 949, 73, - /* 120 */ 113, -51, 1567, 1567, 1567, 536, 536, 536, 99, 99, - /* 130 */ 813, 813, 667, 205, 240, 949, 949, 949, 949, 949, - /* 140 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949, - /* 150 */ 949, 949, 949, 949, 949, 332, 1011, 422, 422, 113, - /* 160 */ 30, 30, 30, 30, 30, 30, 1567, 1567, 1567, 922, - /* 170 */ -94, -94, 384, 613, 828, 420, 765, 804, 851, 949, - /* 180 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949, - /* 190 */ 949, 949, 949, 949, 949, 672, 672, 672, 949, 949, - /* 200 */ 657, 949, 949, 949, -18, 949, 949, 994, 949, 949, - /* 210 */ 949, 949, 949, 949, 949, 949, 949, 949, 772, 1118, - /* 220 */ 712, 712, 712, 810, 45, 769, 1219, 1133, 418, 418, - /* 230 */ 569, 1133, 569, 830, 607, 663, 882, 418, 693, 882, - /* 240 */ 882, 848, 1152, 1065, 1286, 1238, 1238, 1287, 1287, 1238, - /* 250 */ 1344, 1341, 1239, 1353, 1353, 1353, 1353, 1238, 1355, 1239, - /* 260 */ 1344, 1341, 1341, 1239, 1238, 1355, 1243, 1312, 1238, 1238, - /* 270 */ 1355, 1370, 1238, 1355, 1238, 1355, 1370, 1290, 1290, 1290, - /* 280 */ 1327, 1370, 1290, 1301, 1290, 1327, 1290, 1290, 1284, 1304, - /* 290 */ 1284, 1304, 1284, 1304, 1284, 1304, 1238, 1391, 1238, 1280, - /* 300 */ 1370, 1366, 1366, 1370, 1302, 1308, 1310, 1309, 1239, 1414, - /* 310 */ 1416, 1431, 1431, 1440, 1440, 1440, 1440, 1567, 1567, 1567, - /* 320 */ 1567, 1567, 1567, 1567, 1567, 519, 978, 1210, 1225, 104, - /* 330 */ 1141, 1189, 1246, 1248, 1251, 1252, 1253, 1257, 1258, 1273, - /* 340 */ 1003, 1187, 1293, 1170, 1272, 1279, 1234, 1281, 1176, 1177, - /* 350 */ 1289, 1242, 1195, 1453, 1455, 1437, 1319, 1447, 1369, 1452, - /* 360 */ 1446, 1448, 1352, 1345, 1364, 1354, 1458, 1356, 1463, 1479, - /* 370 */ 1359, 1357, 1449, 1450, 1454, 1456, 1372, 1428, 1421, 1367, - /* 380 */ 1489, 1487, 1472, 1388, 1358, 1417, 1470, 1419, 1413, 1429, - /* 390 */ 1395, 1480, 1483, 1486, 1394, 1402, 1488, 1430, 1490, 1491, - /* 400 */ 1485, 1492, 1432, 1457, 1494, 1438, 1451, 1495, 1497, 1498, - /* 410 */ 1496, 1407, 1502, 1503, 1505, 1499, 1406, 1506, 1507, 1475, - /* 420 */ 1468, 1511, 1410, 1509, 1473, 1510, 1474, 1516, 1509, 1517, - /* 430 */ 1518, 1519, 1520, 1521, 1523, 1532, 1524, 1526, 1525, 1527, - /* 440 */ 1528, 1530, 1531, 1527, 1533, 1535, 1536, 1537, 1539, 1436, - /* 450 */ 1441, 1442, 1443, 1543, 1547, 1549, +#define YY_SHIFT_COUNT (550) +#define YY_SHIFT_MIN (0) +#define YY_SHIFT_MAX (1948) +static const unsigned short int yy_shift_ofst[] = { + /* 0 */ 1448, 1277, 1668, 1072, 1072, 340, 1122, 1225, 1332, 1481, + /* 10 */ 1481, 1481, 335, 0, 0, 180, 897, 1481, 1481, 1481, + /* 20 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, + /* 30 */ 930, 930, 1020, 1020, 290, 1, 340, 340, 340, 340, + /* 40 */ 340, 340, 40, 110, 219, 288, 327, 396, 435, 504, + /* 50 */ 543, 612, 651, 720, 877, 897, 897, 897, 897, 897, + /* 60 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897, + /* 70 */ 897, 897, 897, 917, 897, 1019, 763, 763, 1451, 1481, + /* 80 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, + /* 90 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, + /* 100 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, + /* 110 */ 1481, 1481, 1553, 1481, 1481, 1481, 1481, 1481, 1481, 1481, + /* 120 */ 1481, 1481, 1481, 1481, 1481, 1481, 147, 258, 258, 258, + /* 130 */ 258, 258, 79, 65, 84, 449, 19, 786, 449, 636, + /* 140 */ 636, 449, 880, 880, 880, 880, 113, 142, 142, 472, + /* 150 */ 150, 1958, 1958, 399, 399, 399, 93, 237, 341, 237, + /* 160 */ 237, 1074, 1074, 437, 350, 704, 1080, 449, 449, 449, + /* 170 */ 449, 449, 449, 449, 449, 449, 449, 449, 449, 449, + /* 180 */ 449, 449, 449, 449, 449, 449, 449, 449, 818, 818, + /* 190 */ 449, 1088, 217, 217, 734, 734, 1124, 1126, 1958, 1958, + /* 200 */ 1958, 739, 840, 840, 453, 454, 511, 187, 563, 570, + /* 210 */ 898, 669, 449, 449, 449, 449, 449, 449, 449, 449, + /* 220 */ 449, 670, 449, 449, 449, 449, 449, 449, 449, 449, + /* 230 */ 449, 449, 449, 449, 674, 674, 674, 449, 449, 449, + /* 240 */ 449, 1034, 449, 449, 449, 972, 1107, 449, 449, 1193, + /* 250 */ 449, 449, 449, 449, 449, 449, 449, 449, 260, 177, + /* 260 */ 489, 1241, 1241, 1241, 1241, 1192, 489, 489, 952, 1197, + /* 270 */ 625, 1235, 1139, 181, 181, 1086, 1139, 1139, 1086, 1187, + /* 280 */ 1131, 1237, 1314, 1314, 1314, 181, 1245, 1245, 1109, 1299, + /* 290 */ 549, 1340, 1606, 1531, 1531, 1639, 1639, 1531, 1538, 1576, + /* 300 */ 1669, 1647, 1546, 1677, 1677, 1677, 1677, 1531, 1693, 1546, + /* 310 */ 1546, 1576, 1669, 1647, 1647, 1546, 1531, 1693, 1567, 1661, + /* 320 */ 1531, 1693, 1706, 1531, 1693, 1531, 1693, 1706, 1622, 1622, + /* 330 */ 1622, 1675, 1720, 1720, 1706, 1622, 1619, 1622, 1675, 1622, + /* 340 */ 1622, 1582, 1706, 1634, 1634, 1706, 1605, 1649, 1605, 1649, + /* 350 */ 1605, 1649, 1605, 1649, 1531, 1679, 1679, 1690, 1690, 1629, + /* 360 */ 1635, 1755, 1531, 1626, 1629, 1637, 1640, 1546, 1760, 1762, + /* 370 */ 1773, 1773, 1787, 1787, 1787, 1958, 1958, 1958, 1958, 1958, + /* 380 */ 1958, 1958, 1958, 1958, 1958, 1958, 1958, 1958, 1958, 1958, + /* 390 */ 308, 835, 954, 1232, 879, 715, 728, 1323, 864, 1318, + /* 400 */ 1253, 1373, 297, 1409, 1419, 1440, 1489, 1497, 1520, 1242, + /* 410 */ 1309, 1447, 1435, 1341, 1521, 1525, 1392, 1548, 1329, 1354, + /* 420 */ 1585, 1587, 1353, 1382, 1812, 1814, 1799, 1662, 1811, 1730, + /* 430 */ 1813, 1807, 1808, 1695, 1685, 1707, 1810, 1696, 1817, 1697, + /* 440 */ 1822, 1839, 1701, 1694, 1714, 1783, 1809, 1699, 1792, 1795, + /* 450 */ 1796, 1797, 1724, 1740, 1821, 1717, 1856, 1853, 1837, 1747, + /* 460 */ 1703, 1794, 1838, 1798, 1788, 1824, 1728, 1756, 1844, 1850, + /* 470 */ 1852, 1743, 1750, 1854, 1815, 1855, 1857, 1851, 1858, 1816, + /* 480 */ 1819, 1860, 1779, 1859, 1863, 1823, 1849, 1865, 1734, 1867, + /* 490 */ 1868, 1869, 1870, 1871, 1872, 1874, 1875, 1877, 1876, 1878, + /* 500 */ 1764, 1881, 1882, 1780, 1873, 1879, 1765, 1883, 1880, 1884, + /* 510 */ 1885, 1886, 1820, 1835, 1825, 1887, 1840, 1828, 1888, 1889, + /* 520 */ 1891, 1892, 1897, 1898, 1893, 1894, 1883, 1902, 1903, 1905, + /* 530 */ 1906, 1904, 1909, 1911, 1923, 1913, 1914, 1915, 1916, 1918, + /* 540 */ 1919, 1917, 1804, 1803, 1805, 1806, 1818, 1924, 1931, 1947, + /* 550 */ 1948, }; -#define YY_REDUCE_USE_DFLT (-130) -#define YY_REDUCE_COUNT (324) -#define YY_REDUCE_MIN (-129) -#define YY_REDUCE_MAX (1300) +#define YY_REDUCE_COUNT (389) +#define YY_REDUCE_MIN (-262) +#define YY_REDUCE_MAX (1617) static const short yy_reduce_ofst[] = { - /* 0 */ -29, 566, 525, 605, -49, 307, 491, 533, 668, 435, - /* 10 */ 601, 644, 148, 747, 786, 795, 419, 788, 827, 790, - /* 20 */ 454, 832, 889, 495, 824, 734, 76, 76, 76, 76, - /* 30 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, - /* 40 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, - /* 50 */ 76, 76, 76, 76, 76, 76, 76, 76, 783, 898, - /* 60 */ 905, 907, 911, 921, 933, 936, 940, 943, 947, 950, - /* 70 */ 952, 955, 958, 962, 965, 969, 974, 977, 980, 984, - /* 80 */ 988, 991, 993, 996, 999, 1002, 1006, 1010, 1018, 1021, - /* 90 */ 1024, 1028, 1032, 1034, 1036, 1040, 1046, 1051, 1058, 1062, - /* 100 */ 1064, 1068, 1070, 1073, 76, 76, 76, 76, 76, 76, - /* 110 */ 76, 76, 76, 855, 36, 523, 235, 416, 777, 76, - /* 120 */ 278, 76, 76, 76, 76, 700, 700, 700, 150, 220, - /* 130 */ 147, 217, 221, 306, 306, 611, 5, 535, 556, 620, - /* 140 */ 720, 872, 897, 116, 864, 349, 1035, 1037, 404, 1047, - /* 150 */ 992, -129, 1050, 492, 62, 722, 879, 1072, 1089, 808, - /* 160 */ 1066, 1094, 1095, 1096, 1097, 1098, 776, 1054, 557, 57, - /* 170 */ 112, 131, 167, 182, 250, 272, 291, 331, 364, 438, - /* 180 */ 497, 517, 591, 653, 690, 739, 775, 798, 892, 908, - /* 190 */ 924, 930, 1015, 1063, 1069, 355, 784, 799, 981, 1101, - /* 200 */ 926, 1151, 1161, 1162, 945, 1164, 1166, 1128, 1168, 1171, - /* 210 */ 1172, 250, 1173, 1174, 1175, 1178, 1180, 1181, 1088, 1102, - /* 220 */ 1119, 1124, 1126, 926, 1131, 1139, 1188, 1140, 1129, 1130, - /* 230 */ 1103, 1144, 1107, 1179, 1156, 1167, 1182, 1134, 1122, 1183, - /* 240 */ 1184, 1150, 1153, 1197, 1111, 1202, 1203, 1123, 1125, 1205, - /* 250 */ 1147, 1185, 1169, 1186, 1190, 1191, 1192, 1213, 1217, 1193, - /* 260 */ 1157, 1196, 1198, 1194, 1220, 1218, 1145, 1154, 1229, 1231, - /* 270 */ 1233, 1216, 1237, 1240, 1241, 1244, 1222, 1227, 1230, 1232, - /* 280 */ 1223, 1235, 1236, 1245, 1249, 1226, 1250, 1254, 1199, 1201, - /* 290 */ 1204, 1207, 1209, 1211, 1214, 1212, 1255, 1208, 1259, 1215, - /* 300 */ 1256, 1200, 1206, 1260, 1247, 1261, 1263, 1262, 1266, 1278, - /* 310 */ 1282, 1292, 1294, 1297, 1298, 1299, 1300, 1221, 1224, 1228, - /* 320 */ 1288, 1291, 1276, 1277, 1295, + /* 0 */ 490, -122, 545, 645, 650, -120, -189, -187, -184, -182, + /* 10 */ -178, -176, 45, 30, 200, -251, -134, 390, 392, 521, + /* 20 */ 523, 213, 692, 821, 284, 589, 872, 666, 671, 866, + /* 30 */ 71, 111, 273, 389, 686, 815, 904, 932, 948, 955, + /* 40 */ 964, 969, -259, -259, -259, -259, -259, -259, -259, -259, + /* 50 */ -259, -259, -259, -259, -259, -259, -259, -259, -259, -259, + /* 60 */ -259, -259, -259, -259, -259, -259, -259, -259, -259, -259, + /* 70 */ -259, -259, -259, -259, -259, -259, -259, -259, 428, 430, + /* 80 */ 899, 985, 1021, 1028, 1057, 1069, 1081, 1108, 1110, 1115, + /* 90 */ 1117, 1123, 1149, 1154, 1159, 1170, 1174, 1178, 1183, 1194, + /* 100 */ 1198, 1204, 1208, 1212, 1218, 1222, 1229, 1278, 1280, 1283, + /* 110 */ 1285, 1313, 1316, 1320, 1322, 1325, 1327, 1330, 1366, 1371, + /* 120 */ 1379, 1387, 1417, 1425, 1430, 1432, -259, -259, -259, -259, + /* 130 */ -259, -259, -259, -259, -259, 557, 974, -214, -174, -9, + /* 140 */ 431, -124, 806, 925, 806, 925, 251, 928, 940, -259, + /* 150 */ -259, -259, -259, -198, -198, -198, 127, -186, -168, 212, + /* 160 */ 646, 617, 799, -262, 555, 220, 220, 491, 605, 1040, + /* 170 */ 1060, 699, -11, 600, 848, 862, 345, -129, 724, -91, + /* 180 */ 158, 749, 716, 900, 304, 822, 929, 926, 499, 793, + /* 190 */ 322, 892, 813, 845, 958, 1056, 751, 905, 1133, 1062, + /* 200 */ 803, -210, -185, -179, -148, -167, -89, 121, 274, 281, + /* 210 */ 320, 336, 439, 663, 711, 957, 1064, 1068, 1116, 1127, + /* 220 */ 1134, -196, 1147, 1180, 1184, 1195, 1203, 1209, 1254, 1263, + /* 230 */ 1275, 1288, 1304, 1310, 205, 422, 638, 1319, 1324, 1346, + /* 240 */ 1360, 1168, 1364, 1370, 1372, 869, 1189, 1380, 1399, 1276, + /* 250 */ 1403, 121, 1405, 1420, 1426, 1427, 1428, 1429, 1249, 1282, + /* 260 */ 1344, 1375, 1376, 1377, 1388, 1168, 1344, 1344, 1384, 1411, + /* 270 */ 1436, 1349, 1389, 1386, 1391, 1361, 1407, 1408, 1365, 1431, + /* 280 */ 1433, 1434, 1439, 1441, 1442, 1396, 1416, 1418, 1390, 1421, + /* 290 */ 1437, 1472, 1381, 1478, 1480, 1397, 1400, 1487, 1412, 1444, + /* 300 */ 1438, 1463, 1453, 1464, 1465, 1467, 1469, 1514, 1517, 1473, + /* 310 */ 1474, 1452, 1449, 1490, 1491, 1475, 1522, 1526, 1443, 1445, + /* 320 */ 1528, 1530, 1513, 1534, 1536, 1537, 1539, 1516, 1523, 1524, + /* 330 */ 1527, 1519, 1529, 1532, 1540, 1541, 1535, 1542, 1544, 1545, + /* 340 */ 1547, 1450, 1543, 1477, 1482, 1551, 1505, 1508, 1512, 1509, + /* 350 */ 1515, 1518, 1533, 1552, 1573, 1466, 1468, 1549, 1550, 1555, + /* 360 */ 1554, 1510, 1583, 1511, 1556, 1559, 1561, 1565, 1588, 1592, + /* 370 */ 1601, 1602, 1607, 1608, 1609, 1498, 1557, 1558, 1610, 1600, + /* 380 */ 1603, 1611, 1612, 1613, 1596, 1597, 1614, 1615, 1617, 1616, }; static const YYACTIONTYPE yy_default[] = { - /* 0 */ 1281, 1271, 1271, 1271, 1203, 1203, 1203, 1203, 1271, 1096, - /* 10 */ 1125, 1125, 1255, 1332, 1332, 1332, 1332, 1332, 1332, 1202, - /* 20 */ 1332, 1332, 1332, 1332, 1271, 1100, 1131, 1332, 1332, 1332, - /* 30 */ 1332, 1204, 1205, 1332, 1332, 1332, 1254, 1256, 1141, 1140, - /* 40 */ 1139, 1138, 1237, 1112, 1136, 1129, 1133, 1204, 1198, 1199, - /* 50 */ 1197, 1201, 1205, 1332, 1132, 1167, 1182, 1166, 1332, 1332, - /* 60 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 70 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 80 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 90 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 100 */ 1332, 1332, 1332, 1332, 1176, 1181, 1188, 1180, 1177, 1169, - /* 110 */ 1168, 1170, 1171, 1332, 1019, 1067, 1332, 1332, 1332, 1172, - /* 120 */ 1332, 1173, 1185, 1184, 1183, 1262, 1289, 1288, 1332, 1332, - /* 130 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 140 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 150 */ 1332, 1332, 1332, 1332, 1332, 1281, 1271, 1025, 1025, 1332, - /* 160 */ 1271, 1271, 1271, 1271, 1271, 1271, 1267, 1100, 1091, 1332, - /* 170 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 180 */ 1259, 1257, 1332, 1218, 1332, 1332, 1332, 1332, 1332, 1332, - /* 190 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 200 */ 1332, 1332, 1332, 1332, 1096, 1332, 1332, 1332, 1332, 1332, - /* 210 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1283, 1332, 1232, - /* 220 */ 1096, 1096, 1096, 1098, 1080, 1090, 1004, 1135, 1114, 1114, - /* 230 */ 1321, 1135, 1321, 1042, 1303, 1039, 1125, 1114, 1200, 1125, - /* 240 */ 1125, 1097, 1090, 1332, 1324, 1105, 1105, 1323, 1323, 1105, - /* 250 */ 1146, 1070, 1135, 1076, 1076, 1076, 1076, 1105, 1016, 1135, - /* 260 */ 1146, 1070, 1070, 1135, 1105, 1016, 1236, 1318, 1105, 1105, - /* 270 */ 1016, 1211, 1105, 1016, 1105, 1016, 1211, 1068, 1068, 1068, - /* 280 */ 1057, 1211, 1068, 1042, 1068, 1057, 1068, 1068, 1118, 1113, - /* 290 */ 1118, 1113, 1118, 1113, 1118, 1113, 1105, 1206, 1105, 1332, - /* 300 */ 1211, 1215, 1215, 1211, 1130, 1119, 1128, 1126, 1135, 1022, - /* 310 */ 1060, 1286, 1286, 1282, 1282, 1282, 1282, 1329, 1329, 1267, - /* 320 */ 1298, 1298, 1044, 1044, 1298, 1332, 1332, 1332, 1332, 1332, - /* 330 */ 1332, 1293, 1332, 1220, 1332, 1332, 1332, 1332, 1332, 1332, - /* 340 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 350 */ 1332, 1332, 1152, 1332, 1000, 1264, 1332, 1332, 1263, 1332, - /* 360 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 370 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1320, - /* 380 */ 1332, 1332, 1332, 1332, 1332, 1332, 1235, 1234, 1332, 1332, - /* 390 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 400 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, - /* 410 */ 1332, 1082, 1332, 1332, 1332, 1307, 1332, 1332, 1332, 1332, - /* 420 */ 1332, 1332, 1332, 1127, 1332, 1120, 1332, 1332, 1311, 1332, - /* 430 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1273, - /* 440 */ 1332, 1332, 1332, 1272, 1332, 1332, 1332, 1332, 1332, 1154, - /* 450 */ 1332, 1153, 1157, 1332, 1010, 1332, + /* 0 */ 1573, 1573, 1573, 1409, 1186, 1295, 1186, 1186, 1186, 1409, + /* 10 */ 1409, 1409, 1186, 1325, 1325, 1462, 1217, 1186, 1186, 1186, + /* 20 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1408, 1186, 1186, + /* 30 */ 1186, 1186, 1492, 1492, 1186, 1186, 1186, 1186, 1186, 1186, + /* 40 */ 1186, 1186, 1186, 1334, 1186, 1186, 1186, 1186, 1186, 1186, + /* 50 */ 1410, 1411, 1186, 1186, 1186, 1461, 1463, 1426, 1344, 1343, + /* 60 */ 1342, 1341, 1444, 1312, 1339, 1332, 1336, 1404, 1405, 1403, + /* 70 */ 1407, 1411, 1410, 1186, 1335, 1375, 1389, 1374, 1186, 1186, + /* 80 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 90 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 100 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 110 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 120 */ 1186, 1186, 1186, 1186, 1186, 1186, 1383, 1388, 1394, 1387, + /* 130 */ 1384, 1377, 1376, 1378, 1379, 1186, 1207, 1259, 1186, 1186, + /* 140 */ 1186, 1186, 1480, 1479, 1186, 1186, 1217, 1369, 1368, 1380, + /* 150 */ 1381, 1391, 1390, 1469, 1527, 1526, 1427, 1186, 1186, 1186, + /* 160 */ 1186, 1186, 1186, 1492, 1186, 1186, 1186, 1186, 1186, 1186, + /* 170 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 180 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1492, 1492, + /* 190 */ 1186, 1217, 1492, 1492, 1213, 1213, 1319, 1186, 1475, 1295, + /* 200 */ 1286, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 210 */ 1186, 1186, 1186, 1186, 1186, 1466, 1464, 1186, 1186, 1186, + /* 220 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 230 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 240 */ 1186, 1186, 1186, 1186, 1186, 1291, 1186, 1186, 1186, 1186, + /* 250 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1521, 1186, 1439, + /* 260 */ 1273, 1291, 1291, 1291, 1291, 1293, 1274, 1272, 1285, 1218, + /* 270 */ 1193, 1565, 1338, 1314, 1314, 1562, 1338, 1338, 1562, 1234, + /* 280 */ 1543, 1229, 1325, 1325, 1325, 1314, 1319, 1319, 1406, 1292, + /* 290 */ 1285, 1186, 1565, 1300, 1300, 1564, 1564, 1300, 1427, 1347, + /* 300 */ 1353, 1262, 1338, 1268, 1268, 1268, 1268, 1300, 1204, 1338, + /* 310 */ 1338, 1347, 1353, 1262, 1262, 1338, 1300, 1204, 1443, 1559, + /* 320 */ 1300, 1204, 1417, 1300, 1204, 1300, 1204, 1417, 1260, 1260, + /* 330 */ 1260, 1249, 1186, 1186, 1417, 1260, 1234, 1260, 1249, 1260, + /* 340 */ 1260, 1510, 1417, 1421, 1421, 1417, 1318, 1313, 1318, 1313, + /* 350 */ 1318, 1313, 1318, 1313, 1300, 1502, 1502, 1328, 1328, 1333, + /* 360 */ 1319, 1412, 1300, 1186, 1333, 1331, 1329, 1338, 1210, 1252, + /* 370 */ 1524, 1524, 1520, 1520, 1520, 1570, 1570, 1475, 1536, 1217, + /* 380 */ 1217, 1217, 1217, 1536, 1236, 1236, 1218, 1218, 1217, 1536, + /* 390 */ 1186, 1186, 1186, 1186, 1186, 1186, 1531, 1186, 1428, 1304, + /* 400 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 410 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 420 */ 1186, 1186, 1186, 1358, 1186, 1189, 1472, 1186, 1186, 1470, + /* 430 */ 1186, 1186, 1186, 1186, 1186, 1186, 1305, 1186, 1186, 1186, + /* 440 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 450 */ 1186, 1186, 1186, 1186, 1186, 1561, 1186, 1186, 1186, 1186, + /* 460 */ 1186, 1186, 1442, 1441, 1186, 1186, 1302, 1186, 1186, 1186, + /* 470 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 480 */ 1232, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 490 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 500 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1330, 1186, 1186, + /* 510 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 520 */ 1186, 1186, 1507, 1320, 1186, 1186, 1552, 1186, 1186, 1186, + /* 530 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, + /* 540 */ 1186, 1547, 1276, 1360, 1186, 1359, 1363, 1186, 1198, 1186, + /* 550 */ 1186, }; /********** End of lemon-generated parsing tables *****************************/ @@ -136789,36 +156906,52 @@ static const YYACTIONTYPE yy_default[] = { static const YYCODETYPE yyFallback[] = { 0, /* $ => nothing */ 0, /* SEMI => nothing */ - 55, /* EXPLAIN => ID */ - 55, /* QUERY => ID */ - 55, /* PLAN => ID */ - 55, /* BEGIN => ID */ + 59, /* EXPLAIN => ID */ + 59, /* QUERY => ID */ + 59, /* PLAN => ID */ + 59, /* BEGIN => ID */ 0, /* TRANSACTION => nothing */ - 55, /* DEFERRED => ID */ - 55, /* IMMEDIATE => ID */ - 55, /* EXCLUSIVE => ID */ + 59, /* DEFERRED => ID */ + 59, /* IMMEDIATE => ID */ + 59, /* EXCLUSIVE => ID */ 0, /* COMMIT => nothing */ - 55, /* END => ID */ - 55, /* ROLLBACK => ID */ - 55, /* SAVEPOINT => ID */ - 55, /* RELEASE => ID */ + 59, /* END => ID */ + 59, /* ROLLBACK => ID */ + 59, /* SAVEPOINT => ID */ + 59, /* RELEASE => ID */ 0, /* TO => nothing */ 0, /* TABLE => nothing */ 0, /* CREATE => nothing */ - 55, /* IF => ID */ + 59, /* IF => ID */ 0, /* NOT => nothing */ 0, /* EXISTS => nothing */ - 55, /* TEMP => ID */ + 59, /* TEMP => ID */ 0, /* LP => nothing */ 0, /* RP => nothing */ 0, /* AS => nothing */ - 55, /* WITHOUT => ID */ + 59, /* WITHOUT => ID */ 0, /* COMMA => nothing */ + 59, /* ABORT => ID */ + 59, /* ACTION => ID */ + 59, /* AFTER => ID */ + 59, /* ANALYZE => ID */ + 59, /* ASC => ID */ + 59, /* ATTACH => ID */ + 59, /* BEFORE => ID */ + 59, /* BY => ID */ + 59, /* CASCADE => ID */ + 59, /* CAST => ID */ + 59, /* CONFLICT => ID */ + 59, /* DATABASE => ID */ + 59, /* DESC => ID */ + 59, /* DETACH => ID */ + 59, /* EACH => ID */ + 59, /* FAIL => ID */ 0, /* OR => nothing */ 0, /* AND => nothing */ 0, /* IS => nothing */ - 55, /* MATCH => ID */ - 55, /* LIKE_KW => ID */ + 59, /* MATCH => ID */ + 59, /* LIKE_KW => ID */ 0, /* BETWEEN => nothing */ 0, /* IN => nothing */ 0, /* ISNULL => nothing */ @@ -136830,6 +156963,48 @@ static const YYCODETYPE yyFallback[] = { 0, /* LT => nothing */ 0, /* GE => nothing */ 0, /* ESCAPE => nothing */ + 0, /* ID => nothing */ + 59, /* COLUMNKW => ID */ + 59, /* DO => ID */ + 59, /* FOR => ID */ + 59, /* IGNORE => ID */ + 59, /* INITIALLY => ID */ + 59, /* INSTEAD => ID */ + 59, /* NO => ID */ + 59, /* KEY => ID */ + 59, /* OF => ID */ + 59, /* OFFSET => ID */ + 59, /* PRAGMA => ID */ + 59, /* RAISE => ID */ + 59, /* RECURSIVE => ID */ + 59, /* REPLACE => ID */ + 59, /* RESTRICT => ID */ + 59, /* ROW => ID */ + 59, /* ROWS => ID */ + 59, /* TRIGGER => ID */ + 59, /* VACUUM => ID */ + 59, /* VIEW => ID */ + 59, /* VIRTUAL => ID */ + 59, /* WITH => ID */ + 59, /* NULLS => ID */ + 59, /* FIRST => ID */ + 59, /* LAST => ID */ + 59, /* CURRENT => ID */ + 59, /* FOLLOWING => ID */ + 59, /* PARTITION => ID */ + 59, /* PRECEDING => ID */ + 59, /* RANGE => ID */ + 59, /* UNBOUNDED => ID */ + 59, /* EXCLUDE => ID */ + 59, /* GROUPS => ID */ + 59, /* OTHERS => ID */ + 59, /* TIES => ID */ + 59, /* GENERATED => ID */ + 59, /* ALWAYS => ID */ + 59, /* REINDEX => ID */ + 59, /* RENAME => ID */ + 59, /* CTIME_KW => ID */ + 0, /* ANY => nothing */ 0, /* BITAND => nothing */ 0, /* BITOR => nothing */ 0, /* LSHIFT => nothing */ @@ -136842,47 +157017,74 @@ static const YYCODETYPE yyFallback[] = { 0, /* CONCAT => nothing */ 0, /* COLLATE => nothing */ 0, /* BITNOT => nothing */ - 0, /* ID => nothing */ + 0, /* ON => nothing */ 0, /* INDEXED => nothing */ - 55, /* ABORT => ID */ - 55, /* ACTION => ID */ - 55, /* AFTER => ID */ - 55, /* ANALYZE => ID */ - 55, /* ASC => ID */ - 55, /* ATTACH => ID */ - 55, /* BEFORE => ID */ - 55, /* BY => ID */ - 55, /* CASCADE => ID */ - 55, /* CAST => ID */ - 55, /* COLUMNKW => ID */ - 55, /* CONFLICT => ID */ - 55, /* DATABASE => ID */ - 55, /* DESC => ID */ - 55, /* DETACH => ID */ - 55, /* EACH => ID */ - 55, /* FAIL => ID */ - 55, /* FOR => ID */ - 55, /* IGNORE => ID */ - 55, /* INITIALLY => ID */ - 55, /* INSTEAD => ID */ - 55, /* NO => ID */ - 55, /* KEY => ID */ - 55, /* OF => ID */ - 55, /* OFFSET => ID */ - 55, /* PRAGMA => ID */ - 55, /* RAISE => ID */ - 55, /* RECURSIVE => ID */ - 55, /* REPLACE => ID */ - 55, /* RESTRICT => ID */ - 55, /* ROW => ID */ - 55, /* TRIGGER => ID */ - 55, /* VACUUM => ID */ - 55, /* VIEW => ID */ - 55, /* VIRTUAL => ID */ - 55, /* WITH => ID */ - 55, /* REINDEX => ID */ - 55, /* RENAME => ID */ - 55, /* CTIME_KW => ID */ + 0, /* STRING => nothing */ + 0, /* JOIN_KW => nothing */ + 0, /* CONSTRAINT => nothing */ + 0, /* DEFAULT => nothing */ + 0, /* NULL => nothing */ + 0, /* PRIMARY => nothing */ + 0, /* UNIQUE => nothing */ + 0, /* CHECK => nothing */ + 0, /* REFERENCES => nothing */ + 0, /* AUTOINCR => nothing */ + 0, /* INSERT => nothing */ + 0, /* DELETE => nothing */ + 0, /* UPDATE => nothing */ + 0, /* SET => nothing */ + 0, /* DEFERRABLE => nothing */ + 0, /* FOREIGN => nothing */ + 0, /* DROP => nothing */ + 0, /* UNION => nothing */ + 0, /* ALL => nothing */ + 0, /* EXCEPT => nothing */ + 0, /* INTERSECT => nothing */ + 0, /* SELECT => nothing */ + 0, /* VALUES => nothing */ + 0, /* DISTINCT => nothing */ + 0, /* DOT => nothing */ + 0, /* FROM => nothing */ + 0, /* JOIN => nothing */ + 0, /* USING => nothing */ + 0, /* ORDER => nothing */ + 0, /* GROUP => nothing */ + 0, /* HAVING => nothing */ + 0, /* LIMIT => nothing */ + 0, /* WHERE => nothing */ + 0, /* INTO => nothing */ + 0, /* NOTHING => nothing */ + 0, /* FLOAT => nothing */ + 0, /* BLOB => nothing */ + 0, /* INTEGER => nothing */ + 0, /* VARIABLE => nothing */ + 0, /* CASE => nothing */ + 0, /* WHEN => nothing */ + 0, /* THEN => nothing */ + 0, /* ELSE => nothing */ + 0, /* INDEX => nothing */ + 0, /* ALTER => nothing */ + 0, /* ADD => nothing */ + 0, /* WINDOW => nothing */ + 0, /* OVER => nothing */ + 0, /* FILTER => nothing */ + 0, /* COLUMN => nothing */ + 0, /* AGG_FUNCTION => nothing */ + 0, /* AGG_COLUMN => nothing */ + 0, /* TRUEFALSE => nothing */ + 0, /* ISNOT => nothing */ + 0, /* FUNCTION => nothing */ + 0, /* UMINUS => nothing */ + 0, /* UPLUS => nothing */ + 0, /* TRUTH => nothing */ + 0, /* REGISTER => nothing */ + 0, /* VECTOR => nothing */ + 0, /* SELECT_COLUMN => nothing */ + 0, /* IF_NULL_ROW => nothing */ + 0, /* ASTERISK => nothing */ + 0, /* SPAN => nothing */ + 0, /* SPACE => nothing */ + 0, /* ILLEGAL => nothing */ }; #endif /* YYFALLBACK */ @@ -136921,13 +157123,15 @@ struct yyParser { #ifndef YYNOERRORRECOVERY int yyerrcnt; /* Shifts left before out of the error */ #endif - sqlite3ParserARG_SDECL /* A place to hold %extra_argument */ + tdsqlite3ParserARG_SDECL /* A place to hold %extra_argument */ + tdsqlite3ParserCTX_SDECL /* A place to hold %extra_context */ #if YYSTACKDEPTH<=0 int yystksz; /* Current side of the stack */ yyStackEntry *yystack; /* The parser's stack */ yyStackEntry yystk0; /* First stack entry */ #else yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ + yyStackEntry *yystackEnd; /* Last entry in the stack */ #endif }; typedef struct yyParser yyParser; @@ -136956,7 +157160,7 @@ static char *yyTracePrompt = 0; ** Outputs: ** None. */ -SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){ +SQLITE_PRIVATE void tdsqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){ yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if( yyTraceFILE==0 ) yyTracePrompt = 0; @@ -136964,75 +157168,322 @@ SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){ } #endif /* NDEBUG */ -#ifndef NDEBUG +#if defined(YYCOVERAGE) || !defined(NDEBUG) /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *const yyTokenName[] = { - "$", "SEMI", "EXPLAIN", "QUERY", - "PLAN", "BEGIN", "TRANSACTION", "DEFERRED", - "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END", - "ROLLBACK", "SAVEPOINT", "RELEASE", "TO", - "TABLE", "CREATE", "IF", "NOT", - "EXISTS", "TEMP", "LP", "RP", - "AS", "WITHOUT", "COMMA", "OR", - "AND", "IS", "MATCH", "LIKE_KW", - "BETWEEN", "IN", "ISNULL", "NOTNULL", - "NE", "EQ", "GT", "LE", - "LT", "GE", "ESCAPE", "BITAND", - "BITOR", "LSHIFT", "RSHIFT", "PLUS", - "MINUS", "STAR", "SLASH", "REM", - "CONCAT", "COLLATE", "BITNOT", "ID", - "INDEXED", "ABORT", "ACTION", "AFTER", - "ANALYZE", "ASC", "ATTACH", "BEFORE", - "BY", "CASCADE", "CAST", "COLUMNKW", - "CONFLICT", "DATABASE", "DESC", "DETACH", - "EACH", "FAIL", "FOR", "IGNORE", - "INITIALLY", "INSTEAD", "NO", "KEY", - "OF", "OFFSET", "PRAGMA", "RAISE", - "RECURSIVE", "REPLACE", "RESTRICT", "ROW", - "TRIGGER", "VACUUM", "VIEW", "VIRTUAL", - "WITH", "REINDEX", "RENAME", "CTIME_KW", - "ANY", "STRING", "JOIN_KW", "CONSTRAINT", - "DEFAULT", "NULL", "PRIMARY", "UNIQUE", - "CHECK", "REFERENCES", "AUTOINCR", "ON", - "INSERT", "DELETE", "UPDATE", "SET", - "DEFERRABLE", "FOREIGN", "DROP", "UNION", - "ALL", "EXCEPT", "INTERSECT", "SELECT", - "VALUES", "DISTINCT", "DOT", "FROM", - "JOIN", "USING", "ORDER", "GROUP", - "HAVING", "LIMIT", "WHERE", "INTO", - "FLOAT", "BLOB", "INTEGER", "VARIABLE", - "CASE", "WHEN", "THEN", "ELSE", - "INDEX", "ALTER", "ADD", "error", - "input", "cmdlist", "ecmd", "explain", - "cmdx", "cmd", "transtype", "trans_opt", - "nm", "savepoint_opt", "create_table", "create_table_args", - "createkw", "temp", "ifnotexists", "dbnm", - "columnlist", "conslist_opt", "table_options", "select", - "columnname", "carglist", "typetoken", "typename", - "signed", "plus_num", "minus_num", "ccons", - "term", "expr", "onconf", "sortorder", - "autoinc", "eidlist_opt", "refargs", "defer_subclause", - "refarg", "refact", "init_deferred_pred_opt", "conslist", - "tconscomma", "tcons", "sortlist", "eidlist", - "defer_subclause_opt", "orconf", "resolvetype", "raisetype", - "ifexists", "fullname", "selectnowith", "oneselect", - "with", "multiselect_op", "distinct", "selcollist", - "from", "where_opt", "groupby_opt", "having_opt", - "orderby_opt", "limit_opt", "values", "nexprlist", - "exprlist", "sclp", "as", "seltablist", - "stl_prefix", "joinop", "indexed_opt", "on_opt", - "using_opt", "idlist", "setlist", "insert_cmd", - "idlist_opt", "likeop", "between_op", "in_op", - "paren_exprlist", "case_operand", "case_exprlist", "case_else", - "uniqueflag", "collate", "nmnum", "trigger_decl", - "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause", - "when_clause", "trigger_cmd", "trnm", "tridxby", - "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt", - "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken", - "lp", "anylist", "wqlist", + /* 0 */ "$", + /* 1 */ "SEMI", + /* 2 */ "EXPLAIN", + /* 3 */ "QUERY", + /* 4 */ "PLAN", + /* 5 */ "BEGIN", + /* 6 */ "TRANSACTION", + /* 7 */ "DEFERRED", + /* 8 */ "IMMEDIATE", + /* 9 */ "EXCLUSIVE", + /* 10 */ "COMMIT", + /* 11 */ "END", + /* 12 */ "ROLLBACK", + /* 13 */ "SAVEPOINT", + /* 14 */ "RELEASE", + /* 15 */ "TO", + /* 16 */ "TABLE", + /* 17 */ "CREATE", + /* 18 */ "IF", + /* 19 */ "NOT", + /* 20 */ "EXISTS", + /* 21 */ "TEMP", + /* 22 */ "LP", + /* 23 */ "RP", + /* 24 */ "AS", + /* 25 */ "WITHOUT", + /* 26 */ "COMMA", + /* 27 */ "ABORT", + /* 28 */ "ACTION", + /* 29 */ "AFTER", + /* 30 */ "ANALYZE", + /* 31 */ "ASC", + /* 32 */ "ATTACH", + /* 33 */ "BEFORE", + /* 34 */ "BY", + /* 35 */ "CASCADE", + /* 36 */ "CAST", + /* 37 */ "CONFLICT", + /* 38 */ "DATABASE", + /* 39 */ "DESC", + /* 40 */ "DETACH", + /* 41 */ "EACH", + /* 42 */ "FAIL", + /* 43 */ "OR", + /* 44 */ "AND", + /* 45 */ "IS", + /* 46 */ "MATCH", + /* 47 */ "LIKE_KW", + /* 48 */ "BETWEEN", + /* 49 */ "IN", + /* 50 */ "ISNULL", + /* 51 */ "NOTNULL", + /* 52 */ "NE", + /* 53 */ "EQ", + /* 54 */ "GT", + /* 55 */ "LE", + /* 56 */ "LT", + /* 57 */ "GE", + /* 58 */ "ESCAPE", + /* 59 */ "ID", + /* 60 */ "COLUMNKW", + /* 61 */ "DO", + /* 62 */ "FOR", + /* 63 */ "IGNORE", + /* 64 */ "INITIALLY", + /* 65 */ "INSTEAD", + /* 66 */ "NO", + /* 67 */ "KEY", + /* 68 */ "OF", + /* 69 */ "OFFSET", + /* 70 */ "PRAGMA", + /* 71 */ "RAISE", + /* 72 */ "RECURSIVE", + /* 73 */ "REPLACE", + /* 74 */ "RESTRICT", + /* 75 */ "ROW", + /* 76 */ "ROWS", + /* 77 */ "TRIGGER", + /* 78 */ "VACUUM", + /* 79 */ "VIEW", + /* 80 */ "VIRTUAL", + /* 81 */ "WITH", + /* 82 */ "NULLS", + /* 83 */ "FIRST", + /* 84 */ "LAST", + /* 85 */ "CURRENT", + /* 86 */ "FOLLOWING", + /* 87 */ "PARTITION", + /* 88 */ "PRECEDING", + /* 89 */ "RANGE", + /* 90 */ "UNBOUNDED", + /* 91 */ "EXCLUDE", + /* 92 */ "GROUPS", + /* 93 */ "OTHERS", + /* 94 */ "TIES", + /* 95 */ "GENERATED", + /* 96 */ "ALWAYS", + /* 97 */ "REINDEX", + /* 98 */ "RENAME", + /* 99 */ "CTIME_KW", + /* 100 */ "ANY", + /* 101 */ "BITAND", + /* 102 */ "BITOR", + /* 103 */ "LSHIFT", + /* 104 */ "RSHIFT", + /* 105 */ "PLUS", + /* 106 */ "MINUS", + /* 107 */ "STAR", + /* 108 */ "SLASH", + /* 109 */ "REM", + /* 110 */ "CONCAT", + /* 111 */ "COLLATE", + /* 112 */ "BITNOT", + /* 113 */ "ON", + /* 114 */ "INDEXED", + /* 115 */ "STRING", + /* 116 */ "JOIN_KW", + /* 117 */ "CONSTRAINT", + /* 118 */ "DEFAULT", + /* 119 */ "NULL", + /* 120 */ "PRIMARY", + /* 121 */ "UNIQUE", + /* 122 */ "CHECK", + /* 123 */ "REFERENCES", + /* 124 */ "AUTOINCR", + /* 125 */ "INSERT", + /* 126 */ "DELETE", + /* 127 */ "UPDATE", + /* 128 */ "SET", + /* 129 */ "DEFERRABLE", + /* 130 */ "FOREIGN", + /* 131 */ "DROP", + /* 132 */ "UNION", + /* 133 */ "ALL", + /* 134 */ "EXCEPT", + /* 135 */ "INTERSECT", + /* 136 */ "SELECT", + /* 137 */ "VALUES", + /* 138 */ "DISTINCT", + /* 139 */ "DOT", + /* 140 */ "FROM", + /* 141 */ "JOIN", + /* 142 */ "USING", + /* 143 */ "ORDER", + /* 144 */ "GROUP", + /* 145 */ "HAVING", + /* 146 */ "LIMIT", + /* 147 */ "WHERE", + /* 148 */ "INTO", + /* 149 */ "NOTHING", + /* 150 */ "FLOAT", + /* 151 */ "BLOB", + /* 152 */ "INTEGER", + /* 153 */ "VARIABLE", + /* 154 */ "CASE", + /* 155 */ "WHEN", + /* 156 */ "THEN", + /* 157 */ "ELSE", + /* 158 */ "INDEX", + /* 159 */ "ALTER", + /* 160 */ "ADD", + /* 161 */ "WINDOW", + /* 162 */ "OVER", + /* 163 */ "FILTER", + /* 164 */ "COLUMN", + /* 165 */ "AGG_FUNCTION", + /* 166 */ "AGG_COLUMN", + /* 167 */ "TRUEFALSE", + /* 168 */ "ISNOT", + /* 169 */ "FUNCTION", + /* 170 */ "UMINUS", + /* 171 */ "UPLUS", + /* 172 */ "TRUTH", + /* 173 */ "REGISTER", + /* 174 */ "VECTOR", + /* 175 */ "SELECT_COLUMN", + /* 176 */ "IF_NULL_ROW", + /* 177 */ "ASTERISK", + /* 178 */ "SPAN", + /* 179 */ "SPACE", + /* 180 */ "ILLEGAL", + /* 181 */ "input", + /* 182 */ "cmdlist", + /* 183 */ "ecmd", + /* 184 */ "cmdx", + /* 185 */ "explain", + /* 186 */ "cmd", + /* 187 */ "transtype", + /* 188 */ "trans_opt", + /* 189 */ "nm", + /* 190 */ "savepoint_opt", + /* 191 */ "create_table", + /* 192 */ "create_table_args", + /* 193 */ "createkw", + /* 194 */ "temp", + /* 195 */ "ifnotexists", + /* 196 */ "dbnm", + /* 197 */ "columnlist", + /* 198 */ "conslist_opt", + /* 199 */ "table_options", + /* 200 */ "select", + /* 201 */ "columnname", + /* 202 */ "carglist", + /* 203 */ "typetoken", + /* 204 */ "typename", + /* 205 */ "signed", + /* 206 */ "plus_num", + /* 207 */ "minus_num", + /* 208 */ "scanpt", + /* 209 */ "scantok", + /* 210 */ "ccons", + /* 211 */ "term", + /* 212 */ "expr", + /* 213 */ "onconf", + /* 214 */ "sortorder", + /* 215 */ "autoinc", + /* 216 */ "eidlist_opt", + /* 217 */ "refargs", + /* 218 */ "defer_subclause", + /* 219 */ "generated", + /* 220 */ "refarg", + /* 221 */ "refact", + /* 222 */ "init_deferred_pred_opt", + /* 223 */ "conslist", + /* 224 */ "tconscomma", + /* 225 */ "tcons", + /* 226 */ "sortlist", + /* 227 */ "eidlist", + /* 228 */ "defer_subclause_opt", + /* 229 */ "orconf", + /* 230 */ "resolvetype", + /* 231 */ "raisetype", + /* 232 */ "ifexists", + /* 233 */ "fullname", + /* 234 */ "selectnowith", + /* 235 */ "oneselect", + /* 236 */ "wqlist", + /* 237 */ "multiselect_op", + /* 238 */ "distinct", + /* 239 */ "selcollist", + /* 240 */ "from", + /* 241 */ "where_opt", + /* 242 */ "groupby_opt", + /* 243 */ "having_opt", + /* 244 */ "orderby_opt", + /* 245 */ "limit_opt", + /* 246 */ "window_clause", + /* 247 */ "values", + /* 248 */ "nexprlist", + /* 249 */ "sclp", + /* 250 */ "as", + /* 251 */ "seltablist", + /* 252 */ "stl_prefix", + /* 253 */ "joinop", + /* 254 */ "indexed_opt", + /* 255 */ "on_opt", + /* 256 */ "using_opt", + /* 257 */ "exprlist", + /* 258 */ "xfullname", + /* 259 */ "idlist", + /* 260 */ "nulls", + /* 261 */ "with", + /* 262 */ "setlist", + /* 263 */ "insert_cmd", + /* 264 */ "idlist_opt", + /* 265 */ "upsert", + /* 266 */ "filter_over", + /* 267 */ "likeop", + /* 268 */ "between_op", + /* 269 */ "in_op", + /* 270 */ "paren_exprlist", + /* 271 */ "case_operand", + /* 272 */ "case_exprlist", + /* 273 */ "case_else", + /* 274 */ "uniqueflag", + /* 275 */ "collate", + /* 276 */ "vinto", + /* 277 */ "nmnum", + /* 278 */ "trigger_decl", + /* 279 */ "trigger_cmd_list", + /* 280 */ "trigger_time", + /* 281 */ "trigger_event", + /* 282 */ "foreach_clause", + /* 283 */ "when_clause", + /* 284 */ "trigger_cmd", + /* 285 */ "trnm", + /* 286 */ "tridxby", + /* 287 */ "database_kw_opt", + /* 288 */ "key_opt", + /* 289 */ "add_column_fullname", + /* 290 */ "kwcolumn_opt", + /* 291 */ "create_vtab", + /* 292 */ "vtabarglist", + /* 293 */ "vtabarg", + /* 294 */ "vtabargtoken", + /* 295 */ "lp", + /* 296 */ "anylist", + /* 297 */ "windowdefn_list", + /* 298 */ "windowdefn", + /* 299 */ "window", + /* 300 */ "frame_opt", + /* 301 */ "part_opt", + /* 302 */ "filter_clause", + /* 303 */ "over_clause", + /* 304 */ "range_or_rows", + /* 305 */ "frame_bound", + /* 306 */ "frame_bound_s", + /* 307 */ "frame_bound_e", + /* 308 */ "frame_exclude_opt", + /* 309 */ "frame_exclude", }; -#endif /* NDEBUG */ +#endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. @@ -137046,330 +157497,383 @@ static const char *const yyRuleName[] = { /* 5 */ "transtype ::= DEFERRED", /* 6 */ "transtype ::= IMMEDIATE", /* 7 */ "transtype ::= EXCLUSIVE", - /* 8 */ "cmd ::= COMMIT trans_opt", - /* 9 */ "cmd ::= END trans_opt", - /* 10 */ "cmd ::= ROLLBACK trans_opt", - /* 11 */ "cmd ::= SAVEPOINT nm", - /* 12 */ "cmd ::= RELEASE savepoint_opt nm", - /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm", - /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm", - /* 15 */ "createkw ::= CREATE", - /* 16 */ "ifnotexists ::=", - /* 17 */ "ifnotexists ::= IF NOT EXISTS", - /* 18 */ "temp ::= TEMP", - /* 19 */ "temp ::=", - /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options", - /* 21 */ "create_table_args ::= AS select", - /* 22 */ "table_options ::=", - /* 23 */ "table_options ::= WITHOUT nm", - /* 24 */ "columnname ::= nm typetoken", - /* 25 */ "typetoken ::=", - /* 26 */ "typetoken ::= typename LP signed RP", - /* 27 */ "typetoken ::= typename LP signed COMMA signed RP", - /* 28 */ "typename ::= typename ID|STRING", - /* 29 */ "ccons ::= CONSTRAINT nm", - /* 30 */ "ccons ::= DEFAULT term", - /* 31 */ "ccons ::= DEFAULT LP expr RP", - /* 32 */ "ccons ::= DEFAULT PLUS term", - /* 33 */ "ccons ::= DEFAULT MINUS term", - /* 34 */ "ccons ::= DEFAULT ID|INDEXED", - /* 35 */ "ccons ::= NOT NULL onconf", - /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", - /* 37 */ "ccons ::= UNIQUE onconf", - /* 38 */ "ccons ::= CHECK LP expr RP", - /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs", - /* 40 */ "ccons ::= defer_subclause", - /* 41 */ "ccons ::= COLLATE ID|STRING", - /* 42 */ "autoinc ::=", - /* 43 */ "autoinc ::= AUTOINCR", - /* 44 */ "refargs ::=", - /* 45 */ "refargs ::= refargs refarg", - /* 46 */ "refarg ::= MATCH nm", - /* 47 */ "refarg ::= ON INSERT refact", - /* 48 */ "refarg ::= ON DELETE refact", - /* 49 */ "refarg ::= ON UPDATE refact", - /* 50 */ "refact ::= SET NULL", - /* 51 */ "refact ::= SET DEFAULT", - /* 52 */ "refact ::= CASCADE", - /* 53 */ "refact ::= RESTRICT", - /* 54 */ "refact ::= NO ACTION", - /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", - /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", - /* 57 */ "init_deferred_pred_opt ::=", - /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", - /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", - /* 60 */ "conslist_opt ::=", - /* 61 */ "tconscomma ::= COMMA", - /* 62 */ "tcons ::= CONSTRAINT nm", - /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf", - /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf", - /* 65 */ "tcons ::= CHECK LP expr RP onconf", - /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt", - /* 67 */ "defer_subclause_opt ::=", - /* 68 */ "onconf ::=", - /* 69 */ "onconf ::= ON CONFLICT resolvetype", - /* 70 */ "orconf ::=", - /* 71 */ "orconf ::= OR resolvetype", - /* 72 */ "resolvetype ::= IGNORE", - /* 73 */ "resolvetype ::= REPLACE", - /* 74 */ "cmd ::= DROP TABLE ifexists fullname", - /* 75 */ "ifexists ::= IF EXISTS", - /* 76 */ "ifexists ::=", - /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select", - /* 78 */ "cmd ::= DROP VIEW ifexists fullname", - /* 79 */ "cmd ::= select", - /* 80 */ "select ::= with selectnowith", - /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect", - /* 82 */ "multiselect_op ::= UNION", - /* 83 */ "multiselect_op ::= UNION ALL", - /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT", - /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", - /* 86 */ "values ::= VALUES LP nexprlist RP", - /* 87 */ "values ::= values COMMA LP exprlist RP", - /* 88 */ "distinct ::= DISTINCT", - /* 89 */ "distinct ::= ALL", - /* 90 */ "distinct ::=", - /* 91 */ "sclp ::=", - /* 92 */ "selcollist ::= sclp expr as", - /* 93 */ "selcollist ::= sclp STAR", - /* 94 */ "selcollist ::= sclp nm DOT STAR", - /* 95 */ "as ::= AS nm", - /* 96 */ "as ::=", - /* 97 */ "from ::=", - /* 98 */ "from ::= FROM seltablist", - /* 99 */ "stl_prefix ::= seltablist joinop", - /* 100 */ "stl_prefix ::=", - /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", - /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt", - /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", - /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", - /* 105 */ "dbnm ::=", - /* 106 */ "dbnm ::= DOT nm", - /* 107 */ "fullname ::= nm dbnm", - /* 108 */ "joinop ::= COMMA|JOIN", - /* 109 */ "joinop ::= JOIN_KW JOIN", - /* 110 */ "joinop ::= JOIN_KW nm JOIN", - /* 111 */ "joinop ::= JOIN_KW nm nm JOIN", - /* 112 */ "on_opt ::= ON expr", - /* 113 */ "on_opt ::=", - /* 114 */ "indexed_opt ::=", - /* 115 */ "indexed_opt ::= INDEXED BY nm", - /* 116 */ "indexed_opt ::= NOT INDEXED", - /* 117 */ "using_opt ::= USING LP idlist RP", - /* 118 */ "using_opt ::=", - /* 119 */ "orderby_opt ::=", - /* 120 */ "orderby_opt ::= ORDER BY sortlist", - /* 121 */ "sortlist ::= sortlist COMMA expr sortorder", - /* 122 */ "sortlist ::= expr sortorder", - /* 123 */ "sortorder ::= ASC", - /* 124 */ "sortorder ::= DESC", - /* 125 */ "sortorder ::=", - /* 126 */ "groupby_opt ::=", - /* 127 */ "groupby_opt ::= GROUP BY nexprlist", - /* 128 */ "having_opt ::=", - /* 129 */ "having_opt ::= HAVING expr", - /* 130 */ "limit_opt ::=", - /* 131 */ "limit_opt ::= LIMIT expr", - /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr", - /* 133 */ "limit_opt ::= LIMIT expr COMMA expr", - /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt", - /* 135 */ "where_opt ::=", - /* 136 */ "where_opt ::= WHERE expr", - /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt", - /* 138 */ "setlist ::= setlist COMMA nm EQ expr", - /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr", - /* 140 */ "setlist ::= nm EQ expr", - /* 141 */ "setlist ::= LP idlist RP EQ expr", - /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select", - /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES", - /* 144 */ "insert_cmd ::= INSERT orconf", - /* 145 */ "insert_cmd ::= REPLACE", - /* 146 */ "idlist_opt ::=", - /* 147 */ "idlist_opt ::= LP idlist RP", - /* 148 */ "idlist ::= idlist COMMA nm", - /* 149 */ "idlist ::= nm", - /* 150 */ "expr ::= LP expr RP", - /* 151 */ "term ::= NULL", - /* 152 */ "expr ::= ID|INDEXED", - /* 153 */ "expr ::= JOIN_KW", - /* 154 */ "expr ::= nm DOT nm", - /* 155 */ "expr ::= nm DOT nm DOT nm", - /* 156 */ "term ::= FLOAT|BLOB", - /* 157 */ "term ::= STRING", - /* 158 */ "term ::= INTEGER", - /* 159 */ "expr ::= VARIABLE", - /* 160 */ "expr ::= expr COLLATE ID|STRING", - /* 161 */ "expr ::= CAST LP expr AS typetoken RP", - /* 162 */ "expr ::= ID|INDEXED LP distinct exprlist RP", - /* 163 */ "expr ::= ID|INDEXED LP STAR RP", - /* 164 */ "term ::= CTIME_KW", - /* 165 */ "expr ::= LP nexprlist COMMA expr RP", - /* 166 */ "expr ::= expr AND expr", - /* 167 */ "expr ::= expr OR expr", - /* 168 */ "expr ::= expr LT|GT|GE|LE expr", - /* 169 */ "expr ::= expr EQ|NE expr", - /* 170 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", - /* 171 */ "expr ::= expr PLUS|MINUS expr", - /* 172 */ "expr ::= expr STAR|SLASH|REM expr", - /* 173 */ "expr ::= expr CONCAT expr", - /* 174 */ "likeop ::= LIKE_KW|MATCH", - /* 175 */ "likeop ::= NOT LIKE_KW|MATCH", - /* 176 */ "expr ::= expr likeop expr", - /* 177 */ "expr ::= expr likeop expr ESCAPE expr", - /* 178 */ "expr ::= expr ISNULL|NOTNULL", - /* 179 */ "expr ::= expr NOT NULL", - /* 180 */ "expr ::= expr IS expr", - /* 181 */ "expr ::= expr IS NOT expr", - /* 182 */ "expr ::= NOT expr", - /* 183 */ "expr ::= BITNOT expr", - /* 184 */ "expr ::= MINUS expr", - /* 185 */ "expr ::= PLUS expr", - /* 186 */ "between_op ::= BETWEEN", - /* 187 */ "between_op ::= NOT BETWEEN", - /* 188 */ "expr ::= expr between_op expr AND expr", - /* 189 */ "in_op ::= IN", - /* 190 */ "in_op ::= NOT IN", - /* 191 */ "expr ::= expr in_op LP exprlist RP", - /* 192 */ "expr ::= LP select RP", - /* 193 */ "expr ::= expr in_op LP select RP", - /* 194 */ "expr ::= expr in_op nm dbnm paren_exprlist", - /* 195 */ "expr ::= EXISTS LP select RP", - /* 196 */ "expr ::= CASE case_operand case_exprlist case_else END", - /* 197 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", - /* 198 */ "case_exprlist ::= WHEN expr THEN expr", - /* 199 */ "case_else ::= ELSE expr", - /* 200 */ "case_else ::=", - /* 201 */ "case_operand ::= expr", - /* 202 */ "case_operand ::=", - /* 203 */ "exprlist ::=", - /* 204 */ "nexprlist ::= nexprlist COMMA expr", - /* 205 */ "nexprlist ::= expr", - /* 206 */ "paren_exprlist ::=", - /* 207 */ "paren_exprlist ::= LP exprlist RP", - /* 208 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt", - /* 209 */ "uniqueflag ::= UNIQUE", - /* 210 */ "uniqueflag ::=", - /* 211 */ "eidlist_opt ::=", - /* 212 */ "eidlist_opt ::= LP eidlist RP", - /* 213 */ "eidlist ::= eidlist COMMA nm collate sortorder", - /* 214 */ "eidlist ::= nm collate sortorder", - /* 215 */ "collate ::=", - /* 216 */ "collate ::= COLLATE ID|STRING", - /* 217 */ "cmd ::= DROP INDEX ifexists fullname", - /* 218 */ "cmd ::= VACUUM", - /* 219 */ "cmd ::= VACUUM nm", - /* 220 */ "cmd ::= PRAGMA nm dbnm", - /* 221 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", - /* 222 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", - /* 223 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", - /* 224 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", - /* 225 */ "plus_num ::= PLUS INTEGER|FLOAT", - /* 226 */ "minus_num ::= MINUS INTEGER|FLOAT", - /* 227 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", - /* 228 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", - /* 229 */ "trigger_time ::= BEFORE", - /* 230 */ "trigger_time ::= AFTER", - /* 231 */ "trigger_time ::= INSTEAD OF", - /* 232 */ "trigger_time ::=", - /* 233 */ "trigger_event ::= DELETE|INSERT", - /* 234 */ "trigger_event ::= UPDATE", - /* 235 */ "trigger_event ::= UPDATE OF idlist", - /* 236 */ "when_clause ::=", - /* 237 */ "when_clause ::= WHEN expr", - /* 238 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", - /* 239 */ "trigger_cmd_list ::= trigger_cmd SEMI", - /* 240 */ "trnm ::= nm DOT nm", - /* 241 */ "tridxby ::= INDEXED BY nm", - /* 242 */ "tridxby ::= NOT INDEXED", - /* 243 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt", - /* 244 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select", - /* 245 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt", - /* 246 */ "trigger_cmd ::= select", - /* 247 */ "expr ::= RAISE LP IGNORE RP", - /* 248 */ "expr ::= RAISE LP raisetype COMMA nm RP", - /* 249 */ "raisetype ::= ROLLBACK", - /* 250 */ "raisetype ::= ABORT", - /* 251 */ "raisetype ::= FAIL", - /* 252 */ "cmd ::= DROP TRIGGER ifexists fullname", - /* 253 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", - /* 254 */ "cmd ::= DETACH database_kw_opt expr", - /* 255 */ "key_opt ::=", - /* 256 */ "key_opt ::= KEY expr", - /* 257 */ "cmd ::= REINDEX", - /* 258 */ "cmd ::= REINDEX nm dbnm", - /* 259 */ "cmd ::= ANALYZE", - /* 260 */ "cmd ::= ANALYZE nm dbnm", - /* 261 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", - /* 262 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist", - /* 263 */ "add_column_fullname ::= fullname", - /* 264 */ "cmd ::= create_vtab", - /* 265 */ "cmd ::= create_vtab LP vtabarglist RP", - /* 266 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", - /* 267 */ "vtabarg ::=", - /* 268 */ "vtabargtoken ::= ANY", - /* 269 */ "vtabargtoken ::= lp anylist RP", - /* 270 */ "lp ::= LP", - /* 271 */ "with ::=", - /* 272 */ "with ::= WITH wqlist", - /* 273 */ "with ::= WITH RECURSIVE wqlist", - /* 274 */ "wqlist ::= nm eidlist_opt AS LP select RP", - /* 275 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP", - /* 276 */ "input ::= cmdlist", - /* 277 */ "cmdlist ::= cmdlist ecmd", - /* 278 */ "cmdlist ::= ecmd", - /* 279 */ "ecmd ::= SEMI", - /* 280 */ "ecmd ::= explain cmdx SEMI", - /* 281 */ "explain ::=", - /* 282 */ "trans_opt ::=", - /* 283 */ "trans_opt ::= TRANSACTION", - /* 284 */ "trans_opt ::= TRANSACTION nm", - /* 285 */ "savepoint_opt ::= SAVEPOINT", - /* 286 */ "savepoint_opt ::=", - /* 287 */ "cmd ::= create_table create_table_args", - /* 288 */ "columnlist ::= columnlist COMMA columnname carglist", - /* 289 */ "columnlist ::= columnname carglist", - /* 290 */ "nm ::= ID|INDEXED", - /* 291 */ "nm ::= STRING", - /* 292 */ "nm ::= JOIN_KW", - /* 293 */ "typetoken ::= typename", - /* 294 */ "typename ::= ID|STRING", - /* 295 */ "signed ::= plus_num", - /* 296 */ "signed ::= minus_num", - /* 297 */ "carglist ::= carglist ccons", - /* 298 */ "carglist ::=", - /* 299 */ "ccons ::= NULL onconf", - /* 300 */ "conslist_opt ::= COMMA conslist", - /* 301 */ "conslist ::= conslist tconscomma tcons", - /* 302 */ "conslist ::= tcons", - /* 303 */ "tconscomma ::=", - /* 304 */ "defer_subclause_opt ::= defer_subclause", - /* 305 */ "resolvetype ::= raisetype", - /* 306 */ "selectnowith ::= oneselect", - /* 307 */ "oneselect ::= values", - /* 308 */ "sclp ::= selcollist COMMA", - /* 309 */ "as ::= ID|STRING", - /* 310 */ "expr ::= term", - /* 311 */ "exprlist ::= nexprlist", - /* 312 */ "nmnum ::= plus_num", - /* 313 */ "nmnum ::= nm", - /* 314 */ "nmnum ::= ON", - /* 315 */ "nmnum ::= DELETE", - /* 316 */ "nmnum ::= DEFAULT", - /* 317 */ "plus_num ::= INTEGER|FLOAT", - /* 318 */ "foreach_clause ::=", - /* 319 */ "foreach_clause ::= FOR EACH ROW", - /* 320 */ "trnm ::= nm", - /* 321 */ "tridxby ::=", - /* 322 */ "database_kw_opt ::= DATABASE", - /* 323 */ "database_kw_opt ::=", - /* 324 */ "kwcolumn_opt ::=", - /* 325 */ "kwcolumn_opt ::= COLUMNKW", - /* 326 */ "vtabarglist ::= vtabarg", - /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg", - /* 328 */ "vtabarg ::= vtabarg vtabargtoken", - /* 329 */ "anylist ::=", - /* 330 */ "anylist ::= anylist LP anylist RP", - /* 331 */ "anylist ::= anylist ANY", + /* 8 */ "cmd ::= COMMIT|END trans_opt", + /* 9 */ "cmd ::= ROLLBACK trans_opt", + /* 10 */ "cmd ::= SAVEPOINT nm", + /* 11 */ "cmd ::= RELEASE savepoint_opt nm", + /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm", + /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm", + /* 14 */ "createkw ::= CREATE", + /* 15 */ "ifnotexists ::=", + /* 16 */ "ifnotexists ::= IF NOT EXISTS", + /* 17 */ "temp ::= TEMP", + /* 18 */ "temp ::=", + /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options", + /* 20 */ "create_table_args ::= AS select", + /* 21 */ "table_options ::=", + /* 22 */ "table_options ::= WITHOUT nm", + /* 23 */ "columnname ::= nm typetoken", + /* 24 */ "typetoken ::=", + /* 25 */ "typetoken ::= typename LP signed RP", + /* 26 */ "typetoken ::= typename LP signed COMMA signed RP", + /* 27 */ "typename ::= typename ID|STRING", + /* 28 */ "scanpt ::=", + /* 29 */ "scantok ::=", + /* 30 */ "ccons ::= CONSTRAINT nm", + /* 31 */ "ccons ::= DEFAULT scantok term", + /* 32 */ "ccons ::= DEFAULT LP expr RP", + /* 33 */ "ccons ::= DEFAULT PLUS scantok term", + /* 34 */ "ccons ::= DEFAULT MINUS scantok term", + /* 35 */ "ccons ::= DEFAULT scantok ID|INDEXED", + /* 36 */ "ccons ::= NOT NULL onconf", + /* 37 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", + /* 38 */ "ccons ::= UNIQUE onconf", + /* 39 */ "ccons ::= CHECK LP expr RP", + /* 40 */ "ccons ::= REFERENCES nm eidlist_opt refargs", + /* 41 */ "ccons ::= defer_subclause", + /* 42 */ "ccons ::= COLLATE ID|STRING", + /* 43 */ "generated ::= LP expr RP", + /* 44 */ "generated ::= LP expr RP ID", + /* 45 */ "autoinc ::=", + /* 46 */ "autoinc ::= AUTOINCR", + /* 47 */ "refargs ::=", + /* 48 */ "refargs ::= refargs refarg", + /* 49 */ "refarg ::= MATCH nm", + /* 50 */ "refarg ::= ON INSERT refact", + /* 51 */ "refarg ::= ON DELETE refact", + /* 52 */ "refarg ::= ON UPDATE refact", + /* 53 */ "refact ::= SET NULL", + /* 54 */ "refact ::= SET DEFAULT", + /* 55 */ "refact ::= CASCADE", + /* 56 */ "refact ::= RESTRICT", + /* 57 */ "refact ::= NO ACTION", + /* 58 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", + /* 59 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", + /* 60 */ "init_deferred_pred_opt ::=", + /* 61 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", + /* 62 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", + /* 63 */ "conslist_opt ::=", + /* 64 */ "tconscomma ::= COMMA", + /* 65 */ "tcons ::= CONSTRAINT nm", + /* 66 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf", + /* 67 */ "tcons ::= UNIQUE LP sortlist RP onconf", + /* 68 */ "tcons ::= CHECK LP expr RP onconf", + /* 69 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt", + /* 70 */ "defer_subclause_opt ::=", + /* 71 */ "onconf ::=", + /* 72 */ "onconf ::= ON CONFLICT resolvetype", + /* 73 */ "orconf ::=", + /* 74 */ "orconf ::= OR resolvetype", + /* 75 */ "resolvetype ::= IGNORE", + /* 76 */ "resolvetype ::= REPLACE", + /* 77 */ "cmd ::= DROP TABLE ifexists fullname", + /* 78 */ "ifexists ::= IF EXISTS", + /* 79 */ "ifexists ::=", + /* 80 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select", + /* 81 */ "cmd ::= DROP VIEW ifexists fullname", + /* 82 */ "cmd ::= select", + /* 83 */ "select ::= WITH wqlist selectnowith", + /* 84 */ "select ::= WITH RECURSIVE wqlist selectnowith", + /* 85 */ "select ::= selectnowith", + /* 86 */ "selectnowith ::= selectnowith multiselect_op oneselect", + /* 87 */ "multiselect_op ::= UNION", + /* 88 */ "multiselect_op ::= UNION ALL", + /* 89 */ "multiselect_op ::= EXCEPT|INTERSECT", + /* 90 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", + /* 91 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt", + /* 92 */ "values ::= VALUES LP nexprlist RP", + /* 93 */ "values ::= values COMMA LP nexprlist RP", + /* 94 */ "distinct ::= DISTINCT", + /* 95 */ "distinct ::= ALL", + /* 96 */ "distinct ::=", + /* 97 */ "sclp ::=", + /* 98 */ "selcollist ::= sclp scanpt expr scanpt as", + /* 99 */ "selcollist ::= sclp scanpt STAR", + /* 100 */ "selcollist ::= sclp scanpt nm DOT STAR", + /* 101 */ "as ::= AS nm", + /* 102 */ "as ::=", + /* 103 */ "from ::=", + /* 104 */ "from ::= FROM seltablist", + /* 105 */ "stl_prefix ::= seltablist joinop", + /* 106 */ "stl_prefix ::=", + /* 107 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", + /* 108 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt", + /* 109 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", + /* 110 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", + /* 111 */ "dbnm ::=", + /* 112 */ "dbnm ::= DOT nm", + /* 113 */ "fullname ::= nm", + /* 114 */ "fullname ::= nm DOT nm", + /* 115 */ "xfullname ::= nm", + /* 116 */ "xfullname ::= nm DOT nm", + /* 117 */ "xfullname ::= nm DOT nm AS nm", + /* 118 */ "xfullname ::= nm AS nm", + /* 119 */ "joinop ::= COMMA|JOIN", + /* 120 */ "joinop ::= JOIN_KW JOIN", + /* 121 */ "joinop ::= JOIN_KW nm JOIN", + /* 122 */ "joinop ::= JOIN_KW nm nm JOIN", + /* 123 */ "on_opt ::= ON expr", + /* 124 */ "on_opt ::=", + /* 125 */ "indexed_opt ::=", + /* 126 */ "indexed_opt ::= INDEXED BY nm", + /* 127 */ "indexed_opt ::= NOT INDEXED", + /* 128 */ "using_opt ::= USING LP idlist RP", + /* 129 */ "using_opt ::=", + /* 130 */ "orderby_opt ::=", + /* 131 */ "orderby_opt ::= ORDER BY sortlist", + /* 132 */ "sortlist ::= sortlist COMMA expr sortorder nulls", + /* 133 */ "sortlist ::= expr sortorder nulls", + /* 134 */ "sortorder ::= ASC", + /* 135 */ "sortorder ::= DESC", + /* 136 */ "sortorder ::=", + /* 137 */ "nulls ::= NULLS FIRST", + /* 138 */ "nulls ::= NULLS LAST", + /* 139 */ "nulls ::=", + /* 140 */ "groupby_opt ::=", + /* 141 */ "groupby_opt ::= GROUP BY nexprlist", + /* 142 */ "having_opt ::=", + /* 143 */ "having_opt ::= HAVING expr", + /* 144 */ "limit_opt ::=", + /* 145 */ "limit_opt ::= LIMIT expr", + /* 146 */ "limit_opt ::= LIMIT expr OFFSET expr", + /* 147 */ "limit_opt ::= LIMIT expr COMMA expr", + /* 148 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt", + /* 149 */ "where_opt ::=", + /* 150 */ "where_opt ::= WHERE expr", + /* 151 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt", + /* 152 */ "setlist ::= setlist COMMA nm EQ expr", + /* 153 */ "setlist ::= setlist COMMA LP idlist RP EQ expr", + /* 154 */ "setlist ::= nm EQ expr", + /* 155 */ "setlist ::= LP idlist RP EQ expr", + /* 156 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert", + /* 157 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES", + /* 158 */ "upsert ::=", + /* 159 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt", + /* 160 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING", + /* 161 */ "upsert ::= ON CONFLICT DO NOTHING", + /* 162 */ "insert_cmd ::= INSERT orconf", + /* 163 */ "insert_cmd ::= REPLACE", + /* 164 */ "idlist_opt ::=", + /* 165 */ "idlist_opt ::= LP idlist RP", + /* 166 */ "idlist ::= idlist COMMA nm", + /* 167 */ "idlist ::= nm", + /* 168 */ "expr ::= LP expr RP", + /* 169 */ "expr ::= ID|INDEXED", + /* 170 */ "expr ::= JOIN_KW", + /* 171 */ "expr ::= nm DOT nm", + /* 172 */ "expr ::= nm DOT nm DOT nm", + /* 173 */ "term ::= NULL|FLOAT|BLOB", + /* 174 */ "term ::= STRING", + /* 175 */ "term ::= INTEGER", + /* 176 */ "expr ::= VARIABLE", + /* 177 */ "expr ::= expr COLLATE ID|STRING", + /* 178 */ "expr ::= CAST LP expr AS typetoken RP", + /* 179 */ "expr ::= ID|INDEXED LP distinct exprlist RP", + /* 180 */ "expr ::= ID|INDEXED LP STAR RP", + /* 181 */ "expr ::= ID|INDEXED LP distinct exprlist RP filter_over", + /* 182 */ "expr ::= ID|INDEXED LP STAR RP filter_over", + /* 183 */ "term ::= CTIME_KW", + /* 184 */ "expr ::= LP nexprlist COMMA expr RP", + /* 185 */ "expr ::= expr AND expr", + /* 186 */ "expr ::= expr OR expr", + /* 187 */ "expr ::= expr LT|GT|GE|LE expr", + /* 188 */ "expr ::= expr EQ|NE expr", + /* 189 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", + /* 190 */ "expr ::= expr PLUS|MINUS expr", + /* 191 */ "expr ::= expr STAR|SLASH|REM expr", + /* 192 */ "expr ::= expr CONCAT expr", + /* 193 */ "likeop ::= NOT LIKE_KW|MATCH", + /* 194 */ "expr ::= expr likeop expr", + /* 195 */ "expr ::= expr likeop expr ESCAPE expr", + /* 196 */ "expr ::= expr ISNULL|NOTNULL", + /* 197 */ "expr ::= expr NOT NULL", + /* 198 */ "expr ::= expr IS expr", + /* 199 */ "expr ::= expr IS NOT expr", + /* 200 */ "expr ::= NOT expr", + /* 201 */ "expr ::= BITNOT expr", + /* 202 */ "expr ::= PLUS|MINUS expr", + /* 203 */ "between_op ::= BETWEEN", + /* 204 */ "between_op ::= NOT BETWEEN", + /* 205 */ "expr ::= expr between_op expr AND expr", + /* 206 */ "in_op ::= IN", + /* 207 */ "in_op ::= NOT IN", + /* 208 */ "expr ::= expr in_op LP exprlist RP", + /* 209 */ "expr ::= LP select RP", + /* 210 */ "expr ::= expr in_op LP select RP", + /* 211 */ "expr ::= expr in_op nm dbnm paren_exprlist", + /* 212 */ "expr ::= EXISTS LP select RP", + /* 213 */ "expr ::= CASE case_operand case_exprlist case_else END", + /* 214 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", + /* 215 */ "case_exprlist ::= WHEN expr THEN expr", + /* 216 */ "case_else ::= ELSE expr", + /* 217 */ "case_else ::=", + /* 218 */ "case_operand ::= expr", + /* 219 */ "case_operand ::=", + /* 220 */ "exprlist ::=", + /* 221 */ "nexprlist ::= nexprlist COMMA expr", + /* 222 */ "nexprlist ::= expr", + /* 223 */ "paren_exprlist ::=", + /* 224 */ "paren_exprlist ::= LP exprlist RP", + /* 225 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt", + /* 226 */ "uniqueflag ::= UNIQUE", + /* 227 */ "uniqueflag ::=", + /* 228 */ "eidlist_opt ::=", + /* 229 */ "eidlist_opt ::= LP eidlist RP", + /* 230 */ "eidlist ::= eidlist COMMA nm collate sortorder", + /* 231 */ "eidlist ::= nm collate sortorder", + /* 232 */ "collate ::=", + /* 233 */ "collate ::= COLLATE ID|STRING", + /* 234 */ "cmd ::= DROP INDEX ifexists fullname", + /* 235 */ "cmd ::= VACUUM vinto", + /* 236 */ "cmd ::= VACUUM nm vinto", + /* 237 */ "vinto ::= INTO expr", + /* 238 */ "vinto ::=", + /* 239 */ "cmd ::= PRAGMA nm dbnm", + /* 240 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", + /* 241 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", + /* 242 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", + /* 243 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", + /* 244 */ "plus_num ::= PLUS INTEGER|FLOAT", + /* 245 */ "minus_num ::= MINUS INTEGER|FLOAT", + /* 246 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", + /* 247 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", + /* 248 */ "trigger_time ::= BEFORE|AFTER", + /* 249 */ "trigger_time ::= INSTEAD OF", + /* 250 */ "trigger_time ::=", + /* 251 */ "trigger_event ::= DELETE|INSERT", + /* 252 */ "trigger_event ::= UPDATE", + /* 253 */ "trigger_event ::= UPDATE OF idlist", + /* 254 */ "when_clause ::=", + /* 255 */ "when_clause ::= WHEN expr", + /* 256 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", + /* 257 */ "trigger_cmd_list ::= trigger_cmd SEMI", + /* 258 */ "trnm ::= nm DOT nm", + /* 259 */ "tridxby ::= INDEXED BY nm", + /* 260 */ "tridxby ::= NOT INDEXED", + /* 261 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt", + /* 262 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt", + /* 263 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt", + /* 264 */ "trigger_cmd ::= scanpt select scanpt", + /* 265 */ "expr ::= RAISE LP IGNORE RP", + /* 266 */ "expr ::= RAISE LP raisetype COMMA nm RP", + /* 267 */ "raisetype ::= ROLLBACK", + /* 268 */ "raisetype ::= ABORT", + /* 269 */ "raisetype ::= FAIL", + /* 270 */ "cmd ::= DROP TRIGGER ifexists fullname", + /* 271 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", + /* 272 */ "cmd ::= DETACH database_kw_opt expr", + /* 273 */ "key_opt ::=", + /* 274 */ "key_opt ::= KEY expr", + /* 275 */ "cmd ::= REINDEX", + /* 276 */ "cmd ::= REINDEX nm dbnm", + /* 277 */ "cmd ::= ANALYZE", + /* 278 */ "cmd ::= ANALYZE nm dbnm", + /* 279 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", + /* 280 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist", + /* 281 */ "add_column_fullname ::= fullname", + /* 282 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm", + /* 283 */ "cmd ::= create_vtab", + /* 284 */ "cmd ::= create_vtab LP vtabarglist RP", + /* 285 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", + /* 286 */ "vtabarg ::=", + /* 287 */ "vtabargtoken ::= ANY", + /* 288 */ "vtabargtoken ::= lp anylist RP", + /* 289 */ "lp ::= LP", + /* 290 */ "with ::= WITH wqlist", + /* 291 */ "with ::= WITH RECURSIVE wqlist", + /* 292 */ "wqlist ::= nm eidlist_opt AS LP select RP", + /* 293 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP", + /* 294 */ "windowdefn_list ::= windowdefn", + /* 295 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn", + /* 296 */ "windowdefn ::= nm AS LP window RP", + /* 297 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt", + /* 298 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt", + /* 299 */ "window ::= ORDER BY sortlist frame_opt", + /* 300 */ "window ::= nm ORDER BY sortlist frame_opt", + /* 301 */ "window ::= frame_opt", + /* 302 */ "window ::= nm frame_opt", + /* 303 */ "frame_opt ::=", + /* 304 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt", + /* 305 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt", + /* 306 */ "range_or_rows ::= RANGE|ROWS|GROUPS", + /* 307 */ "frame_bound_s ::= frame_bound", + /* 308 */ "frame_bound_s ::= UNBOUNDED PRECEDING", + /* 309 */ "frame_bound_e ::= frame_bound", + /* 310 */ "frame_bound_e ::= UNBOUNDED FOLLOWING", + /* 311 */ "frame_bound ::= expr PRECEDING|FOLLOWING", + /* 312 */ "frame_bound ::= CURRENT ROW", + /* 313 */ "frame_exclude_opt ::=", + /* 314 */ "frame_exclude_opt ::= EXCLUDE frame_exclude", + /* 315 */ "frame_exclude ::= NO OTHERS", + /* 316 */ "frame_exclude ::= CURRENT ROW", + /* 317 */ "frame_exclude ::= GROUP|TIES", + /* 318 */ "window_clause ::= WINDOW windowdefn_list", + /* 319 */ "filter_over ::= filter_clause over_clause", + /* 320 */ "filter_over ::= over_clause", + /* 321 */ "filter_over ::= filter_clause", + /* 322 */ "over_clause ::= OVER LP window RP", + /* 323 */ "over_clause ::= OVER nm", + /* 324 */ "filter_clause ::= FILTER LP WHERE expr RP", + /* 325 */ "input ::= cmdlist", + /* 326 */ "cmdlist ::= cmdlist ecmd", + /* 327 */ "cmdlist ::= ecmd", + /* 328 */ "ecmd ::= SEMI", + /* 329 */ "ecmd ::= cmdx SEMI", + /* 330 */ "ecmd ::= explain cmdx SEMI", + /* 331 */ "trans_opt ::=", + /* 332 */ "trans_opt ::= TRANSACTION", + /* 333 */ "trans_opt ::= TRANSACTION nm", + /* 334 */ "savepoint_opt ::= SAVEPOINT", + /* 335 */ "savepoint_opt ::=", + /* 336 */ "cmd ::= create_table create_table_args", + /* 337 */ "columnlist ::= columnlist COMMA columnname carglist", + /* 338 */ "columnlist ::= columnname carglist", + /* 339 */ "nm ::= ID|INDEXED", + /* 340 */ "nm ::= STRING", + /* 341 */ "nm ::= JOIN_KW", + /* 342 */ "typetoken ::= typename", + /* 343 */ "typename ::= ID|STRING", + /* 344 */ "signed ::= plus_num", + /* 345 */ "signed ::= minus_num", + /* 346 */ "carglist ::= carglist ccons", + /* 347 */ "carglist ::=", + /* 348 */ "ccons ::= NULL onconf", + /* 349 */ "ccons ::= GENERATED ALWAYS AS generated", + /* 350 */ "ccons ::= AS generated", + /* 351 */ "conslist_opt ::= COMMA conslist", + /* 352 */ "conslist ::= conslist tconscomma tcons", + /* 353 */ "conslist ::= tcons", + /* 354 */ "tconscomma ::=", + /* 355 */ "defer_subclause_opt ::= defer_subclause", + /* 356 */ "resolvetype ::= raisetype", + /* 357 */ "selectnowith ::= oneselect", + /* 358 */ "oneselect ::= values", + /* 359 */ "sclp ::= selcollist COMMA", + /* 360 */ "as ::= ID|STRING", + /* 361 */ "expr ::= term", + /* 362 */ "likeop ::= LIKE_KW|MATCH", + /* 363 */ "exprlist ::= nexprlist", + /* 364 */ "nmnum ::= plus_num", + /* 365 */ "nmnum ::= nm", + /* 366 */ "nmnum ::= ON", + /* 367 */ "nmnum ::= DELETE", + /* 368 */ "nmnum ::= DEFAULT", + /* 369 */ "plus_num ::= INTEGER|FLOAT", + /* 370 */ "foreach_clause ::=", + /* 371 */ "foreach_clause ::= FOR EACH ROW", + /* 372 */ "trnm ::= nm", + /* 373 */ "tridxby ::=", + /* 374 */ "database_kw_opt ::= DATABASE", + /* 375 */ "database_kw_opt ::=", + /* 376 */ "kwcolumn_opt ::=", + /* 377 */ "kwcolumn_opt ::= COLUMNKW", + /* 378 */ "vtabarglist ::= vtabarg", + /* 379 */ "vtabarglist ::= vtabarglist COMMA vtabarg", + /* 380 */ "vtabarg ::= vtabarg vtabargtoken", + /* 381 */ "anylist ::=", + /* 382 */ "anylist ::= anylist LP anylist RP", + /* 383 */ "anylist ::= anylist ANY", + /* 384 */ "with ::=", }; #endif /* NDEBUG */ @@ -137408,7 +157912,7 @@ static int yyGrowStack(yyParser *p){ #endif /* Datatype of the argument to the memory allocated passed as the -** second argument to sqlite3ParserAlloc() below. This can be changed by +** second argument to tdsqlite3ParserAlloc() below. This can be changed by ** putting an appropriate #define in the %include section of the input ** grammar. */ @@ -137416,6 +157920,35 @@ static int yyGrowStack(yyParser *p){ # define YYMALLOCARGTYPE size_t #endif +/* Initialize a new parser that has already been allocated. +*/ +SQLITE_PRIVATE void tdsqlite3ParserInit(void *yypRawParser tdsqlite3ParserCTX_PDECL){ + yyParser *yypParser = (yyParser*)yypRawParser; + tdsqlite3ParserCTX_STORE +#ifdef YYTRACKMAXSTACKDEPTH + yypParser->yyhwm = 0; +#endif +#if YYSTACKDEPTH<=0 + yypParser->yytos = NULL; + yypParser->yystack = NULL; + yypParser->yystksz = 0; + if( yyGrowStack(yypParser) ){ + yypParser->yystack = &yypParser->yystk0; + yypParser->yystksz = 1; + } +#endif +#ifndef YYNOERRORRECOVERY + yypParser->yyerrcnt = -1; +#endif + yypParser->yytos = yypParser->yystack; + yypParser->yystack[0].stateno = 0; + yypParser->yystack[0].major = 0; +#if YYSTACKDEPTH>0 + yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1]; +#endif +} + +#ifndef tdsqlite3Parser_ENGINEALWAYSONSTACK /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like @@ -137426,33 +157959,19 @@ static int yyGrowStack(yyParser *p){ ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls -** to sqlite3Parser and sqlite3ParserFree. +** to tdsqlite3Parser and tdsqlite3ParserFree. */ -SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){ - yyParser *pParser; - pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) ); - if( pParser ){ -#ifdef YYTRACKMAXSTACKDEPTH - pParser->yyhwm = 0; -#endif -#if YYSTACKDEPTH<=0 - pParser->yytos = NULL; - pParser->yystack = NULL; - pParser->yystksz = 0; - if( yyGrowStack(pParser) ){ - pParser->yystack = &pParser->yystk0; - pParser->yystksz = 1; - } -#endif -#ifndef YYNOERRORRECOVERY - pParser->yyerrcnt = -1; -#endif - pParser->yytos = pParser->yystack; - pParser->yystack[0].stateno = 0; - pParser->yystack[0].major = 0; +SQLITE_PRIVATE void *tdsqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) tdsqlite3ParserCTX_PDECL){ + yyParser *yypParser; + yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) ); + if( yypParser ){ + tdsqlite3ParserCTX_STORE + tdsqlite3ParserInit(yypParser tdsqlite3ParserCTX_PARAM); } - return pParser; + return (void*)yypParser; } +#endif /* tdsqlite3Parser_ENGINEALWAYSONSTACK */ + /* The following function deletes the "minor type" or semantic value ** associated with a symbol. The symbol can be either a terminal @@ -137466,7 +157985,8 @@ static void yy_destructor( YYCODETYPE yymajor, /* Type code for object to destroy */ YYMINORTYPE *yypminor /* The object to be destroyed */ ){ - sqlite3ParserARG_FETCH; + tdsqlite3ParserARG_FETCH + tdsqlite3ParserCTX_FETCH switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen @@ -137479,77 +157999,98 @@ static void yy_destructor( ** inside the C code. */ /********* Begin destructor definitions ***************************************/ - case 163: /* select */ - case 194: /* selectnowith */ - case 195: /* oneselect */ - case 206: /* values */ + case 200: /* select */ + case 234: /* selectnowith */ + case 235: /* oneselect */ + case 247: /* values */ +{ +tdsqlite3SelectDelete(pParse->db, (yypminor->yy539)); +} + break; + case 211: /* term */ + case 212: /* expr */ + case 241: /* where_opt */ + case 243: /* having_opt */ + case 255: /* on_opt */ + case 271: /* case_operand */ + case 273: /* case_else */ + case 276: /* vinto */ + case 283: /* when_clause */ + case 288: /* key_opt */ + case 302: /* filter_clause */ +{ +tdsqlite3ExprDelete(pParse->db, (yypminor->yy202)); +} + break; + case 216: /* eidlist_opt */ + case 226: /* sortlist */ + case 227: /* eidlist */ + case 239: /* selcollist */ + case 242: /* groupby_opt */ + case 244: /* orderby_opt */ + case 248: /* nexprlist */ + case 249: /* sclp */ + case 257: /* exprlist */ + case 262: /* setlist */ + case 270: /* paren_exprlist */ + case 272: /* case_exprlist */ + case 301: /* part_opt */ { -sqlite3SelectDelete(pParse->db, (yypminor->yy243)); +tdsqlite3ExprListDelete(pParse->db, (yypminor->yy242)); } break; - case 172: /* term */ - case 173: /* expr */ + case 233: /* fullname */ + case 240: /* from */ + case 251: /* seltablist */ + case 252: /* stl_prefix */ + case 258: /* xfullname */ { -sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr); +tdsqlite3SrcListDelete(pParse->db, (yypminor->yy47)); } break; - case 177: /* eidlist_opt */ - case 186: /* sortlist */ - case 187: /* eidlist */ - case 199: /* selcollist */ - case 202: /* groupby_opt */ - case 204: /* orderby_opt */ - case 207: /* nexprlist */ - case 208: /* exprlist */ - case 209: /* sclp */ - case 218: /* setlist */ - case 224: /* paren_exprlist */ - case 226: /* case_exprlist */ + case 236: /* wqlist */ { -sqlite3ExprListDelete(pParse->db, (yypminor->yy148)); +tdsqlite3WithDelete(pParse->db, (yypminor->yy131)); } break; - case 193: /* fullname */ - case 200: /* from */ - case 211: /* seltablist */ - case 212: /* stl_prefix */ + case 246: /* window_clause */ + case 297: /* windowdefn_list */ { -sqlite3SrcListDelete(pParse->db, (yypminor->yy185)); +tdsqlite3WindowListDelete(pParse->db, (yypminor->yy303)); } break; - case 196: /* with */ - case 250: /* wqlist */ + case 256: /* using_opt */ + case 259: /* idlist */ + case 264: /* idlist_opt */ { -sqlite3WithDelete(pParse->db, (yypminor->yy285)); +tdsqlite3IdListDelete(pParse->db, (yypminor->yy600)); } break; - case 201: /* where_opt */ - case 203: /* having_opt */ - case 215: /* on_opt */ - case 225: /* case_operand */ - case 227: /* case_else */ - case 236: /* when_clause */ - case 241: /* key_opt */ + case 266: /* filter_over */ + case 298: /* windowdefn */ + case 299: /* window */ + case 300: /* frame_opt */ + case 303: /* over_clause */ { -sqlite3ExprDelete(pParse->db, (yypminor->yy72)); +tdsqlite3WindowDelete(pParse->db, (yypminor->yy303)); } break; - case 216: /* using_opt */ - case 217: /* idlist */ - case 220: /* idlist_opt */ + case 279: /* trigger_cmd_list */ + case 284: /* trigger_cmd */ { -sqlite3IdListDelete(pParse->db, (yypminor->yy254)); +tdsqlite3DeleteTriggerStep(pParse->db, (yypminor->yy447)); } break; - case 232: /* trigger_cmd_list */ - case 237: /* trigger_cmd */ + case 281: /* trigger_event */ { -sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145)); +tdsqlite3IdListDelete(pParse->db, (yypminor->yy230).b); } break; - case 234: /* trigger_event */ + case 305: /* frame_bound */ + case 306: /* frame_bound_s */ + case 307: /* frame_bound_e */ { -sqlite3IdListDelete(pParse->db, (yypminor->yy332).b); +tdsqlite3ExprDelete(pParse->db, (yypminor->yy77).pExpr); } break; /********* End destructor definitions *****************************************/ @@ -137578,6 +158119,18 @@ static void yy_pop_parser_stack(yyParser *pParser){ yy_destructor(pParser, yytos->major, &yytos->minor); } +/* +** Clear all secondary memory allocations from the parser +*/ +SQLITE_PRIVATE void tdsqlite3ParserFinalize(void *p){ + yyParser *pParser = (yyParser*)p; + while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser); +#if YYSTACKDEPTH<=0 + if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack); +#endif +} + +#ifndef tdsqlite3Parser_ENGINEALWAYSONSTACK /* ** Deallocate and destroy a parser. Destructors are called for ** all stack elements before shutting the parser down. @@ -137586,53 +158139,95 @@ static void yy_pop_parser_stack(yyParser *pParser){ ** is defined in a %include section of the input grammar) then it is ** assumed that the input pointer is never NULL. */ -SQLITE_PRIVATE void sqlite3ParserFree( +SQLITE_PRIVATE void tdsqlite3ParserFree( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ - yyParser *pParser = (yyParser*)p; #ifndef YYPARSEFREENEVERNULL - if( pParser==0 ) return; -#endif - while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser); -#if YYSTACKDEPTH<=0 - if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack); + if( p==0 ) return; #endif - (*freeProc)((void*)pParser); + tdsqlite3ParserFinalize(p); + (*freeProc)(p); } +#endif /* tdsqlite3Parser_ENGINEALWAYSONSTACK */ /* ** Return the peak depth of the stack for a parser. */ #ifdef YYTRACKMAXSTACKDEPTH -SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){ +SQLITE_PRIVATE int tdsqlite3ParserStackPeak(void *p){ yyParser *pParser = (yyParser*)p; return pParser->yyhwm; } #endif +/* This array of booleans keeps track of the parser statement +** coverage. The element yycoverage[X][Y] is set when the parser +** is in state X and has a lookahead token Y. In a well-tested +** systems, every element of this matrix should end up being set. +*/ +#if defined(YYCOVERAGE) +static unsigned char yycoverage[YYNSTATE][YYNTOKEN]; +#endif + +/* +** Write into out a description of every state/lookahead combination that +** +** (1) has not been used by the parser, and +** (2) is not a syntax error. +** +** Return the number of missed state/lookahead combinations. +*/ +#if defined(YYCOVERAGE) +SQLITE_PRIVATE int tdsqlite3ParserCoverage(FILE *out){ + int stateno, iLookAhead, i; + int nMissed = 0; + for(stateno=0; stateno<YYNSTATE; stateno++){ + i = yy_shift_ofst[stateno]; + for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){ + if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue; + if( yycoverage[stateno][iLookAhead]==0 ) nMissed++; + if( out ){ + fprintf(out,"State %d lookahead %s %s\n", stateno, + yyTokenName[iLookAhead], + yycoverage[stateno][iLookAhead] ? "ok" : "missed"); + } + } + } + return nMissed; +} +#endif + /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. */ -static unsigned int yy_find_shift_action( - yyParser *pParser, /* The parser */ - YYCODETYPE iLookAhead /* The look-ahead token */ +static YYACTIONTYPE yy_find_shift_action( + YYCODETYPE iLookAhead, /* The look-ahead token */ + YYACTIONTYPE stateno /* Current state number */ ){ int i; - int stateno = pParser->yytos->stateno; - - if( stateno>=YY_MIN_REDUCE ) return stateno; + + if( stateno>YY_MAX_SHIFT ) return stateno; assert( stateno <= YY_SHIFT_COUNT ); +#if defined(YYCOVERAGE) + yycoverage[stateno][iLookAhead] = 1; +#endif do{ i = yy_shift_ofst[stateno]; + assert( i>=0 ); + assert( i<=YY_ACTTAB_COUNT ); + assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD ); assert( iLookAhead!=YYNOCODE ); + assert( iLookAhead < YYNTOKEN ); i += iLookAhead; - if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ + assert( i<(int)YY_NLOOKAHEAD ); + if( yy_lookahead[i]!=iLookAhead ){ #ifdef YYFALLBACK YYCODETYPE iFallback; /* Fallback token */ - if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) - && (iFallback = yyFallback[iLookAhead])!=0 ){ + assert( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) ); + iFallback = yyFallback[iLookAhead]; + if( iFallback!=0 ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n", @@ -137647,15 +158242,8 @@ static unsigned int yy_find_shift_action( #ifdef YYWILDCARD { int j = i - iLookAhead + YYWILDCARD; - if( -#if YY_SHIFT_MIN+YYWILDCARD<0 - j>=0 && -#endif -#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT - j<YY_ACTTAB_COUNT && -#endif - yy_lookahead[j]==YYWILDCARD && iLookAhead>0 - ){ + assert( j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) ); + if( yy_lookahead[j]==YYWILDCARD && iLookAhead>0 ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n", @@ -137669,6 +158257,7 @@ static unsigned int yy_find_shift_action( #endif /* YYWILDCARD */ return yy_default[stateno]; }else{ + assert( i>=0 && i<sizeof(yy_action)/sizeof(yy_action[0]) ); return yy_action[i]; } }while(1); @@ -137678,8 +158267,8 @@ static unsigned int yy_find_shift_action( ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. */ -static int yy_find_reduce_action( - int stateno, /* Current state number */ +static YYACTIONTYPE yy_find_reduce_action( + YYACTIONTYPE stateno, /* Current state number */ YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; @@ -137691,7 +158280,6 @@ static int yy_find_reduce_action( assert( stateno<=YY_REDUCE_COUNT ); #endif i = yy_reduce_ofst[stateno]; - assert( i!=YY_REDUCE_USE_DFLT ); assert( iLookAhead!=YYNOCODE ); i += iLookAhead; #ifdef YYERRORSYMBOL @@ -137709,8 +158297,8 @@ static int yy_find_reduce_action( ** The following routine is called if the stack overflows. */ static void yyStackOverflow(yyParser *yypParser){ - sqlite3ParserARG_FETCH; - yypParser->yytos--; + tdsqlite3ParserARG_FETCH + tdsqlite3ParserCTX_FETCH #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); @@ -137721,29 +158309,31 @@ static void yyStackOverflow(yyParser *yypParser){ ** stack every overflows */ /******** Begin %stack_overflow code ******************************************/ - sqlite3ErrorMsg(pParse, "parser stack overflow"); + tdsqlite3ErrorMsg(pParse, "parser stack overflow"); /******** End %stack_overflow code ********************************************/ - sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */ + tdsqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */ + tdsqlite3ParserCTX_STORE } /* ** Print tracing information for a SHIFT action */ #ifndef NDEBUG -static void yyTraceShift(yyParser *yypParser, int yyNewState){ +static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){ if( yyTraceFILE ){ if( yyNewState<YYNSTATE ){ - fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n", - yyTracePrompt,yyTokenName[yypParser->yytos->major], + fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n", + yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major], yyNewState); }else{ - fprintf(yyTraceFILE,"%sShift '%s'\n", - yyTracePrompt,yyTokenName[yypParser->yytos->major]); + fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n", + yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major], + yyNewState - YY_MIN_REDUCE); } } } #else -# define yyTraceShift(X,Y) +# define yyTraceShift(X,Y,Z) #endif /* @@ -137751,9 +158341,9 @@ static void yyTraceShift(yyParser *yypParser, int yyNewState){ */ static void yy_shift( yyParser *yypParser, /* The parser to be shifted */ - int yyNewState, /* The new state to shift in */ - int yyMajor, /* The major token to shift in */ - sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */ + YYACTIONTYPE yyNewState, /* The new state to shift in */ + YYCODETYPE yyMajor, /* The major token to shift in */ + tdsqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */ ){ yyStackEntry *yytos; yypParser->yytos++; @@ -137764,13 +158354,15 @@ static void yy_shift( } #endif #if YYSTACKDEPTH>0 - if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){ + if( yypParser->yytos>yypParser->yystackEnd ){ + yypParser->yytos--; yyStackOverflow(yypParser); return; } #else if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){ if( yyGrowStack(yypParser) ){ + yypParser->yytos--; yyStackOverflow(yypParser); return; } @@ -137780,351 +158372,790 @@ static void yy_shift( yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE; } yytos = yypParser->yytos; - yytos->stateno = (YYACTIONTYPE)yyNewState; - yytos->major = (YYCODETYPE)yyMajor; + yytos->stateno = yyNewState; + yytos->major = yyMajor; yytos->minor.yy0 = yyMinor; - yyTraceShift(yypParser, yyNewState); -} + yyTraceShift(yypParser, yyNewState, "Shift"); +} + +/* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side +** of that rule */ +static const YYCODETYPE yyRuleInfoLhs[] = { + 185, /* (0) explain ::= EXPLAIN */ + 185, /* (1) explain ::= EXPLAIN QUERY PLAN */ + 184, /* (2) cmdx ::= cmd */ + 186, /* (3) cmd ::= BEGIN transtype trans_opt */ + 187, /* (4) transtype ::= */ + 187, /* (5) transtype ::= DEFERRED */ + 187, /* (6) transtype ::= IMMEDIATE */ + 187, /* (7) transtype ::= EXCLUSIVE */ + 186, /* (8) cmd ::= COMMIT|END trans_opt */ + 186, /* (9) cmd ::= ROLLBACK trans_opt */ + 186, /* (10) cmd ::= SAVEPOINT nm */ + 186, /* (11) cmd ::= RELEASE savepoint_opt nm */ + 186, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ + 191, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */ + 193, /* (14) createkw ::= CREATE */ + 195, /* (15) ifnotexists ::= */ + 195, /* (16) ifnotexists ::= IF NOT EXISTS */ + 194, /* (17) temp ::= TEMP */ + 194, /* (18) temp ::= */ + 192, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */ + 192, /* (20) create_table_args ::= AS select */ + 199, /* (21) table_options ::= */ + 199, /* (22) table_options ::= WITHOUT nm */ + 201, /* (23) columnname ::= nm typetoken */ + 203, /* (24) typetoken ::= */ + 203, /* (25) typetoken ::= typename LP signed RP */ + 203, /* (26) typetoken ::= typename LP signed COMMA signed RP */ + 204, /* (27) typename ::= typename ID|STRING */ + 208, /* (28) scanpt ::= */ + 209, /* (29) scantok ::= */ + 210, /* (30) ccons ::= CONSTRAINT nm */ + 210, /* (31) ccons ::= DEFAULT scantok term */ + 210, /* (32) ccons ::= DEFAULT LP expr RP */ + 210, /* (33) ccons ::= DEFAULT PLUS scantok term */ + 210, /* (34) ccons ::= DEFAULT MINUS scantok term */ + 210, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */ + 210, /* (36) ccons ::= NOT NULL onconf */ + 210, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */ + 210, /* (38) ccons ::= UNIQUE onconf */ + 210, /* (39) ccons ::= CHECK LP expr RP */ + 210, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */ + 210, /* (41) ccons ::= defer_subclause */ + 210, /* (42) ccons ::= COLLATE ID|STRING */ + 219, /* (43) generated ::= LP expr RP */ + 219, /* (44) generated ::= LP expr RP ID */ + 215, /* (45) autoinc ::= */ + 215, /* (46) autoinc ::= AUTOINCR */ + 217, /* (47) refargs ::= */ + 217, /* (48) refargs ::= refargs refarg */ + 220, /* (49) refarg ::= MATCH nm */ + 220, /* (50) refarg ::= ON INSERT refact */ + 220, /* (51) refarg ::= ON DELETE refact */ + 220, /* (52) refarg ::= ON UPDATE refact */ + 221, /* (53) refact ::= SET NULL */ + 221, /* (54) refact ::= SET DEFAULT */ + 221, /* (55) refact ::= CASCADE */ + 221, /* (56) refact ::= RESTRICT */ + 221, /* (57) refact ::= NO ACTION */ + 218, /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ + 218, /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ + 222, /* (60) init_deferred_pred_opt ::= */ + 222, /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */ + 222, /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ + 198, /* (63) conslist_opt ::= */ + 224, /* (64) tconscomma ::= COMMA */ + 225, /* (65) tcons ::= CONSTRAINT nm */ + 225, /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ + 225, /* (67) tcons ::= UNIQUE LP sortlist RP onconf */ + 225, /* (68) tcons ::= CHECK LP expr RP onconf */ + 225, /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ + 228, /* (70) defer_subclause_opt ::= */ + 213, /* (71) onconf ::= */ + 213, /* (72) onconf ::= ON CONFLICT resolvetype */ + 229, /* (73) orconf ::= */ + 229, /* (74) orconf ::= OR resolvetype */ + 230, /* (75) resolvetype ::= IGNORE */ + 230, /* (76) resolvetype ::= REPLACE */ + 186, /* (77) cmd ::= DROP TABLE ifexists fullname */ + 232, /* (78) ifexists ::= IF EXISTS */ + 232, /* (79) ifexists ::= */ + 186, /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ + 186, /* (81) cmd ::= DROP VIEW ifexists fullname */ + 186, /* (82) cmd ::= select */ + 200, /* (83) select ::= WITH wqlist selectnowith */ + 200, /* (84) select ::= WITH RECURSIVE wqlist selectnowith */ + 200, /* (85) select ::= selectnowith */ + 234, /* (86) selectnowith ::= selectnowith multiselect_op oneselect */ + 237, /* (87) multiselect_op ::= UNION */ + 237, /* (88) multiselect_op ::= UNION ALL */ + 237, /* (89) multiselect_op ::= EXCEPT|INTERSECT */ + 235, /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ + 235, /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */ + 247, /* (92) values ::= VALUES LP nexprlist RP */ + 247, /* (93) values ::= values COMMA LP nexprlist RP */ + 238, /* (94) distinct ::= DISTINCT */ + 238, /* (95) distinct ::= ALL */ + 238, /* (96) distinct ::= */ + 249, /* (97) sclp ::= */ + 239, /* (98) selcollist ::= sclp scanpt expr scanpt as */ + 239, /* (99) selcollist ::= sclp scanpt STAR */ + 239, /* (100) selcollist ::= sclp scanpt nm DOT STAR */ + 250, /* (101) as ::= AS nm */ + 250, /* (102) as ::= */ + 240, /* (103) from ::= */ + 240, /* (104) from ::= FROM seltablist */ + 252, /* (105) stl_prefix ::= seltablist joinop */ + 252, /* (106) stl_prefix ::= */ + 251, /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ + 251, /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ + 251, /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */ + 251, /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ + 196, /* (111) dbnm ::= */ + 196, /* (112) dbnm ::= DOT nm */ + 233, /* (113) fullname ::= nm */ + 233, /* (114) fullname ::= nm DOT nm */ + 258, /* (115) xfullname ::= nm */ + 258, /* (116) xfullname ::= nm DOT nm */ + 258, /* (117) xfullname ::= nm DOT nm AS nm */ + 258, /* (118) xfullname ::= nm AS nm */ + 253, /* (119) joinop ::= COMMA|JOIN */ + 253, /* (120) joinop ::= JOIN_KW JOIN */ + 253, /* (121) joinop ::= JOIN_KW nm JOIN */ + 253, /* (122) joinop ::= JOIN_KW nm nm JOIN */ + 255, /* (123) on_opt ::= ON expr */ + 255, /* (124) on_opt ::= */ + 254, /* (125) indexed_opt ::= */ + 254, /* (126) indexed_opt ::= INDEXED BY nm */ + 254, /* (127) indexed_opt ::= NOT INDEXED */ + 256, /* (128) using_opt ::= USING LP idlist RP */ + 256, /* (129) using_opt ::= */ + 244, /* (130) orderby_opt ::= */ + 244, /* (131) orderby_opt ::= ORDER BY sortlist */ + 226, /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */ + 226, /* (133) sortlist ::= expr sortorder nulls */ + 214, /* (134) sortorder ::= ASC */ + 214, /* (135) sortorder ::= DESC */ + 214, /* (136) sortorder ::= */ + 260, /* (137) nulls ::= NULLS FIRST */ + 260, /* (138) nulls ::= NULLS LAST */ + 260, /* (139) nulls ::= */ + 242, /* (140) groupby_opt ::= */ + 242, /* (141) groupby_opt ::= GROUP BY nexprlist */ + 243, /* (142) having_opt ::= */ + 243, /* (143) having_opt ::= HAVING expr */ + 245, /* (144) limit_opt ::= */ + 245, /* (145) limit_opt ::= LIMIT expr */ + 245, /* (146) limit_opt ::= LIMIT expr OFFSET expr */ + 245, /* (147) limit_opt ::= LIMIT expr COMMA expr */ + 186, /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */ + 241, /* (149) where_opt ::= */ + 241, /* (150) where_opt ::= WHERE expr */ + 186, /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */ + 262, /* (152) setlist ::= setlist COMMA nm EQ expr */ + 262, /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */ + 262, /* (154) setlist ::= nm EQ expr */ + 262, /* (155) setlist ::= LP idlist RP EQ expr */ + 186, /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */ + 186, /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */ + 265, /* (158) upsert ::= */ + 265, /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */ + 265, /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */ + 265, /* (161) upsert ::= ON CONFLICT DO NOTHING */ + 263, /* (162) insert_cmd ::= INSERT orconf */ + 263, /* (163) insert_cmd ::= REPLACE */ + 264, /* (164) idlist_opt ::= */ + 264, /* (165) idlist_opt ::= LP idlist RP */ + 259, /* (166) idlist ::= idlist COMMA nm */ + 259, /* (167) idlist ::= nm */ + 212, /* (168) expr ::= LP expr RP */ + 212, /* (169) expr ::= ID|INDEXED */ + 212, /* (170) expr ::= JOIN_KW */ + 212, /* (171) expr ::= nm DOT nm */ + 212, /* (172) expr ::= nm DOT nm DOT nm */ + 211, /* (173) term ::= NULL|FLOAT|BLOB */ + 211, /* (174) term ::= STRING */ + 211, /* (175) term ::= INTEGER */ + 212, /* (176) expr ::= VARIABLE */ + 212, /* (177) expr ::= expr COLLATE ID|STRING */ + 212, /* (178) expr ::= CAST LP expr AS typetoken RP */ + 212, /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */ + 212, /* (180) expr ::= ID|INDEXED LP STAR RP */ + 212, /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */ + 212, /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */ + 211, /* (183) term ::= CTIME_KW */ + 212, /* (184) expr ::= LP nexprlist COMMA expr RP */ + 212, /* (185) expr ::= expr AND expr */ + 212, /* (186) expr ::= expr OR expr */ + 212, /* (187) expr ::= expr LT|GT|GE|LE expr */ + 212, /* (188) expr ::= expr EQ|NE expr */ + 212, /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ + 212, /* (190) expr ::= expr PLUS|MINUS expr */ + 212, /* (191) expr ::= expr STAR|SLASH|REM expr */ + 212, /* (192) expr ::= expr CONCAT expr */ + 267, /* (193) likeop ::= NOT LIKE_KW|MATCH */ + 212, /* (194) expr ::= expr likeop expr */ + 212, /* (195) expr ::= expr likeop expr ESCAPE expr */ + 212, /* (196) expr ::= expr ISNULL|NOTNULL */ + 212, /* (197) expr ::= expr NOT NULL */ + 212, /* (198) expr ::= expr IS expr */ + 212, /* (199) expr ::= expr IS NOT expr */ + 212, /* (200) expr ::= NOT expr */ + 212, /* (201) expr ::= BITNOT expr */ + 212, /* (202) expr ::= PLUS|MINUS expr */ + 268, /* (203) between_op ::= BETWEEN */ + 268, /* (204) between_op ::= NOT BETWEEN */ + 212, /* (205) expr ::= expr between_op expr AND expr */ + 269, /* (206) in_op ::= IN */ + 269, /* (207) in_op ::= NOT IN */ + 212, /* (208) expr ::= expr in_op LP exprlist RP */ + 212, /* (209) expr ::= LP select RP */ + 212, /* (210) expr ::= expr in_op LP select RP */ + 212, /* (211) expr ::= expr in_op nm dbnm paren_exprlist */ + 212, /* (212) expr ::= EXISTS LP select RP */ + 212, /* (213) expr ::= CASE case_operand case_exprlist case_else END */ + 272, /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */ + 272, /* (215) case_exprlist ::= WHEN expr THEN expr */ + 273, /* (216) case_else ::= ELSE expr */ + 273, /* (217) case_else ::= */ + 271, /* (218) case_operand ::= expr */ + 271, /* (219) case_operand ::= */ + 257, /* (220) exprlist ::= */ + 248, /* (221) nexprlist ::= nexprlist COMMA expr */ + 248, /* (222) nexprlist ::= expr */ + 270, /* (223) paren_exprlist ::= */ + 270, /* (224) paren_exprlist ::= LP exprlist RP */ + 186, /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ + 274, /* (226) uniqueflag ::= UNIQUE */ + 274, /* (227) uniqueflag ::= */ + 216, /* (228) eidlist_opt ::= */ + 216, /* (229) eidlist_opt ::= LP eidlist RP */ + 227, /* (230) eidlist ::= eidlist COMMA nm collate sortorder */ + 227, /* (231) eidlist ::= nm collate sortorder */ + 275, /* (232) collate ::= */ + 275, /* (233) collate ::= COLLATE ID|STRING */ + 186, /* (234) cmd ::= DROP INDEX ifexists fullname */ + 186, /* (235) cmd ::= VACUUM vinto */ + 186, /* (236) cmd ::= VACUUM nm vinto */ + 276, /* (237) vinto ::= INTO expr */ + 276, /* (238) vinto ::= */ + 186, /* (239) cmd ::= PRAGMA nm dbnm */ + 186, /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */ + 186, /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */ + 186, /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */ + 186, /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */ + 206, /* (244) plus_num ::= PLUS INTEGER|FLOAT */ + 207, /* (245) minus_num ::= MINUS INTEGER|FLOAT */ + 186, /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ + 278, /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ + 280, /* (248) trigger_time ::= BEFORE|AFTER */ + 280, /* (249) trigger_time ::= INSTEAD OF */ + 280, /* (250) trigger_time ::= */ + 281, /* (251) trigger_event ::= DELETE|INSERT */ + 281, /* (252) trigger_event ::= UPDATE */ + 281, /* (253) trigger_event ::= UPDATE OF idlist */ + 283, /* (254) when_clause ::= */ + 283, /* (255) when_clause ::= WHEN expr */ + 279, /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ + 279, /* (257) trigger_cmd_list ::= trigger_cmd SEMI */ + 285, /* (258) trnm ::= nm DOT nm */ + 286, /* (259) tridxby ::= INDEXED BY nm */ + 286, /* (260) tridxby ::= NOT INDEXED */ + 284, /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */ + 284, /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */ + 284, /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */ + 284, /* (264) trigger_cmd ::= scanpt select scanpt */ + 212, /* (265) expr ::= RAISE LP IGNORE RP */ + 212, /* (266) expr ::= RAISE LP raisetype COMMA nm RP */ + 231, /* (267) raisetype ::= ROLLBACK */ + 231, /* (268) raisetype ::= ABORT */ + 231, /* (269) raisetype ::= FAIL */ + 186, /* (270) cmd ::= DROP TRIGGER ifexists fullname */ + 186, /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ + 186, /* (272) cmd ::= DETACH database_kw_opt expr */ + 288, /* (273) key_opt ::= */ + 288, /* (274) key_opt ::= KEY expr */ + 186, /* (275) cmd ::= REINDEX */ + 186, /* (276) cmd ::= REINDEX nm dbnm */ + 186, /* (277) cmd ::= ANALYZE */ + 186, /* (278) cmd ::= ANALYZE nm dbnm */ + 186, /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */ + 186, /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ + 289, /* (281) add_column_fullname ::= fullname */ + 186, /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ + 186, /* (283) cmd ::= create_vtab */ + 186, /* (284) cmd ::= create_vtab LP vtabarglist RP */ + 291, /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ + 293, /* (286) vtabarg ::= */ + 294, /* (287) vtabargtoken ::= ANY */ + 294, /* (288) vtabargtoken ::= lp anylist RP */ + 295, /* (289) lp ::= LP */ + 261, /* (290) with ::= WITH wqlist */ + 261, /* (291) with ::= WITH RECURSIVE wqlist */ + 236, /* (292) wqlist ::= nm eidlist_opt AS LP select RP */ + 236, /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ + 297, /* (294) windowdefn_list ::= windowdefn */ + 297, /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */ + 298, /* (296) windowdefn ::= nm AS LP window RP */ + 299, /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */ + 299, /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ + 299, /* (299) window ::= ORDER BY sortlist frame_opt */ + 299, /* (300) window ::= nm ORDER BY sortlist frame_opt */ + 299, /* (301) window ::= frame_opt */ + 299, /* (302) window ::= nm frame_opt */ + 300, /* (303) frame_opt ::= */ + 300, /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ + 300, /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ + 304, /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */ + 306, /* (307) frame_bound_s ::= frame_bound */ + 306, /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */ + 307, /* (309) frame_bound_e ::= frame_bound */ + 307, /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */ + 305, /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */ + 305, /* (312) frame_bound ::= CURRENT ROW */ + 308, /* (313) frame_exclude_opt ::= */ + 308, /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */ + 309, /* (315) frame_exclude ::= NO OTHERS */ + 309, /* (316) frame_exclude ::= CURRENT ROW */ + 309, /* (317) frame_exclude ::= GROUP|TIES */ + 246, /* (318) window_clause ::= WINDOW windowdefn_list */ + 266, /* (319) filter_over ::= filter_clause over_clause */ + 266, /* (320) filter_over ::= over_clause */ + 266, /* (321) filter_over ::= filter_clause */ + 303, /* (322) over_clause ::= OVER LP window RP */ + 303, /* (323) over_clause ::= OVER nm */ + 302, /* (324) filter_clause ::= FILTER LP WHERE expr RP */ + 181, /* (325) input ::= cmdlist */ + 182, /* (326) cmdlist ::= cmdlist ecmd */ + 182, /* (327) cmdlist ::= ecmd */ + 183, /* (328) ecmd ::= SEMI */ + 183, /* (329) ecmd ::= cmdx SEMI */ + 183, /* (330) ecmd ::= explain cmdx SEMI */ + 188, /* (331) trans_opt ::= */ + 188, /* (332) trans_opt ::= TRANSACTION */ + 188, /* (333) trans_opt ::= TRANSACTION nm */ + 190, /* (334) savepoint_opt ::= SAVEPOINT */ + 190, /* (335) savepoint_opt ::= */ + 186, /* (336) cmd ::= create_table create_table_args */ + 197, /* (337) columnlist ::= columnlist COMMA columnname carglist */ + 197, /* (338) columnlist ::= columnname carglist */ + 189, /* (339) nm ::= ID|INDEXED */ + 189, /* (340) nm ::= STRING */ + 189, /* (341) nm ::= JOIN_KW */ + 203, /* (342) typetoken ::= typename */ + 204, /* (343) typename ::= ID|STRING */ + 205, /* (344) signed ::= plus_num */ + 205, /* (345) signed ::= minus_num */ + 202, /* (346) carglist ::= carglist ccons */ + 202, /* (347) carglist ::= */ + 210, /* (348) ccons ::= NULL onconf */ + 210, /* (349) ccons ::= GENERATED ALWAYS AS generated */ + 210, /* (350) ccons ::= AS generated */ + 198, /* (351) conslist_opt ::= COMMA conslist */ + 223, /* (352) conslist ::= conslist tconscomma tcons */ + 223, /* (353) conslist ::= tcons */ + 224, /* (354) tconscomma ::= */ + 228, /* (355) defer_subclause_opt ::= defer_subclause */ + 230, /* (356) resolvetype ::= raisetype */ + 234, /* (357) selectnowith ::= oneselect */ + 235, /* (358) oneselect ::= values */ + 249, /* (359) sclp ::= selcollist COMMA */ + 250, /* (360) as ::= ID|STRING */ + 212, /* (361) expr ::= term */ + 267, /* (362) likeop ::= LIKE_KW|MATCH */ + 257, /* (363) exprlist ::= nexprlist */ + 277, /* (364) nmnum ::= plus_num */ + 277, /* (365) nmnum ::= nm */ + 277, /* (366) nmnum ::= ON */ + 277, /* (367) nmnum ::= DELETE */ + 277, /* (368) nmnum ::= DEFAULT */ + 206, /* (369) plus_num ::= INTEGER|FLOAT */ + 282, /* (370) foreach_clause ::= */ + 282, /* (371) foreach_clause ::= FOR EACH ROW */ + 285, /* (372) trnm ::= nm */ + 286, /* (373) tridxby ::= */ + 287, /* (374) database_kw_opt ::= DATABASE */ + 287, /* (375) database_kw_opt ::= */ + 290, /* (376) kwcolumn_opt ::= */ + 290, /* (377) kwcolumn_opt ::= COLUMNKW */ + 292, /* (378) vtabarglist ::= vtabarg */ + 292, /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ + 293, /* (380) vtabarg ::= vtabarg vtabargtoken */ + 296, /* (381) anylist ::= */ + 296, /* (382) anylist ::= anylist LP anylist RP */ + 296, /* (383) anylist ::= anylist ANY */ + 261, /* (384) with ::= */ +}; -/* The following table contains information about every rule that -** is used during the reduce. -*/ -static const struct { - YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ - unsigned char nrhs; /* Number of right-hand side symbols in the rule */ -} yyRuleInfo[] = { - { 147, 1 }, - { 147, 3 }, - { 148, 1 }, - { 149, 3 }, - { 150, 0 }, - { 150, 1 }, - { 150, 1 }, - { 150, 1 }, - { 149, 2 }, - { 149, 2 }, - { 149, 2 }, - { 149, 2 }, - { 149, 3 }, - { 149, 5 }, - { 154, 6 }, - { 156, 1 }, - { 158, 0 }, - { 158, 3 }, - { 157, 1 }, - { 157, 0 }, - { 155, 5 }, - { 155, 2 }, - { 162, 0 }, - { 162, 2 }, - { 164, 2 }, - { 166, 0 }, - { 166, 4 }, - { 166, 6 }, - { 167, 2 }, - { 171, 2 }, - { 171, 2 }, - { 171, 4 }, - { 171, 3 }, - { 171, 3 }, - { 171, 2 }, - { 171, 3 }, - { 171, 5 }, - { 171, 2 }, - { 171, 4 }, - { 171, 4 }, - { 171, 1 }, - { 171, 2 }, - { 176, 0 }, - { 176, 1 }, - { 178, 0 }, - { 178, 2 }, - { 180, 2 }, - { 180, 3 }, - { 180, 3 }, - { 180, 3 }, - { 181, 2 }, - { 181, 2 }, - { 181, 1 }, - { 181, 1 }, - { 181, 2 }, - { 179, 3 }, - { 179, 2 }, - { 182, 0 }, - { 182, 2 }, - { 182, 2 }, - { 161, 0 }, - { 184, 1 }, - { 185, 2 }, - { 185, 7 }, - { 185, 5 }, - { 185, 5 }, - { 185, 10 }, - { 188, 0 }, - { 174, 0 }, - { 174, 3 }, - { 189, 0 }, - { 189, 2 }, - { 190, 1 }, - { 190, 1 }, - { 149, 4 }, - { 192, 2 }, - { 192, 0 }, - { 149, 9 }, - { 149, 4 }, - { 149, 1 }, - { 163, 2 }, - { 194, 3 }, - { 197, 1 }, - { 197, 2 }, - { 197, 1 }, - { 195, 9 }, - { 206, 4 }, - { 206, 5 }, - { 198, 1 }, - { 198, 1 }, - { 198, 0 }, - { 209, 0 }, - { 199, 3 }, - { 199, 2 }, - { 199, 4 }, - { 210, 2 }, - { 210, 0 }, - { 200, 0 }, - { 200, 2 }, - { 212, 2 }, - { 212, 0 }, - { 211, 7 }, - { 211, 9 }, - { 211, 7 }, - { 211, 7 }, - { 159, 0 }, - { 159, 2 }, - { 193, 2 }, - { 213, 1 }, - { 213, 2 }, - { 213, 3 }, - { 213, 4 }, - { 215, 2 }, - { 215, 0 }, - { 214, 0 }, - { 214, 3 }, - { 214, 2 }, - { 216, 4 }, - { 216, 0 }, - { 204, 0 }, - { 204, 3 }, - { 186, 4 }, - { 186, 2 }, - { 175, 1 }, - { 175, 1 }, - { 175, 0 }, - { 202, 0 }, - { 202, 3 }, - { 203, 0 }, - { 203, 2 }, - { 205, 0 }, - { 205, 2 }, - { 205, 4 }, - { 205, 4 }, - { 149, 6 }, - { 201, 0 }, - { 201, 2 }, - { 149, 8 }, - { 218, 5 }, - { 218, 7 }, - { 218, 3 }, - { 218, 5 }, - { 149, 6 }, - { 149, 7 }, - { 219, 2 }, - { 219, 1 }, - { 220, 0 }, - { 220, 3 }, - { 217, 3 }, - { 217, 1 }, - { 173, 3 }, - { 172, 1 }, - { 173, 1 }, - { 173, 1 }, - { 173, 3 }, - { 173, 5 }, - { 172, 1 }, - { 172, 1 }, - { 172, 1 }, - { 173, 1 }, - { 173, 3 }, - { 173, 6 }, - { 173, 5 }, - { 173, 4 }, - { 172, 1 }, - { 173, 5 }, - { 173, 3 }, - { 173, 3 }, - { 173, 3 }, - { 173, 3 }, - { 173, 3 }, - { 173, 3 }, - { 173, 3 }, - { 173, 3 }, - { 221, 1 }, - { 221, 2 }, - { 173, 3 }, - { 173, 5 }, - { 173, 2 }, - { 173, 3 }, - { 173, 3 }, - { 173, 4 }, - { 173, 2 }, - { 173, 2 }, - { 173, 2 }, - { 173, 2 }, - { 222, 1 }, - { 222, 2 }, - { 173, 5 }, - { 223, 1 }, - { 223, 2 }, - { 173, 5 }, - { 173, 3 }, - { 173, 5 }, - { 173, 5 }, - { 173, 4 }, - { 173, 5 }, - { 226, 5 }, - { 226, 4 }, - { 227, 2 }, - { 227, 0 }, - { 225, 1 }, - { 225, 0 }, - { 208, 0 }, - { 207, 3 }, - { 207, 1 }, - { 224, 0 }, - { 224, 3 }, - { 149, 12 }, - { 228, 1 }, - { 228, 0 }, - { 177, 0 }, - { 177, 3 }, - { 187, 5 }, - { 187, 3 }, - { 229, 0 }, - { 229, 2 }, - { 149, 4 }, - { 149, 1 }, - { 149, 2 }, - { 149, 3 }, - { 149, 5 }, - { 149, 6 }, - { 149, 5 }, - { 149, 6 }, - { 169, 2 }, - { 170, 2 }, - { 149, 5 }, - { 231, 11 }, - { 233, 1 }, - { 233, 1 }, - { 233, 2 }, - { 233, 0 }, - { 234, 1 }, - { 234, 1 }, - { 234, 3 }, - { 236, 0 }, - { 236, 2 }, - { 232, 3 }, - { 232, 2 }, - { 238, 3 }, - { 239, 3 }, - { 239, 2 }, - { 237, 7 }, - { 237, 5 }, - { 237, 5 }, - { 237, 1 }, - { 173, 4 }, - { 173, 6 }, - { 191, 1 }, - { 191, 1 }, - { 191, 1 }, - { 149, 4 }, - { 149, 6 }, - { 149, 3 }, - { 241, 0 }, - { 241, 2 }, - { 149, 1 }, - { 149, 3 }, - { 149, 1 }, - { 149, 3 }, - { 149, 6 }, - { 149, 7 }, - { 242, 1 }, - { 149, 1 }, - { 149, 4 }, - { 244, 8 }, - { 246, 0 }, - { 247, 1 }, - { 247, 3 }, - { 248, 1 }, - { 196, 0 }, - { 196, 2 }, - { 196, 3 }, - { 250, 6 }, - { 250, 8 }, - { 144, 1 }, - { 145, 2 }, - { 145, 1 }, - { 146, 1 }, - { 146, 3 }, - { 147, 0 }, - { 151, 0 }, - { 151, 1 }, - { 151, 2 }, - { 153, 1 }, - { 153, 0 }, - { 149, 2 }, - { 160, 4 }, - { 160, 2 }, - { 152, 1 }, - { 152, 1 }, - { 152, 1 }, - { 166, 1 }, - { 167, 1 }, - { 168, 1 }, - { 168, 1 }, - { 165, 2 }, - { 165, 0 }, - { 171, 2 }, - { 161, 2 }, - { 183, 3 }, - { 183, 1 }, - { 184, 0 }, - { 188, 1 }, - { 190, 1 }, - { 194, 1 }, - { 195, 1 }, - { 209, 2 }, - { 210, 1 }, - { 173, 1 }, - { 208, 1 }, - { 230, 1 }, - { 230, 1 }, - { 230, 1 }, - { 230, 1 }, - { 230, 1 }, - { 169, 1 }, - { 235, 0 }, - { 235, 3 }, - { 238, 1 }, - { 239, 0 }, - { 240, 1 }, - { 240, 0 }, - { 243, 0 }, - { 243, 1 }, - { 245, 1 }, - { 245, 3 }, - { 246, 2 }, - { 249, 0 }, - { 249, 4 }, - { 249, 2 }, +/* For rule J, yyRuleInfoNRhs[J] contains the negative of the number +** of symbols on the right-hand side of that rule. */ +static const signed char yyRuleInfoNRhs[] = { + -1, /* (0) explain ::= EXPLAIN */ + -3, /* (1) explain ::= EXPLAIN QUERY PLAN */ + -1, /* (2) cmdx ::= cmd */ + -3, /* (3) cmd ::= BEGIN transtype trans_opt */ + 0, /* (4) transtype ::= */ + -1, /* (5) transtype ::= DEFERRED */ + -1, /* (6) transtype ::= IMMEDIATE */ + -1, /* (7) transtype ::= EXCLUSIVE */ + -2, /* (8) cmd ::= COMMIT|END trans_opt */ + -2, /* (9) cmd ::= ROLLBACK trans_opt */ + -2, /* (10) cmd ::= SAVEPOINT nm */ + -3, /* (11) cmd ::= RELEASE savepoint_opt nm */ + -5, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ + -6, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */ + -1, /* (14) createkw ::= CREATE */ + 0, /* (15) ifnotexists ::= */ + -3, /* (16) ifnotexists ::= IF NOT EXISTS */ + -1, /* (17) temp ::= TEMP */ + 0, /* (18) temp ::= */ + -5, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */ + -2, /* (20) create_table_args ::= AS select */ + 0, /* (21) table_options ::= */ + -2, /* (22) table_options ::= WITHOUT nm */ + -2, /* (23) columnname ::= nm typetoken */ + 0, /* (24) typetoken ::= */ + -4, /* (25) typetoken ::= typename LP signed RP */ + -6, /* (26) typetoken ::= typename LP signed COMMA signed RP */ + -2, /* (27) typename ::= typename ID|STRING */ + 0, /* (28) scanpt ::= */ + 0, /* (29) scantok ::= */ + -2, /* (30) ccons ::= CONSTRAINT nm */ + -3, /* (31) ccons ::= DEFAULT scantok term */ + -4, /* (32) ccons ::= DEFAULT LP expr RP */ + -4, /* (33) ccons ::= DEFAULT PLUS scantok term */ + -4, /* (34) ccons ::= DEFAULT MINUS scantok term */ + -3, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */ + -3, /* (36) ccons ::= NOT NULL onconf */ + -5, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */ + -2, /* (38) ccons ::= UNIQUE onconf */ + -4, /* (39) ccons ::= CHECK LP expr RP */ + -4, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */ + -1, /* (41) ccons ::= defer_subclause */ + -2, /* (42) ccons ::= COLLATE ID|STRING */ + -3, /* (43) generated ::= LP expr RP */ + -4, /* (44) generated ::= LP expr RP ID */ + 0, /* (45) autoinc ::= */ + -1, /* (46) autoinc ::= AUTOINCR */ + 0, /* (47) refargs ::= */ + -2, /* (48) refargs ::= refargs refarg */ + -2, /* (49) refarg ::= MATCH nm */ + -3, /* (50) refarg ::= ON INSERT refact */ + -3, /* (51) refarg ::= ON DELETE refact */ + -3, /* (52) refarg ::= ON UPDATE refact */ + -2, /* (53) refact ::= SET NULL */ + -2, /* (54) refact ::= SET DEFAULT */ + -1, /* (55) refact ::= CASCADE */ + -1, /* (56) refact ::= RESTRICT */ + -2, /* (57) refact ::= NO ACTION */ + -3, /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ + -2, /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ + 0, /* (60) init_deferred_pred_opt ::= */ + -2, /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */ + -2, /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ + 0, /* (63) conslist_opt ::= */ + -1, /* (64) tconscomma ::= COMMA */ + -2, /* (65) tcons ::= CONSTRAINT nm */ + -7, /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ + -5, /* (67) tcons ::= UNIQUE LP sortlist RP onconf */ + -5, /* (68) tcons ::= CHECK LP expr RP onconf */ + -10, /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ + 0, /* (70) defer_subclause_opt ::= */ + 0, /* (71) onconf ::= */ + -3, /* (72) onconf ::= ON CONFLICT resolvetype */ + 0, /* (73) orconf ::= */ + -2, /* (74) orconf ::= OR resolvetype */ + -1, /* (75) resolvetype ::= IGNORE */ + -1, /* (76) resolvetype ::= REPLACE */ + -4, /* (77) cmd ::= DROP TABLE ifexists fullname */ + -2, /* (78) ifexists ::= IF EXISTS */ + 0, /* (79) ifexists ::= */ + -9, /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ + -4, /* (81) cmd ::= DROP VIEW ifexists fullname */ + -1, /* (82) cmd ::= select */ + -3, /* (83) select ::= WITH wqlist selectnowith */ + -4, /* (84) select ::= WITH RECURSIVE wqlist selectnowith */ + -1, /* (85) select ::= selectnowith */ + -3, /* (86) selectnowith ::= selectnowith multiselect_op oneselect */ + -1, /* (87) multiselect_op ::= UNION */ + -2, /* (88) multiselect_op ::= UNION ALL */ + -1, /* (89) multiselect_op ::= EXCEPT|INTERSECT */ + -9, /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ + -10, /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */ + -4, /* (92) values ::= VALUES LP nexprlist RP */ + -5, /* (93) values ::= values COMMA LP nexprlist RP */ + -1, /* (94) distinct ::= DISTINCT */ + -1, /* (95) distinct ::= ALL */ + 0, /* (96) distinct ::= */ + 0, /* (97) sclp ::= */ + -5, /* (98) selcollist ::= sclp scanpt expr scanpt as */ + -3, /* (99) selcollist ::= sclp scanpt STAR */ + -5, /* (100) selcollist ::= sclp scanpt nm DOT STAR */ + -2, /* (101) as ::= AS nm */ + 0, /* (102) as ::= */ + 0, /* (103) from ::= */ + -2, /* (104) from ::= FROM seltablist */ + -2, /* (105) stl_prefix ::= seltablist joinop */ + 0, /* (106) stl_prefix ::= */ + -7, /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ + -9, /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ + -7, /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */ + -7, /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ + 0, /* (111) dbnm ::= */ + -2, /* (112) dbnm ::= DOT nm */ + -1, /* (113) fullname ::= nm */ + -3, /* (114) fullname ::= nm DOT nm */ + -1, /* (115) xfullname ::= nm */ + -3, /* (116) xfullname ::= nm DOT nm */ + -5, /* (117) xfullname ::= nm DOT nm AS nm */ + -3, /* (118) xfullname ::= nm AS nm */ + -1, /* (119) joinop ::= COMMA|JOIN */ + -2, /* (120) joinop ::= JOIN_KW JOIN */ + -3, /* (121) joinop ::= JOIN_KW nm JOIN */ + -4, /* (122) joinop ::= JOIN_KW nm nm JOIN */ + -2, /* (123) on_opt ::= ON expr */ + 0, /* (124) on_opt ::= */ + 0, /* (125) indexed_opt ::= */ + -3, /* (126) indexed_opt ::= INDEXED BY nm */ + -2, /* (127) indexed_opt ::= NOT INDEXED */ + -4, /* (128) using_opt ::= USING LP idlist RP */ + 0, /* (129) using_opt ::= */ + 0, /* (130) orderby_opt ::= */ + -3, /* (131) orderby_opt ::= ORDER BY sortlist */ + -5, /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */ + -3, /* (133) sortlist ::= expr sortorder nulls */ + -1, /* (134) sortorder ::= ASC */ + -1, /* (135) sortorder ::= DESC */ + 0, /* (136) sortorder ::= */ + -2, /* (137) nulls ::= NULLS FIRST */ + -2, /* (138) nulls ::= NULLS LAST */ + 0, /* (139) nulls ::= */ + 0, /* (140) groupby_opt ::= */ + -3, /* (141) groupby_opt ::= GROUP BY nexprlist */ + 0, /* (142) having_opt ::= */ + -2, /* (143) having_opt ::= HAVING expr */ + 0, /* (144) limit_opt ::= */ + -2, /* (145) limit_opt ::= LIMIT expr */ + -4, /* (146) limit_opt ::= LIMIT expr OFFSET expr */ + -4, /* (147) limit_opt ::= LIMIT expr COMMA expr */ + -6, /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */ + 0, /* (149) where_opt ::= */ + -2, /* (150) where_opt ::= WHERE expr */ + -8, /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */ + -5, /* (152) setlist ::= setlist COMMA nm EQ expr */ + -7, /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */ + -3, /* (154) setlist ::= nm EQ expr */ + -5, /* (155) setlist ::= LP idlist RP EQ expr */ + -7, /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */ + -7, /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */ + 0, /* (158) upsert ::= */ + -11, /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */ + -8, /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */ + -4, /* (161) upsert ::= ON CONFLICT DO NOTHING */ + -2, /* (162) insert_cmd ::= INSERT orconf */ + -1, /* (163) insert_cmd ::= REPLACE */ + 0, /* (164) idlist_opt ::= */ + -3, /* (165) idlist_opt ::= LP idlist RP */ + -3, /* (166) idlist ::= idlist COMMA nm */ + -1, /* (167) idlist ::= nm */ + -3, /* (168) expr ::= LP expr RP */ + -1, /* (169) expr ::= ID|INDEXED */ + -1, /* (170) expr ::= JOIN_KW */ + -3, /* (171) expr ::= nm DOT nm */ + -5, /* (172) expr ::= nm DOT nm DOT nm */ + -1, /* (173) term ::= NULL|FLOAT|BLOB */ + -1, /* (174) term ::= STRING */ + -1, /* (175) term ::= INTEGER */ + -1, /* (176) expr ::= VARIABLE */ + -3, /* (177) expr ::= expr COLLATE ID|STRING */ + -6, /* (178) expr ::= CAST LP expr AS typetoken RP */ + -5, /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */ + -4, /* (180) expr ::= ID|INDEXED LP STAR RP */ + -6, /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */ + -5, /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */ + -1, /* (183) term ::= CTIME_KW */ + -5, /* (184) expr ::= LP nexprlist COMMA expr RP */ + -3, /* (185) expr ::= expr AND expr */ + -3, /* (186) expr ::= expr OR expr */ + -3, /* (187) expr ::= expr LT|GT|GE|LE expr */ + -3, /* (188) expr ::= expr EQ|NE expr */ + -3, /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ + -3, /* (190) expr ::= expr PLUS|MINUS expr */ + -3, /* (191) expr ::= expr STAR|SLASH|REM expr */ + -3, /* (192) expr ::= expr CONCAT expr */ + -2, /* (193) likeop ::= NOT LIKE_KW|MATCH */ + -3, /* (194) expr ::= expr likeop expr */ + -5, /* (195) expr ::= expr likeop expr ESCAPE expr */ + -2, /* (196) expr ::= expr ISNULL|NOTNULL */ + -3, /* (197) expr ::= expr NOT NULL */ + -3, /* (198) expr ::= expr IS expr */ + -4, /* (199) expr ::= expr IS NOT expr */ + -2, /* (200) expr ::= NOT expr */ + -2, /* (201) expr ::= BITNOT expr */ + -2, /* (202) expr ::= PLUS|MINUS expr */ + -1, /* (203) between_op ::= BETWEEN */ + -2, /* (204) between_op ::= NOT BETWEEN */ + -5, /* (205) expr ::= expr between_op expr AND expr */ + -1, /* (206) in_op ::= IN */ + -2, /* (207) in_op ::= NOT IN */ + -5, /* (208) expr ::= expr in_op LP exprlist RP */ + -3, /* (209) expr ::= LP select RP */ + -5, /* (210) expr ::= expr in_op LP select RP */ + -5, /* (211) expr ::= expr in_op nm dbnm paren_exprlist */ + -4, /* (212) expr ::= EXISTS LP select RP */ + -5, /* (213) expr ::= CASE case_operand case_exprlist case_else END */ + -5, /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */ + -4, /* (215) case_exprlist ::= WHEN expr THEN expr */ + -2, /* (216) case_else ::= ELSE expr */ + 0, /* (217) case_else ::= */ + -1, /* (218) case_operand ::= expr */ + 0, /* (219) case_operand ::= */ + 0, /* (220) exprlist ::= */ + -3, /* (221) nexprlist ::= nexprlist COMMA expr */ + -1, /* (222) nexprlist ::= expr */ + 0, /* (223) paren_exprlist ::= */ + -3, /* (224) paren_exprlist ::= LP exprlist RP */ + -12, /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ + -1, /* (226) uniqueflag ::= UNIQUE */ + 0, /* (227) uniqueflag ::= */ + 0, /* (228) eidlist_opt ::= */ + -3, /* (229) eidlist_opt ::= LP eidlist RP */ + -5, /* (230) eidlist ::= eidlist COMMA nm collate sortorder */ + -3, /* (231) eidlist ::= nm collate sortorder */ + 0, /* (232) collate ::= */ + -2, /* (233) collate ::= COLLATE ID|STRING */ + -4, /* (234) cmd ::= DROP INDEX ifexists fullname */ + -2, /* (235) cmd ::= VACUUM vinto */ + -3, /* (236) cmd ::= VACUUM nm vinto */ + -2, /* (237) vinto ::= INTO expr */ + 0, /* (238) vinto ::= */ + -3, /* (239) cmd ::= PRAGMA nm dbnm */ + -5, /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */ + -6, /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */ + -5, /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */ + -6, /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */ + -2, /* (244) plus_num ::= PLUS INTEGER|FLOAT */ + -2, /* (245) minus_num ::= MINUS INTEGER|FLOAT */ + -5, /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ + -11, /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ + -1, /* (248) trigger_time ::= BEFORE|AFTER */ + -2, /* (249) trigger_time ::= INSTEAD OF */ + 0, /* (250) trigger_time ::= */ + -1, /* (251) trigger_event ::= DELETE|INSERT */ + -1, /* (252) trigger_event ::= UPDATE */ + -3, /* (253) trigger_event ::= UPDATE OF idlist */ + 0, /* (254) when_clause ::= */ + -2, /* (255) when_clause ::= WHEN expr */ + -3, /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ + -2, /* (257) trigger_cmd_list ::= trigger_cmd SEMI */ + -3, /* (258) trnm ::= nm DOT nm */ + -3, /* (259) tridxby ::= INDEXED BY nm */ + -2, /* (260) tridxby ::= NOT INDEXED */ + -8, /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */ + -8, /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */ + -6, /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */ + -3, /* (264) trigger_cmd ::= scanpt select scanpt */ + -4, /* (265) expr ::= RAISE LP IGNORE RP */ + -6, /* (266) expr ::= RAISE LP raisetype COMMA nm RP */ + -1, /* (267) raisetype ::= ROLLBACK */ + -1, /* (268) raisetype ::= ABORT */ + -1, /* (269) raisetype ::= FAIL */ + -4, /* (270) cmd ::= DROP TRIGGER ifexists fullname */ + -6, /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ + -3, /* (272) cmd ::= DETACH database_kw_opt expr */ + 0, /* (273) key_opt ::= */ + -2, /* (274) key_opt ::= KEY expr */ + -1, /* (275) cmd ::= REINDEX */ + -3, /* (276) cmd ::= REINDEX nm dbnm */ + -1, /* (277) cmd ::= ANALYZE */ + -3, /* (278) cmd ::= ANALYZE nm dbnm */ + -6, /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */ + -7, /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ + -1, /* (281) add_column_fullname ::= fullname */ + -8, /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ + -1, /* (283) cmd ::= create_vtab */ + -4, /* (284) cmd ::= create_vtab LP vtabarglist RP */ + -8, /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ + 0, /* (286) vtabarg ::= */ + -1, /* (287) vtabargtoken ::= ANY */ + -3, /* (288) vtabargtoken ::= lp anylist RP */ + -1, /* (289) lp ::= LP */ + -2, /* (290) with ::= WITH wqlist */ + -3, /* (291) with ::= WITH RECURSIVE wqlist */ + -6, /* (292) wqlist ::= nm eidlist_opt AS LP select RP */ + -8, /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ + -1, /* (294) windowdefn_list ::= windowdefn */ + -3, /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */ + -5, /* (296) windowdefn ::= nm AS LP window RP */ + -5, /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */ + -6, /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ + -4, /* (299) window ::= ORDER BY sortlist frame_opt */ + -5, /* (300) window ::= nm ORDER BY sortlist frame_opt */ + -1, /* (301) window ::= frame_opt */ + -2, /* (302) window ::= nm frame_opt */ + 0, /* (303) frame_opt ::= */ + -3, /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ + -6, /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ + -1, /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */ + -1, /* (307) frame_bound_s ::= frame_bound */ + -2, /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */ + -1, /* (309) frame_bound_e ::= frame_bound */ + -2, /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */ + -2, /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */ + -2, /* (312) frame_bound ::= CURRENT ROW */ + 0, /* (313) frame_exclude_opt ::= */ + -2, /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */ + -2, /* (315) frame_exclude ::= NO OTHERS */ + -2, /* (316) frame_exclude ::= CURRENT ROW */ + -1, /* (317) frame_exclude ::= GROUP|TIES */ + -2, /* (318) window_clause ::= WINDOW windowdefn_list */ + -2, /* (319) filter_over ::= filter_clause over_clause */ + -1, /* (320) filter_over ::= over_clause */ + -1, /* (321) filter_over ::= filter_clause */ + -4, /* (322) over_clause ::= OVER LP window RP */ + -2, /* (323) over_clause ::= OVER nm */ + -5, /* (324) filter_clause ::= FILTER LP WHERE expr RP */ + -1, /* (325) input ::= cmdlist */ + -2, /* (326) cmdlist ::= cmdlist ecmd */ + -1, /* (327) cmdlist ::= ecmd */ + -1, /* (328) ecmd ::= SEMI */ + -2, /* (329) ecmd ::= cmdx SEMI */ + -3, /* (330) ecmd ::= explain cmdx SEMI */ + 0, /* (331) trans_opt ::= */ + -1, /* (332) trans_opt ::= TRANSACTION */ + -2, /* (333) trans_opt ::= TRANSACTION nm */ + -1, /* (334) savepoint_opt ::= SAVEPOINT */ + 0, /* (335) savepoint_opt ::= */ + -2, /* (336) cmd ::= create_table create_table_args */ + -4, /* (337) columnlist ::= columnlist COMMA columnname carglist */ + -2, /* (338) columnlist ::= columnname carglist */ + -1, /* (339) nm ::= ID|INDEXED */ + -1, /* (340) nm ::= STRING */ + -1, /* (341) nm ::= JOIN_KW */ + -1, /* (342) typetoken ::= typename */ + -1, /* (343) typename ::= ID|STRING */ + -1, /* (344) signed ::= plus_num */ + -1, /* (345) signed ::= minus_num */ + -2, /* (346) carglist ::= carglist ccons */ + 0, /* (347) carglist ::= */ + -2, /* (348) ccons ::= NULL onconf */ + -4, /* (349) ccons ::= GENERATED ALWAYS AS generated */ + -2, /* (350) ccons ::= AS generated */ + -2, /* (351) conslist_opt ::= COMMA conslist */ + -3, /* (352) conslist ::= conslist tconscomma tcons */ + -1, /* (353) conslist ::= tcons */ + 0, /* (354) tconscomma ::= */ + -1, /* (355) defer_subclause_opt ::= defer_subclause */ + -1, /* (356) resolvetype ::= raisetype */ + -1, /* (357) selectnowith ::= oneselect */ + -1, /* (358) oneselect ::= values */ + -2, /* (359) sclp ::= selcollist COMMA */ + -1, /* (360) as ::= ID|STRING */ + -1, /* (361) expr ::= term */ + -1, /* (362) likeop ::= LIKE_KW|MATCH */ + -1, /* (363) exprlist ::= nexprlist */ + -1, /* (364) nmnum ::= plus_num */ + -1, /* (365) nmnum ::= nm */ + -1, /* (366) nmnum ::= ON */ + -1, /* (367) nmnum ::= DELETE */ + -1, /* (368) nmnum ::= DEFAULT */ + -1, /* (369) plus_num ::= INTEGER|FLOAT */ + 0, /* (370) foreach_clause ::= */ + -3, /* (371) foreach_clause ::= FOR EACH ROW */ + -1, /* (372) trnm ::= nm */ + 0, /* (373) tridxby ::= */ + -1, /* (374) database_kw_opt ::= DATABASE */ + 0, /* (375) database_kw_opt ::= */ + 0, /* (376) kwcolumn_opt ::= */ + -1, /* (377) kwcolumn_opt ::= COLUMNKW */ + -1, /* (378) vtabarglist ::= vtabarg */ + -3, /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ + -2, /* (380) vtabarg ::= vtabarg vtabargtoken */ + 0, /* (381) anylist ::= */ + -4, /* (382) anylist ::= anylist LP anylist RP */ + -2, /* (383) anylist ::= anylist ANY */ + 0, /* (384) with ::= */ }; static void yy_accept(yyParser*); /* Forward Declaration */ @@ -138132,29 +159163,49 @@ static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. +** +** The yyLookahead and yyLookaheadToken parameters provide reduce actions +** access to the lookahead token (if any). The yyLookahead will be YYNOCODE +** if the lookahead token has already been consumed. As this procedure is +** only called from one place, optimizing compilers will in-line it, which +** means that the extra parameters have no performance impact. */ -static void yy_reduce( +static YYACTIONTYPE yy_reduce( yyParser *yypParser, /* The parser */ - unsigned int yyruleno /* Number of the rule by which to reduce */ + unsigned int yyruleno, /* Number of the rule by which to reduce */ + int yyLookahead, /* Lookahead token, or YYNOCODE if none */ + tdsqlite3ParserTOKENTYPE yyLookaheadToken /* Value of the lookahead token */ + tdsqlite3ParserCTX_PDECL /* %extra_context */ ){ int yygoto; /* The next state */ - int yyact; /* The next action */ + YYACTIONTYPE yyact; /* The next action */ yyStackEntry *yymsp; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ - sqlite3ParserARG_FETCH; + tdsqlite3ParserARG_FETCH + (void)yyLookahead; + (void)yyLookaheadToken; yymsp = yypParser->yytos; #ifndef NDEBUG if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ - yysize = yyRuleInfo[yyruleno].nrhs; - fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt, - yyRuleName[yyruleno], yymsp[-yysize].stateno); + yysize = yyRuleInfoNRhs[yyruleno]; + if( yysize ){ + fprintf(yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n", + yyTracePrompt, + yyruleno, yyRuleName[yyruleno], + yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action", + yymsp[yysize].stateno); + }else{ + fprintf(yyTraceFILE, "%sReduce %d [%s]%s.\n", + yyTracePrompt, yyruleno, yyRuleName[yyruleno], + yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action"); + } } #endif /* NDEBUG */ /* Check that the stack is large enough to grow by a single entry ** if the RHS of the rule is empty. This ensures that there is room ** enough on the stack to push the LHS value */ - if( yyRuleInfo[yyruleno].nrhs==0 ){ + if( yyRuleInfoNRhs[yyruleno]==0 ){ #ifdef YYTRACKMAXSTACKDEPTH if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){ yypParser->yyhwm++; @@ -138162,15 +159213,21 @@ static void yy_reduce( } #endif #if YYSTACKDEPTH>0 - if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){ + if( yypParser->yytos>=yypParser->yystackEnd ){ yyStackOverflow(yypParser); - return; + /* The call to yyStackOverflow() above pops the stack until it is + ** empty, causing the main parser loop to exit. So the return value + ** is never used and does not matter. */ + return 0; } #else if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){ if( yyGrowStack(yypParser) ){ yyStackOverflow(yypParser); - return; + /* The call to yyStackOverflow() above pops the stack until it is + ** empty, causing the main parser loop to exit. So the return value + ** is never used and does not matter. */ + return 0; } yymsp = yypParser->yytos; } @@ -138195,804 +159252,880 @@ static void yy_reduce( { pParse->explain = 2; } break; case 2: /* cmdx ::= cmd */ -{ sqlite3FinishCoding(pParse); } +{ tdsqlite3FinishCoding(pParse); } break; case 3: /* cmd ::= BEGIN transtype trans_opt */ -{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);} +{tdsqlite3BeginTransaction(pParse, yymsp[-1].minor.yy192);} break; case 4: /* transtype ::= */ -{yymsp[1].minor.yy194 = TK_DEFERRED;} +{yymsp[1].minor.yy192 = TK_DEFERRED;} break; case 5: /* transtype ::= DEFERRED */ case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6); case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7); -{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/} - break; - case 8: /* cmd ::= COMMIT trans_opt */ - case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9); -{sqlite3CommitTransaction(pParse);} + case 306: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==306); +{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/} break; - case 10: /* cmd ::= ROLLBACK trans_opt */ -{sqlite3RollbackTransaction(pParse);} + case 8: /* cmd ::= COMMIT|END trans_opt */ + case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9); +{tdsqlite3EndTransaction(pParse,yymsp[-1].major);} break; - case 11: /* cmd ::= SAVEPOINT nm */ + case 10: /* cmd ::= SAVEPOINT nm */ { - sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0); + tdsqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0); } break; - case 12: /* cmd ::= RELEASE savepoint_opt nm */ + case 11: /* cmd ::= RELEASE savepoint_opt nm */ { - sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0); + tdsqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0); } break; - case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ + case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ { - sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0); + tdsqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0); } break; - case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ + case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ { - sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194); + tdsqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy192,0,0,yymsp[-2].minor.yy192); } break; - case 15: /* createkw ::= CREATE */ + case 14: /* createkw ::= CREATE */ {disableLookaside(pParse);} break; - case 16: /* ifnotexists ::= */ - case 19: /* temp ::= */ yytestcase(yyruleno==19); - case 22: /* table_options ::= */ yytestcase(yyruleno==22); - case 42: /* autoinc ::= */ yytestcase(yyruleno==42); - case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57); - case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67); - case 76: /* ifexists ::= */ yytestcase(yyruleno==76); - case 90: /* distinct ::= */ yytestcase(yyruleno==90); - case 215: /* collate ::= */ yytestcase(yyruleno==215); -{yymsp[1].minor.yy194 = 0;} - break; - case 17: /* ifnotexists ::= IF NOT EXISTS */ -{yymsp[-2].minor.yy194 = 1;} - break; - case 18: /* temp ::= TEMP */ - case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43); -{yymsp[0].minor.yy194 = 1;} - break; - case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */ + case 15: /* ifnotexists ::= */ + case 18: /* temp ::= */ yytestcase(yyruleno==18); + case 21: /* table_options ::= */ yytestcase(yyruleno==21); + case 45: /* autoinc ::= */ yytestcase(yyruleno==45); + case 60: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==60); + case 70: /* defer_subclause_opt ::= */ yytestcase(yyruleno==70); + case 79: /* ifexists ::= */ yytestcase(yyruleno==79); + case 96: /* distinct ::= */ yytestcase(yyruleno==96); + case 232: /* collate ::= */ yytestcase(yyruleno==232); +{yymsp[1].minor.yy192 = 0;} + break; + case 16: /* ifnotexists ::= IF NOT EXISTS */ +{yymsp[-2].minor.yy192 = 1;} + break; + case 17: /* temp ::= TEMP */ + case 46: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==46); +{yymsp[0].minor.yy192 = 1;} + break; + case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */ { - sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0); + tdsqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy192,0); } break; - case 21: /* create_table_args ::= AS select */ + case 20: /* create_table_args ::= AS select */ { - sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243); - sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); + tdsqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy539); + tdsqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539); } break; - case 23: /* table_options ::= WITHOUT nm */ + case 22: /* table_options ::= WITHOUT nm */ { - if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){ - yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid; + if( yymsp[0].minor.yy0.n==5 && tdsqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){ + yymsp[-1].minor.yy192 = TF_WithoutRowid | TF_NoVisibleRowid; }else{ - yymsp[-1].minor.yy194 = 0; - sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z); + yymsp[-1].minor.yy192 = 0; + tdsqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z); } } break; - case 24: /* columnname ::= nm typetoken */ -{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);} + case 23: /* columnname ::= nm typetoken */ +{tdsqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);} break; - case 25: /* typetoken ::= */ - case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60); - case 96: /* as ::= */ yytestcase(yyruleno==96); + case 24: /* typetoken ::= */ + case 63: /* conslist_opt ::= */ yytestcase(yyruleno==63); + case 102: /* as ::= */ yytestcase(yyruleno==102); {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;} break; - case 26: /* typetoken ::= typename LP signed RP */ + case 25: /* typetoken ::= typename LP signed RP */ { yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z); } break; - case 27: /* typetoken ::= typename LP signed COMMA signed RP */ + case 26: /* typetoken ::= typename LP signed COMMA signed RP */ { yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z); } break; - case 28: /* typename ::= typename ID|STRING */ + case 27: /* typename ::= typename ID|STRING */ {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);} break; - case 29: /* ccons ::= CONSTRAINT nm */ - case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62); + case 28: /* scanpt ::= */ +{ + assert( yyLookahead!=YYNOCODE ); + yymsp[1].minor.yy436 = yyLookaheadToken.z; +} + break; + case 29: /* scantok ::= */ +{ + assert( yyLookahead!=YYNOCODE ); + yymsp[1].minor.yy0 = yyLookaheadToken; +} + break; + case 30: /* ccons ::= CONSTRAINT nm */ + case 65: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==65); {pParse->constraintName = yymsp[0].minor.yy0;} break; - case 30: /* ccons ::= DEFAULT term */ - case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32); -{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);} + case 31: /* ccons ::= DEFAULT scantok term */ +{tdsqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);} + break; + case 32: /* ccons ::= DEFAULT LP expr RP */ +{tdsqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy202,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);} break; - case 31: /* ccons ::= DEFAULT LP expr RP */ -{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);} + case 33: /* ccons ::= DEFAULT PLUS scantok term */ +{tdsqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);} break; - case 33: /* ccons ::= DEFAULT MINUS term */ + case 34: /* ccons ::= DEFAULT MINUS scantok term */ { - ExprSpan v; - v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0, 0); - v.zStart = yymsp[-1].minor.yy0.z; - v.zEnd = yymsp[0].minor.yy190.zEnd; - sqlite3AddDefaultValue(pParse,&v); + Expr *p = tdsqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy202, 0); + tdsqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]); } break; - case 34: /* ccons ::= DEFAULT ID|INDEXED */ + case 35: /* ccons ::= DEFAULT scantok ID|INDEXED */ { - ExprSpan v; - spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0); - sqlite3AddDefaultValue(pParse,&v); + Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0); + if( p ){ + tdsqlite3ExprIdToTrueFalse(p); + testcase( p->op==TK_TRUEFALSE && tdsqlite3ExprTruthValue(p) ); + } + tdsqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n); } break; - case 35: /* ccons ::= NOT NULL onconf */ -{sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);} + case 36: /* ccons ::= NOT NULL onconf */ +{tdsqlite3AddNotNull(pParse, yymsp[0].minor.yy192);} break; - case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ -{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);} + case 37: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ +{tdsqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy192,yymsp[0].minor.yy192,yymsp[-2].minor.yy192);} break; - case 37: /* ccons ::= UNIQUE onconf */ -{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0, + case 38: /* ccons ::= UNIQUE onconf */ +{tdsqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy192,0,0,0,0, SQLITE_IDXTYPE_UNIQUE);} break; - case 38: /* ccons ::= CHECK LP expr RP */ -{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);} + case 39: /* ccons ::= CHECK LP expr RP */ +{tdsqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy202);} + break; + case 40: /* ccons ::= REFERENCES nm eidlist_opt refargs */ +{tdsqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy242,yymsp[0].minor.yy192);} break; - case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */ -{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);} + case 41: /* ccons ::= defer_subclause */ +{tdsqlite3DeferForeignKey(pParse,yymsp[0].minor.yy192);} break; - case 40: /* ccons ::= defer_subclause */ -{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);} + case 42: /* ccons ::= COLLATE ID|STRING */ +{tdsqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);} break; - case 41: /* ccons ::= COLLATE ID|STRING */ -{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);} + case 43: /* generated ::= LP expr RP */ +{tdsqlite3AddGenerated(pParse,yymsp[-1].minor.yy202,0);} break; - case 44: /* refargs ::= */ -{ yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */} + case 44: /* generated ::= LP expr RP ID */ +{tdsqlite3AddGenerated(pParse,yymsp[-2].minor.yy202,&yymsp[0].minor.yy0);} break; - case 45: /* refargs ::= refargs refarg */ -{ yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; } + case 47: /* refargs ::= */ +{ yymsp[1].minor.yy192 = OE_None*0x0101; /* EV: R-19803-45884 */} break; - case 46: /* refarg ::= MATCH nm */ -{ yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; } + case 48: /* refargs ::= refargs refarg */ +{ yymsp[-1].minor.yy192 = (yymsp[-1].minor.yy192 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; } break; - case 47: /* refarg ::= ON INSERT refact */ -{ yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; } + case 49: /* refarg ::= MATCH nm */ +{ yymsp[-1].minor.yy207.value = 0; yymsp[-1].minor.yy207.mask = 0x000000; } break; - case 48: /* refarg ::= ON DELETE refact */ -{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; } + case 50: /* refarg ::= ON INSERT refact */ +{ yymsp[-2].minor.yy207.value = 0; yymsp[-2].minor.yy207.mask = 0x000000; } break; - case 49: /* refarg ::= ON UPDATE refact */ -{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; } + case 51: /* refarg ::= ON DELETE refact */ +{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192; yymsp[-2].minor.yy207.mask = 0x0000ff; } break; - case 50: /* refact ::= SET NULL */ -{ yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */} + case 52: /* refarg ::= ON UPDATE refact */ +{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192<<8; yymsp[-2].minor.yy207.mask = 0x00ff00; } break; - case 51: /* refact ::= SET DEFAULT */ -{ yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */} + case 53: /* refact ::= SET NULL */ +{ yymsp[-1].minor.yy192 = OE_SetNull; /* EV: R-33326-45252 */} break; - case 52: /* refact ::= CASCADE */ -{ yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */} + case 54: /* refact ::= SET DEFAULT */ +{ yymsp[-1].minor.yy192 = OE_SetDflt; /* EV: R-33326-45252 */} break; - case 53: /* refact ::= RESTRICT */ -{ yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */} + case 55: /* refact ::= CASCADE */ +{ yymsp[0].minor.yy192 = OE_Cascade; /* EV: R-33326-45252 */} break; - case 54: /* refact ::= NO ACTION */ -{ yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */} + case 56: /* refact ::= RESTRICT */ +{ yymsp[0].minor.yy192 = OE_Restrict; /* EV: R-33326-45252 */} break; - case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ -{yymsp[-2].minor.yy194 = 0;} + case 57: /* refact ::= NO ACTION */ +{ yymsp[-1].minor.yy192 = OE_None; /* EV: R-33326-45252 */} break; - case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ - case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71); - case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144); -{yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;} + case 58: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ +{yymsp[-2].minor.yy192 = 0;} break; - case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ - case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75); - case 187: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==187); - case 190: /* in_op ::= NOT IN */ yytestcase(yyruleno==190); - case 216: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==216); -{yymsp[-1].minor.yy194 = 1;} + case 59: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ + case 74: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==74); + case 162: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==162); +{yymsp[-1].minor.yy192 = yymsp[0].minor.yy192;} break; - case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ -{yymsp[-1].minor.yy194 = 0;} + case 61: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ + case 78: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==78); + case 204: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==204); + case 207: /* in_op ::= NOT IN */ yytestcase(yyruleno==207); + case 233: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==233); +{yymsp[-1].minor.yy192 = 1;} break; - case 61: /* tconscomma ::= COMMA */ + case 62: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ +{yymsp[-1].minor.yy192 = 0;} + break; + case 64: /* tconscomma ::= COMMA */ {pParse->constraintName.n = 0;} break; - case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ -{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);} + case 66: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ +{tdsqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy242,yymsp[0].minor.yy192,yymsp[-2].minor.yy192,0);} break; - case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */ -{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0, + case 67: /* tcons ::= UNIQUE LP sortlist RP onconf */ +{tdsqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy242,yymsp[0].minor.yy192,0,0,0,0, SQLITE_IDXTYPE_UNIQUE);} break; - case 65: /* tcons ::= CHECK LP expr RP onconf */ -{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);} + case 68: /* tcons ::= CHECK LP expr RP onconf */ +{tdsqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy202);} break; - case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ + case 69: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ { - sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194); - sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194); + tdsqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy242, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy192); + tdsqlite3DeferForeignKey(pParse, yymsp[0].minor.yy192); } break; - case 68: /* onconf ::= */ - case 70: /* orconf ::= */ yytestcase(yyruleno==70); -{yymsp[1].minor.yy194 = OE_Default;} + case 71: /* onconf ::= */ + case 73: /* orconf ::= */ yytestcase(yyruleno==73); +{yymsp[1].minor.yy192 = OE_Default;} break; - case 69: /* onconf ::= ON CONFLICT resolvetype */ -{yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;} + case 72: /* onconf ::= ON CONFLICT resolvetype */ +{yymsp[-2].minor.yy192 = yymsp[0].minor.yy192;} break; - case 72: /* resolvetype ::= IGNORE */ -{yymsp[0].minor.yy194 = OE_Ignore;} + case 75: /* resolvetype ::= IGNORE */ +{yymsp[0].minor.yy192 = OE_Ignore;} break; - case 73: /* resolvetype ::= REPLACE */ - case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145); -{yymsp[0].minor.yy194 = OE_Replace;} + case 76: /* resolvetype ::= REPLACE */ + case 163: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==163); +{yymsp[0].minor.yy192 = OE_Replace;} break; - case 74: /* cmd ::= DROP TABLE ifexists fullname */ + case 77: /* cmd ::= DROP TABLE ifexists fullname */ { - sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194); + tdsqlite3DropTable(pParse, yymsp[0].minor.yy47, 0, yymsp[-1].minor.yy192); } break; - case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ + case 80: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ { - sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194); + tdsqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[0].minor.yy539, yymsp[-7].minor.yy192, yymsp[-5].minor.yy192); } break; - case 78: /* cmd ::= DROP VIEW ifexists fullname */ + case 81: /* cmd ::= DROP VIEW ifexists fullname */ { - sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194); + tdsqlite3DropTable(pParse, yymsp[0].minor.yy47, 1, yymsp[-1].minor.yy192); } break; - case 79: /* cmd ::= select */ + case 82: /* cmd ::= select */ { SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0}; - sqlite3Select(pParse, yymsp[0].minor.yy243, &dest); - sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); + tdsqlite3Select(pParse, yymsp[0].minor.yy539, &dest); + tdsqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539); +} + break; + case 83: /* select ::= WITH wqlist selectnowith */ +{ + Select *p = yymsp[0].minor.yy539; + if( p ){ + p->pWith = yymsp[-1].minor.yy131; + parserDoubleLinkSelect(pParse, p); + }else{ + tdsqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131); + } + yymsp[-2].minor.yy539 = p; } break; - case 80: /* select ::= with selectnowith */ + case 84: /* select ::= WITH RECURSIVE wqlist selectnowith */ { - Select *p = yymsp[0].minor.yy243; + Select *p = yymsp[0].minor.yy539; if( p ){ - p->pWith = yymsp[-1].minor.yy285; + p->pWith = yymsp[-1].minor.yy131; parserDoubleLinkSelect(pParse, p); }else{ - sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285); + tdsqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131); } - yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/ + yymsp[-3].minor.yy539 = p; } break; - case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */ + case 85: /* select ::= selectnowith */ { - Select *pRhs = yymsp[0].minor.yy243; - Select *pLhs = yymsp[-2].minor.yy243; + Select *p = yymsp[0].minor.yy539; + if( p ){ + parserDoubleLinkSelect(pParse, p); + } + yymsp[0].minor.yy539 = p; /*A-overwrites-X*/ +} + break; + case 86: /* selectnowith ::= selectnowith multiselect_op oneselect */ +{ + Select *pRhs = yymsp[0].minor.yy539; + Select *pLhs = yymsp[-2].minor.yy539; if( pRhs && pRhs->pPrior ){ SrcList *pFrom; Token x; x.n = 0; parserDoubleLinkSelect(pParse, pRhs); - pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0); - pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0); + pFrom = tdsqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0); + pRhs = tdsqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0); } if( pRhs ){ - pRhs->op = (u8)yymsp[-1].minor.yy194; + pRhs->op = (u8)yymsp[-1].minor.yy192; pRhs->pPrior = pLhs; if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue; pRhs->selFlags &= ~SF_MultiValue; - if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1; + if( yymsp[-1].minor.yy192!=TK_ALL ) pParse->hasCompound = 1; }else{ - sqlite3SelectDelete(pParse->db, pLhs); + tdsqlite3SelectDelete(pParse->db, pLhs); } - yymsp[-2].minor.yy243 = pRhs; + yymsp[-2].minor.yy539 = pRhs; } break; - case 82: /* multiselect_op ::= UNION */ - case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84); -{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/} + case 87: /* multiselect_op ::= UNION */ + case 89: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==89); +{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-OP*/} break; - case 83: /* multiselect_op ::= UNION ALL */ -{yymsp[-1].minor.yy194 = TK_ALL;} + case 88: /* multiselect_op ::= UNION ALL */ +{yymsp[-1].minor.yy192 = TK_ALL;} break; - case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ + case 90: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ { -#if SELECTTRACE_ENABLED - Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/ -#endif - yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset); -#if SELECTTRACE_ENABLED - /* Populate the Select.zSelName[] string that is used to help with - ** query planner debugging, to differentiate between multiple Select - ** objects in a complex query. - ** - ** If the SELECT keyword is immediately followed by a C-style comment - ** then extract the first few alphanumeric characters from within that - ** comment to be the zSelName value. Otherwise, the label is #N where - ** is an integer that is incremented with each SELECT statement seen. - */ - if( yymsp[-8].minor.yy243!=0 ){ - const char *z = s.z+6; - int i; - sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d", - ++pParse->nSelect); - while( z[0]==' ' ) z++; - if( z[0]=='/' && z[1]=='*' ){ - z += 2; - while( z[0]==' ' ) z++; - for(i=0; sqlite3Isalnum(z[i]); i++){} - sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z); - } + yymsp[-8].minor.yy539 = tdsqlite3SelectNew(pParse,yymsp[-6].minor.yy242,yymsp[-5].minor.yy47,yymsp[-4].minor.yy202,yymsp[-3].minor.yy242,yymsp[-2].minor.yy202,yymsp[-1].minor.yy242,yymsp[-7].minor.yy192,yymsp[0].minor.yy202); +} + break; + case 91: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */ +{ + yymsp[-9].minor.yy539 = tdsqlite3SelectNew(pParse,yymsp[-7].minor.yy242,yymsp[-6].minor.yy47,yymsp[-5].minor.yy202,yymsp[-4].minor.yy242,yymsp[-3].minor.yy202,yymsp[-1].minor.yy242,yymsp[-8].minor.yy192,yymsp[0].minor.yy202); + if( yymsp[-9].minor.yy539 ){ + yymsp[-9].minor.yy539->pWinDefn = yymsp[-2].minor.yy303; + }else{ + tdsqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy303); } -#endif /* SELECTRACE_ENABLED */ } break; - case 86: /* values ::= VALUES LP nexprlist RP */ + case 92: /* values ::= VALUES LP nexprlist RP */ { - yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0); + yymsp[-3].minor.yy539 = tdsqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values,0); } break; - case 87: /* values ::= values COMMA LP exprlist RP */ + case 93: /* values ::= values COMMA LP nexprlist RP */ { - Select *pRight, *pLeft = yymsp[-4].minor.yy243; - pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0); + Select *pRight, *pLeft = yymsp[-4].minor.yy539; + pRight = tdsqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values|SF_MultiValue,0); if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue; if( pRight ){ pRight->op = TK_ALL; pRight->pPrior = pLeft; - yymsp[-4].minor.yy243 = pRight; + yymsp[-4].minor.yy539 = pRight; }else{ - yymsp[-4].minor.yy243 = pLeft; + yymsp[-4].minor.yy539 = pLeft; } } break; - case 88: /* distinct ::= DISTINCT */ -{yymsp[0].minor.yy194 = SF_Distinct;} + case 94: /* distinct ::= DISTINCT */ +{yymsp[0].minor.yy192 = SF_Distinct;} break; - case 89: /* distinct ::= ALL */ -{yymsp[0].minor.yy194 = SF_All;} + case 95: /* distinct ::= ALL */ +{yymsp[0].minor.yy192 = SF_All;} break; - case 91: /* sclp ::= */ - case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119); - case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126); - case 203: /* exprlist ::= */ yytestcase(yyruleno==203); - case 206: /* paren_exprlist ::= */ yytestcase(yyruleno==206); - case 211: /* eidlist_opt ::= */ yytestcase(yyruleno==211); -{yymsp[1].minor.yy148 = 0;} + case 97: /* sclp ::= */ + case 130: /* orderby_opt ::= */ yytestcase(yyruleno==130); + case 140: /* groupby_opt ::= */ yytestcase(yyruleno==140); + case 220: /* exprlist ::= */ yytestcase(yyruleno==220); + case 223: /* paren_exprlist ::= */ yytestcase(yyruleno==223); + case 228: /* eidlist_opt ::= */ yytestcase(yyruleno==228); +{yymsp[1].minor.yy242 = 0;} break; - case 92: /* selcollist ::= sclp expr as */ + case 98: /* selcollist ::= sclp scanpt expr scanpt as */ { - yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr); - if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1); - sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190); + yymsp[-4].minor.yy242 = tdsqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[-2].minor.yy202); + if( yymsp[0].minor.yy0.n>0 ) tdsqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[0].minor.yy0, 1); + tdsqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy242,yymsp[-3].minor.yy436,yymsp[-1].minor.yy436); } break; - case 93: /* selcollist ::= sclp STAR */ + case 99: /* selcollist ::= sclp scanpt STAR */ { - Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0); - yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p); + Expr *p = tdsqlite3Expr(pParse->db, TK_ASTERISK, 0); + yymsp[-2].minor.yy242 = tdsqlite3ExprListAppend(pParse, yymsp[-2].minor.yy242, p); } break; - case 94: /* selcollist ::= sclp nm DOT STAR */ + case 100: /* selcollist ::= sclp scanpt nm DOT STAR */ { - Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, 0); - Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0); - Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); - yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot); + Expr *pRight = tdsqlite3PExpr(pParse, TK_ASTERISK, 0, 0); + Expr *pLeft = tdsqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); + Expr *pDot = tdsqlite3PExpr(pParse, TK_DOT, pLeft, pRight); + yymsp[-4].minor.yy242 = tdsqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, pDot); } break; - case 95: /* as ::= AS nm */ - case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106); - case 225: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==225); - case 226: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==226); + case 101: /* as ::= AS nm */ + case 112: /* dbnm ::= DOT nm */ yytestcase(yyruleno==112); + case 244: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==244); + case 245: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==245); {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;} break; - case 97: /* from ::= */ -{yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));} + case 103: /* from ::= */ +{yymsp[1].minor.yy47 = tdsqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy47));} break; - case 98: /* from ::= FROM seltablist */ + case 104: /* from ::= FROM seltablist */ { - yymsp[-1].minor.yy185 = yymsp[0].minor.yy185; - sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185); + yymsp[-1].minor.yy47 = yymsp[0].minor.yy47; + tdsqlite3SrcListShiftJoinType(yymsp[-1].minor.yy47); } break; - case 99: /* stl_prefix ::= seltablist joinop */ + case 105: /* stl_prefix ::= seltablist joinop */ { - if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194; + if( ALWAYS(yymsp[-1].minor.yy47 && yymsp[-1].minor.yy47->nSrc>0) ) yymsp[-1].minor.yy47->a[yymsp[-1].minor.yy47->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy192; } break; - case 100: /* stl_prefix ::= */ -{yymsp[1].minor.yy185 = 0;} + case 106: /* stl_prefix ::= */ +{yymsp[1].minor.yy47 = 0;} break; - case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ + case 107: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ { - yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); - sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0); + yymsp[-6].minor.yy47 = tdsqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); + tdsqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy47, &yymsp[-2].minor.yy0); } break; - case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ + case 108: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ { - yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); - sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148); + yymsp[-8].minor.yy47 = tdsqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy47,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); + tdsqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy47, yymsp[-4].minor.yy242); } break; - case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ + case 109: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ { - yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); + yymsp[-6].minor.yy47 = tdsqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy539,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); } break; - case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ + case 110: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ { - if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){ - yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185; - }else if( yymsp[-4].minor.yy185->nSrc==1 ){ - yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); - if( yymsp[-6].minor.yy185 ){ - struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1]; - struct SrcList_item *pOld = yymsp[-4].minor.yy185->a; + if( yymsp[-6].minor.yy47==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy202==0 && yymsp[0].minor.yy600==0 ){ + yymsp[-6].minor.yy47 = yymsp[-4].minor.yy47; + }else if( yymsp[-4].minor.yy47->nSrc==1 ){ + yymsp[-6].minor.yy47 = tdsqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); + if( yymsp[-6].minor.yy47 ){ + struct SrcList_item *pNew = &yymsp[-6].minor.yy47->a[yymsp[-6].minor.yy47->nSrc-1]; + struct SrcList_item *pOld = yymsp[-4].minor.yy47->a; pNew->zName = pOld->zName; pNew->zDatabase = pOld->zDatabase; pNew->pSelect = pOld->pSelect; + if( pOld->fg.isTabFunc ){ + pNew->u1.pFuncArg = pOld->u1.pFuncArg; + pOld->u1.pFuncArg = 0; + pOld->fg.isTabFunc = 0; + pNew->fg.isTabFunc = 1; + } pOld->zName = pOld->zDatabase = 0; pOld->pSelect = 0; } - sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185); + tdsqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy47); }else{ Select *pSubquery; - sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185); - pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0); - yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); + tdsqlite3SrcListShiftJoinType(yymsp[-4].minor.yy47); + pSubquery = tdsqlite3SelectNew(pParse,0,yymsp[-4].minor.yy47,0,0,0,0,SF_NestedFrom,0); + yymsp[-6].minor.yy47 = tdsqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); } } break; - case 105: /* dbnm ::= */ - case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114); + case 111: /* dbnm ::= */ + case 125: /* indexed_opt ::= */ yytestcase(yyruleno==125); {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;} break; - case 107: /* fullname ::= nm dbnm */ -{yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/} + case 113: /* fullname ::= nm */ +{ + yylhsminor.yy47 = tdsqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); + if( IN_RENAME_OBJECT && yylhsminor.yy47 ) tdsqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0); +} + yymsp[0].minor.yy47 = yylhsminor.yy47; + break; + case 114: /* fullname ::= nm DOT nm */ +{ + yylhsminor.yy47 = tdsqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); + if( IN_RENAME_OBJECT && yylhsminor.yy47 ) tdsqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0); +} + yymsp[-2].minor.yy47 = yylhsminor.yy47; + break; + case 115: /* xfullname ::= nm */ +{yymsp[0].minor.yy47 = tdsqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/} + break; + case 116: /* xfullname ::= nm DOT nm */ +{yymsp[-2].minor.yy47 = tdsqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/} + break; + case 117: /* xfullname ::= nm DOT nm AS nm */ +{ + yymsp[-4].minor.yy47 = tdsqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/ + if( yymsp[-4].minor.yy47 ) yymsp[-4].minor.yy47->a[0].zAlias = tdsqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0); +} + break; + case 118: /* xfullname ::= nm AS nm */ +{ + yymsp[-2].minor.yy47 = tdsqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/ + if( yymsp[-2].minor.yy47 ) yymsp[-2].minor.yy47->a[0].zAlias = tdsqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0); +} break; - case 108: /* joinop ::= COMMA|JOIN */ -{ yymsp[0].minor.yy194 = JT_INNER; } + case 119: /* joinop ::= COMMA|JOIN */ +{ yymsp[0].minor.yy192 = JT_INNER; } break; - case 109: /* joinop ::= JOIN_KW JOIN */ -{yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/} + case 120: /* joinop ::= JOIN_KW JOIN */ +{yymsp[-1].minor.yy192 = tdsqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/} break; - case 110: /* joinop ::= JOIN_KW nm JOIN */ -{yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/} + case 121: /* joinop ::= JOIN_KW nm JOIN */ +{yymsp[-2].minor.yy192 = tdsqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/} break; - case 111: /* joinop ::= JOIN_KW nm nm JOIN */ -{yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/} + case 122: /* joinop ::= JOIN_KW nm nm JOIN */ +{yymsp[-3].minor.yy192 = tdsqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/} break; - case 112: /* on_opt ::= ON expr */ - case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129); - case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136); - case 199: /* case_else ::= ELSE expr */ yytestcase(yyruleno==199); -{yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;} + case 123: /* on_opt ::= ON expr */ + case 143: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==143); + case 150: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==150); + case 216: /* case_else ::= ELSE expr */ yytestcase(yyruleno==216); + case 237: /* vinto ::= INTO expr */ yytestcase(yyruleno==237); +{yymsp[-1].minor.yy202 = yymsp[0].minor.yy202;} break; - case 113: /* on_opt ::= */ - case 128: /* having_opt ::= */ yytestcase(yyruleno==128); - case 135: /* where_opt ::= */ yytestcase(yyruleno==135); - case 200: /* case_else ::= */ yytestcase(yyruleno==200); - case 202: /* case_operand ::= */ yytestcase(yyruleno==202); -{yymsp[1].minor.yy72 = 0;} + case 124: /* on_opt ::= */ + case 142: /* having_opt ::= */ yytestcase(yyruleno==142); + case 144: /* limit_opt ::= */ yytestcase(yyruleno==144); + case 149: /* where_opt ::= */ yytestcase(yyruleno==149); + case 217: /* case_else ::= */ yytestcase(yyruleno==217); + case 219: /* case_operand ::= */ yytestcase(yyruleno==219); + case 238: /* vinto ::= */ yytestcase(yyruleno==238); +{yymsp[1].minor.yy202 = 0;} break; - case 115: /* indexed_opt ::= INDEXED BY nm */ + case 126: /* indexed_opt ::= INDEXED BY nm */ {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;} break; - case 116: /* indexed_opt ::= NOT INDEXED */ + case 127: /* indexed_opt ::= NOT INDEXED */ {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;} break; - case 117: /* using_opt ::= USING LP idlist RP */ -{yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;} + case 128: /* using_opt ::= USING LP idlist RP */ +{yymsp[-3].minor.yy600 = yymsp[-1].minor.yy600;} break; - case 118: /* using_opt ::= */ - case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146); -{yymsp[1].minor.yy254 = 0;} + case 129: /* using_opt ::= */ + case 164: /* idlist_opt ::= */ yytestcase(yyruleno==164); +{yymsp[1].minor.yy600 = 0;} break; - case 120: /* orderby_opt ::= ORDER BY sortlist */ - case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127); -{yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;} + case 131: /* orderby_opt ::= ORDER BY sortlist */ + case 141: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==141); +{yymsp[-2].minor.yy242 = yymsp[0].minor.yy242;} break; - case 121: /* sortlist ::= sortlist COMMA expr sortorder */ + case 132: /* sortlist ::= sortlist COMMA expr sortorder nulls */ { - yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr); - sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194); + yymsp[-4].minor.yy242 = tdsqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202); + tdsqlite3ExprListSetSortOrder(yymsp[-4].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192); } break; - case 122: /* sortlist ::= expr sortorder */ + case 133: /* sortlist ::= expr sortorder nulls */ { - yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/ - sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194); + yymsp[-2].minor.yy242 = tdsqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy202); /*A-overwrites-Y*/ + tdsqlite3ExprListSetSortOrder(yymsp[-2].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192); } break; - case 123: /* sortorder ::= ASC */ -{yymsp[0].minor.yy194 = SQLITE_SO_ASC;} + case 134: /* sortorder ::= ASC */ +{yymsp[0].minor.yy192 = SQLITE_SO_ASC;} break; - case 124: /* sortorder ::= DESC */ -{yymsp[0].minor.yy194 = SQLITE_SO_DESC;} + case 135: /* sortorder ::= DESC */ +{yymsp[0].minor.yy192 = SQLITE_SO_DESC;} break; - case 125: /* sortorder ::= */ -{yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;} + case 136: /* sortorder ::= */ + case 139: /* nulls ::= */ yytestcase(yyruleno==139); +{yymsp[1].minor.yy192 = SQLITE_SO_UNDEFINED;} break; - case 130: /* limit_opt ::= */ -{yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;} + case 137: /* nulls ::= NULLS FIRST */ +{yymsp[-1].minor.yy192 = SQLITE_SO_ASC;} break; - case 131: /* limit_opt ::= LIMIT expr */ -{yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;} + case 138: /* nulls ::= NULLS LAST */ +{yymsp[-1].minor.yy192 = SQLITE_SO_DESC;} break; - case 132: /* limit_opt ::= LIMIT expr OFFSET expr */ -{yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;} + case 145: /* limit_opt ::= LIMIT expr */ +{yymsp[-1].minor.yy202 = tdsqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,0);} break; - case 133: /* limit_opt ::= LIMIT expr COMMA expr */ -{yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;} + case 146: /* limit_opt ::= LIMIT expr OFFSET expr */ +{yymsp[-3].minor.yy202 = tdsqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);} break; - case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */ + case 147: /* limit_opt ::= LIMIT expr COMMA expr */ +{yymsp[-3].minor.yy202 = tdsqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,yymsp[-2].minor.yy202);} + break; + case 148: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */ { - sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); - sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0); - sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72); + tdsqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy47, &yymsp[-1].minor.yy0); + tdsqlite3DeleteFrom(pParse,yymsp[-2].minor.yy47,yymsp[0].minor.yy202,0,0); } break; - case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */ + case 151: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */ { - sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1); - sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0); - sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list"); - sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194); + tdsqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy47, &yymsp[-3].minor.yy0); + tdsqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy242,"set list"); + tdsqlite3Update(pParse,yymsp[-4].minor.yy47,yymsp[-1].minor.yy242,yymsp[0].minor.yy202,yymsp[-5].minor.yy192,0,0,0); } break; - case 138: /* setlist ::= setlist COMMA nm EQ expr */ + case 152: /* setlist ::= setlist COMMA nm EQ expr */ { - yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); - sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1); + yymsp[-4].minor.yy242 = tdsqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[0].minor.yy202); + tdsqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, 1); } break; - case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */ + case 153: /* setlist ::= setlist COMMA LP idlist RP EQ expr */ { - yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); + yymsp[-6].minor.yy242 = tdsqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy242, yymsp[-3].minor.yy600, yymsp[0].minor.yy202); } break; - case 140: /* setlist ::= nm EQ expr */ + case 154: /* setlist ::= nm EQ expr */ { - yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr); - sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1); + yylhsminor.yy242 = tdsqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy202); + tdsqlite3ExprListSetName(pParse, yylhsminor.yy242, &yymsp[-2].minor.yy0, 1); } - yymsp[-2].minor.yy148 = yylhsminor.yy148; + yymsp[-2].minor.yy242 = yylhsminor.yy242; break; - case 141: /* setlist ::= LP idlist RP EQ expr */ + case 155: /* setlist ::= LP idlist RP EQ expr */ { - yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); + yymsp[-4].minor.yy242 = tdsqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy600, yymsp[0].minor.yy202); } break; - case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */ + case 156: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */ { - sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); - sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194); + tdsqlite3Insert(pParse, yymsp[-3].minor.yy47, yymsp[-1].minor.yy539, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, yymsp[0].minor.yy318); } break; - case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */ + case 157: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */ { - sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1); - sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194); + tdsqlite3Insert(pParse, yymsp[-3].minor.yy47, 0, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, 0); } break; - case 147: /* idlist_opt ::= LP idlist RP */ -{yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;} + case 158: /* upsert ::= */ +{ yymsp[1].minor.yy318 = 0; } + break; + case 159: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */ +{ yymsp[-10].minor.yy318 = tdsqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy242,yymsp[-5].minor.yy202,yymsp[-1].minor.yy242,yymsp[0].minor.yy202);} + break; + case 160: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */ +{ yymsp[-7].minor.yy318 = tdsqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202,0,0); } break; - case 148: /* idlist ::= idlist COMMA nm */ -{yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);} + case 161: /* upsert ::= ON CONFLICT DO NOTHING */ +{ yymsp[-3].minor.yy318 = tdsqlite3UpsertNew(pParse->db,0,0,0,0); } break; - case 149: /* idlist ::= nm */ -{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/} + case 165: /* idlist_opt ::= LP idlist RP */ +{yymsp[-2].minor.yy600 = yymsp[-1].minor.yy600;} break; - case 150: /* expr ::= LP expr RP */ -{spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;} + case 166: /* idlist ::= idlist COMMA nm */ +{yymsp[-2].minor.yy600 = tdsqlite3IdListAppend(pParse,yymsp[-2].minor.yy600,&yymsp[0].minor.yy0);} break; - case 151: /* term ::= NULL */ - case 156: /* term ::= FLOAT|BLOB */ yytestcase(yyruleno==156); - case 157: /* term ::= STRING */ yytestcase(yyruleno==157); -{spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/} + case 167: /* idlist ::= nm */ +{yymsp[0].minor.yy600 = tdsqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/} break; - case 152: /* expr ::= ID|INDEXED */ - case 153: /* expr ::= JOIN_KW */ yytestcase(yyruleno==153); -{spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/} + case 168: /* expr ::= LP expr RP */ +{yymsp[-2].minor.yy202 = yymsp[-1].minor.yy202;} break; - case 154: /* expr ::= nm DOT nm */ + case 169: /* expr ::= ID|INDEXED */ + case 170: /* expr ::= JOIN_KW */ yytestcase(yyruleno==170); +{yymsp[0].minor.yy202=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/} + break; + case 171: /* expr ::= nm DOT nm */ { - Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); - Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); - spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0); + Expr *temp1 = tdsqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); + Expr *temp2 = tdsqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0); + tdsqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0); + } + yylhsminor.yy202 = tdsqlite3PExpr(pParse, TK_DOT, temp1, temp2); } + yymsp[-2].minor.yy202 = yylhsminor.yy202; break; - case 155: /* expr ::= nm DOT nm DOT nm */ + case 172: /* expr ::= nm DOT nm DOT nm */ { - Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1); - Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); - Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); - Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0); - spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0); + Expr *temp1 = tdsqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1); + Expr *temp2 = tdsqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); + Expr *temp3 = tdsqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); + Expr *temp4 = tdsqlite3PExpr(pParse, TK_DOT, temp2, temp3); + if( IN_RENAME_OBJECT ){ + tdsqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0); + tdsqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0); + } + yylhsminor.yy202 = tdsqlite3PExpr(pParse, TK_DOT, temp1, temp4); } + yymsp[-4].minor.yy202 = yylhsminor.yy202; break; - case 158: /* term ::= INTEGER */ + case 173: /* term ::= NULL|FLOAT|BLOB */ + case 174: /* term ::= STRING */ yytestcase(yyruleno==174); +{yymsp[0].minor.yy202=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/} + break; + case 175: /* term ::= INTEGER */ { - yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1); - yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z; - yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n; - if( yylhsminor.yy190.pExpr ) yylhsminor.yy190.pExpr->flags |= EP_Leaf; + yylhsminor.yy202 = tdsqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1); } - yymsp[0].minor.yy190 = yylhsminor.yy190; + yymsp[0].minor.yy202 = yylhsminor.yy202; break; - case 159: /* expr ::= VARIABLE */ + case 176: /* expr ::= VARIABLE */ { - if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){ + if( !(yymsp[0].minor.yy0.z[0]=='#' && tdsqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){ u32 n = yymsp[0].minor.yy0.n; - spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0); - sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n); + yymsp[0].minor.yy202 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0); + tdsqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy202, n); }else{ /* When doing a nested parse, one can include terms in an expression ** that look like this: #1 #2 ... These terms refer to registers ** in the virtual machine. #N is the N-th register. */ Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/ assert( t.n>=2 ); - spanSet(&yymsp[0].minor.yy190, &t, &t); if( pParse->nested==0 ){ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t); - yymsp[0].minor.yy190.pExpr = 0; + tdsqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t); + yymsp[0].minor.yy202 = 0; }else{ - yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, 0); - if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable); + yymsp[0].minor.yy202 = tdsqlite3PExpr(pParse, TK_REGISTER, 0, 0); + if( yymsp[0].minor.yy202 ) tdsqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy202->iTable); } } } break; - case 160: /* expr ::= expr COLLATE ID|STRING */ + case 177: /* expr ::= expr COLLATE ID|STRING */ { - yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1); - yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; + yymsp[-2].minor.yy202 = tdsqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy202, &yymsp[0].minor.yy0, 1); } break; - case 161: /* expr ::= CAST LP expr AS typetoken RP */ + case 178: /* expr ::= CAST LP expr AS typetoken RP */ { - spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy190.pExpr, 0, &yymsp[-1].minor.yy0); + yymsp[-5].minor.yy202 = tdsqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1); + tdsqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy202, yymsp[-3].minor.yy202, 0); } break; - case 162: /* expr ::= ID|INDEXED LP distinct exprlist RP */ + case 179: /* expr ::= ID|INDEXED LP distinct exprlist RP */ { - if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ - sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0); - } - yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0); - spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); - if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){ - yylhsminor.yy190.pExpr->flags |= EP_Distinct; - } + yylhsminor.yy202 = tdsqlite3ExprFunction(pParse, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy192); } - yymsp[-4].minor.yy190 = yylhsminor.yy190; + yymsp[-4].minor.yy202 = yylhsminor.yy202; break; - case 163: /* expr ::= ID|INDEXED LP STAR RP */ + case 180: /* expr ::= ID|INDEXED LP STAR RP */ { - yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0); - spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); + yylhsminor.yy202 = tdsqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0); } - yymsp[-3].minor.yy190 = yylhsminor.yy190; + yymsp[-3].minor.yy202 = yylhsminor.yy202; break; - case 164: /* term ::= CTIME_KW */ + case 181: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */ { - yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0); - spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0); + yylhsminor.yy202 = tdsqlite3ExprFunction(pParse, yymsp[-2].minor.yy242, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy192); + tdsqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303); } - yymsp[0].minor.yy190 = yylhsminor.yy190; + yymsp[-5].minor.yy202 = yylhsminor.yy202; break; - case 165: /* expr ::= LP nexprlist COMMA expr RP */ + case 182: /* expr ::= ID|INDEXED LP STAR RP filter_over */ { - ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr); - yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0, 0); - if( yylhsminor.yy190.pExpr ){ - yylhsminor.yy190.pExpr->x.pList = pList; - spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0); + yylhsminor.yy202 = tdsqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0); + tdsqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303); +} + yymsp[-4].minor.yy202 = yylhsminor.yy202; + break; + case 183: /* term ::= CTIME_KW */ +{ + yylhsminor.yy202 = tdsqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0); +} + yymsp[0].minor.yy202 = yylhsminor.yy202; + break; + case 184: /* expr ::= LP nexprlist COMMA expr RP */ +{ + ExprList *pList = tdsqlite3ExprListAppend(pParse, yymsp[-3].minor.yy242, yymsp[-1].minor.yy202); + yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_VECTOR, 0, 0); + if( yymsp[-4].minor.yy202 ){ + yymsp[-4].minor.yy202->x.pList = pList; + if( ALWAYS(pList->nExpr) ){ + yymsp[-4].minor.yy202->flags |= pList->a[0].pExpr->flags & EP_Propagate; + } }else{ - sqlite3ExprListDelete(pParse->db, pList); + tdsqlite3ExprListDelete(pParse->db, pList); } } - yymsp[-4].minor.yy190 = yylhsminor.yy190; break; - case 166: /* expr ::= expr AND expr */ - case 167: /* expr ::= expr OR expr */ yytestcase(yyruleno==167); - case 168: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==168); - case 169: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==169); - case 170: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==170); - case 171: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==171); - case 172: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==172); - case 173: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==173); -{spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);} + case 185: /* expr ::= expr AND expr */ +{yymsp[-2].minor.yy202=tdsqlite3ExprAnd(pParse,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);} break; - case 174: /* likeop ::= LIKE_KW|MATCH */ -{yymsp[0].minor.yy0=yymsp[0].minor.yy0;/*A-overwrites-X*/} + case 186: /* expr ::= expr OR expr */ + case 187: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==187); + case 188: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==188); + case 189: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==189); + case 190: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==190); + case 191: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==191); + case 192: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==192); +{yymsp[-2].minor.yy202=tdsqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);} break; - case 175: /* likeop ::= NOT LIKE_KW|MATCH */ + case 193: /* likeop ::= NOT LIKE_KW|MATCH */ {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/} break; - case 176: /* expr ::= expr likeop expr */ + case 194: /* expr ::= expr likeop expr */ { ExprList *pList; int bNot = yymsp[-1].minor.yy0.n & 0x80000000; yymsp[-1].minor.yy0.n &= 0x7fffffff; - pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr); - yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0); - exprNot(pParse, bNot, &yymsp[-2].minor.yy190); - yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; - if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc; + pList = tdsqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy202); + pList = tdsqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy202); + yymsp[-2].minor.yy202 = tdsqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0); + if( bNot ) yymsp[-2].minor.yy202 = tdsqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy202, 0); + if( yymsp[-2].minor.yy202 ) yymsp[-2].minor.yy202->flags |= EP_InfixFunc; } break; - case 177: /* expr ::= expr likeop expr ESCAPE expr */ + case 195: /* expr ::= expr likeop expr ESCAPE expr */ { ExprList *pList; int bNot = yymsp[-3].minor.yy0.n & 0x80000000; yymsp[-3].minor.yy0.n &= 0x7fffffff; - pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); - yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0); - exprNot(pParse, bNot, &yymsp[-4].minor.yy190); - yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; - if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc; + pList = tdsqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202); + pList = tdsqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy202); + pList = tdsqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202); + yymsp[-4].minor.yy202 = tdsqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0); + if( bNot ) yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); + if( yymsp[-4].minor.yy202 ) yymsp[-4].minor.yy202->flags |= EP_InfixFunc; } break; - case 178: /* expr ::= expr ISNULL|NOTNULL */ -{spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);} + case 196: /* expr ::= expr ISNULL|NOTNULL */ +{yymsp[-1].minor.yy202 = tdsqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy202,0);} break; - case 179: /* expr ::= expr NOT NULL */ -{spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);} + case 197: /* expr ::= expr NOT NULL */ +{yymsp[-2].minor.yy202 = tdsqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy202,0);} break; - case 180: /* expr ::= expr IS expr */ + case 198: /* expr ::= expr IS expr */ { - spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL); + yymsp[-2].minor.yy202 = tdsqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy202,yymsp[0].minor.yy202); + binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-2].minor.yy202, TK_ISNULL); } break; - case 181: /* expr ::= expr IS NOT expr */ + case 199: /* expr ::= expr IS NOT expr */ { - spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL); + yymsp[-3].minor.yy202 = tdsqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy202,yymsp[0].minor.yy202); + binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-3].minor.yy202, TK_NOTNULL); } break; - case 182: /* expr ::= NOT expr */ - case 183: /* expr ::= BITNOT expr */ yytestcase(yyruleno==183); -{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} + case 200: /* expr ::= NOT expr */ + case 201: /* expr ::= BITNOT expr */ yytestcase(yyruleno==201); +{yymsp[-1].minor.yy202 = tdsqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy202, 0);/*A-overwrites-B*/} break; - case 184: /* expr ::= MINUS expr */ -{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} - break; - case 185: /* expr ::= PLUS expr */ -{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} + case 202: /* expr ::= PLUS|MINUS expr */ +{ + yymsp[-1].minor.yy202 = tdsqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy202, 0); + /*A-overwrites-B*/ +} break; - case 186: /* between_op ::= BETWEEN */ - case 189: /* in_op ::= IN */ yytestcase(yyruleno==189); -{yymsp[0].minor.yy194 = 0;} + case 203: /* between_op ::= BETWEEN */ + case 206: /* in_op ::= IN */ yytestcase(yyruleno==206); +{yymsp[0].minor.yy192 = 0;} break; - case 188: /* expr ::= expr between_op expr AND expr */ + case 205: /* expr ::= expr between_op expr AND expr */ { - ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0, 0); - if( yymsp[-4].minor.yy190.pExpr ){ - yymsp[-4].minor.yy190.pExpr->x.pList = pList; + ExprList *pList = tdsqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202); + pList = tdsqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202); + yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy202, 0); + if( yymsp[-4].minor.yy202 ){ + yymsp[-4].minor.yy202->x.pList = pList; }else{ - sqlite3ExprListDelete(pParse->db, pList); + tdsqlite3ExprListDelete(pParse->db, pList); } - exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); - yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; + if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); } break; - case 191: /* expr ::= expr in_op LP exprlist RP */ + case 208: /* expr ::= expr in_op LP exprlist RP */ { - if( yymsp[-1].minor.yy148==0 ){ + if( yymsp[-1].minor.yy242==0 ){ /* Expressions of the form ** ** expr1 IN () @@ -139001,440 +160134,556 @@ static void yy_reduce( ** simplify to constants 0 (false) and 1 (true), respectively, ** regardless of the value of expr1. */ - sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr); - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy194]); - }else if( yymsp[-1].minor.yy148->nExpr==1 ){ - /* Expressions of the form: - ** - ** expr1 IN (?1) - ** expr1 NOT IN (?2) - ** - ** with exactly one value on the RHS can be simplified to something - ** like this: - ** - ** expr1 == ?1 - ** expr1 <> ?2 - ** - ** But, the RHS of the == or <> is marked with the EP_Generic flag - ** so that it may not contribute to the computation of comparison - ** affinity or the collating sequence to use for comparison. Otherwise, - ** the semantics would be subtly different from IN or NOT IN. - */ - Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr; - yymsp[-1].minor.yy148->a[0].pExpr = 0; - sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); - /* pRHS cannot be NULL because a malloc error would have been detected - ** before now and control would have never reached this point */ - if( ALWAYS(pRHS) ){ - pRHS->flags &= ~EP_Collate; - pRHS->flags |= EP_Generic; - } - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS, 0); - }else{ - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0); - if( yymsp[-4].minor.yy190.pExpr ){ - yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148; - sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); + tdsqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy202); + yymsp[-4].minor.yy202 = tdsqlite3Expr(pParse->db, TK_INTEGER, yymsp[-3].minor.yy192 ? "1" : "0"); + }else{ + yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0); + if( yymsp[-4].minor.yy202 ){ + yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy242; + tdsqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202); }else{ - sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); + tdsqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242); } - exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); + if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); } - yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; } break; - case 192: /* expr ::= LP select RP */ + case 209: /* expr ::= LP select RP */ { - spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ - yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0); - sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243); + yymsp[-2].minor.yy202 = tdsqlite3PExpr(pParse, TK_SELECT, 0, 0); + tdsqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy202, yymsp[-1].minor.yy539); } break; - case 193: /* expr ::= expr in_op LP select RP */ + case 210: /* expr ::= expr in_op LP select RP */ { - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0); - sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243); - exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); - yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; + yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0); + tdsqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, yymsp[-1].minor.yy539); + if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); } break; - case 194: /* expr ::= expr in_op nm dbnm paren_exprlist */ + case 211: /* expr ::= expr in_op nm dbnm paren_exprlist */ { - SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); - Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0); - if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148); - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0); - sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect); - exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); - yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n]; + SrcList *pSrc = tdsqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); + Select *pSelect = tdsqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0); + if( yymsp[0].minor.yy242 ) tdsqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy242); + yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0); + tdsqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, pSelect); + if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); } break; - case 195: /* expr ::= EXISTS LP select RP */ + case 212: /* expr ::= EXISTS LP select RP */ { Expr *p; - spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ - p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0); - sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243); + p = yymsp[-3].minor.yy202 = tdsqlite3PExpr(pParse, TK_EXISTS, 0, 0); + tdsqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy539); } break; - case 196: /* expr ::= CASE case_operand case_exprlist case_else END */ + case 213: /* expr ::= CASE case_operand case_exprlist case_else END */ { - spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/ - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0, 0); - if( yymsp[-4].minor.yy190.pExpr ){ - yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148; - sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); + yymsp[-4].minor.yy202 = tdsqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy202, 0); + if( yymsp[-4].minor.yy202 ){ + yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy202 ? tdsqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[-1].minor.yy202) : yymsp[-2].minor.yy242; + tdsqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202); }else{ - sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148); - sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72); + tdsqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy242); + tdsqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy202); } } break; - case 197: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ + case 214: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ { - yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr); - yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); + yymsp[-4].minor.yy242 = tdsqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[-2].minor.yy202); + yymsp[-4].minor.yy242 = tdsqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[0].minor.yy202); } break; - case 198: /* case_exprlist ::= WHEN expr THEN expr */ + case 215: /* case_exprlist ::= WHEN expr THEN expr */ { - yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); - yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr); + yymsp[-3].minor.yy242 = tdsqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202); + yymsp[-3].minor.yy242 = tdsqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242, yymsp[0].minor.yy202); } break; - case 201: /* case_operand ::= expr */ -{yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/} + case 218: /* case_operand ::= expr */ +{yymsp[0].minor.yy202 = yymsp[0].minor.yy202; /*A-overwrites-X*/} break; - case 204: /* nexprlist ::= nexprlist COMMA expr */ -{yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);} + case 221: /* nexprlist ::= nexprlist COMMA expr */ +{yymsp[-2].minor.yy242 = tdsqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[0].minor.yy202);} break; - case 205: /* nexprlist ::= expr */ -{yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/} + case 222: /* nexprlist ::= expr */ +{yymsp[0].minor.yy242 = tdsqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy202); /*A-overwrites-Y*/} break; - case 207: /* paren_exprlist ::= LP exprlist RP */ - case 212: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==212); -{yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;} + case 224: /* paren_exprlist ::= LP exprlist RP */ + case 229: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==229); +{yymsp[-2].minor.yy242 = yymsp[-1].minor.yy242;} break; - case 208: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ + case 225: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ { - sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, - sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194, - &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF); + tdsqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, + tdsqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy242, yymsp[-10].minor.yy192, + &yymsp[-11].minor.yy0, yymsp[0].minor.yy202, SQLITE_SO_ASC, yymsp[-8].minor.yy192, SQLITE_IDXTYPE_APPDEF); + if( IN_RENAME_OBJECT && pParse->pNewIndex ){ + tdsqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0); + } } break; - case 209: /* uniqueflag ::= UNIQUE */ - case 250: /* raisetype ::= ABORT */ yytestcase(yyruleno==250); -{yymsp[0].minor.yy194 = OE_Abort;} + case 226: /* uniqueflag ::= UNIQUE */ + case 268: /* raisetype ::= ABORT */ yytestcase(yyruleno==268); +{yymsp[0].minor.yy192 = OE_Abort;} break; - case 210: /* uniqueflag ::= */ -{yymsp[1].minor.yy194 = OE_None;} + case 227: /* uniqueflag ::= */ +{yymsp[1].minor.yy192 = OE_None;} break; - case 213: /* eidlist ::= eidlist COMMA nm collate sortorder */ + case 230: /* eidlist ::= eidlist COMMA nm collate sortorder */ { - yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); + yymsp[-4].minor.yy242 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192); } break; - case 214: /* eidlist ::= nm collate sortorder */ + case 231: /* eidlist ::= nm collate sortorder */ { - yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/ + yymsp[-2].minor.yy242 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192); /*A-overwrites-Y*/ } break; - case 217: /* cmd ::= DROP INDEX ifexists fullname */ -{sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);} + case 234: /* cmd ::= DROP INDEX ifexists fullname */ +{tdsqlite3DropIndex(pParse, yymsp[0].minor.yy47, yymsp[-1].minor.yy192);} break; - case 218: /* cmd ::= VACUUM */ -{sqlite3Vacuum(pParse,0);} + case 235: /* cmd ::= VACUUM vinto */ +{tdsqlite3Vacuum(pParse,0,yymsp[0].minor.yy202);} break; - case 219: /* cmd ::= VACUUM nm */ -{sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);} + case 236: /* cmd ::= VACUUM nm vinto */ +{tdsqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy202);} break; - case 220: /* cmd ::= PRAGMA nm dbnm */ -{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);} + case 239: /* cmd ::= PRAGMA nm dbnm */ +{tdsqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);} break; - case 221: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ -{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);} + case 240: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ +{tdsqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);} break; - case 222: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ -{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);} + case 241: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ +{tdsqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);} break; - case 223: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ -{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);} + case 242: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ +{tdsqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);} break; - case 224: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ -{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);} + case 243: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ +{tdsqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);} break; - case 227: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ + case 246: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ { Token all; all.z = yymsp[-3].minor.yy0.z; all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n; - sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all); + tdsqlite3FinishTrigger(pParse, yymsp[-1].minor.yy447, &all); } break; - case 228: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ + case 247: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ { - sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194); + tdsqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy192, yymsp[-4].minor.yy230.a, yymsp[-4].minor.yy230.b, yymsp[-2].minor.yy47, yymsp[0].minor.yy202, yymsp[-10].minor.yy192, yymsp[-8].minor.yy192); yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/ } break; - case 229: /* trigger_time ::= BEFORE */ -{ yymsp[0].minor.yy194 = TK_BEFORE; } - break; - case 230: /* trigger_time ::= AFTER */ -{ yymsp[0].minor.yy194 = TK_AFTER; } + case 248: /* trigger_time ::= BEFORE|AFTER */ +{ yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/ } break; - case 231: /* trigger_time ::= INSTEAD OF */ -{ yymsp[-1].minor.yy194 = TK_INSTEAD;} + case 249: /* trigger_time ::= INSTEAD OF */ +{ yymsp[-1].minor.yy192 = TK_INSTEAD;} break; - case 232: /* trigger_time ::= */ -{ yymsp[1].minor.yy194 = TK_BEFORE; } + case 250: /* trigger_time ::= */ +{ yymsp[1].minor.yy192 = TK_BEFORE; } break; - case 233: /* trigger_event ::= DELETE|INSERT */ - case 234: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==234); -{yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;} + case 251: /* trigger_event ::= DELETE|INSERT */ + case 252: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==252); +{yymsp[0].minor.yy230.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy230.b = 0;} break; - case 235: /* trigger_event ::= UPDATE OF idlist */ -{yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;} + case 253: /* trigger_event ::= UPDATE OF idlist */ +{yymsp[-2].minor.yy230.a = TK_UPDATE; yymsp[-2].minor.yy230.b = yymsp[0].minor.yy600;} break; - case 236: /* when_clause ::= */ - case 255: /* key_opt ::= */ yytestcase(yyruleno==255); -{ yymsp[1].minor.yy72 = 0; } + case 254: /* when_clause ::= */ + case 273: /* key_opt ::= */ yytestcase(yyruleno==273); +{ yymsp[1].minor.yy202 = 0; } break; - case 237: /* when_clause ::= WHEN expr */ - case 256: /* key_opt ::= KEY expr */ yytestcase(yyruleno==256); -{ yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; } + case 255: /* when_clause ::= WHEN expr */ + case 274: /* key_opt ::= KEY expr */ yytestcase(yyruleno==274); +{ yymsp[-1].minor.yy202 = yymsp[0].minor.yy202; } break; - case 238: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ + case 256: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ { - assert( yymsp[-2].minor.yy145!=0 ); - yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145; - yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145; + assert( yymsp[-2].minor.yy447!=0 ); + yymsp[-2].minor.yy447->pLast->pNext = yymsp[-1].minor.yy447; + yymsp[-2].minor.yy447->pLast = yymsp[-1].minor.yy447; } break; - case 239: /* trigger_cmd_list ::= trigger_cmd SEMI */ + case 257: /* trigger_cmd_list ::= trigger_cmd SEMI */ { - assert( yymsp[-1].minor.yy145!=0 ); - yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145; + assert( yymsp[-1].minor.yy447!=0 ); + yymsp[-1].minor.yy447->pLast = yymsp[-1].minor.yy447; } break; - case 240: /* trnm ::= nm DOT nm */ + case 258: /* trnm ::= nm DOT nm */ { yymsp[-2].minor.yy0 = yymsp[0].minor.yy0; - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "qualified table names are not allowed on INSERT, UPDATE, and DELETE " "statements within triggers"); } break; - case 241: /* tridxby ::= INDEXED BY nm */ + case 259: /* tridxby ::= INDEXED BY nm */ { - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " "within triggers"); } break; - case 242: /* tridxby ::= NOT INDEXED */ + case 260: /* tridxby ::= NOT INDEXED */ { - sqlite3ErrorMsg(pParse, + tdsqlite3ErrorMsg(pParse, "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " "within triggers"); } break; - case 243: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */ -{yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);} + case 261: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */ +{yylhsminor.yy447 = tdsqlite3TriggerUpdateStep(pParse, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy202, yymsp[-6].minor.yy192, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy436);} + yymsp[-7].minor.yy447 = yylhsminor.yy447; break; - case 244: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */ -{yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/} + case 262: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */ +{ + yylhsminor.yy447 = tdsqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy600,yymsp[-2].minor.yy539,yymsp[-6].minor.yy192,yymsp[-1].minor.yy318,yymsp[-7].minor.yy436,yymsp[0].minor.yy436);/*yylhsminor.yy447-overwrites-yymsp[-6].minor.yy192*/ +} + yymsp[-7].minor.yy447 = yylhsminor.yy447; break; - case 245: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */ -{yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);} + case 263: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */ +{yylhsminor.yy447 = tdsqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy202, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy436);} + yymsp[-5].minor.yy447 = yylhsminor.yy447; break; - case 246: /* trigger_cmd ::= select */ -{yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/} + case 264: /* trigger_cmd ::= scanpt select scanpt */ +{yylhsminor.yy447 = tdsqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy539, yymsp[-2].minor.yy436, yymsp[0].minor.yy436); /*yylhsminor.yy447-overwrites-yymsp[-1].minor.yy539*/} + yymsp[-2].minor.yy447 = yylhsminor.yy447; break; - case 247: /* expr ::= RAISE LP IGNORE RP */ + case 265: /* expr ::= RAISE LP IGNORE RP */ { - spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); - if( yymsp[-3].minor.yy190.pExpr ){ - yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore; + yymsp[-3].minor.yy202 = tdsqlite3PExpr(pParse, TK_RAISE, 0, 0); + if( yymsp[-3].minor.yy202 ){ + yymsp[-3].minor.yy202->affExpr = OE_Ignore; } } break; - case 248: /* expr ::= RAISE LP raisetype COMMA nm RP */ + case 266: /* expr ::= RAISE LP raisetype COMMA nm RP */ { - spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); - if( yymsp[-5].minor.yy190.pExpr ) { - yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194; + yymsp[-5].minor.yy202 = tdsqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1); + if( yymsp[-5].minor.yy202 ) { + yymsp[-5].minor.yy202->affExpr = (char)yymsp[-3].minor.yy192; } } break; - case 249: /* raisetype ::= ROLLBACK */ -{yymsp[0].minor.yy194 = OE_Rollback;} + case 267: /* raisetype ::= ROLLBACK */ +{yymsp[0].minor.yy192 = OE_Rollback;} break; - case 251: /* raisetype ::= FAIL */ -{yymsp[0].minor.yy194 = OE_Fail;} + case 269: /* raisetype ::= FAIL */ +{yymsp[0].minor.yy192 = OE_Fail;} break; - case 252: /* cmd ::= DROP TRIGGER ifexists fullname */ + case 270: /* cmd ::= DROP TRIGGER ifexists fullname */ { - sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194); + tdsqlite3DropTrigger(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy192); } break; - case 253: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ + case 271: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ { - sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72); + tdsqlite3Attach(pParse, yymsp[-3].minor.yy202, yymsp[-1].minor.yy202, yymsp[0].minor.yy202); } break; - case 254: /* cmd ::= DETACH database_kw_opt expr */ + case 272: /* cmd ::= DETACH database_kw_opt expr */ { - sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr); + tdsqlite3Detach(pParse, yymsp[0].minor.yy202); } break; - case 257: /* cmd ::= REINDEX */ -{sqlite3Reindex(pParse, 0, 0);} + case 275: /* cmd ::= REINDEX */ +{tdsqlite3Reindex(pParse, 0, 0);} break; - case 258: /* cmd ::= REINDEX nm dbnm */ -{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} + case 276: /* cmd ::= REINDEX nm dbnm */ +{tdsqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} break; - case 259: /* cmd ::= ANALYZE */ -{sqlite3Analyze(pParse, 0, 0);} + case 277: /* cmd ::= ANALYZE */ +{tdsqlite3Analyze(pParse, 0, 0);} break; - case 260: /* cmd ::= ANALYZE nm dbnm */ -{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} + case 278: /* cmd ::= ANALYZE nm dbnm */ +{tdsqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} break; - case 261: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ + case 279: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ { - sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0); + tdsqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy47,&yymsp[0].minor.yy0); } break; - case 262: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ + case 280: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ { yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n; - sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0); + tdsqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0); } break; - case 263: /* add_column_fullname ::= fullname */ + case 281: /* add_column_fullname ::= fullname */ { disableLookaside(pParse); - sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185); + tdsqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy47); +} + break; + case 282: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ +{ + tdsqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy47, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0); +} + break; + case 283: /* cmd ::= create_vtab */ +{tdsqlite3VtabFinishParse(pParse,0);} + break; + case 284: /* cmd ::= create_vtab LP vtabarglist RP */ +{tdsqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} + break; + case 285: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ +{ + tdsqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy192); +} + break; + case 286: /* vtabarg ::= */ +{tdsqlite3VtabArgInit(pParse);} + break; + case 287: /* vtabargtoken ::= ANY */ + case 288: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==288); + case 289: /* lp ::= LP */ yytestcase(yyruleno==289); +{tdsqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} + break; + case 290: /* with ::= WITH wqlist */ + case 291: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==291); +{ tdsqlite3WithPush(pParse, yymsp[0].minor.yy131, 1); } + break; + case 292: /* wqlist ::= nm eidlist_opt AS LP select RP */ +{ + yymsp[-5].minor.yy131 = tdsqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539); /*A-overwrites-X*/ } break; - case 264: /* cmd ::= create_vtab */ -{sqlite3VtabFinishParse(pParse,0);} + case 293: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ +{ + yymsp[-7].minor.yy131 = tdsqlite3WithAdd(pParse, yymsp[-7].minor.yy131, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539); +} break; - case 265: /* cmd ::= create_vtab LP vtabarglist RP */ -{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} + case 294: /* windowdefn_list ::= windowdefn */ +{ yylhsminor.yy303 = yymsp[0].minor.yy303; } + yymsp[0].minor.yy303 = yylhsminor.yy303; break; - case 266: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ + case 295: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */ { - sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194); + assert( yymsp[0].minor.yy303!=0 ); + tdsqlite3WindowChain(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy303); + yymsp[0].minor.yy303->pNextWin = yymsp[-2].minor.yy303; + yylhsminor.yy303 = yymsp[0].minor.yy303; } + yymsp[-2].minor.yy303 = yylhsminor.yy303; break; - case 267: /* vtabarg ::= */ -{sqlite3VtabArgInit(pParse);} + case 296: /* windowdefn ::= nm AS LP window RP */ +{ + if( ALWAYS(yymsp[-1].minor.yy303) ){ + yymsp[-1].minor.yy303->zName = tdsqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n); + } + yylhsminor.yy303 = yymsp[-1].minor.yy303; +} + yymsp[-4].minor.yy303 = yylhsminor.yy303; break; - case 268: /* vtabargtoken ::= ANY */ - case 269: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==269); - case 270: /* lp ::= LP */ yytestcase(yyruleno==270); -{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} + case 297: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */ +{ + yymsp[-4].minor.yy303 = tdsqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, 0); +} break; - case 271: /* with ::= */ -{yymsp[1].minor.yy285 = 0;} + case 298: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ +{ + yylhsminor.yy303 = tdsqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, &yymsp[-5].minor.yy0); +} + yymsp[-5].minor.yy303 = yylhsminor.yy303; break; - case 272: /* with ::= WITH wqlist */ -{ yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; } + case 299: /* window ::= ORDER BY sortlist frame_opt */ +{ + yymsp[-3].minor.yy303 = tdsqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, 0); +} break; - case 273: /* with ::= WITH RECURSIVE wqlist */ -{ yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; } + case 300: /* window ::= nm ORDER BY sortlist frame_opt */ +{ + yylhsminor.yy303 = tdsqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0); +} + yymsp[-4].minor.yy303 = yylhsminor.yy303; break; - case 274: /* wqlist ::= nm eidlist_opt AS LP select RP */ + case 301: /* window ::= frame_opt */ + case 320: /* filter_over ::= over_clause */ yytestcase(yyruleno==320); { - yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/ + yylhsminor.yy303 = yymsp[0].minor.yy303; } + yymsp[0].minor.yy303 = yylhsminor.yy303; break; - case 275: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ + case 302: /* window ::= nm frame_opt */ { - yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); + yylhsminor.yy303 = tdsqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, 0, &yymsp[-1].minor.yy0); +} + yymsp[-1].minor.yy303 = yylhsminor.yy303; + break; + case 303: /* frame_opt ::= */ +{ + yymsp[1].minor.yy303 = tdsqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0); } break; + case 304: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ +{ + yylhsminor.yy303 = tdsqlite3WindowAlloc(pParse, yymsp[-2].minor.yy192, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy58); +} + yymsp[-2].minor.yy303 = yylhsminor.yy303; + break; + case 305: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ +{ + yylhsminor.yy303 = tdsqlite3WindowAlloc(pParse, yymsp[-5].minor.yy192, yymsp[-3].minor.yy77.eType, yymsp[-3].minor.yy77.pExpr, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, yymsp[0].minor.yy58); +} + yymsp[-5].minor.yy303 = yylhsminor.yy303; + break; + case 307: /* frame_bound_s ::= frame_bound */ + case 309: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==309); +{yylhsminor.yy77 = yymsp[0].minor.yy77;} + yymsp[0].minor.yy77 = yylhsminor.yy77; + break; + case 308: /* frame_bound_s ::= UNBOUNDED PRECEDING */ + case 310: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==310); + case 312: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==312); +{yylhsminor.yy77.eType = yymsp[-1].major; yylhsminor.yy77.pExpr = 0;} + yymsp[-1].minor.yy77 = yylhsminor.yy77; + break; + case 311: /* frame_bound ::= expr PRECEDING|FOLLOWING */ +{yylhsminor.yy77.eType = yymsp[0].major; yylhsminor.yy77.pExpr = yymsp[-1].minor.yy202;} + yymsp[-1].minor.yy77 = yylhsminor.yy77; + break; + case 313: /* frame_exclude_opt ::= */ +{yymsp[1].minor.yy58 = 0;} + break; + case 314: /* frame_exclude_opt ::= EXCLUDE frame_exclude */ +{yymsp[-1].minor.yy58 = yymsp[0].minor.yy58;} + break; + case 315: /* frame_exclude ::= NO OTHERS */ + case 316: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==316); +{yymsp[-1].minor.yy58 = yymsp[-1].major; /*A-overwrites-X*/} + break; + case 317: /* frame_exclude ::= GROUP|TIES */ +{yymsp[0].minor.yy58 = yymsp[0].major; /*A-overwrites-X*/} + break; + case 318: /* window_clause ::= WINDOW windowdefn_list */ +{ yymsp[-1].minor.yy303 = yymsp[0].minor.yy303; } + break; + case 319: /* filter_over ::= filter_clause over_clause */ +{ + yymsp[0].minor.yy303->pFilter = yymsp[-1].minor.yy202; + yylhsminor.yy303 = yymsp[0].minor.yy303; +} + yymsp[-1].minor.yy303 = yylhsminor.yy303; + break; + case 321: /* filter_over ::= filter_clause */ +{ + yylhsminor.yy303 = (Window*)tdsqlite3DbMallocZero(pParse->db, sizeof(Window)); + if( yylhsminor.yy303 ){ + yylhsminor.yy303->eFrmType = TK_FILTER; + yylhsminor.yy303->pFilter = yymsp[0].minor.yy202; + }else{ + tdsqlite3ExprDelete(pParse->db, yymsp[0].minor.yy202); + } +} + yymsp[0].minor.yy303 = yylhsminor.yy303; + break; + case 322: /* over_clause ::= OVER LP window RP */ +{ + yymsp[-3].minor.yy303 = yymsp[-1].minor.yy303; + assert( yymsp[-3].minor.yy303!=0 ); +} + break; + case 323: /* over_clause ::= OVER nm */ +{ + yymsp[-1].minor.yy303 = (Window*)tdsqlite3DbMallocZero(pParse->db, sizeof(Window)); + if( yymsp[-1].minor.yy303 ){ + yymsp[-1].minor.yy303->zName = tdsqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n); + } +} + break; + case 324: /* filter_clause ::= FILTER LP WHERE expr RP */ +{ yymsp[-4].minor.yy202 = yymsp[-1].minor.yy202; } + break; default: - /* (276) input ::= cmdlist */ yytestcase(yyruleno==276); - /* (277) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==277); - /* (278) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=278); - /* (279) ecmd ::= SEMI */ yytestcase(yyruleno==279); - /* (280) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==280); - /* (281) explain ::= */ yytestcase(yyruleno==281); - /* (282) trans_opt ::= */ yytestcase(yyruleno==282); - /* (283) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==283); - /* (284) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==284); - /* (285) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==285); - /* (286) savepoint_opt ::= */ yytestcase(yyruleno==286); - /* (287) cmd ::= create_table create_table_args */ yytestcase(yyruleno==287); - /* (288) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==288); - /* (289) columnlist ::= columnname carglist */ yytestcase(yyruleno==289); - /* (290) nm ::= ID|INDEXED */ yytestcase(yyruleno==290); - /* (291) nm ::= STRING */ yytestcase(yyruleno==291); - /* (292) nm ::= JOIN_KW */ yytestcase(yyruleno==292); - /* (293) typetoken ::= typename */ yytestcase(yyruleno==293); - /* (294) typename ::= ID|STRING */ yytestcase(yyruleno==294); - /* (295) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=295); - /* (296) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=296); - /* (297) carglist ::= carglist ccons */ yytestcase(yyruleno==297); - /* (298) carglist ::= */ yytestcase(yyruleno==298); - /* (299) ccons ::= NULL onconf */ yytestcase(yyruleno==299); - /* (300) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==300); - /* (301) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==301); - /* (302) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=302); - /* (303) tconscomma ::= */ yytestcase(yyruleno==303); - /* (304) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=304); - /* (305) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=305); - /* (306) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=306); - /* (307) oneselect ::= values */ yytestcase(yyruleno==307); - /* (308) sclp ::= selcollist COMMA */ yytestcase(yyruleno==308); - /* (309) as ::= ID|STRING */ yytestcase(yyruleno==309); - /* (310) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=310); - /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311); - /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312); - /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313); - /* (314) nmnum ::= ON */ yytestcase(yyruleno==314); - /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315); - /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316); - /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317); - /* (318) foreach_clause ::= */ yytestcase(yyruleno==318); - /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319); - /* (320) trnm ::= nm */ yytestcase(yyruleno==320); - /* (321) tridxby ::= */ yytestcase(yyruleno==321); - /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322); - /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323); - /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324); - /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325); - /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326); - /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327); - /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328); - /* (329) anylist ::= */ yytestcase(yyruleno==329); - /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330); - /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331); + /* (325) input ::= cmdlist */ yytestcase(yyruleno==325); + /* (326) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==326); + /* (327) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=327); + /* (328) ecmd ::= SEMI */ yytestcase(yyruleno==328); + /* (329) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==329); + /* (330) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=330); + /* (331) trans_opt ::= */ yytestcase(yyruleno==331); + /* (332) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==332); + /* (333) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==333); + /* (334) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==334); + /* (335) savepoint_opt ::= */ yytestcase(yyruleno==335); + /* (336) cmd ::= create_table create_table_args */ yytestcase(yyruleno==336); + /* (337) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==337); + /* (338) columnlist ::= columnname carglist */ yytestcase(yyruleno==338); + /* (339) nm ::= ID|INDEXED */ yytestcase(yyruleno==339); + /* (340) nm ::= STRING */ yytestcase(yyruleno==340); + /* (341) nm ::= JOIN_KW */ yytestcase(yyruleno==341); + /* (342) typetoken ::= typename */ yytestcase(yyruleno==342); + /* (343) typename ::= ID|STRING */ yytestcase(yyruleno==343); + /* (344) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=344); + /* (345) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=345); + /* (346) carglist ::= carglist ccons */ yytestcase(yyruleno==346); + /* (347) carglist ::= */ yytestcase(yyruleno==347); + /* (348) ccons ::= NULL onconf */ yytestcase(yyruleno==348); + /* (349) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==349); + /* (350) ccons ::= AS generated */ yytestcase(yyruleno==350); + /* (351) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==351); + /* (352) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==352); + /* (353) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=353); + /* (354) tconscomma ::= */ yytestcase(yyruleno==354); + /* (355) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=355); + /* (356) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=356); + /* (357) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=357); + /* (358) oneselect ::= values */ yytestcase(yyruleno==358); + /* (359) sclp ::= selcollist COMMA */ yytestcase(yyruleno==359); + /* (360) as ::= ID|STRING */ yytestcase(yyruleno==360); + /* (361) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=361); + /* (362) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==362); + /* (363) exprlist ::= nexprlist */ yytestcase(yyruleno==363); + /* (364) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=364); + /* (365) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=365); + /* (366) nmnum ::= ON */ yytestcase(yyruleno==366); + /* (367) nmnum ::= DELETE */ yytestcase(yyruleno==367); + /* (368) nmnum ::= DEFAULT */ yytestcase(yyruleno==368); + /* (369) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==369); + /* (370) foreach_clause ::= */ yytestcase(yyruleno==370); + /* (371) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==371); + /* (372) trnm ::= nm */ yytestcase(yyruleno==372); + /* (373) tridxby ::= */ yytestcase(yyruleno==373); + /* (374) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==374); + /* (375) database_kw_opt ::= */ yytestcase(yyruleno==375); + /* (376) kwcolumn_opt ::= */ yytestcase(yyruleno==376); + /* (377) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==377); + /* (378) vtabarglist ::= vtabarg */ yytestcase(yyruleno==378); + /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==379); + /* (380) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==380); + /* (381) anylist ::= */ yytestcase(yyruleno==381); + /* (382) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==382); + /* (383) anylist ::= anylist ANY */ yytestcase(yyruleno==383); + /* (384) with ::= */ yytestcase(yyruleno==384); break; /********** End reduce actions ************************************************/ }; - assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) ); - yygoto = yyRuleInfo[yyruleno].lhs; - yysize = yyRuleInfo[yyruleno].nrhs; - yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); - if( yyact <= YY_MAX_SHIFTREDUCE ){ - if( yyact>YY_MAX_SHIFT ){ - yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE; - } - yymsp -= yysize-1; - yypParser->yytos = yymsp; - yymsp->stateno = (YYACTIONTYPE)yyact; - yymsp->major = (YYCODETYPE)yygoto; - yyTraceShift(yypParser, yyact); - }else{ - assert( yyact == YY_ACCEPT_ACTION ); - yypParser->yytos -= yysize; - yy_accept(yypParser); - } + assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) ); + yygoto = yyRuleInfoLhs[yyruleno]; + yysize = yyRuleInfoNRhs[yyruleno]; + yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto); + + /* There are no SHIFTREDUCE actions on nonterminals because the table + ** generator has simplified them to pure REDUCE actions. */ + assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) ); + + /* It is not possible for a REDUCE to be followed by an error */ + assert( yyact!=YY_ERROR_ACTION ); + + yymsp += yysize+1; + yypParser->yytos = yymsp; + yymsp->stateno = (YYACTIONTYPE)yyact; + yymsp->major = (YYCODETYPE)yygoto; + yyTraceShift(yypParser, yyact, "... then shift"); + return yyact; } /* @@ -139444,7 +160693,8 @@ static void yy_reduce( static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ - sqlite3ParserARG_FETCH; + tdsqlite3ParserARG_FETCH + tdsqlite3ParserCTX_FETCH #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); @@ -139455,7 +160705,8 @@ static void yy_parse_failed( ** parser fails */ /************ Begin %parse_failure code ***************************************/ /************ End %parse_failure code *****************************************/ - sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ + tdsqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */ + tdsqlite3ParserCTX_STORE } #endif /* YYNOERRORRECOVERY */ @@ -139465,17 +160716,22 @@ static void yy_parse_failed( static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ - sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */ + tdsqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */ ){ - sqlite3ParserARG_FETCH; + tdsqlite3ParserARG_FETCH + tdsqlite3ParserCTX_FETCH #define TOKEN yyminor /************ Begin %syntax_error code ****************************************/ UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ - assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); + if( TOKEN.z[0] ){ + tdsqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); + }else{ + tdsqlite3ErrorMsg(pParse, "incomplete input"); + } /************ End %syntax_error code ******************************************/ - sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ + tdsqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */ + tdsqlite3ParserCTX_STORE } /* @@ -139484,7 +160740,8 @@ static void yy_syntax_error( static void yy_accept( yyParser *yypParser /* The parser */ ){ - sqlite3ParserARG_FETCH; + tdsqlite3ParserARG_FETCH + tdsqlite3ParserCTX_FETCH #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); @@ -139498,12 +160755,13 @@ static void yy_accept( ** parser accepts */ /*********** Begin %parse_accept code *****************************************/ /*********** End %parse_accept code *******************************************/ - sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ + tdsqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */ + tdsqlite3ParserCTX_STORE } /* The main parser program. ** The first argument is a pointer to a structure obtained from -** "sqlite3ParserAlloc" which describes the current state of the parser. +** "tdsqlite3ParserAlloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for @@ -139520,45 +160778,58 @@ static void yy_accept( ** Outputs: ** None. */ -SQLITE_PRIVATE void sqlite3Parser( +SQLITE_PRIVATE void tdsqlite3Parser( void *yyp, /* The parser */ int yymajor, /* The major token code number */ - sqlite3ParserTOKENTYPE yyminor /* The value for the token */ - sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ + tdsqlite3ParserTOKENTYPE yyminor /* The value for the token */ + tdsqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ ){ YYMINORTYPE yyminorunion; - unsigned int yyact; /* The parser action. */ + YYACTIONTYPE yyact; /* The parser action. */ #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) int yyendofinput; /* True if we are at the end of input */ #endif #ifdef YYERRORSYMBOL int yyerrorhit = 0; /* True if yymajor has invoked an error */ #endif - yyParser *yypParser; /* The parser */ + yyParser *yypParser = (yyParser*)yyp; /* The parser */ + tdsqlite3ParserCTX_FETCH + tdsqlite3ParserARG_STORE - yypParser = (yyParser*)yyp; assert( yypParser->yytos!=0 ); #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) yyendofinput = (yymajor==0); #endif - sqlite3ParserARG_STORE; + yyact = yypParser->yytos->stateno; #ifndef NDEBUG if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]); + if( yyact < YY_MIN_REDUCE ){ + fprintf(yyTraceFILE,"%sInput '%s' in state %d\n", + yyTracePrompt,yyTokenName[yymajor],yyact); + }else{ + fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n", + yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE); + } } #endif do{ - yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); - if( yyact <= YY_MAX_SHIFTREDUCE ){ - yy_shift(yypParser,yyact,yymajor,yyminor); + assert( yyact==yypParser->yytos->stateno ); + yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact); + if( yyact >= YY_MIN_REDUCE ){ + yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor, + yyminor tdsqlite3ParserCTX_PARAM); + }else if( yyact <= YY_MAX_SHIFTREDUCE ){ + yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor); #ifndef YYNOERRORRECOVERY yypParser->yyerrcnt--; #endif - yymajor = YYNOCODE; - }else if( yyact <= YY_MAX_REDUCE ){ - yy_reduce(yypParser,yyact-YY_MIN_REDUCE); + break; + }else if( yyact==YY_ACCEPT_ACTION ){ + yypParser->yytos--; + yy_accept(yypParser); + return; }else{ assert( yyact == YY_ERROR_ACTION ); yyminorunion.yy0 = yyminor; @@ -139605,10 +160876,9 @@ SQLITE_PRIVATE void sqlite3Parser( yymajor = YYNOCODE; }else{ while( yypParser->yytos >= yypParser->yystack - && yymx != YYERRORSYMBOL && (yyact = yy_find_reduce_action( yypParser->yytos->stateno, - YYERRORSYMBOL)) >= YY_MIN_REDUCE + YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE ){ yy_pop_parser_stack(yypParser); } @@ -139625,6 +160895,8 @@ SQLITE_PRIVATE void sqlite3Parser( } yypParser->yyerrcnt = 3; yyerrorhit = 1; + if( yymajor==YYNOCODE ) break; + yyact = yypParser->yytos->stateno; #elif defined(YYNOERRORRECOVERY) /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to ** do any kind of error recovery. Instead, simply invoke the syntax @@ -139635,8 +160907,7 @@ SQLITE_PRIVATE void sqlite3Parser( */ yy_syntax_error(yypParser,yymajor, yyminor); yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - yymajor = YYNOCODE; - + break; #else /* YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** @@ -139658,10 +160929,10 @@ SQLITE_PRIVATE void sqlite3Parser( yypParser->yyerrcnt = -1; #endif } - yymajor = YYNOCODE; + break; #endif } - }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack ); + }while( yypParser->yytos>yypParser->yystack ); #ifndef NDEBUG if( yyTraceFILE ){ yyStackEntry *i; @@ -139677,6 +160948,20 @@ SQLITE_PRIVATE void sqlite3Parser( return; } +/* +** Return the fallback token corresponding to canonical token iToken, or +** 0 if iToken has no fallback. +*/ +SQLITE_PRIVATE int tdsqlite3ParserFallback(int iToken){ +#ifdef YYFALLBACK + assert( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) ); + return yyFallback[iToken]; +#else + (void)iToken; + return 0; +#endif +} + /************** End of parse.c ***********************************************/ /************** Begin file tokenize.c ****************************************/ /* @@ -139701,7 +160986,7 @@ SQLITE_PRIVATE void sqlite3Parser( /* Character classes for tokenizing ** -** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented +** In the tdsqlite3GetToken() function, a switch() on aiClass[c] is implemented ** using a lookup table, whereas a switch() directly on c uses a binary search. ** The lookup table is much faster. To maximize speed, and to ensure that ** a lookup table is used, all of the classes need to be small integers and @@ -139735,11 +161020,12 @@ SQLITE_PRIVATE void sqlite3Parser( #define CC_TILDA 25 /* '~' */ #define CC_DOT 26 /* '.' */ #define CC_ILLEGAL 27 /* Illegal character */ +#define CC_NUL 28 /* 0x00 */ static const unsigned char aiClass[] = { #ifdef SQLITE_ASCII /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ -/* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27, +/* 0x */ 28, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27, /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16, /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6, @@ -139762,13 +161048,13 @@ static const unsigned char aiClass[] = { /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -/* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 12, 17, 20, 10, +/* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10, /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27, -/* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 7, +/* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6, /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8, /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, -/* 9x */ 25, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, +/* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27, /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, @@ -139787,7 +161073,7 @@ static const unsigned char aiClass[] = { ** Used by keywordhash.h */ #ifdef SQLITE_ASCII -# define charMap(X) sqlite3UpperToLower[(unsigned char)X] +# define charMap(X) tdsqlite3UpperToLower[(unsigned char)X] #endif #ifdef SQLITE_EBCDIC # define charMap(X) ebcdicToAscii[(unsigned char)X] @@ -139813,7 +161099,7 @@ const unsigned char ebcdicToAscii[] = { #endif /* -** The sqlite3KeywordCode function looks up an identifier to determine if +** The tdsqlite3KeywordCode function looks up an identifier to determine if ** it is a keyword. If it is a keyword, the token code of that keyword is ** returned. If the input is not a keyword, TK_ID is returned. ** @@ -139838,135 +161124,291 @@ const unsigned char ebcdicToAscii[] = { ** is substantially reduced. This is important for embedded applications ** on platforms with limited memory. */ -/* Hash score: 182 */ +/* Hash score: 227 */ +/* zKWText[] encodes 984 bytes of keyword text in 648 bytes */ +/* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ +/* ABLEFTHENDEFERRABLELSEXCLUDELETEMPORARYISNULLSAVEPOINTERSECT */ +/* IESNOTNULLIKEXCEPTRANSACTIONATURALTERAISEXCLUSIVEXISTS */ +/* CONSTRAINTOFFSETRIGGERANGENERATEDETACHAVINGLOBEGINNEREFERENCES */ +/* UNIQUERYWITHOUTERELEASEATTACHBETWEENOTHINGROUPSCASCADEFAULT */ +/* CASECOLLATECREATECURRENT_DATEIMMEDIATEJOINSERTMATCHPLANALYZE */ +/* PRAGMABORTUPDATEVALUESVIRTUALWAYSWHENWHERECURSIVEAFTERENAMEAND */ +/* EFERREDISTINCTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */ +/* CURRENT_TIMESTAMPARTITIONDROPRECEDINGFAILASTFILTEREPLACEFIRST */ +/* FOLLOWINGFROMFULLIMITIFORDERESTRICTOTHERSOVERIGHTROLLBACKROWS */ +/* UNBOUNDEDUNIONUSINGVACUUMVIEWINDOWBYINITIALLYPRIMARY */ +static const char zKWText[647] = { + 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', + 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', + 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', + 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', + 'E','R','R','A','B','L','E','L','S','E','X','C','L','U','D','E','L','E', + 'T','E','M','P','O','R','A','R','Y','I','S','N','U','L','L','S','A','V', + 'E','P','O','I','N','T','E','R','S','E','C','T','I','E','S','N','O','T', + 'N','U','L','L','I','K','E','X','C','E','P','T','R','A','N','S','A','C', + 'T','I','O','N','A','T','U','R','A','L','T','E','R','A','I','S','E','X', + 'C','L','U','S','I','V','E','X','I','S','T','S','C','O','N','S','T','R', + 'A','I','N','T','O','F','F','S','E','T','R','I','G','G','E','R','A','N', + 'G','E','N','E','R','A','T','E','D','E','T','A','C','H','A','V','I','N', + 'G','L','O','B','E','G','I','N','N','E','R','E','F','E','R','E','N','C', + 'E','S','U','N','I','Q','U','E','R','Y','W','I','T','H','O','U','T','E', + 'R','E','L','E','A','S','E','A','T','T','A','C','H','B','E','T','W','E', + 'E','N','O','T','H','I','N','G','R','O','U','P','S','C','A','S','C','A', + 'D','E','F','A','U','L','T','C','A','S','E','C','O','L','L','A','T','E', + 'C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A','T','E', + 'I','M','M','E','D','I','A','T','E','J','O','I','N','S','E','R','T','M', + 'A','T','C','H','P','L','A','N','A','L','Y','Z','E','P','R','A','G','M', + 'A','B','O','R','T','U','P','D','A','T','E','V','A','L','U','E','S','V', + 'I','R','T','U','A','L','W','A','Y','S','W','H','E','N','W','H','E','R', + 'E','C','U','R','S','I','V','E','A','F','T','E','R','E','N','A','M','E', + 'A','N','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','A', + 'U','T','O','I','N','C','R','E','M','E','N','T','C','A','S','T','C','O', + 'L','U','M','N','C','O','M','M','I','T','C','O','N','F','L','I','C','T', + 'C','R','O','S','S','C','U','R','R','E','N','T','_','T','I','M','E','S', + 'T','A','M','P','A','R','T','I','T','I','O','N','D','R','O','P','R','E', + 'C','E','D','I','N','G','F','A','I','L','A','S','T','F','I','L','T','E', + 'R','E','P','L','A','C','E','F','I','R','S','T','F','O','L','L','O','W', + 'I','N','G','F','R','O','M','F','U','L','L','I','M','I','T','I','F','O', + 'R','D','E','R','E','S','T','R','I','C','T','O','T','H','E','R','S','O', + 'V','E','R','I','G','H','T','R','O','L','L','B','A','C','K','R','O','W', + 'S','U','N','B','O','U','N','D','E','D','U','N','I','O','N','U','S','I', + 'N','G','V','A','C','U','U','M','V','I','E','W','I','N','D','O','W','B', + 'Y','I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R','Y', +}; +/* aKWHash[i] is the hash value for the i-th keyword */ +static const unsigned char aKWHash[127] = { + 84, 102, 132, 82, 114, 29, 0, 0, 91, 0, 85, 72, 0, + 53, 35, 86, 15, 0, 42, 94, 54, 126, 133, 19, 0, 0, + 138, 0, 40, 128, 0, 22, 104, 0, 9, 0, 0, 122, 80, + 0, 78, 6, 0, 65, 99, 145, 0, 134, 112, 0, 0, 48, + 0, 100, 24, 0, 17, 0, 27, 70, 23, 26, 5, 60, 140, + 107, 121, 0, 73, 101, 71, 143, 61, 119, 74, 0, 49, 0, + 11, 41, 0, 110, 0, 0, 0, 106, 10, 108, 113, 124, 14, + 50, 123, 0, 89, 0, 18, 120, 142, 56, 129, 137, 88, 83, + 37, 30, 125, 0, 0, 105, 51, 130, 127, 0, 34, 0, 0, + 44, 0, 95, 38, 39, 0, 20, 45, 116, 90, +}; +/* aKWNext[] forms the hash collision chain. If aKWHash[i]==0 +** then the i-th keyword has no more hash collisions. Otherwise, +** the next keyword with the same hash is aKWHash[i]-1. */ +static const unsigned char aKWNext[145] = { + 0, 0, 0, 0, 4, 0, 43, 0, 0, 103, 111, 0, 0, + 0, 2, 0, 0, 141, 0, 0, 0, 13, 0, 0, 0, 0, + 139, 0, 0, 118, 52, 0, 0, 135, 12, 0, 0, 62, 0, + 136, 0, 131, 0, 0, 36, 0, 0, 28, 77, 0, 0, 0, + 0, 59, 0, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 69, 0, 0, 0, 0, 0, 144, 3, 0, 58, 0, 1, + 75, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 64, 66, + 63, 0, 0, 0, 0, 46, 0, 16, 0, 115, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 81, 97, 0, 8, 0, 109, + 21, 7, 67, 0, 79, 93, 117, 0, 0, 68, 0, 0, 96, + 0, 55, 0, 76, 0, 92, 32, 33, 57, 25, 0, 98, 0, + 0, 87, +}; +/* aKWLen[i] is the length (in bytes) of the i-th keyword */ +static const unsigned char aKWLen[145] = { + 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, + 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 7, + 6, 9, 4, 2, 6, 5, 9, 9, 4, 7, 3, 2, 4, + 4, 6, 11, 6, 2, 7, 5, 5, 9, 6, 10, 4, 6, + 2, 3, 7, 5, 9, 6, 6, 4, 5, 5, 10, 6, 5, + 7, 4, 5, 7, 6, 7, 7, 6, 5, 7, 3, 7, 4, + 7, 6, 12, 9, 4, 6, 5, 4, 7, 6, 5, 6, 6, + 7, 6, 4, 5, 9, 5, 6, 3, 8, 8, 2, 13, 2, + 2, 4, 6, 6, 8, 5, 17, 12, 7, 9, 4, 9, 4, + 4, 6, 7, 5, 9, 4, 4, 5, 2, 5, 8, 6, 4, + 5, 8, 4, 3, 9, 5, 5, 6, 4, 6, 2, 2, 9, + 3, 7, +}; +/* aKWOffset[i] is the index into zKWText[] of the start of +** the text for the i-th keyword. */ +static const unsigned short int aKWOffset[145] = { + 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, + 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, + 86, 90, 90, 94, 99, 101, 105, 111, 119, 123, 123, 123, 126, + 129, 132, 137, 142, 146, 147, 152, 156, 160, 168, 174, 181, 184, + 184, 187, 189, 195, 198, 206, 211, 216, 219, 222, 226, 236, 239, + 244, 244, 248, 252, 259, 265, 271, 277, 277, 283, 284, 288, 295, + 299, 306, 312, 324, 333, 335, 341, 346, 348, 355, 360, 365, 371, + 377, 382, 388, 392, 395, 404, 408, 414, 416, 423, 424, 431, 433, + 435, 444, 448, 454, 460, 468, 473, 473, 473, 489, 498, 501, 510, + 513, 517, 522, 529, 534, 543, 547, 550, 555, 557, 561, 569, 575, + 578, 583, 591, 591, 595, 604, 609, 614, 620, 623, 626, 629, 631, + 636, 640, +}; +/* aKWCode[i] is the parser symbol code for the i-th keyword */ +static const unsigned char aKWCode[145] = { + TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, + TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, + TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, + TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, + TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, + TK_EXCLUDE, TK_DELETE, TK_TEMP, TK_TEMP, TK_OR, + TK_ISNULL, TK_NULLS, TK_SAVEPOINT, TK_INTERSECT, TK_TIES, + TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW, + TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW, + TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_CONSTRAINT, + TK_INTO, TK_OFFSET, TK_OF, TK_SET, TK_TRIGGER, + TK_RANGE, TK_GENERATED, TK_DETACH, TK_HAVING, TK_LIKE_KW, + TK_BEGIN, TK_JOIN_KW, TK_REFERENCES, TK_UNIQUE, TK_QUERY, + TK_WITHOUT, TK_WITH, TK_JOIN_KW, TK_RELEASE, TK_ATTACH, + TK_BETWEEN, TK_NOTHING, TK_GROUPS, TK_GROUP, TK_CASCADE, + TK_ASC, TK_DEFAULT, TK_CASE, TK_COLLATE, TK_CREATE, + TK_CTIME_KW, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH, + TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_UPDATE, + TK_VALUES, TK_VIRTUAL, TK_ALWAYS, TK_WHEN, TK_WHERE, + TK_RECURSIVE, TK_AFTER, TK_RENAME, TK_AND, TK_DEFERRED, + TK_DISTINCT, TK_IS, TK_AUTOINCR, TK_TO, TK_IN, + TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, + TK_CTIME_KW, TK_CTIME_KW, TK_CURRENT, TK_PARTITION, TK_DROP, + TK_PRECEDING, TK_FAIL, TK_LAST, TK_FILTER, TK_REPLACE, + TK_FIRST, TK_FOLLOWING, TK_FROM, TK_JOIN_KW, TK_LIMIT, + TK_IF, TK_ORDER, TK_RESTRICT, TK_OTHERS, TK_OVER, + TK_JOIN_KW, TK_ROLLBACK, TK_ROWS, TK_ROW, TK_UNBOUNDED, + TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_WINDOW, + TK_DO, TK_BY, TK_INITIALLY, TK_ALL, TK_PRIMARY, +}; +/* Hash table decoded: +** 0: INSERT +** 1: IS +** 2: ROLLBACK TRIGGER +** 3: IMMEDIATE +** 4: PARTITION +** 5: TEMP +** 6: +** 7: +** 8: VALUES WITHOUT +** 9: +** 10: MATCH +** 11: NOTHING +** 12: +** 13: OF +** 14: TIES IGNORE +** 15: PLAN +** 16: INSTEAD INDEXED +** 17: +** 18: TRANSACTION RIGHT +** 19: WHEN +** 20: SET HAVING +** 21: IF +** 22: ROWS +** 23: SELECT +** 24: +** 25: +** 26: VACUUM SAVEPOINT +** 27: +** 28: LIKE UNION VIRTUAL REFERENCES +** 29: RESTRICT +** 30: +** 31: THEN REGEXP +** 32: TO +** 33: +** 34: BEFORE +** 35: +** 36: +** 37: FOLLOWING COLLATE CASCADE +** 38: CREATE +** 39: +** 40: CASE REINDEX +** 41: EACH +** 42: +** 43: QUERY +** 44: AND ADD +** 45: PRIMARY ANALYZE +** 46: +** 47: ROW ASC DETACH +** 48: CURRENT_TIME CURRENT_DATE +** 49: +** 50: +** 51: EXCLUSIVE TEMPORARY +** 52: +** 53: DEFERRED +** 54: DEFERRABLE +** 55: +** 56: DATABASE +** 57: +** 58: DELETE VIEW GENERATED +** 59: ATTACH +** 60: END +** 61: EXCLUDE +** 62: ESCAPE DESC +** 63: GLOB +** 64: WINDOW ELSE +** 65: COLUMN +** 66: FIRST +** 67: +** 68: GROUPS ALL +** 69: DISTINCT DROP KEY +** 70: BETWEEN +** 71: INITIALLY +** 72: BEGIN +** 73: FILTER CHECK ACTION +** 74: GROUP INDEX +** 75: +** 76: EXISTS DEFAULT +** 77: +** 78: FOR CURRENT_TIMESTAMP +** 79: EXCEPT +** 80: +** 81: CROSS +** 82: +** 83: +** 84: +** 85: CAST +** 86: FOREIGN AUTOINCREMENT +** 87: COMMIT +** 88: CURRENT AFTER ALTER +** 89: FULL FAIL CONFLICT +** 90: EXPLAIN +** 91: CONSTRAINT +** 92: FROM ALWAYS +** 93: +** 94: ABORT +** 95: +** 96: AS DO +** 97: REPLACE WITH RELEASE +** 98: BY RENAME +** 99: RANGE RAISE +** 100: OTHERS +** 101: USING NULLS +** 102: PRAGMA +** 103: JOIN ISNULL OFFSET +** 104: NOT +** 105: OR LAST LEFT +** 106: LIMIT +** 107: +** 108: +** 109: IN +** 110: INTO +** 111: OVER RECURSIVE +** 112: ORDER OUTER +** 113: +** 114: INTERSECT UNBOUNDED +** 115: +** 116: +** 117: ON +** 118: +** 119: WHERE +** 120: NO INNER +** 121: NULL +** 122: +** 123: TABLE +** 124: NATURAL NOTNULL +** 125: PRECEDING +** 126: UPDATE UNIQUE +*/ +/* Check to see if z[0..n-1] is a keyword. If it is, write the +** parser symbol code for that keyword into *pType. Always +** return the integer n (the length of the token). */ static int keywordCode(const char *z, int n, int *pType){ - /* zText[] encodes 834 bytes of keywords in 554 bytes */ - /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ - /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ - /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ - /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */ - /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */ - /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */ - /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */ - /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */ - /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */ - /* VACUUMVIEWINITIALLY */ - static const char zText[553] = { - 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', - 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', - 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', - 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', - 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N', - 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I', - 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E', - 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E', - 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T', - 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q', - 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S', - 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A', - 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E', - 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A', - 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A', - 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A', - 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J', - 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L', - 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E', - 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H', - 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E', - 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E', - 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M', - 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R', - 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A', - 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D', - 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O', - 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T', - 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R', - 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M', - 'V','I','E','W','I','N','I','T','I','A','L','L','Y', - }; - static const unsigned char aHash[127] = { - 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0, - 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0, - 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71, - 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44, - 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25, - 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0, - 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14, - 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113, - 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0, - 29, 0, 86, 63, 64, 0, 20, 61, 0, 56, - }; - static const unsigned char aNext[124] = { - 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, - 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50, - 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38, - 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0, - 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34, - 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8, - 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37, - 73, 83, 0, 35, 68, 0, 0, - }; - static const unsigned char aLen[124] = { - 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, - 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6, - 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, - 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7, - 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4, - 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4, - 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7, - 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8, - 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8, - 3, 5, 5, 6, 4, 9, 3, - }; - static const unsigned short int aOffset[124] = { - 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, - 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, - 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, - 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192, - 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246, - 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318, - 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380, - 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459, - 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513, - 521, 524, 529, 534, 540, 544, 549, - }; - static const unsigned char aCode[124] = { - TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, - TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, - TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, - TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, - TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, - TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW, - TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, - TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, - TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP, - TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH, - TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP, - TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN, - TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW, - TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, - TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, - TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, - TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, - TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, - TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, - TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, - TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, - TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, - TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, - TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING, - TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL, - }; int i, j; const char *zKW; if( n>=2 ){ i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127; - for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){ - if( aLen[i]!=n ) continue; + for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){ + if( aKWLen[i]!=n ) continue; j = 0; - zKW = &zText[aOffset[i]]; + zKW = &zKWText[aKWOffset[i]]; #ifdef SQLITE_ASCII while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; } #endif @@ -139999,117 +161441,148 @@ static int keywordCode(const char *z, int n, int *pType){ testcase( i==22 ); /* END */ testcase( i==23 ); /* DEFERRABLE */ testcase( i==24 ); /* ELSE */ - testcase( i==25 ); /* EXCEPT */ - testcase( i==26 ); /* TRANSACTION */ - testcase( i==27 ); /* ACTION */ - testcase( i==28 ); /* ON */ - testcase( i==29 ); /* NATURAL */ - testcase( i==30 ); /* ALTER */ - testcase( i==31 ); /* RAISE */ - testcase( i==32 ); /* EXCLUSIVE */ - testcase( i==33 ); /* EXISTS */ - testcase( i==34 ); /* SAVEPOINT */ - testcase( i==35 ); /* INTERSECT */ - testcase( i==36 ); /* TRIGGER */ - testcase( i==37 ); /* REFERENCES */ - testcase( i==38 ); /* CONSTRAINT */ - testcase( i==39 ); /* INTO */ - testcase( i==40 ); /* OFFSET */ - testcase( i==41 ); /* OF */ - testcase( i==42 ); /* SET */ - testcase( i==43 ); /* TEMPORARY */ - testcase( i==44 ); /* TEMP */ - testcase( i==45 ); /* OR */ - testcase( i==46 ); /* UNIQUE */ - testcase( i==47 ); /* QUERY */ - testcase( i==48 ); /* WITHOUT */ - testcase( i==49 ); /* WITH */ - testcase( i==50 ); /* OUTER */ - testcase( i==51 ); /* RELEASE */ - testcase( i==52 ); /* ATTACH */ - testcase( i==53 ); /* HAVING */ - testcase( i==54 ); /* GROUP */ - testcase( i==55 ); /* UPDATE */ - testcase( i==56 ); /* BEGIN */ - testcase( i==57 ); /* INNER */ - testcase( i==58 ); /* RECURSIVE */ - testcase( i==59 ); /* BETWEEN */ - testcase( i==60 ); /* NOTNULL */ - testcase( i==61 ); /* NOT */ - testcase( i==62 ); /* NO */ - testcase( i==63 ); /* NULL */ - testcase( i==64 ); /* LIKE */ - testcase( i==65 ); /* CASCADE */ - testcase( i==66 ); /* ASC */ - testcase( i==67 ); /* DELETE */ - testcase( i==68 ); /* CASE */ - testcase( i==69 ); /* COLLATE */ - testcase( i==70 ); /* CREATE */ - testcase( i==71 ); /* CURRENT_DATE */ - testcase( i==72 ); /* DETACH */ - testcase( i==73 ); /* IMMEDIATE */ - testcase( i==74 ); /* JOIN */ - testcase( i==75 ); /* INSERT */ - testcase( i==76 ); /* MATCH */ - testcase( i==77 ); /* PLAN */ - testcase( i==78 ); /* ANALYZE */ - testcase( i==79 ); /* PRAGMA */ - testcase( i==80 ); /* ABORT */ - testcase( i==81 ); /* VALUES */ - testcase( i==82 ); /* VIRTUAL */ - testcase( i==83 ); /* LIMIT */ - testcase( i==84 ); /* WHEN */ - testcase( i==85 ); /* WHERE */ - testcase( i==86 ); /* RENAME */ - testcase( i==87 ); /* AFTER */ - testcase( i==88 ); /* REPLACE */ - testcase( i==89 ); /* AND */ - testcase( i==90 ); /* DEFAULT */ - testcase( i==91 ); /* AUTOINCREMENT */ - testcase( i==92 ); /* TO */ - testcase( i==93 ); /* IN */ - testcase( i==94 ); /* CAST */ - testcase( i==95 ); /* COLUMN */ - testcase( i==96 ); /* COMMIT */ - testcase( i==97 ); /* CONFLICT */ - testcase( i==98 ); /* CROSS */ - testcase( i==99 ); /* CURRENT_TIMESTAMP */ - testcase( i==100 ); /* CURRENT_TIME */ - testcase( i==101 ); /* PRIMARY */ - testcase( i==102 ); /* DEFERRED */ - testcase( i==103 ); /* DISTINCT */ - testcase( i==104 ); /* IS */ - testcase( i==105 ); /* DROP */ - testcase( i==106 ); /* FAIL */ - testcase( i==107 ); /* FROM */ - testcase( i==108 ); /* FULL */ - testcase( i==109 ); /* GLOB */ - testcase( i==110 ); /* BY */ - testcase( i==111 ); /* IF */ - testcase( i==112 ); /* ISNULL */ - testcase( i==113 ); /* ORDER */ - testcase( i==114 ); /* RESTRICT */ - testcase( i==115 ); /* RIGHT */ - testcase( i==116 ); /* ROLLBACK */ - testcase( i==117 ); /* ROW */ - testcase( i==118 ); /* UNION */ - testcase( i==119 ); /* USING */ - testcase( i==120 ); /* VACUUM */ - testcase( i==121 ); /* VIEW */ - testcase( i==122 ); /* INITIALLY */ - testcase( i==123 ); /* ALL */ - *pType = aCode[i]; + testcase( i==25 ); /* EXCLUDE */ + testcase( i==26 ); /* DELETE */ + testcase( i==27 ); /* TEMPORARY */ + testcase( i==28 ); /* TEMP */ + testcase( i==29 ); /* OR */ + testcase( i==30 ); /* ISNULL */ + testcase( i==31 ); /* NULLS */ + testcase( i==32 ); /* SAVEPOINT */ + testcase( i==33 ); /* INTERSECT */ + testcase( i==34 ); /* TIES */ + testcase( i==35 ); /* NOTNULL */ + testcase( i==36 ); /* NOT */ + testcase( i==37 ); /* NO */ + testcase( i==38 ); /* NULL */ + testcase( i==39 ); /* LIKE */ + testcase( i==40 ); /* EXCEPT */ + testcase( i==41 ); /* TRANSACTION */ + testcase( i==42 ); /* ACTION */ + testcase( i==43 ); /* ON */ + testcase( i==44 ); /* NATURAL */ + testcase( i==45 ); /* ALTER */ + testcase( i==46 ); /* RAISE */ + testcase( i==47 ); /* EXCLUSIVE */ + testcase( i==48 ); /* EXISTS */ + testcase( i==49 ); /* CONSTRAINT */ + testcase( i==50 ); /* INTO */ + testcase( i==51 ); /* OFFSET */ + testcase( i==52 ); /* OF */ + testcase( i==53 ); /* SET */ + testcase( i==54 ); /* TRIGGER */ + testcase( i==55 ); /* RANGE */ + testcase( i==56 ); /* GENERATED */ + testcase( i==57 ); /* DETACH */ + testcase( i==58 ); /* HAVING */ + testcase( i==59 ); /* GLOB */ + testcase( i==60 ); /* BEGIN */ + testcase( i==61 ); /* INNER */ + testcase( i==62 ); /* REFERENCES */ + testcase( i==63 ); /* UNIQUE */ + testcase( i==64 ); /* QUERY */ + testcase( i==65 ); /* WITHOUT */ + testcase( i==66 ); /* WITH */ + testcase( i==67 ); /* OUTER */ + testcase( i==68 ); /* RELEASE */ + testcase( i==69 ); /* ATTACH */ + testcase( i==70 ); /* BETWEEN */ + testcase( i==71 ); /* NOTHING */ + testcase( i==72 ); /* GROUPS */ + testcase( i==73 ); /* GROUP */ + testcase( i==74 ); /* CASCADE */ + testcase( i==75 ); /* ASC */ + testcase( i==76 ); /* DEFAULT */ + testcase( i==77 ); /* CASE */ + testcase( i==78 ); /* COLLATE */ + testcase( i==79 ); /* CREATE */ + testcase( i==80 ); /* CURRENT_DATE */ + testcase( i==81 ); /* IMMEDIATE */ + testcase( i==82 ); /* JOIN */ + testcase( i==83 ); /* INSERT */ + testcase( i==84 ); /* MATCH */ + testcase( i==85 ); /* PLAN */ + testcase( i==86 ); /* ANALYZE */ + testcase( i==87 ); /* PRAGMA */ + testcase( i==88 ); /* ABORT */ + testcase( i==89 ); /* UPDATE */ + testcase( i==90 ); /* VALUES */ + testcase( i==91 ); /* VIRTUAL */ + testcase( i==92 ); /* ALWAYS */ + testcase( i==93 ); /* WHEN */ + testcase( i==94 ); /* WHERE */ + testcase( i==95 ); /* RECURSIVE */ + testcase( i==96 ); /* AFTER */ + testcase( i==97 ); /* RENAME */ + testcase( i==98 ); /* AND */ + testcase( i==99 ); /* DEFERRED */ + testcase( i==100 ); /* DISTINCT */ + testcase( i==101 ); /* IS */ + testcase( i==102 ); /* AUTOINCREMENT */ + testcase( i==103 ); /* TO */ + testcase( i==104 ); /* IN */ + testcase( i==105 ); /* CAST */ + testcase( i==106 ); /* COLUMN */ + testcase( i==107 ); /* COMMIT */ + testcase( i==108 ); /* CONFLICT */ + testcase( i==109 ); /* CROSS */ + testcase( i==110 ); /* CURRENT_TIMESTAMP */ + testcase( i==111 ); /* CURRENT_TIME */ + testcase( i==112 ); /* CURRENT */ + testcase( i==113 ); /* PARTITION */ + testcase( i==114 ); /* DROP */ + testcase( i==115 ); /* PRECEDING */ + testcase( i==116 ); /* FAIL */ + testcase( i==117 ); /* LAST */ + testcase( i==118 ); /* FILTER */ + testcase( i==119 ); /* REPLACE */ + testcase( i==120 ); /* FIRST */ + testcase( i==121 ); /* FOLLOWING */ + testcase( i==122 ); /* FROM */ + testcase( i==123 ); /* FULL */ + testcase( i==124 ); /* LIMIT */ + testcase( i==125 ); /* IF */ + testcase( i==126 ); /* ORDER */ + testcase( i==127 ); /* RESTRICT */ + testcase( i==128 ); /* OTHERS */ + testcase( i==129 ); /* OVER */ + testcase( i==130 ); /* RIGHT */ + testcase( i==131 ); /* ROLLBACK */ + testcase( i==132 ); /* ROWS */ + testcase( i==133 ); /* ROW */ + testcase( i==134 ); /* UNBOUNDED */ + testcase( i==135 ); /* UNION */ + testcase( i==136 ); /* USING */ + testcase( i==137 ); /* VACUUM */ + testcase( i==138 ); /* VIEW */ + testcase( i==139 ); /* WINDOW */ + testcase( i==140 ); /* DO */ + testcase( i==141 ); /* BY */ + testcase( i==142 ); /* INITIALLY */ + testcase( i==143 ); /* ALL */ + testcase( i==144 ); /* PRIMARY */ + *pType = aKWCode[i]; break; } } return n; } -SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){ +SQLITE_PRIVATE int tdsqlite3KeywordCode(const unsigned char *z, int n){ int id = TK_ID; keywordCode((char*)z, n, &id); return id; } -#define SQLITE_N_KEYWORD 124 +#define SQLITE_N_KEYWORD 145 +SQLITE_API int tdsqlite3_keyword_name(int i,const char **pzName,int *pnName){ + if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR; + *pzName = zKWText + aKWOffset[i]; + *pnName = aKWLen[i]; + return SQLITE_OK; +} +SQLITE_API int tdsqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; } +SQLITE_API int tdsqlite3_keyword_check(const char *zName, int nName){ + return TK_ID!=tdsqlite3KeywordCode((const u8*)zName, nName); +} /************** End of keywordhash.h *****************************************/ /************** Continuing where we left off in tokenize.c *******************/ @@ -140121,7 +161594,7 @@ SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){ ** ** For ASCII, any character with the high-order bit set is ** allowed in an identifier. For 7-bit characters, -** sqlite3IsIdChar[X] must be 1. +** tdsqlite3IsIdChar[X] must be 1. ** ** For EBCDIC, the rules are more complex but have the same ** end result. @@ -140132,10 +161605,10 @@ SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){ ** But the feature is undocumented. */ #ifdef SQLITE_ASCII -#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) +#define IdChar(C) ((tdsqlite3CtypeMap[(unsigned char)C]&0x46)!=0) #endif #ifdef SQLITE_EBCDIC -SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = { +SQLITE_PRIVATE const char tdsqlite3IsEbcdicIdChar[] = { /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */ @@ -140150,20 +161623,94 @@ SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = { 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */ }; -#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) +#define IdChar(C) (((c=C)>=0x42 && tdsqlite3IsEbcdicIdChar[c-0x40])) #endif -/* Make the IdChar function accessible from ctime.c */ -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); } -#endif +/* Make the IdChar function accessible from ctime.c and alter.c */ +SQLITE_PRIVATE int tdsqlite3IsIdChar(u8 c){ return IdChar(c); } +#ifndef SQLITE_OMIT_WINDOWFUNC +/* +** Return the id of the next token in string (*pz). Before returning, set +** (*pz) to point to the byte following the parsed token. +*/ +static int getToken(const unsigned char **pz){ + const unsigned char *z = *pz; + int t; /* Token type to return */ + do { + z += tdsqlite3GetToken(z, &t); + }while( t==TK_SPACE ); + if( t==TK_ID + || t==TK_STRING + || t==TK_JOIN_KW + || t==TK_WINDOW + || t==TK_OVER + || tdsqlite3ParserFallback(t)==TK_ID + ){ + t = TK_ID; + } + *pz = z; + return t; +} + +/* +** The following three functions are called immediately after the tokenizer +** reads the keywords WINDOW, OVER and FILTER, respectively, to determine +** whether the token should be treated as a keyword or an SQL identifier. +** This cannot be handled by the usual lemon %fallback method, due to +** the ambiguity in some constructions. e.g. +** +** SELECT sum(x) OVER ... +** +** In the above, "OVER" might be a keyword, or it might be an alias for the +** sum(x) expression. If a "%fallback ID OVER" directive were added to +** grammar, then SQLite would always treat "OVER" as an alias, making it +** impossible to call a window-function without a FILTER clause. +** +** WINDOW is treated as a keyword if: +** +** * the following token is an identifier, or a keyword that can fallback +** to being an identifier, and +** * the token after than one is TK_AS. +** +** OVER is a keyword if: +** +** * the previous token was TK_RP, and +** * the next token is either TK_LP or an identifier. +** +** FILTER is a keyword if: +** +** * the previous token was TK_RP, and +** * the next token is TK_LP. +*/ +static int analyzeWindowKeyword(const unsigned char *z){ + int t; + t = getToken(&z); + if( t!=TK_ID ) return TK_ID; + t = getToken(&z); + if( t!=TK_AS ) return TK_ID; + return TK_WINDOW; +} +static int analyzeOverKeyword(const unsigned char *z, int lastToken){ + if( lastToken==TK_RP ){ + int t = getToken(&z); + if( t==TK_LP || t==TK_ID ) return TK_OVER; + } + return TK_ID; +} +static int analyzeFilterKeyword(const unsigned char *z, int lastToken){ + if( lastToken==TK_RP && getToken(&z)==TK_LP ){ + return TK_FILTER; + } + return TK_ID; +} +#endif /* SQLITE_OMIT_WINDOWFUNC */ /* ** Return the length (in bytes) of the token that begins at z[0]. ** Store the token type in *tokenType before returning. */ -SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ +SQLITE_PRIVATE int tdsqlite3GetToken(const unsigned char *z, int *tokenType){ int i, c; switch( aiClass[*z] ){ /* Switch on the character-class of the first byte ** of the token. See the comment on the CC_ defines @@ -140174,7 +161721,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ testcase( z[0]=='\n' ); testcase( z[0]=='\f' ); testcase( z[0]=='\r' ); - for(i=1; sqlite3Isspace(z[i]); i++){} + for(i=1; tdsqlite3Isspace(z[i]); i++){} *tokenType = TK_SPACE; return i; } @@ -140309,7 +161856,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ } case CC_DOT: { #ifndef SQLITE_OMIT_FLOATING_POINT - if( !sqlite3Isdigit(z[1]) ) + if( !tdsqlite3Isdigit(z[1]) ) #endif { *tokenType = TK_DOT; @@ -140325,25 +161872,25 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ testcase( z[0]=='9' ); *tokenType = TK_INTEGER; #ifndef SQLITE_OMIT_HEX_INTEGER - if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){ - for(i=3; sqlite3Isxdigit(z[i]); i++){} + if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && tdsqlite3Isxdigit(z[2]) ){ + for(i=3; tdsqlite3Isxdigit(z[i]); i++){} return i; } #endif - for(i=0; sqlite3Isdigit(z[i]); i++){} + for(i=0; tdsqlite3Isdigit(z[i]); i++){} #ifndef SQLITE_OMIT_FLOATING_POINT if( z[i]=='.' ){ i++; - while( sqlite3Isdigit(z[i]) ){ i++; } + while( tdsqlite3Isdigit(z[i]) ){ i++; } *tokenType = TK_FLOAT; } if( (z[i]=='e' || z[i]=='E') && - ( sqlite3Isdigit(z[i+1]) - || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2])) + ( tdsqlite3Isdigit(z[i+1]) + || ((z[i+1]=='+' || z[i+1]=='-') && tdsqlite3Isdigit(z[i+2])) ) ){ i += 2; - while( sqlite3Isdigit(z[i]) ){ i++; } + while( tdsqlite3Isdigit(z[i]) ){ i++; } *tokenType = TK_FLOAT; } #endif @@ -140360,7 +161907,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ } case CC_VARNUM: { *tokenType = TK_VARIABLE; - for(i=1; sqlite3Isdigit(z[i]); i++){} + for(i=1; tdsqlite3Isdigit(z[i]); i++){} return i; } case CC_DOLLAR: @@ -140376,7 +161923,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ }else if( c=='(' && n>0 ){ do{ i++; - }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' ); + }while( (c=z[i])!=0 && !tdsqlite3Isspace(c) && c!=')' ); if( c==')' ){ i++; }else{ @@ -140410,7 +161957,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ testcase( z[0]=='x' ); testcase( z[0]=='X' ); if( z[1]=='\'' ){ *tokenType = TK_BLOB; - for(i=2; sqlite3Isxdigit(z[i]); i++){} + for(i=2; tdsqlite3Isxdigit(z[i]); i++){} if( z[i]!='\'' || i%2 ){ *tokenType = TK_ILLEGAL; while( z[i] && z[i]!='\'' ){ i++; } @@ -140426,6 +161973,10 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ i = 1; break; } + case CC_NUL: { + *tokenType = TK_ILLEGAL; + return 0; + } default: { *tokenType = TK_ILLEGAL; return 1; @@ -140440,17 +161991,21 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ ** Run the parser on the given SQL string. The parser structure is ** passed in. An SQLITE_ status code is returned. If an error occurs ** then an and attempt is made to write an error message into -** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that +** memory obtained from tdsqlite3_malloc() and to make *pzErrMsg point to that ** error message. */ -SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){ +SQLITE_PRIVATE int tdsqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){ int nErr = 0; /* Number of errors encountered */ - int i; /* Loop counter */ void *pEngine; /* The LEMON-generated LALR(1) parser */ + int n = 0; /* Length of the next token token */ int tokenType; /* type of the next token */ int lastTokenParsed = -1; /* type of the previous token */ - sqlite3 *db = pParse->db; /* The database connection */ + tdsqlite3 *db = pParse->db; /* The database connection */ int mxSqlLen; /* Max length of an SQL string */ +#ifdef tdsqlite3Parser_ENGINEALWAYSONSTACK + yyParser sEngine; /* Space to hold the Lemon-generated Parser object */ +#endif + VVA_ONLY( u8 startedWithOom = db->mallocFailed ); assert( zSql!=0 ); mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; @@ -140459,121 +162014,297 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr } pParse->rc = SQLITE_OK; pParse->zTail = zSql; - i = 0; assert( pzErrMsg!=0 ); - /* sqlite3ParserTrace(stdout, "parser: "); */ - pEngine = sqlite3ParserAlloc(sqlite3Malloc); +#ifdef SQLITE_DEBUG + if( db->flags & SQLITE_ParserTrace ){ + printf("parser: [[[%s]]]\n", zSql); + tdsqlite3ParserTrace(stdout, "parser: "); + }else{ + tdsqlite3ParserTrace(0, 0); + } +#endif +#ifdef tdsqlite3Parser_ENGINEALWAYSONSTACK + pEngine = &sEngine; + tdsqlite3ParserInit(pEngine, pParse); +#else + pEngine = tdsqlite3ParserAlloc(tdsqlite3Malloc, pParse); if( pEngine==0 ){ - sqlite3OomFault(db); + tdsqlite3OomFault(db); return SQLITE_NOMEM_BKPT; } +#endif assert( pParse->pNewTable==0 ); assert( pParse->pNewTrigger==0 ); assert( pParse->nVar==0 ); - assert( pParse->nzVar==0 ); - assert( pParse->azVar==0 ); + assert( pParse->pVList==0 ); + pParse->pParentParse = db->pParse; + db->pParse = pParse; while( 1 ){ - assert( i>=0 ); - if( zSql[i]!=0 ){ - pParse->sLastToken.z = &zSql[i]; - pParse->sLastToken.n = sqlite3GetToken((u8*)&zSql[i],&tokenType); - i += pParse->sLastToken.n; - if( i>mxSqlLen ){ - pParse->rc = SQLITE_TOOBIG; - break; - } - }else{ - /* Upon reaching the end of input, call the parser two more times - ** with tokens TK_SEMI and 0, in that order. */ - if( lastTokenParsed==TK_SEMI ){ - tokenType = 0; - }else if( lastTokenParsed==0 ){ - break; - }else{ - tokenType = TK_SEMI; - } + n = tdsqlite3GetToken((u8*)zSql, &tokenType); + mxSqlLen -= n; + if( mxSqlLen<0 ){ + pParse->rc = SQLITE_TOOBIG; + break; } +#ifndef SQLITE_OMIT_WINDOWFUNC + if( tokenType>=TK_WINDOW ){ + assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER + || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW + ); +#else if( tokenType>=TK_SPACE ){ assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL ); +#endif /* SQLITE_OMIT_WINDOWFUNC */ if( db->u1.isInterrupted ){ pParse->rc = SQLITE_INTERRUPT; break; } - if( tokenType==TK_ILLEGAL ){ - sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"", - &pParse->sLastToken); + if( tokenType==TK_SPACE ){ + zSql += n; + continue; + } + if( zSql[0]==0 ){ + /* Upon reaching the end of input, call the parser two more times + ** with tokens TK_SEMI and 0, in that order. */ + if( lastTokenParsed==TK_SEMI ){ + tokenType = 0; + }else if( lastTokenParsed==0 ){ + break; + }else{ + tokenType = TK_SEMI; + } + n = 0; +#ifndef SQLITE_OMIT_WINDOWFUNC + }else if( tokenType==TK_WINDOW ){ + assert( n==6 ); + tokenType = analyzeWindowKeyword((const u8*)&zSql[6]); + }else if( tokenType==TK_OVER ){ + assert( n==4 ); + tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed); + }else if( tokenType==TK_FILTER ){ + assert( n==6 ); + tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed); +#endif /* SQLITE_OMIT_WINDOWFUNC */ + }else{ + tdsqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql); break; } - }else{ - sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse); - lastTokenParsed = tokenType; - if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break; } + pParse->sLastToken.z = zSql; + pParse->sLastToken.n = n; + tdsqlite3Parser(pEngine, tokenType, pParse->sLastToken); + lastTokenParsed = tokenType; + zSql += n; + assert( db->mallocFailed==0 || pParse->rc!=SQLITE_OK || startedWithOom ); + if( pParse->rc!=SQLITE_OK ) break; } assert( nErr==0 ); - pParse->zTail = &zSql[i]; #ifdef YYTRACKMAXSTACKDEPTH - sqlite3_mutex_enter(sqlite3MallocMutex()); - sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK, - sqlite3ParserStackPeak(pEngine) + tdsqlite3_mutex_enter(tdsqlite3MallocMutex()); + tdsqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK, + tdsqlite3ParserStackPeak(pEngine) ); - sqlite3_mutex_leave(sqlite3MallocMutex()); + tdsqlite3_mutex_leave(tdsqlite3MallocMutex()); #endif /* YYDEBUG */ - sqlite3ParserFree(pEngine, sqlite3_free); +#ifdef tdsqlite3Parser_ENGINEALWAYSONSTACK + tdsqlite3ParserFinalize(pEngine); +#else + tdsqlite3ParserFree(pEngine, tdsqlite3_free); +#endif if( db->mallocFailed ){ pParse->rc = SQLITE_NOMEM_BKPT; } if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){ - pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc)); + pParse->zErrMsg = tdsqlite3MPrintf(db, "%s", tdsqlite3ErrStr(pParse->rc)); } assert( pzErrMsg!=0 ); if( pParse->zErrMsg ){ *pzErrMsg = pParse->zErrMsg; - sqlite3_log(pParse->rc, "%s", *pzErrMsg); + tdsqlite3_log(pParse->rc, "%s in \"%s\"", + *pzErrMsg, pParse->zTail); pParse->zErrMsg = 0; nErr++; } + pParse->zTail = zSql; if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){ - sqlite3VdbeDelete(pParse->pVdbe); + tdsqlite3VdbeDelete(pParse->pVdbe); pParse->pVdbe = 0; } #ifndef SQLITE_OMIT_SHARED_CACHE if( pParse->nested==0 ){ - sqlite3DbFree(db, pParse->aTableLock); + tdsqlite3DbFree(db, pParse->aTableLock); pParse->aTableLock = 0; pParse->nTableLock = 0; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE - sqlite3_free(pParse->apVtabLock); + tdsqlite3_free(pParse->apVtabLock); #endif - if( !IN_DECLARE_VTAB ){ + if( !IN_SPECIAL_PARSE ){ /* If the pParse->declareVtab flag is set, do not delete any table ** structure built up in pParse->pNewTable. The calling code (see vtab.c) ** will take responsibility for freeing the Table structure. */ - sqlite3DeleteTable(db, pParse->pNewTable); + tdsqlite3DeleteTable(db, pParse->pNewTable); + } + if( !IN_RENAME_OBJECT ){ + tdsqlite3DeleteTrigger(db, pParse->pNewTrigger); } - if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree); - sqlite3DeleteTrigger(db, pParse->pNewTrigger); - for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]); - sqlite3DbFree(db, pParse->azVar); + if( pParse->pWithToFree ) tdsqlite3WithDelete(db, pParse->pWithToFree); + tdsqlite3DbFree(db, pParse->pVList); while( pParse->pAinc ){ AutoincInfo *p = pParse->pAinc; pParse->pAinc = p->pNext; - sqlite3DbFree(db, p); + tdsqlite3DbFreeNN(db, p); } while( pParse->pZombieTab ){ Table *p = pParse->pZombieTab; pParse->pZombieTab = p->pNextZombie; - sqlite3DeleteTable(db, p); + tdsqlite3DeleteTable(db, p); } + db->pParse = pParse->pParentParse; + pParse->pParentParse = 0; assert( nErr==0 || pParse->rc!=SQLITE_OK ); return nErr; } + +#ifdef SQLITE_ENABLE_NORMALIZE +/* +** Insert a single space character into pStr if the current string +** ends with an identifier +*/ +static void addSpaceSeparator(tdsqlite3_str *pStr){ + if( pStr->nChar && tdsqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){ + tdsqlite3_str_append(pStr, " ", 1); + } +} + +/* +** Compute a normalization of the SQL given by zSql[0..nSql-1]. Return +** the normalization in space obtained from tdsqlite3DbMalloc(). Or return +** NULL if anything goes wrong or if zSql is NULL. +*/ +SQLITE_PRIVATE char *tdsqlite3Normalize( + Vdbe *pVdbe, /* VM being reprepared */ + const char *zSql /* The original SQL string */ +){ + tdsqlite3 *db; /* The database connection */ + int i; /* Next unread byte of zSql[] */ + int n; /* length of current token */ + int tokenType; /* type of current token */ + int prevType = 0; /* Previous non-whitespace token */ + int nParen; /* Number of nested levels of parentheses */ + int iStartIN; /* Start of RHS of IN operator in z[] */ + int nParenAtIN; /* Value of nParent at start of RHS of IN operator */ + u32 j; /* Bytes of normalized SQL generated so far */ + tdsqlite3_str *pStr; /* The normalized SQL string under construction */ + + db = tdsqlite3VdbeDb(pVdbe); + tokenType = -1; + nParen = iStartIN = nParenAtIN = 0; + pStr = tdsqlite3_str_new(db); + assert( pStr!=0 ); /* tdsqlite3_str_new() never returns NULL */ + for(i=0; zSql[i] && pStr->accError==0; i+=n){ + if( tokenType!=TK_SPACE ){ + prevType = tokenType; + } + n = tdsqlite3GetToken((unsigned char*)zSql+i, &tokenType); + if( NEVER(n<=0) ) break; + switch( tokenType ){ + case TK_SPACE: { + break; + } + case TK_NULL: { + if( prevType==TK_IS || prevType==TK_NOT ){ + tdsqlite3_str_append(pStr, " NULL", 5); + break; + } + /* Fall through */ + } + case TK_STRING: + case TK_INTEGER: + case TK_FLOAT: + case TK_VARIABLE: + case TK_BLOB: { + tdsqlite3_str_append(pStr, "?", 1); + break; + } + case TK_LP: { + nParen++; + if( prevType==TK_IN ){ + iStartIN = pStr->nChar; + nParenAtIN = nParen; + } + tdsqlite3_str_append(pStr, "(", 1); + break; + } + case TK_RP: { + if( iStartIN>0 && nParen==nParenAtIN ){ + assert( pStr->nChar>=(u32)iStartIN ); + pStr->nChar = iStartIN+1; + tdsqlite3_str_append(pStr, "?,?,?", 5); + iStartIN = 0; + } + nParen--; + tdsqlite3_str_append(pStr, ")", 1); + break; + } + case TK_ID: { + iStartIN = 0; + j = pStr->nChar; + if( tdsqlite3Isquote(zSql[i]) ){ + char *zId = tdsqlite3DbStrNDup(db, zSql+i, n); + int nId; + int eType = 0; + if( zId==0 ) break; + tdsqlite3Dequote(zId); + if( zSql[i]=='"' && tdsqlite3VdbeUsesDoubleQuotedString(pVdbe, zId) ){ + tdsqlite3_str_append(pStr, "?", 1); + tdsqlite3DbFree(db, zId); + break; + } + nId = tdsqlite3Strlen30(zId); + if( tdsqlite3GetToken((u8*)zId, &eType)==nId && eType==TK_ID ){ + addSpaceSeparator(pStr); + tdsqlite3_str_append(pStr, zId, nId); + }else{ + tdsqlite3_str_appendf(pStr, "\"%w\"", zId); + } + tdsqlite3DbFree(db, zId); + }else{ + addSpaceSeparator(pStr); + tdsqlite3_str_append(pStr, zSql+i, n); + } + while( j<pStr->nChar ){ + pStr->zText[j] = tdsqlite3Tolower(pStr->zText[j]); + j++; + } + break; + } + case TK_SELECT: { + iStartIN = 0; + /* fall through */ + } + default: { + if( tdsqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr); + j = pStr->nChar; + tdsqlite3_str_append(pStr, zSql+i, n); + while( j<pStr->nChar ){ + pStr->zText[j] = tdsqlite3Toupper(pStr->zText[j]); + j++; + } + break; + } + } + } + if( tokenType!=TK_SEMI ) tdsqlite3_str_append(pStr, ";", 1); + return tdsqlite3_str_finish(pStr); +} +#endif /* SQLITE_ENABLE_NORMALIZE */ + /************** End of tokenize.c ********************************************/ /************** Begin file complete.c ****************************************/ /* @@ -140589,7 +162320,7 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr ************************************************************************* ** An tokenizer for SQL ** -** This file contains C code that implements the sqlite3_complete() API. +** This file contains C code that implements the tdsqlite3_complete() API. ** This code used to be part of the tokenizer.c source file. But by ** separating it out, the code will be automatically omitted from ** static links that do not use it. @@ -140602,17 +162333,17 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr */ #ifndef SQLITE_AMALGAMATION #ifdef SQLITE_ASCII -#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) +#define IdChar(C) ((tdsqlite3CtypeMap[(unsigned char)C]&0x46)!=0) #endif #ifdef SQLITE_EBCDIC -SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[]; -#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) +SQLITE_PRIVATE const char tdsqlite3IsEbcdicIdChar[]; +#define IdChar(C) (((c=C)>=0x42 && tdsqlite3IsEbcdicIdChar[c-0x40])) #endif #endif /* SQLITE_AMALGAMATION */ /* -** Token types used by the sqlite3_complete() routine. See the header +** Token types used by the tdsqlite3_complete() routine. See the header ** comments on that procedure for additional information. */ #define tkSEMI 0 @@ -140679,7 +162410,7 @@ SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[]; ** to recognize the end of a trigger can be omitted. All we have to do ** is look for a semicolon that is not part of an string or comment. */ -SQLITE_API int sqlite3_complete(const char *zSql){ +SQLITE_API int tdsqlite3_complete(const char *zSql){ u8 state = 0; /* Current state, using numbers defined in header comment */ u8 token; /* Value of the next token */ @@ -140785,7 +162516,7 @@ SQLITE_API int sqlite3_complete(const char *zSql){ #else switch( *zSql ){ case 'c': case 'C': { - if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){ + if( nId==6 && tdsqlite3StrNICmp(zSql, "create", 6)==0 ){ token = tkCREATE; }else{ token = tkOTHER; @@ -140793,11 +162524,11 @@ SQLITE_API int sqlite3_complete(const char *zSql){ break; } case 't': case 'T': { - if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){ + if( nId==7 && tdsqlite3StrNICmp(zSql, "trigger", 7)==0 ){ token = tkTRIGGER; - }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){ + }else if( nId==4 && tdsqlite3StrNICmp(zSql, "temp", 4)==0 ){ token = tkTEMP; - }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){ + }else if( nId==9 && tdsqlite3StrNICmp(zSql, "temporary", 9)==0 ){ token = tkTEMP; }else{ token = tkOTHER; @@ -140805,11 +162536,11 @@ SQLITE_API int sqlite3_complete(const char *zSql){ break; } case 'e': case 'E': { - if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){ + if( nId==3 && tdsqlite3StrNICmp(zSql, "end", 3)==0 ){ token = tkEND; }else #ifndef SQLITE_OMIT_EXPLAIN - if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){ + if( nId==7 && tdsqlite3StrNICmp(zSql, "explain", 7)==0 ){ token = tkEXPLAIN; }else #endif @@ -140840,28 +162571,28 @@ SQLITE_API int sqlite3_complete(const char *zSql){ #ifndef SQLITE_OMIT_UTF16 /* -** This routine is the same as the sqlite3_complete() routine described +** This routine is the same as the tdsqlite3_complete() routine described ** above, except that the parameter is required to be UTF-16 encoded, not ** UTF-8. */ -SQLITE_API int sqlite3_complete16(const void *zSql){ - sqlite3_value *pVal; +SQLITE_API int tdsqlite3_complete16(const void *zSql){ + tdsqlite3_value *pVal; char const *zSql8; int rc; #ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); + rc = tdsqlite3_initialize(); if( rc ) return rc; #endif - pVal = sqlite3ValueNew(0); - sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); - zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); + pVal = tdsqlite3ValueNew(0); + tdsqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); + zSql8 = tdsqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ - rc = sqlite3_complete(zSql8); + rc = tdsqlite3_complete(zSql8); }else{ rc = SQLITE_NOMEM_BKPT; } - sqlite3ValueFree(pVal); + tdsqlite3ValueFree(pVal); return rc & 0xff; } #endif /* SQLITE_OMIT_UTF16 */ @@ -140903,7 +162634,7 @@ SQLITE_API int sqlite3_complete16(const void *zSql){ ****************************************************************************** ** ** This header file is used by programs that want to link against the -** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. +** FTS3 library. All it does is declare the tdsqlite3Fts3Init() interface. */ /* #include "sqlite3.h" */ @@ -140911,7 +162642,7 @@ SQLITE_API int sqlite3_complete16(const void *zSql){ extern "C" { #endif /* __cplusplus */ -SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db); +SQLITE_PRIVATE int tdsqlite3Fts3Init(tdsqlite3 *db); #if 0 } /* extern "C" */ @@ -140936,15 +162667,19 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db); ****************************************************************************** ** ** This header file is used by programs that want to link against the -** RTREE library. All it does is declare the sqlite3RtreeInit() interface. +** RTREE library. All it does is declare the tdsqlite3RtreeInit() interface. */ /* #include "sqlite3.h" */ +#ifdef SQLITE_OMIT_VIRTUALTABLE +# undef SQLITE_ENABLE_RTREE +#endif + #if 0 extern "C" { #endif /* __cplusplus */ -SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); +SQLITE_PRIVATE int tdsqlite3RtreeInit(tdsqlite3 *db); #if 0 } /* extern "C" */ @@ -140953,7 +162688,7 @@ SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); /************** End of rtree.h ***********************************************/ /************** Continuing where we left off in main.c ***********************/ #endif -#ifdef SQLITE_ENABLE_ICU +#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS) /************** Include sqliteicu.h in the middle of main.c ******************/ /************** Begin file sqliteicu.h ***************************************/ /* @@ -140969,7 +162704,7 @@ SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); ****************************************************************************** ** ** This header file is used by programs that want to link against the -** ICU extension. All it does is declare the sqlite3IcuInit() interface. +** ICU extension. All it does is declare the tdsqlite3IcuInit() interface. */ /* #include "sqlite3.h" */ @@ -140977,7 +162712,7 @@ SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); extern "C" { #endif /* __cplusplus */ -SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db); +SQLITE_PRIVATE int tdsqlite3IcuInit(tdsqlite3 *db); #if 0 } /* extern "C" */ @@ -140988,40 +162723,45 @@ SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db); /************** Continuing where we left off in main.c ***********************/ #endif #ifdef SQLITE_ENABLE_JSON1 -SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*); +SQLITE_PRIVATE int tdsqlite3Json1Init(tdsqlite3*); +#endif +#ifdef SQLITE_ENABLE_STMTVTAB +SQLITE_PRIVATE int tdsqlite3StmtVtabInit(tdsqlite3*); #endif #ifdef SQLITE_ENABLE_FTS5 -SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*); +SQLITE_PRIVATE int tdsqlite3Fts5Init(tdsqlite3*); #endif #ifndef SQLITE_AMALGAMATION -/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant +/* IMPLEMENTATION-OF: R-46656-45156 The tdsqlite3_version[] string constant ** contains the text of SQLITE_VERSION macro. */ -SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; +SQLITE_API const char tdsqlite3_version[] = SQLITE_VERSION; #endif -/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns -** a pointer to the to the sqlite3_version[] string constant. +/* IMPLEMENTATION-OF: R-53536-42575 The tdsqlite3_libversion() function returns +** a pointer to the to the tdsqlite3_version[] string constant. */ -SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; } +SQLITE_API const char *tdsqlite3_libversion(void){ return tdsqlite3_version; } -/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a +/* IMPLEMENTATION-OF: R-25063-23286 The tdsqlite3_sourceid() function returns a ** pointer to a string constant whose value is the same as the -** SQLITE_SOURCE_ID C preprocessor macro. +** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using +** an edited copy of the amalgamation, then the last four characters of +** the hash might be different from SQLITE_SOURCE_ID. */ -SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } +/* SQLITE_API const char *tdsqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */ -/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function +/* IMPLEMENTATION-OF: R-35210-63508 The tdsqlite3_libversion_number() function ** returns an integer equal to SQLITE_VERSION_NUMBER. */ -SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } +SQLITE_API int tdsqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } -/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns +/* IMPLEMENTATION-OF: R-20790-14025 The tdsqlite3_threadsafe() function returns ** zero if and only if SQLite was compiled with mutexing code omitted due to ** the SQLITE_THREADSAFE compile-time option being set to 0. */ -SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } +SQLITE_API int tdsqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } /* ** When compiling the test fixture or with debugging enabled (on Win32), @@ -141032,7 +162772,7 @@ SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } # ifndef SQLITE_DEBUG_OS_TRACE # define SQLITE_DEBUG_OS_TRACE 0 # endif - int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; + int tdsqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; #endif #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) @@ -141042,7 +162782,7 @@ SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } ** I/O active are written using this function. These messages ** are intended for debugging activity only. */ -SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0; +SQLITE_API void (SQLITE_CDECL *tdsqlite3IoTrace)(const char*, ...) = 0; #endif /* @@ -141052,7 +162792,7 @@ SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0; ** ** See also the "PRAGMA temp_store_directory" SQL command. */ -SQLITE_API char *sqlite3_temp_directory = 0; +SQLITE_API char *tdsqlite3_temp_directory = 0; /* ** If the following global variable points to a string which is the @@ -141061,7 +162801,7 @@ SQLITE_API char *sqlite3_temp_directory = 0; ** ** See also the "PRAGMA data_store_directory" SQL command. */ -SQLITE_API char *sqlite3_data_directory = 0; +SQLITE_API char *tdsqlite3_data_directory = 0; /* ** Initialize SQLite. @@ -141070,10 +162810,10 @@ SQLITE_API char *sqlite3_data_directory = 0; ** VFS, and mutex subsystems prior to doing any serious work with ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT ** this routine will be called automatically by key routines such as -** sqlite3_open(). +** tdsqlite3_open(). ** ** This routine is a no-op except on its very first call for the process, -** or for the first call after a call to sqlite3_shutdown. +** or for the first call after a call to tdsqlite3_shutdown. ** ** The first thread to call this routine runs the initialization to ** completion. If subsequent threads call this routine before the first @@ -141094,15 +162834,15 @@ SQLITE_API char *sqlite3_data_directory = 0; ** * Recursive calls to this routine from thread X return immediately ** without blocking. */ -SQLITE_API int sqlite3_initialize(void){ - MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ +SQLITE_API int tdsqlite3_initialize(void){ + MUTEX_LOGIC( tdsqlite3_mutex *pMaster; ) /* The main static mutex */ int rc; /* Result code */ #ifdef SQLITE_EXTRA_INIT int bRunExtraInit = 0; /* Extra initialization needed */ #endif #ifdef SQLITE_OMIT_WSD - rc = sqlite3_wsd_init(4096, 24); + rc = tdsqlite3_wsd_init(4096, 24); if( rc!=SQLITE_OK ){ return rc; } @@ -141114,11 +162854,11 @@ SQLITE_API int sqlite3_initialize(void){ assert( SQLITE_PTRSIZE==sizeof(char*) ); /* If SQLite is already completely initialized, then this call - ** to sqlite3_initialize() should be a no-op. But the initialization + ** to tdsqlite3_initialize() should be a no-op. But the initialization ** must be complete. So isInit must not be set until the very end ** of this routine. */ - if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; + if( tdsqlite3GlobalConfig.isInit ) return SQLITE_OK; /* Make sure the mutex subsystem is initialized. If unable to ** initialize the mutex subsystem, return early with the error. @@ -141128,7 +162868,7 @@ SQLITE_API int sqlite3_initialize(void){ ** The mutex subsystem must take care of serializing its own ** initialization. */ - rc = sqlite3MutexInit(); + rc = tdsqlite3MutexInit(); if( rc ) return rc; /* Initialize the malloc() system and the recursive pInitMutex mutex. @@ -141137,26 +162877,26 @@ SQLITE_API int sqlite3_initialize(void){ ** malloc subsystem - this implies that the allocation of a static ** mutex must not require support from the malloc subsystem. */ - MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) - sqlite3_mutex_enter(pMaster); - sqlite3GlobalConfig.isMutexInit = 1; - if( !sqlite3GlobalConfig.isMallocInit ){ - rc = sqlite3MallocInit(); + MUTEX_LOGIC( pMaster = tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) + tdsqlite3_mutex_enter(pMaster); + tdsqlite3GlobalConfig.isMutexInit = 1; + if( !tdsqlite3GlobalConfig.isMallocInit ){ + rc = tdsqlite3MallocInit(); } if( rc==SQLITE_OK ){ - sqlite3GlobalConfig.isMallocInit = 1; - if( !sqlite3GlobalConfig.pInitMutex ){ - sqlite3GlobalConfig.pInitMutex = - sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); - if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ + tdsqlite3GlobalConfig.isMallocInit = 1; + if( !tdsqlite3GlobalConfig.pInitMutex ){ + tdsqlite3GlobalConfig.pInitMutex = + tdsqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); + if( tdsqlite3GlobalConfig.bCoreMutex && !tdsqlite3GlobalConfig.pInitMutex ){ rc = SQLITE_NOMEM_BKPT; } } } if( rc==SQLITE_OK ){ - sqlite3GlobalConfig.nRefInitMutex++; + tdsqlite3GlobalConfig.nRefInitMutex++; } - sqlite3_mutex_leave(pMaster); + tdsqlite3_mutex_leave(pMaster); /* If rc is not SQLITE_OK at this point, then either the malloc ** subsystem could not be initialized or the system failed to allocate @@ -141167,58 +162907,63 @@ SQLITE_API int sqlite3_initialize(void){ /* Do the rest of the initialization under the recursive mutex so ** that we will be able to handle recursive calls into - ** sqlite3_initialize(). The recursive calls normally come through - ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other + ** tdsqlite3_initialize(). The recursive calls normally come through + ** tdsqlite3_os_init() when it invokes tdsqlite3_vfs_register(), but other ** recursive calls might also be possible. ** ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls ** to the xInit method, so the xInit method need not be threadsafe. ** ** The following mutex is what serializes access to the appdef pcache xInit - ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the - ** call to sqlite3PcacheInitialize(). + ** methods. The tdsqlite3_pcache_methods.xInit() all is embedded in the + ** call to tdsqlite3PcacheInitialize(). */ - sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); - if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ - sqlite3GlobalConfig.inProgress = 1; + tdsqlite3_mutex_enter(tdsqlite3GlobalConfig.pInitMutex); + if( tdsqlite3GlobalConfig.isInit==0 && tdsqlite3GlobalConfig.inProgress==0 ){ + tdsqlite3GlobalConfig.inProgress = 1; #ifdef SQLITE_ENABLE_SQLLOG { - extern void sqlite3_init_sqllog(void); - sqlite3_init_sqllog(); + extern void tdsqlite3_init_sqllog(void); + tdsqlite3_init_sqllog(); } #endif - memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions)); - sqlite3RegisterBuiltinFunctions(); - if( sqlite3GlobalConfig.isPCacheInit==0 ){ - rc = sqlite3PcacheInitialize(); + memset(&tdsqlite3BuiltinFunctions, 0, sizeof(tdsqlite3BuiltinFunctions)); + tdsqlite3RegisterBuiltinFunctions(); + if( tdsqlite3GlobalConfig.isPCacheInit==0 ){ + rc = tdsqlite3PcacheInitialize(); } if( rc==SQLITE_OK ){ - sqlite3GlobalConfig.isPCacheInit = 1; - rc = sqlite3OsInit(); + tdsqlite3GlobalConfig.isPCacheInit = 1; + rc = tdsqlite3OsInit(); } +#ifdef SQLITE_ENABLE_DESERIALIZE if( rc==SQLITE_OK ){ - sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, - sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); - sqlite3GlobalConfig.isInit = 1; + rc = tdsqlite3MemdbInit(); + } +#endif + if( rc==SQLITE_OK ){ + tdsqlite3PCacheBufferSetup( tdsqlite3GlobalConfig.pPage, + tdsqlite3GlobalConfig.szPage, tdsqlite3GlobalConfig.nPage); + tdsqlite3GlobalConfig.isInit = 1; #ifdef SQLITE_EXTRA_INIT bRunExtraInit = 1; #endif } - sqlite3GlobalConfig.inProgress = 0; + tdsqlite3GlobalConfig.inProgress = 0; } - sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); + tdsqlite3_mutex_leave(tdsqlite3GlobalConfig.pInitMutex); /* Go back under the static mutex and clean up the recursive ** mutex to prevent a resource leak. */ - sqlite3_mutex_enter(pMaster); - sqlite3GlobalConfig.nRefInitMutex--; - if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ - assert( sqlite3GlobalConfig.nRefInitMutex==0 ); - sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); - sqlite3GlobalConfig.pInitMutex = 0; + tdsqlite3_mutex_enter(pMaster); + tdsqlite3GlobalConfig.nRefInitMutex--; + if( tdsqlite3GlobalConfig.nRefInitMutex<=0 ){ + assert( tdsqlite3GlobalConfig.nRefInitMutex==0 ); + tdsqlite3_mutex_free(tdsqlite3GlobalConfig.pInitMutex); + tdsqlite3GlobalConfig.pInitMutex = 0; } - sqlite3_mutex_leave(pMaster); + tdsqlite3_mutex_leave(pMaster); /* The following is just a sanity check to make sure SQLite has ** been compiled correctly. It is important to run this code, but @@ -141228,13 +162973,13 @@ SQLITE_API int sqlite3_initialize(void){ #ifndef NDEBUG #ifndef SQLITE_OMIT_FLOATING_POINT /* This section of code's only "output" is via assert() statements. */ - if ( rc==SQLITE_OK ){ + if( rc==SQLITE_OK ){ u64 x = (((u64)1)<<63)-1; double y; assert(sizeof(x)==8); assert(sizeof(x)==sizeof(y)); memcpy(&y, &x, 8); - assert( sqlite3IsNaN(y) ); + assert( tdsqlite3IsNaN(y) ); } #endif #endif @@ -141253,53 +162998,53 @@ SQLITE_API int sqlite3_initialize(void){ } /* -** Undo the effects of sqlite3_initialize(). Must not be called while +** Undo the effects of tdsqlite3_initialize(). Must not be called while ** there are outstanding database connections or memory allocations or ** while any part of SQLite is otherwise in use in any thread. This ** routine is not threadsafe. But it is safe to invoke this routine ** on when SQLite is already shut down. If SQLite is already shut down ** when this routine is invoked, then this routine is a harmless no-op. */ -SQLITE_API int sqlite3_shutdown(void){ +SQLITE_API int tdsqlite3_shutdown(void){ #ifdef SQLITE_OMIT_WSD - int rc = sqlite3_wsd_init(4096, 24); + int rc = tdsqlite3_wsd_init(4096, 24); if( rc!=SQLITE_OK ){ return rc; } #endif - if( sqlite3GlobalConfig.isInit ){ + if( tdsqlite3GlobalConfig.isInit ){ #ifdef SQLITE_EXTRA_SHUTDOWN void SQLITE_EXTRA_SHUTDOWN(void); SQLITE_EXTRA_SHUTDOWN(); #endif - sqlite3_os_end(); - sqlite3_reset_auto_extension(); - sqlite3GlobalConfig.isInit = 0; + tdsqlite3_os_end(); + tdsqlite3_reset_auto_extension(); + tdsqlite3GlobalConfig.isInit = 0; } - if( sqlite3GlobalConfig.isPCacheInit ){ - sqlite3PcacheShutdown(); - sqlite3GlobalConfig.isPCacheInit = 0; + if( tdsqlite3GlobalConfig.isPCacheInit ){ + tdsqlite3PcacheShutdown(); + tdsqlite3GlobalConfig.isPCacheInit = 0; } - if( sqlite3GlobalConfig.isMallocInit ){ - sqlite3MallocEnd(); - sqlite3GlobalConfig.isMallocInit = 0; + if( tdsqlite3GlobalConfig.isMallocInit ){ + tdsqlite3MallocEnd(); + tdsqlite3GlobalConfig.isMallocInit = 0; #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES /* The heap subsystem has now been shutdown and these values are supposed - ** to be NULL or point to memory that was obtained from sqlite3_malloc(), + ** to be NULL or point to memory that was obtained from tdsqlite3_malloc(), ** which would rely on that heap subsystem; therefore, make sure these ** values cannot refer to heap memory that was just invalidated when the ** heap subsystem was shutdown. This is only done if the current call to ** this function resulted in the heap subsystem actually being shutdown. */ - sqlite3_data_directory = 0; - sqlite3_temp_directory = 0; + tdsqlite3_data_directory = 0; + tdsqlite3_temp_directory = 0; #endif } - if( sqlite3GlobalConfig.isMutexInit ){ - sqlite3MutexEnd(); - sqlite3GlobalConfig.isMutexInit = 0; + if( tdsqlite3GlobalConfig.isMutexInit ){ + tdsqlite3MutexEnd(); + tdsqlite3GlobalConfig.isMutexInit = 0; } return SQLITE_OK; @@ -141314,13 +163059,13 @@ SQLITE_API int sqlite3_shutdown(void){ ** threadsafe. Failure to heed these warnings can lead to unpredictable ** behavior. */ -SQLITE_API int sqlite3_config(int op, ...){ +SQLITE_API int tdsqlite3_config(int op, ...){ va_list ap; int rc = SQLITE_OK; - /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while + /* tdsqlite3_config() shall return SQLITE_MISUSE if it is invoked while ** the SQLite library is in use. */ - if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; + if( tdsqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; va_start(ap, op); switch( op ){ @@ -141332,8 +163077,8 @@ SQLITE_API int sqlite3_config(int op, ...){ case SQLITE_CONFIG_SINGLETHREAD: { /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to ** Single-thread. */ - sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */ - sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ + tdsqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */ + tdsqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ break; } #endif @@ -141341,8 +163086,8 @@ SQLITE_API int sqlite3_config(int op, ...){ case SQLITE_CONFIG_MULTITHREAD: { /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to ** Multi-thread. */ - sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ - sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ + tdsqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ + tdsqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ break; } #endif @@ -141350,22 +163095,22 @@ SQLITE_API int sqlite3_config(int op, ...){ case SQLITE_CONFIG_SERIALIZED: { /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to ** Serialized. */ - sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ - sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */ + tdsqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ + tdsqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */ break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */ case SQLITE_CONFIG_MUTEX: { /* Specify an alternative mutex implementation */ - sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); + tdsqlite3GlobalConfig.mutex = *va_arg(ap, tdsqlite3_mutex_methods*); break; } #endif #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */ case SQLITE_CONFIG_GETMUTEX: { /* Retrieve the current mutex implementation */ - *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; + *va_arg(ap, tdsqlite3_mutex_methods*) = tdsqlite3GlobalConfig.mutex; break; } #endif @@ -141373,36 +163118,30 @@ SQLITE_API int sqlite3_config(int op, ...){ case SQLITE_CONFIG_MALLOC: { /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a ** single argument which is a pointer to an instance of the - ** sqlite3_mem_methods structure. The argument specifies alternative + ** tdsqlite3_mem_methods structure. The argument specifies alternative ** low-level memory allocation routines to be used in place of the memory ** allocation routines built into SQLite. */ - sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); + tdsqlite3GlobalConfig.m = *va_arg(ap, tdsqlite3_mem_methods*); break; } case SQLITE_CONFIG_GETMALLOC: { /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a ** single argument which is a pointer to an instance of the - ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is + ** tdsqlite3_mem_methods structure. The tdsqlite3_mem_methods structure is ** filled with the currently defined memory allocation routines. */ - if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); - *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; + if( tdsqlite3GlobalConfig.m.xMalloc==0 ) tdsqlite3MemSetDefault(); + *va_arg(ap, tdsqlite3_mem_methods*) = tdsqlite3GlobalConfig.m; break; } case SQLITE_CONFIG_MEMSTATUS: { /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes ** single argument of type int, interpreted as a boolean, which enables ** or disables the collection of memory allocation statistics. */ - sqlite3GlobalConfig.bMemstat = va_arg(ap, int); + tdsqlite3GlobalConfig.bMemstat = va_arg(ap, int); break; } - case SQLITE_CONFIG_SCRATCH: { - /* EVIDENCE-OF: R-08404-60887 There are three arguments to - ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from - ** which the scratch allocations will be drawn, the size of each scratch - ** allocation (sz), and the maximum number of scratch allocations (N). */ - sqlite3GlobalConfig.pScratch = va_arg(ap, void*); - sqlite3GlobalConfig.szScratch = va_arg(ap, int); - sqlite3GlobalConfig.nScratch = va_arg(ap, int); + case SQLITE_CONFIG_SMALL_MALLOC: { + tdsqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int); break; } case SQLITE_CONFIG_PAGECACHE: { @@ -141410,9 +163149,9 @@ SQLITE_API int sqlite3_config(int op, ...){ ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem), ** the size of each page cache line (sz), and the number of cache lines ** (N). */ - sqlite3GlobalConfig.pPage = va_arg(ap, void*); - sqlite3GlobalConfig.szPage = va_arg(ap, int); - sqlite3GlobalConfig.nPage = va_arg(ap, int); + tdsqlite3GlobalConfig.pPage = va_arg(ap, void*); + tdsqlite3GlobalConfig.szPage = va_arg(ap, int); + tdsqlite3GlobalConfig.nPage = va_arg(ap, int); break; } case SQLITE_CONFIG_PCACHE_HDRSZ: { @@ -141421,9 +163160,9 @@ SQLITE_API int sqlite3_config(int op, ...){ ** that integer the number of extra bytes per page required for each page ** in SQLITE_CONFIG_PAGECACHE. */ *va_arg(ap, int*) = - sqlite3HeaderSizeBtree() + - sqlite3HeaderSizePcache() + - sqlite3HeaderSizePcache1(); + tdsqlite3HeaderSizeBtree() + + tdsqlite3HeaderSizePcache() + + tdsqlite3HeaderSizePcache1(); break; } @@ -141439,21 +163178,21 @@ SQLITE_API int sqlite3_config(int op, ...){ case SQLITE_CONFIG_PCACHE2: { /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a - ** single argument which is a pointer to an sqlite3_pcache_methods2 + ** single argument which is a pointer to an tdsqlite3_pcache_methods2 ** object. This object specifies the interface to a custom page cache ** implementation. */ - sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); + tdsqlite3GlobalConfig.pcache2 = *va_arg(ap, tdsqlite3_pcache_methods2*); break; } case SQLITE_CONFIG_GETPCACHE2: { /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a - ** single argument which is a pointer to an sqlite3_pcache_methods2 + ** single argument which is a pointer to an tdsqlite3_pcache_methods2 ** object. SQLite copies of the current page cache implementation into ** that object. */ - if( sqlite3GlobalConfig.pcache2.xInit==0 ){ - sqlite3PCacheSetDefault(); + if( tdsqlite3GlobalConfig.pcache2.xInit==0 ){ + tdsqlite3PCacheSetDefault(); } - *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; + *va_arg(ap, tdsqlite3_pcache_methods2*) = tdsqlite3GlobalConfig.pcache2; break; } @@ -141466,36 +163205,36 @@ SQLITE_API int sqlite3_config(int op, ...){ ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the ** number of bytes in the memory buffer, and the minimum allocation size. */ - sqlite3GlobalConfig.pHeap = va_arg(ap, void*); - sqlite3GlobalConfig.nHeap = va_arg(ap, int); - sqlite3GlobalConfig.mnReq = va_arg(ap, int); + tdsqlite3GlobalConfig.pHeap = va_arg(ap, void*); + tdsqlite3GlobalConfig.nHeap = va_arg(ap, int); + tdsqlite3GlobalConfig.mnReq = va_arg(ap, int); - if( sqlite3GlobalConfig.mnReq<1 ){ - sqlite3GlobalConfig.mnReq = 1; - }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ + if( tdsqlite3GlobalConfig.mnReq<1 ){ + tdsqlite3GlobalConfig.mnReq = 1; + }else if( tdsqlite3GlobalConfig.mnReq>(1<<12) ){ /* cap min request size at 2^12 */ - sqlite3GlobalConfig.mnReq = (1<<12); + tdsqlite3GlobalConfig.mnReq = (1<<12); } - if( sqlite3GlobalConfig.pHeap==0 ){ + if( tdsqlite3GlobalConfig.pHeap==0 ){ /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer) ** is NULL, then SQLite reverts to using its default memory allocator ** (the system malloc() implementation), undoing any prior invocation of ** SQLITE_CONFIG_MALLOC. ** - ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to - ** revert to its default implementation when sqlite3_initialize() is run + ** Setting tdsqlite3GlobalConfig.m to all zeros will cause malloc to + ** revert to its default implementation when tdsqlite3_initialize() is run */ - memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); + memset(&tdsqlite3GlobalConfig.m, 0, sizeof(tdsqlite3GlobalConfig.m)); }else{ /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the ** alternative memory allocator is engaged to handle all of SQLites ** memory allocation needs. */ #ifdef SQLITE_ENABLE_MEMSYS3 - sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); + tdsqlite3GlobalConfig.m = *tdsqlite3MemGetMemsys3(); #endif #ifdef SQLITE_ENABLE_MEMSYS5 - sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); + tdsqlite3GlobalConfig.m = *tdsqlite3MemGetMemsys5(); #endif } break; @@ -141503,8 +163242,8 @@ SQLITE_API int sqlite3_config(int op, ...){ #endif case SQLITE_CONFIG_LOOKASIDE: { - sqlite3GlobalConfig.szLookaside = va_arg(ap, int); - sqlite3GlobalConfig.nLookaside = va_arg(ap, int); + tdsqlite3GlobalConfig.szLookaside = va_arg(ap, int); + tdsqlite3GlobalConfig.nLookaside = va_arg(ap, int); break; } @@ -141515,25 +163254,25 @@ SQLITE_API int sqlite3_config(int op, ...){ case SQLITE_CONFIG_LOG: { /* MSVC is picky about pulling func ptrs from va lists. ** http://support.microsoft.com/kb/47961 - ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); + ** tdsqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); */ typedef void(*LOGFUNC_t)(void*,int,const char*); - sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); - sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); + tdsqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); + tdsqlite3GlobalConfig.pLogArg = va_arg(ap, void*); break; } /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames ** can be changed at start-time using the - ** sqlite3_config(SQLITE_CONFIG_URI,1) or - ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls. + ** tdsqlite3_config(SQLITE_CONFIG_URI,1) or + ** tdsqlite3_config(SQLITE_CONFIG_URI,0) configuration calls. */ case SQLITE_CONFIG_URI: { /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single ** argument of type int. If non-zero, then URI handling is globally ** enabled. If the parameter is zero, then URI handling is globally ** disabled. */ - sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); + tdsqlite3GlobalConfig.bOpenUri = va_arg(ap, int); break; } @@ -141542,26 +163281,26 @@ SQLITE_API int sqlite3_config(int op, ...){ ** option takes a single integer argument which is interpreted as a ** boolean in order to enable or disable the use of covering indices for ** full table scans in the query optimizer. */ - sqlite3GlobalConfig.bUseCis = va_arg(ap, int); + tdsqlite3GlobalConfig.bUseCis = va_arg(ap, int); break; } #ifdef SQLITE_ENABLE_SQLLOG case SQLITE_CONFIG_SQLLOG: { - typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); - sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); - sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); + typedef void(*SQLLOGFUNC_t)(void*, tdsqlite3*, const char*, int); + tdsqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); + tdsqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); break; } #endif case SQLITE_CONFIG_MMAP_SIZE: { /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit - ** integer (sqlite3_int64) values that are the default mmap size limit + ** integer (tdsqlite3_int64) values that are the default mmap size limit ** (the default setting for PRAGMA mmap_size) and the maximum allowed ** mmap size limit. */ - sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); - sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); + tdsqlite3_int64 szMmap = va_arg(ap, tdsqlite3_int64); + tdsqlite3_int64 mxMmap = va_arg(ap, tdsqlite3_int64); /* EVIDENCE-OF: R-53367-43190 If either argument to this option is ** negative, then that argument is changed to its compile-time default. ** @@ -141575,8 +163314,8 @@ SQLITE_API int sqlite3_config(int op, ...){ } if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; if( szMmap>mxMmap) szMmap = mxMmap; - sqlite3GlobalConfig.mxMmap = mxMmap; - sqlite3GlobalConfig.szMmap = szMmap; + tdsqlite3GlobalConfig.mxMmap = mxMmap; + tdsqlite3GlobalConfig.szMmap = szMmap; break; } @@ -141585,21 +163324,39 @@ SQLITE_API int sqlite3_config(int op, ...){ /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit ** unsigned integer value that specifies the maximum size of the created ** heap. */ - sqlite3GlobalConfig.nHeap = va_arg(ap, int); + tdsqlite3GlobalConfig.nHeap = va_arg(ap, int); break; } #endif case SQLITE_CONFIG_PMASZ: { - sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int); + tdsqlite3GlobalConfig.szPma = va_arg(ap, unsigned int); break; } case SQLITE_CONFIG_STMTJRNL_SPILL: { - sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int); + tdsqlite3GlobalConfig.nStmtSpill = va_arg(ap, int); break; } +#ifdef SQLITE_ENABLE_SORTER_REFERENCES + case SQLITE_CONFIG_SORTERREF_SIZE: { + int iVal = va_arg(ap, int); + if( iVal<0 ){ + iVal = SQLITE_DEFAULT_SORTERREF_SIZE; + } + tdsqlite3GlobalConfig.szSorterRef = (u32)iVal; + break; + } +#endif /* SQLITE_ENABLE_SORTER_REFERENCES */ + +#ifdef SQLITE_ENABLE_DESERIALIZE + case SQLITE_CONFIG_MEMDB_MAXSIZE: { + tdsqlite3GlobalConfig.mxMemdbSize = va_arg(ap, tdsqlite3_int64); + break; + } +#endif /* SQLITE_ENABLE_DESERIALIZE */ + default: { rc = SQLITE_ERROR; break; @@ -141616,14 +163373,18 @@ SQLITE_API int sqlite3_config(int op, ...){ ** ** The sz parameter is the number of bytes in each lookaside slot. ** The cnt parameter is the number of slots. If pStart is NULL the -** space for the lookaside memory is obtained from sqlite3_malloc(). +** space for the lookaside memory is obtained from tdsqlite3_malloc(). ** If pStart is not NULL then it is sz*cnt bytes of memory to use for ** the lookaside memory. */ -static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ +static int setupLookaside(tdsqlite3 *db, void *pBuf, int sz, int cnt){ #ifndef SQLITE_OMIT_LOOKASIDE void *pStart; - if( db->lookaside.nOut ){ + tdsqlite3_int64 szAlloc = sz*(tdsqlite3_int64)cnt; + int nBig; /* Number of full-size slots */ + int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */ + + if( tdsqlite3LookasideUsed(db,0)>0 ){ return SQLITE_BUSY; } /* Free any existing lookaside buffer for this handle before @@ -141631,7 +163392,7 @@ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ ** both at the same time. */ if( db->lookaside.bMalloced ){ - sqlite3_free(db->lookaside.pStart); + tdsqlite3_free(db->lookaside.pStart); } /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger ** than a pointer to be useful. @@ -141643,35 +163404,72 @@ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ sz = 0; pStart = 0; }else if( pBuf==0 ){ - sqlite3BeginBenignMalloc(); - pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ - sqlite3EndBenignMalloc(); - if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; + tdsqlite3BeginBenignMalloc(); + pStart = tdsqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */ + tdsqlite3EndBenignMalloc(); + if( pStart ) szAlloc = tdsqlite3MallocSize(pStart); }else{ pStart = pBuf; } +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + if( sz>=LOOKASIDE_SMALL*3 ){ + nBig = szAlloc/(3*LOOKASIDE_SMALL+sz); + nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL; + }else if( sz>=LOOKASIDE_SMALL*2 ){ + nBig = szAlloc/(LOOKASIDE_SMALL+sz); + nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL; + }else +#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ + if( sz>0 ){ + nBig = szAlloc/sz; + nSm = 0; + }else{ + nBig = nSm = 0; + } db->lookaside.pStart = pStart; + db->lookaside.pInit = 0; db->lookaside.pFree = 0; db->lookaside.sz = (u16)sz; + db->lookaside.szTrue = (u16)sz; if( pStart ){ int i; LookasideSlot *p; assert( sz > (int)sizeof(LookasideSlot*) ); p = (LookasideSlot*)pStart; - for(i=cnt-1; i>=0; i--){ - p->pNext = db->lookaside.pFree; - db->lookaside.pFree = p; + for(i=0; i<nBig; i++){ + p->pNext = db->lookaside.pInit; + db->lookaside.pInit = p; p = (LookasideSlot*)&((u8*)p)[sz]; } +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + db->lookaside.pSmallInit = 0; + db->lookaside.pSmallFree = 0; + db->lookaside.pMiddle = p; + for(i=0; i<nSm; i++){ + p->pNext = db->lookaside.pSmallInit; + db->lookaside.pSmallInit = p; + p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL]; + } +#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ + assert( ((uptr)p)<=szAlloc + (uptr)pStart ); db->lookaside.pEnd = p; db->lookaside.bDisable = 0; db->lookaside.bMalloced = pBuf==0 ?1:0; + db->lookaside.nSlot = nBig+nSm; }else{ db->lookaside.pStart = db; +#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE + db->lookaside.pSmallInit = 0; + db->lookaside.pSmallFree = 0; + db->lookaside.pMiddle = db; +#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ db->lookaside.pEnd = db; db->lookaside.bDisable = 1; + db->lookaside.sz = 0; db->lookaside.bMalloced = 0; + db->lookaside.nSlot = 0; } + assert( tdsqlite3LookasideUsed(db,0)==0 ); #endif /* SQLITE_OMIT_LOOKASIDE */ return SQLITE_OK; } @@ -141679,9 +163477,9 @@ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ /* ** Return the mutex associated with a database connection. */ -SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ +SQLITE_API tdsqlite3_mutex *tdsqlite3_db_mutex(tdsqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } @@ -141693,23 +163491,23 @@ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ ** Free up as much memory as we can from the given database ** connection. */ -SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){ +SQLITE_API int tdsqlite3_db_release_memory(tdsqlite3 *db){ int i; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeEnterAll(db); + tdsqlite3_mutex_enter(db->mutex); + tdsqlite3BtreeEnterAll(db); for(i=0; i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; if( pBt ){ - Pager *pPager = sqlite3BtreePager(pBt); - sqlite3PagerShrink(pPager); + Pager *pPager = tdsqlite3BtreePager(pBt); + tdsqlite3PagerShrink(pPager); } } - sqlite3BtreeLeaveAll(db); - sqlite3_mutex_leave(db->mutex); + tdsqlite3BtreeLeaveAll(db); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_OK; } @@ -141717,41 +163515,43 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){ ** Flush any dirty pages in the pager-cache for any attached database ** to disk. */ -SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){ +SQLITE_API int tdsqlite3_db_cacheflush(tdsqlite3 *db){ int i; int rc = SQLITE_OK; int bSeenBusy = 0; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeEnterAll(db); + tdsqlite3_mutex_enter(db->mutex); + tdsqlite3BtreeEnterAll(db); for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; - if( pBt && sqlite3BtreeIsInTrans(pBt) ){ - Pager *pPager = sqlite3BtreePager(pBt); - rc = sqlite3PagerFlush(pPager); + if( pBt && tdsqlite3BtreeIsInTrans(pBt) ){ + Pager *pPager = tdsqlite3BtreePager(pBt); + rc = tdsqlite3PagerFlush(pPager); if( rc==SQLITE_BUSY ){ bSeenBusy = 1; rc = SQLITE_OK; } } } - sqlite3BtreeLeaveAll(db); - sqlite3_mutex_leave(db->mutex); + tdsqlite3BtreeLeaveAll(db); + tdsqlite3_mutex_leave(db->mutex); return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc); } /* ** Configuration settings for an individual database connection */ -SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ +SQLITE_API int tdsqlite3_db_config(tdsqlite3 *db, int op, ...){ va_list ap; int rc; va_start(ap, op); switch( op ){ case SQLITE_DBCONFIG_MAINDBNAME: { + /* IMP: R-06824-28531 */ + /* IMP: R-36257-52125 */ db->aDb[0].zDbSName = va_arg(ap,char*); rc = SQLITE_OK; break; @@ -141770,8 +163570,21 @@ SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ } aFlagOp[] = { { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, + { SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_EnableView }, { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer }, { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension }, + { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose }, + { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG }, + { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP }, + { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase }, + { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive }, + { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema| + SQLITE_NoSchemaError }, + { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter }, + { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL }, + { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML }, + { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_LegacyFileFmt }, + { SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_TrustedSchema }, }; unsigned int i; rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ @@ -141779,14 +163592,14 @@ SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ if( aFlagOp[i].op==op ){ int onoff = va_arg(ap, int); int *pRes = va_arg(ap, int*); - int oldFlags = db->flags; + u64 oldFlags = db->flags; if( onoff>0 ){ db->flags |= aFlagOp[i].mask; }else if( onoff==0 ){ - db->flags &= ~aFlagOp[i].mask; + db->flags &= ~(u64)aFlagOp[i].mask; } if( oldFlags!=db->flags ){ - sqlite3ExpirePreparedStatements(db); + tdsqlite3ExpirePreparedStatements(db, 0); } if( pRes ){ *pRes = (db->flags & aFlagOp[i].mask)!=0; @@ -141802,51 +163615,54 @@ SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ return rc; } - -/* -** Return true if the buffer z[0..n-1] contains all spaces. -*/ -static int allSpaces(const char *z, int n){ - while( n>0 && z[n-1]==' ' ){ n--; } - return n==0; -} - /* ** This is the default collating function named "BINARY" which is always ** available. -** -** If the padFlag argument is not NULL then space padding at the end -** of strings is ignored. This implements the RTRIM collation. */ static int binCollFunc( - void *padFlag, + void *NotUsed, int nKey1, const void *pKey1, int nKey2, const void *pKey2 ){ int rc, n; + UNUSED_PARAMETER(NotUsed); n = nKey1<nKey2 ? nKey1 : nKey2; /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares ** strings byte by byte using the memcmp() function from the standard C ** library. */ + assert( pKey1 && pKey2 ); rc = memcmp(pKey1, pKey2, n); if( rc==0 ){ - if( padFlag - && allSpaces(((char*)pKey1)+n, nKey1-n) - && allSpaces(((char*)pKey2)+n, nKey2-n) - ){ - /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra - ** spaces at the end of either string do not change the result. In other - ** words, strings will compare equal to one another as long as they - ** differ only in the number of spaces at the end. - */ - }else{ - rc = nKey1 - nKey2; - } + rc = nKey1 - nKey2; } return rc; } /* +** This is the collating function named "RTRIM" which is always +** available. Ignore trailing spaces. +*/ +static int rtrimCollFunc( + void *pUser, + int nKey1, const void *pKey1, + int nKey2, const void *pKey2 +){ + const u8 *pK1 = (const u8*)pKey1; + const u8 *pK2 = (const u8*)pKey2; + while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--; + while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--; + return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2); +} + +/* +** Return true if CollSeq is the default built-in BINARY. +*/ +SQLITE_PRIVATE int tdsqlite3IsBinary(const CollSeq *p){ + assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 ); + return p==0 || p->xCmp==binCollFunc; +} + +/* ** Another built-in collating sequence: NOCASE. ** ** This collating sequence is intended to be used for "case independent @@ -141860,7 +163676,7 @@ static int nocaseCollatingFunc( int nKey1, const void *pKey1, int nKey2, const void *pKey2 ){ - int r = sqlite3StrNICmp( + int r = tdsqlite3StrNICmp( (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2); UNUSED_PARAMETER(NotUsed); if( 0==r ){ @@ -141872,9 +163688,9 @@ static int nocaseCollatingFunc( /* ** Return the ROWID of the most recent insert */ -SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){ +SQLITE_API sqlite_int64 tdsqlite3_last_insert_rowid(tdsqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } @@ -141883,11 +163699,26 @@ SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){ } /* -** Return the number of changes in the most recent call to sqlite3_exec(). +** Set the value returned by the tdsqlite3_last_insert_rowid() API function. */ -SQLITE_API int sqlite3_changes(sqlite3 *db){ +SQLITE_API void tdsqlite3_set_last_insert_rowid(tdsqlite3 *db, tdsqlite3_int64 iRowid){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ + (void)SQLITE_MISUSE_BKPT; + return; + } +#endif + tdsqlite3_mutex_enter(db->mutex); + db->lastRowid = iRowid; + tdsqlite3_mutex_leave(db->mutex); +} + +/* +** Return the number of changes in the most recent call to tdsqlite3_exec(). +*/ +SQLITE_API int tdsqlite3_changes(tdsqlite3 *db){ +#ifdef SQLITE_ENABLE_API_ARMOR + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } @@ -141898,9 +163729,9 @@ SQLITE_API int sqlite3_changes(sqlite3 *db){ /* ** Return the number of changes since the database handle was opened. */ -SQLITE_API int sqlite3_total_changes(sqlite3 *db){ +SQLITE_API int tdsqlite3_total_changes(tdsqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } @@ -141913,11 +163744,11 @@ SQLITE_API int sqlite3_total_changes(sqlite3 *db){ ** database handle object, it does not close any savepoints that may be open ** at the b-tree/pager level. */ -SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3CloseSavepoints(tdsqlite3 *db){ while( db->pSavepoint ){ Savepoint *pTmp = db->pSavepoint; db->pSavepoint = pTmp->pNext; - sqlite3DbFree(db, pTmp); + tdsqlite3DbFree(db, pTmp); } db->nSavepoint = 0; db->nStatement = 0; @@ -141930,43 +163761,43 @@ SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){ ** copies of a single function are created when create_function() is called ** with SQLITE_ANY as the encoding. */ -static void functionDestroy(sqlite3 *db, FuncDef *p){ +static void functionDestroy(tdsqlite3 *db, FuncDef *p){ FuncDestructor *pDestructor = p->u.pDestructor; if( pDestructor ){ pDestructor->nRef--; if( pDestructor->nRef==0 ){ pDestructor->xDestroy(pDestructor->pUserData); - sqlite3DbFree(db, pDestructor); + tdsqlite3DbFree(db, pDestructor); } } } /* -** Disconnect all sqlite3_vtab objects that belong to database connection +** Disconnect all tdsqlite3_vtab objects that belong to database connection ** db. This is called when db is being closed. */ -static void disconnectAllVtab(sqlite3 *db){ +static void disconnectAllVtab(tdsqlite3 *db){ #ifndef SQLITE_OMIT_VIRTUALTABLE int i; HashElem *p; - sqlite3BtreeEnterAll(db); + tdsqlite3BtreeEnterAll(db); for(i=0; i<db->nDb; i++){ Schema *pSchema = db->aDb[i].pSchema; - if( db->aDb[i].pSchema ){ + if( pSchema ){ for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ Table *pTab = (Table *)sqliteHashData(p); - if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); + if( IsVirtual(pTab) ) tdsqlite3VtabDisconnect(db, pTab); } } } for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){ Module *pMod = (Module *)sqliteHashData(p); if( pMod->pEpoTab ){ - sqlite3VtabDisconnect(db, pMod->pEpoTab); + tdsqlite3VtabDisconnect(db, pMod->pEpoTab); } } - sqlite3VtabUnlockList(db); - sqlite3BtreeLeaveAll(db); + tdsqlite3VtabUnlockList(db); + tdsqlite3BtreeLeaveAll(db); #else UNUSED_PARAMETER(db); #endif @@ -141974,15 +163805,15 @@ static void disconnectAllVtab(sqlite3 *db){ /* ** Return TRUE if database connection db has unfinalized prepared -** statements or unfinished sqlite3_backup objects. +** statements or unfinished tdsqlite3_backup objects. */ -static int connectionIsBusy(sqlite3 *db){ +static int connectionIsBusy(tdsqlite3 *db){ int j; - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); if( db->pVdbe ) return 1; for(j=0; j<db->nDb; j++){ Btree *pBt = db->aDb[j].pBt; - if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; + if( pBt && tdsqlite3BtreeIsInBackup(pBt) ) return 1; } return 0; } @@ -141990,16 +163821,16 @@ static int connectionIsBusy(sqlite3 *db){ /* ** Close an existing SQLite database */ -static int sqlite3Close(sqlite3 *db, int forceZombie){ +static int tdsqlite3Close(tdsqlite3 *db, int forceZombie){ if( !db ){ - /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or - ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */ + /* EVIDENCE-OF: R-63257-11740 Calling tdsqlite3_close() or + ** tdsqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */ return SQLITE_OK; } - if( !sqlite3SafetyCheckSickOrOk(db) ){ + if( !tdsqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); if( db->mTrace & SQLITE_TRACE_CLOSE ){ db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0); } @@ -142009,74 +163840,74 @@ static int sqlite3Close(sqlite3 *db, int forceZombie){ /* If a transaction is open, the disconnectAllVtab() call above ** will not have called the xDisconnect() method on any virtual - ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() + ** tables in the db->aVTrans[] array. The following tdsqlite3VtabRollback() ** call will do so. We need to do this before the check for active ** SQL statements below, as the v-table implementation may be storing ** some prepared statements internally. */ - sqlite3VtabRollback(db); + tdsqlite3VtabRollback(db); - /* Legacy behavior (sqlite3_close() behavior) is to return + /* Legacy behavior (tdsqlite3_close() behavior) is to return ** SQLITE_BUSY if the connection can not be closed immediately. */ if( !forceZombie && connectionIsBusy(db) ){ - sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized " + tdsqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized " "statements or unfinished backups"); - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_BUSY; } #ifdef SQLITE_ENABLE_SQLLOG - if( sqlite3GlobalConfig.xSqllog ){ + if( tdsqlite3GlobalConfig.xSqllog ){ /* Closing the handle. Fourth parameter is passed the value 2. */ - sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); + tdsqlite3GlobalConfig.xSqllog(tdsqlite3GlobalConfig.pSqllogArg, db, 0, 2); } #endif /* Convert the connection into a zombie and then close it. */ db->magic = SQLITE_MAGIC_ZOMBIE; - sqlite3LeaveMutexAndCloseZombie(db); + tdsqlite3LeaveMutexAndCloseZombie(db); return SQLITE_OK; } /* ** Two variations on the public interface for closing a database -** connection. The sqlite3_close() version returns SQLITE_BUSY and +** connection. The tdsqlite3_close() version returns SQLITE_BUSY and ** leaves the connection option if there are unfinalized prepared -** statements or unfinished sqlite3_backups. The sqlite3_close_v2() +** statements or unfinished tdsqlite3_backups. The tdsqlite3_close_v2() ** version forces the connection to become a zombie if there are ** unclosed resources, and arranges for deallocation when the last -** prepare statement or sqlite3_backup closes. +** prepare statement or tdsqlite3_backup closes. */ -SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } -SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } +SQLITE_API int tdsqlite3_close(tdsqlite3 *db){ return tdsqlite3Close(db,0); } +SQLITE_API int tdsqlite3_close_v2(tdsqlite3 *db){ return tdsqlite3Close(db,1); } /* ** Close the mutex on database connection db. ** ** Furthermore, if database connection db is a zombie (meaning that there -** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and -** every sqlite3_stmt has now been finalized and every sqlite3_backup has +** has been a prior call to tdsqlite3_close(db) or tdsqlite3_close_v2(db)) and +** every tdsqlite3_stmt has now been finalized and every tdsqlite3_backup has ** finished, then free all resources. */ -SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3LeaveMutexAndCloseZombie(tdsqlite3 *db){ HashElem *i; /* Hash table iterator */ int j; - /* If there are outstanding sqlite3_stmt or sqlite3_backup objects - ** or if the connection has not yet been closed by sqlite3_close_v2(), + /* If there are outstanding tdsqlite3_stmt or tdsqlite3_backup objects + ** or if the connection has not yet been closed by tdsqlite3_close_v2(), ** then just leave the mutex and return. */ if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return; } /* If we reach this point, it means that the database connection has - ** closed all sqlite3_stmt and sqlite3_backup objects and has been - ** passed to sqlite3_close (meaning that it is a zombie). Therefore, + ** closed all tdsqlite3_stmt and tdsqlite3_backup objects and has been + ** passed to tdsqlite3_close (meaning that it is a zombie). Therefore, ** go ahead and free all resources. */ @@ -142084,16 +163915,16 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ ** any database schemas have been modified by an uncommitted transaction ** they are reset. And that the required b-tree mutex is held to make ** the pager rollback and schema reset an atomic operation. */ - sqlite3RollbackAll(db, SQLITE_OK); + tdsqlite3RollbackAll(db, SQLITE_OK); /* Free any outstanding Savepoint structures. */ - sqlite3CloseSavepoints(db); + tdsqlite3CloseSavepoints(db); /* Close all database connections */ for(j=0; j<db->nDb; j++){ struct Db *pDb = &db->aDb[j]; if( pDb->pBt ){ - sqlite3BtreeClose(pDb->pBt); + tdsqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; if( j!=1 ){ pDb->pSchema = 0; @@ -142102,19 +163933,19 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ } /* Clear the TEMP schema separately and last */ if( db->aDb[1].pSchema ){ - sqlite3SchemaClear(db->aDb[1].pSchema); + tdsqlite3SchemaClear(db->aDb[1].pSchema); } - sqlite3VtabUnlockList(db); + tdsqlite3VtabUnlockList(db); /* Free up the array of auxiliary databases */ - sqlite3CollapseDatabaseArray(db); + tdsqlite3CollapseDatabaseArray(db); assert( db->nDb<=2 ); assert( db->aDb==db->aDbStatic ); /* Tell the code in notify.c that the connection no longer holds any ** locks and does not require any further unlock-notify callbacks. */ - sqlite3ConnectionClosed(db); + tdsqlite3ConnectionClosed(db); for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){ FuncDef *pNext, *p; @@ -142122,11 +163953,11 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ do{ functionDestroy(db, p); pNext = p->pNext; - sqlite3DbFree(db, p); + tdsqlite3DbFree(db, p); p = pNext; }while( p ); } - sqlite3HashClear(&db->aFunc); + tdsqlite3HashClear(&db->aFunc); for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ CollSeq *pColl = (CollSeq *)sqliteHashData(i); /* Invoke any destructors registered for collation sequence user data. */ @@ -142135,46 +163966,43 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ pColl[j].xDel(pColl[j].pUser); } } - sqlite3DbFree(db, pColl); + tdsqlite3DbFree(db, pColl); } - sqlite3HashClear(&db->aCollSeq); + tdsqlite3HashClear(&db->aCollSeq); #ifndef SQLITE_OMIT_VIRTUALTABLE for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ Module *pMod = (Module *)sqliteHashData(i); - if( pMod->xDestroy ){ - pMod->xDestroy(pMod->pAux); - } - sqlite3VtabEponymousTableClear(db, pMod); - sqlite3DbFree(db, pMod); + tdsqlite3VtabEponymousTableClear(db, pMod); + tdsqlite3VtabModuleUnref(db, pMod); } - sqlite3HashClear(&db->aModule); + tdsqlite3HashClear(&db->aModule); #endif - sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ - sqlite3ValueFree(db->pErr); - sqlite3CloseExtensions(db); + tdsqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ + tdsqlite3ValueFree(db->pErr); + tdsqlite3CloseExtensions(db); #if SQLITE_USER_AUTHENTICATION - sqlite3_free(db->auth.zAuthUser); - sqlite3_free(db->auth.zAuthPW); + tdsqlite3_free(db->auth.zAuthUser); + tdsqlite3_free(db->auth.zAuthPW); #endif db->magic = SQLITE_MAGIC_ERROR; /* The temp-database schema is allocated differently from the other schema - ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). + ** objects (using sqliteMalloc() directly, instead of tdsqlite3BtreeSchema()). ** So it needs to be freed here. Todo: Why not roll the temp schema into ** the same sqliteMalloc() as the one that allocates the database ** structure? */ - sqlite3DbFree(db, db->aDb[1].pSchema); - sqlite3_mutex_leave(db->mutex); + tdsqlite3DbFree(db, db->aDb[1].pSchema); + tdsqlite3_mutex_leave(db->mutex); db->magic = SQLITE_MAGIC_CLOSED; - sqlite3_mutex_free(db->mutex); - assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ + tdsqlite3_mutex_free(db->mutex); + assert( tdsqlite3LookasideUsed(db,0)==0 ); if( db->lookaside.bMalloced ){ - sqlite3_free(db->lookaside.pStart); + tdsqlite3_free(db->lookaside.pStart); } - sqlite3_free(db); + tdsqlite3_free(db); } /* @@ -142184,12 +164012,12 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ ** attempts to use that cursor. Read cursors remain open and valid ** but are "saved" in case the table pages are moved around. */ -SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){ +SQLITE_PRIVATE void tdsqlite3RollbackAll(tdsqlite3 *db, int tripCode){ int i; int inTrans = 0; int schemaChange; - assert( sqlite3_mutex_held(db->mutex) ); - sqlite3BeginBenignMalloc(); + assert( tdsqlite3_mutex_held(db->mutex) ); + tdsqlite3BeginBenignMalloc(); /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). ** This is important in case the transaction being rolled back has @@ -142197,31 +164025,31 @@ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){ ** here, then another shared-cache connection might sneak in between ** the database rollback and schema reset, which can cause false ** corruption reports in some cases. */ - sqlite3BtreeEnterAll(db); - schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0; + tdsqlite3BtreeEnterAll(db); + schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0; for(i=0; i<db->nDb; i++){ Btree *p = db->aDb[i].pBt; if( p ){ - if( sqlite3BtreeIsInTrans(p) ){ + if( tdsqlite3BtreeIsInTrans(p) ){ inTrans = 1; } - sqlite3BtreeRollback(p, tripCode, !schemaChange); + tdsqlite3BtreeRollback(p, tripCode, !schemaChange); } } - sqlite3VtabRollback(db); - sqlite3EndBenignMalloc(); + tdsqlite3VtabRollback(db); + tdsqlite3EndBenignMalloc(); - if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){ - sqlite3ExpirePreparedStatements(db); - sqlite3ResetAllSchemasOfConnection(db); + if( schemaChange ){ + tdsqlite3ExpirePreparedStatements(db, 0); + tdsqlite3ResetAllSchemasOfConnection(db); } - sqlite3BtreeLeaveAll(db); + tdsqlite3BtreeLeaveAll(db); /* Any deferred constraint violations have now been resolved. */ db->nDeferredCons = 0; db->nDeferredImmCons = 0; - db->flags &= ~SQLITE_DeferFKs; + db->flags &= ~(u64)SQLITE_DeferFKs; /* If one has been configured, invoke the rollback-hook callback */ if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ @@ -142234,13 +164062,14 @@ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){ ** specified in the argument. */ #if defined(SQLITE_NEED_ERR_NAME) -SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ +SQLITE_PRIVATE const char *tdsqlite3ErrName(int rc){ const char *zName = 0; int i, origRc = rc; for(i=0; i<2 && zName==0; i++, rc &= 0xff){ switch( rc ){ case SQLITE_OK: zName = "SQLITE_OK"; break; case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; + case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break; case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; case SQLITE_PERM: zName = "SQLITE_PERM"; break; case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; @@ -142253,9 +164082,10 @@ SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; - case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break; + case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break; case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break; + case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break; case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; @@ -142293,6 +164123,7 @@ SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; + case SQLITE_CANTOPEN_SYMLINK: zName = "SQLITE_CANTOPEN_SYMLINK"; break; case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; @@ -142331,7 +164162,7 @@ SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ } if( zName==0 ){ static char zBuf[50]; - sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); + tdsqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); zName = zBuf; } return zName; @@ -142342,13 +164173,13 @@ SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ ** Return a static string that describes the kind of error specified in the ** argument. */ -SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ +SQLITE_PRIVATE const char *tdsqlite3ErrStr(int rc){ static const char* const aMsg[] = { /* SQLITE_OK */ "not an error", - /* SQLITE_ERROR */ "SQL logic error or missing database", + /* SQLITE_ERROR */ "SQL logic error", /* SQLITE_INTERNAL */ 0, /* SQLITE_PERM */ "access permission denied", - /* SQLITE_ABORT */ "callback requested query abort", + /* SQLITE_ABORT */ "query aborted", /* SQLITE_BUSY */ "database is locked", /* SQLITE_LOCKED */ "database table is locked", /* SQLITE_NOMEM */ "out of memory", @@ -142360,17 +164191,23 @@ SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ /* SQLITE_FULL */ "database or disk is full", /* SQLITE_CANTOPEN */ "unable to open database file", /* SQLITE_PROTOCOL */ "locking protocol", - /* SQLITE_EMPTY */ "table contains no data", + /* SQLITE_EMPTY */ 0, /* SQLITE_SCHEMA */ "database schema has changed", /* SQLITE_TOOBIG */ "string or blob too big", /* SQLITE_CONSTRAINT */ "constraint failed", /* SQLITE_MISMATCH */ "datatype mismatch", - /* SQLITE_MISUSE */ "library routine called out of sequence", + /* SQLITE_MISUSE */ "bad parameter or other API misuse", +#ifdef SQLITE_DISABLE_LFS /* SQLITE_NOLFS */ "large file support is disabled", +#else + /* SQLITE_NOLFS */ 0, +#endif /* SQLITE_AUTH */ "authorization denied", - /* SQLITE_FORMAT */ "auxiliary database format error", - /* SQLITE_RANGE */ "bind or column index out of range", - /* SQLITE_NOTADB */ "file is encrypted or is not a database", + /* SQLITE_FORMAT */ 0, + /* SQLITE_RANGE */ "column index out of range", + /* SQLITE_NOTADB */ "file is not a database", + /* SQLITE_NOTICE */ "notification message", + /* SQLITE_WARNING */ "warning message", }; const char *zErr = "unknown error"; switch( rc ){ @@ -142378,6 +164215,14 @@ SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ zErr = "abort due to ROLLBACK"; break; } + case SQLITE_ROW: { + zErr = "another row available"; + break; + } + case SQLITE_DONE: { + zErr = "no more rows available"; + break; + } default: { rc &= 0xff; if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){ @@ -142394,21 +164239,40 @@ SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ ** again until a timeout value is reached. The timeout value is ** an integer number of milliseconds passed in as the first ** argument. +** +** Return non-zero to retry the lock. Return zero to stop trying +** and cause SQLite to return SQLITE_BUSY. */ static int sqliteDefaultBusyCallback( - void *ptr, /* Database connection */ - int count /* Number of times table has been busy */ + void *ptr, /* Database connection */ + int count, /* Number of times table has been busy */ + tdsqlite3_file *pFile /* The file on which the lock occurred */ ){ #if SQLITE_OS_WIN || HAVE_USLEEP + /* This case is for systems that have support for sleeping for fractions of + ** a second. Examples: All windows systems, unix systems with usleep() */ static const u8 delays[] = { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; static const u8 totals[] = { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; # define NDELAY ArraySize(delays) - sqlite3 *db = (sqlite3 *)ptr; - int timeout = db->busyTimeout; + tdsqlite3 *db = (tdsqlite3 *)ptr; + int tmout = db->busyTimeout; int delay, prior; +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + if( tdsqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){ + if( count ){ + tmout = 0; + tdsqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout); + return 0; + }else{ + return 1; + } + } +#else + UNUSED_PARAMETER(pFile); +#endif assert( count>=0 ); if( count < NDELAY ){ delay = delays[count]; @@ -142417,19 +164281,22 @@ static int sqliteDefaultBusyCallback( delay = delays[NDELAY-1]; prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); } - if( prior + delay > timeout ){ - delay = timeout - prior; + if( prior + delay > tmout ){ + delay = tmout - prior; if( delay<=0 ) return 0; } - sqlite3OsSleep(db->pVfs, delay*1000); + tdsqlite3OsSleep(db->pVfs, delay*1000); return 1; #else - sqlite3 *db = (sqlite3 *)ptr; - int timeout = ((sqlite3 *)ptr)->busyTimeout; - if( (count+1)*1000 > timeout ){ + /* This case for unix systems that lack usleep() support. Sleeping + ** must be done in increments of whole seconds */ + tdsqlite3 *db = (tdsqlite3 *)ptr; + int tmout = ((tdsqlite3 *)ptr)->busyTimeout; + UNUSED_PARAMETER(pFile); + if( (count+1)*1000 > tmout ){ return 0; } - sqlite3OsSleep(db->pVfs, 1000000); + tdsqlite3OsSleep(db->pVfs, 1000000); return 1; #endif } @@ -142437,14 +164304,25 @@ static int sqliteDefaultBusyCallback( /* ** Invoke the given busy handler. ** -** This routine is called when an operation failed with a lock. +** This routine is called when an operation failed to acquire a +** lock on VFS file pFile. +** ** If this routine returns non-zero, the lock is retried. If it ** returns 0, the operation aborts with an SQLITE_BUSY error. */ -SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){ +SQLITE_PRIVATE int tdsqlite3InvokeBusyHandler(BusyHandler *p, tdsqlite3_file *pFile){ int rc; - if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; - rc = p->xFunc(p->pArg, p->nBusy); + if( p->xBusyHandler==0 || p->nBusy<0 ) return 0; + if( p->bExtraFileArg ){ + /* Add an extra parameter with the pFile pointer to the end of the + ** callback argument list */ + int (*xTra)(void*,int,tdsqlite3_file*); + xTra = (int(*)(void*,int,tdsqlite3_file*))p->xBusyHandler; + rc = xTra(p->pBusyArg, p->nBusy, pFile); + }else{ + /* Legacy style busy handler callback */ + rc = p->xBusyHandler(p->pBusyArg, p->nBusy); + } if( rc==0 ){ p->nBusy = -1; }else{ @@ -142457,20 +164335,21 @@ SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){ ** This routine sets the busy callback for an Sqlite database to the ** given callback function with the given argument. */ -SQLITE_API int sqlite3_busy_handler( - sqlite3 *db, +SQLITE_API int tdsqlite3_busy_handler( + tdsqlite3 *db, int (*xBusy)(void*,int), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); - db->busyHandler.xFunc = xBusy; - db->busyHandler.pArg = pArg; + tdsqlite3_mutex_enter(db->mutex); + db->busyHandler.xBusyHandler = xBusy; + db->busyHandler.pBusyArg = pArg; db->busyHandler.nBusy = 0; + db->busyHandler.bExtraFileArg = 0; db->busyTimeout = 0; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_OK; } @@ -142480,19 +164359,19 @@ SQLITE_API int sqlite3_busy_handler( ** given callback function with the given argument. The progress callback will ** be invoked every nOps opcodes. */ -SQLITE_API void sqlite3_progress_handler( - sqlite3 *db, +SQLITE_API void tdsqlite3_progress_handler( + tdsqlite3 *db, int nOps, int (*xProgress)(void*), void *pArg ){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); if( nOps>0 ){ db->xProgress = xProgress; db->nProgressOps = (unsigned)nOps; @@ -142502,7 +164381,7 @@ SQLITE_API void sqlite3_progress_handler( db->nProgressOps = 0; db->pProgressArg = 0; } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); } #endif @@ -142511,15 +164390,17 @@ SQLITE_API void sqlite3_progress_handler( ** This routine installs a default busy handler that waits for the ** specified number of milliseconds before returning 0. */ -SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ +SQLITE_API int tdsqlite3_busy_timeout(tdsqlite3 *db, int ms){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif if( ms>0 ){ - sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); + tdsqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback, + (void*)db); db->busyTimeout = ms; + db->busyHandler.bExtraFileArg = 1; }else{ - sqlite3_busy_handler(db, 0, 0); + tdsqlite3_busy_handler(db, 0, 0); } return SQLITE_OK; } @@ -142527,9 +164408,9 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ /* ** Cause any pending operation to stop at its earliest opportunity. */ -SQLITE_API void sqlite3_interrupt(sqlite3 *db){ +SQLITE_API void tdsqlite3_interrupt(tdsqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){ (void)SQLITE_MISUSE_BKPT; return; } @@ -142539,39 +164420,51 @@ SQLITE_API void sqlite3_interrupt(sqlite3 *db){ /* -** This function is exactly the same as sqlite3_create_function(), except +** This function is exactly the same as tdsqlite3_create_function(), except ** that it is designed to be called by internal code. The difference is -** that if a malloc() fails in sqlite3_create_function(), an error code +** that if a malloc() fails in tdsqlite3_create_function(), an error code ** is returned and the mallocFailed flag cleared. */ -SQLITE_PRIVATE int sqlite3CreateFunc( - sqlite3 *db, +SQLITE_PRIVATE int tdsqlite3CreateFunc( + tdsqlite3 *db, const char *zFunctionName, int nArg, int enc, void *pUserData, - void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), - void (*xStep)(sqlite3_context*,int,sqlite3_value **), - void (*xFinal)(sqlite3_context*), + void (*xSFunc)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*xFinal)(tdsqlite3_context*), + void (*xValue)(tdsqlite3_context*), + void (*xInverse)(tdsqlite3_context*,int,tdsqlite3_value **), FuncDestructor *pDestructor ){ FuncDef *p; int nName; int extraFlags; - assert( sqlite3_mutex_held(db->mutex) ); - if( zFunctionName==0 || - (xSFunc && (xFinal || xStep)) || - (!xSFunc && (xFinal && !xStep)) || - (!xSFunc && (!xFinal && xStep)) || - (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || - (255<(nName = sqlite3Strlen30( zFunctionName))) ){ + assert( tdsqlite3_mutex_held(db->mutex) ); + assert( xValue==0 || xSFunc==0 ); + if( zFunctionName==0 /* Must have a valid name */ + || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */ + || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */ + || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */ + || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) + || (255<(nName = tdsqlite3Strlen30( zFunctionName))) + ){ return SQLITE_MISUSE_BKPT; } assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC ); - extraFlags = enc & SQLITE_DETERMINISTIC; + assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY ); + extraFlags = enc & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY| + SQLITE_SUBTYPE|SQLITE_INNOCUOUS); enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY); + + /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But + ** the meaning is inverted. So flip the bit. */ + assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS ); + extraFlags ^= SQLITE_FUNC_UNSAFE; + #ifndef SQLITE_OMIT_UTF16 /* If SQLITE_UTF16 is specified as the encoding type, transform this @@ -142585,11 +164478,13 @@ SQLITE_PRIVATE int sqlite3CreateFunc( enc = SQLITE_UTF16NATIVE; }else if( enc==SQLITE_ANY ){ int rc; - rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags, - pUserData, xSFunc, xStep, xFinal, pDestructor); + rc = tdsqlite3CreateFunc(db, zFunctionName, nArg, + (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE, + pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor); if( rc==SQLITE_OK ){ - rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags, - pUserData, xSFunc, xStep, xFinal, pDestructor); + rc = tdsqlite3CreateFunc(db, zFunctionName, nArg, + (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE, + pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor); } if( rc!=SQLITE_OK ){ return rc; @@ -142605,19 +164500,19 @@ SQLITE_PRIVATE int sqlite3CreateFunc( ** is being overridden/deleted but there are no active VMs, allow the ** operation to continue but invalidate all precompiled statements. */ - p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0); - if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){ + p = tdsqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0); + if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){ if( db->nVdbeActive ){ - sqlite3ErrorWithMsg(db, SQLITE_BUSY, + tdsqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to delete/modify user-function due to active statements"); assert( !db->mallocFailed ); return SQLITE_BUSY; }else{ - sqlite3ExpirePreparedStatements(db); + tdsqlite3ExpirePreparedStatements(db, 0); } } - p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1); + p = tdsqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1); assert(p || db->mallocFailed); if( !p ){ return SQLITE_NOMEM_BKPT; @@ -142633,102 +164528,169 @@ SQLITE_PRIVATE int sqlite3CreateFunc( p->u.pDestructor = pDestructor; p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags; testcase( p->funcFlags & SQLITE_DETERMINISTIC ); + testcase( p->funcFlags & SQLITE_DIRECTONLY ); p->xSFunc = xSFunc ? xSFunc : xStep; p->xFinalize = xFinal; + p->xValue = xValue; + p->xInverse = xInverse; p->pUserData = pUserData; p->nArg = (u16)nArg; return SQLITE_OK; } /* -** Create new user functions. +** Worker function used by utf-8 APIs that create new functions: +** +** tdsqlite3_create_function() +** tdsqlite3_create_function_v2() +** tdsqlite3_create_window_function() */ -SQLITE_API int sqlite3_create_function( - sqlite3 *db, - const char *zFunc, - int nArg, - int enc, - void *p, - void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), - void (*xStep)(sqlite3_context*,int,sqlite3_value **), - void (*xFinal)(sqlite3_context*) -){ - return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep, - xFinal, 0); -} - -SQLITE_API int sqlite3_create_function_v2( - sqlite3 *db, +static int createFunctionApi( + tdsqlite3 *db, const char *zFunc, int nArg, int enc, void *p, - void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), - void (*xStep)(sqlite3_context*,int,sqlite3_value **), - void (*xFinal)(sqlite3_context*), - void (*xDestroy)(void *) + void (*xSFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*), + void (*xValue)(tdsqlite3_context*), + void (*xInverse)(tdsqlite3_context*,int,tdsqlite3_value**), + void(*xDestroy)(void*) ){ int rc = SQLITE_ERROR; FuncDestructor *pArg = 0; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); if( xDestroy ){ - pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); + pArg = (FuncDestructor *)tdsqlite3Malloc(sizeof(FuncDestructor)); if( !pArg ){ + tdsqlite3OomFault(db); xDestroy(p); goto out; } + pArg->nRef = 0; pArg->xDestroy = xDestroy; pArg->pUserData = p; } - rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg); + rc = tdsqlite3CreateFunc(db, zFunc, nArg, enc, p, + xSFunc, xStep, xFinal, xValue, xInverse, pArg + ); if( pArg && pArg->nRef==0 ){ assert( rc!=SQLITE_OK ); xDestroy(p); - sqlite3DbFree(db, pArg); + tdsqlite3_free(pArg); } out: - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } +/* +** Create new user functions. +*/ +SQLITE_API int tdsqlite3_create_function( + tdsqlite3 *db, + const char *zFunc, + int nArg, + int enc, + void *p, + void (*xSFunc)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*xFinal)(tdsqlite3_context*) +){ + return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep, + xFinal, 0, 0, 0); +} +SQLITE_API int tdsqlite3_create_function_v2( + tdsqlite3 *db, + const char *zFunc, + int nArg, + int enc, + void *p, + void (*xSFunc)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*xFinal)(tdsqlite3_context*), + void (*xDestroy)(void *) +){ + return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep, + xFinal, 0, 0, xDestroy); +} +SQLITE_API int tdsqlite3_create_window_function( + tdsqlite3 *db, + const char *zFunc, + int nArg, + int enc, + void *p, + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*xFinal)(tdsqlite3_context*), + void (*xValue)(tdsqlite3_context*), + void (*xInverse)(tdsqlite3_context*,int,tdsqlite3_value **), + void (*xDestroy)(void *) +){ + return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep, + xFinal, xValue, xInverse, xDestroy); +} + #ifndef SQLITE_OMIT_UTF16 -SQLITE_API int sqlite3_create_function16( - sqlite3 *db, +SQLITE_API int tdsqlite3_create_function16( + tdsqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *p, - void (*xSFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*) + void (*xSFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*) ){ int rc; char *zFunc8; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); - zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); - rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0); - sqlite3DbFree(db, zFunc8); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + zFunc8 = tdsqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); + rc = tdsqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0); + tdsqlite3DbFree(db, zFunc8); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } #endif /* +** The following is the implementation of an SQL function that always +** fails with an error message stating that the function is used in the +** wrong context. The tdsqlite3_overload_function() API might construct +** SQL function that use this routine so that the functions will exist +** for name resolution but are actually overloaded by the xFindFunction +** method of virtual tables. +*/ +static void tdsqlite3InvalidFunction( + tdsqlite3_context *context, /* The function calling context */ + int NotUsed, /* Number of arguments to the function */ + tdsqlite3_value **NotUsed2 /* Value of each argument */ +){ + const char *zName = (const char*)tdsqlite3_user_data(context); + char *zErr; + UNUSED_PARAMETER2(NotUsed, NotUsed2); + zErr = tdsqlite3_mprintf( + "unable to use function %s in the requested context", zName); + tdsqlite3_result_error(context, zErr, -1); + tdsqlite3_free(zErr); +} + +/* ** Declare that a function has been overloaded by a virtual table. ** ** If the function already exists as a regular global function, then @@ -142740,26 +164702,27 @@ SQLITE_API int sqlite3_create_function16( ** A global function must exist in order for name resolution to work ** properly. */ -SQLITE_API int sqlite3_overload_function( - sqlite3 *db, +SQLITE_API int tdsqlite3_overload_function( + tdsqlite3 *db, const char *zName, int nArg ){ - int rc = SQLITE_OK; + int rc; + char *zCopy; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){ + if( !tdsqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){ return SQLITE_MISUSE_BKPT; } #endif - sqlite3_mutex_enter(db->mutex); - if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){ - rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, - 0, sqlite3InvalidFunction, 0, 0, 0); - } - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; + tdsqlite3_mutex_enter(db->mutex); + rc = tdsqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0; + tdsqlite3_mutex_leave(db->mutex); + if( rc ) return SQLITE_OK; + zCopy = tdsqlite3_mprintf(zName); + if( zCopy==0 ) return SQLITE_NOMEM; + return tdsqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8, + zCopy, tdsqlite3InvalidFunction, 0, 0, tdsqlite3_free); } #ifndef SQLITE_OMIT_TRACE @@ -142772,45 +164735,45 @@ SQLITE_API int sqlite3_overload_function( ** SQL statement. */ #ifndef SQLITE_OMIT_DEPRECATED -SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){ +SQLITE_API void *tdsqlite3_trace(tdsqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){ void *pOld; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); pOld = db->pTraceArg; db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0; db->xTrace = (int(*)(u32,void*,void*,void*))xTrace; db->pTraceArg = pArg; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return pOld; } #endif /* SQLITE_OMIT_DEPRECATED */ /* Register a trace callback using the version-2 interface. */ -SQLITE_API int sqlite3_trace_v2( - sqlite3 *db, /* Trace this connection */ +SQLITE_API int tdsqlite3_trace_v2( + tdsqlite3 *db, /* Trace this connection */ unsigned mTrace, /* Mask of events to be traced */ int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */ void *pArg /* Context */ ){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); if( mTrace==0 ) xTrace = 0; if( xTrace==0 ) mTrace = 0; db->mTrace = mTrace; db->xTrace = xTrace; db->pTraceArg = pArg; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_OK; } @@ -142823,24 +164786,26 @@ SQLITE_API int sqlite3_trace_v2( ** profile is a pointer to a function that is invoked at the conclusion of ** each SQL statement that is run. */ -SQLITE_API void *sqlite3_profile( - sqlite3 *db, +SQLITE_API void *tdsqlite3_profile( + tdsqlite3 *db, void (*xProfile)(void*,const char*,sqlite_uint64), void *pArg ){ void *pOld; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); pOld = db->pProfileArg; db->xProfile = xProfile; db->pProfileArg = pArg; - sqlite3_mutex_leave(db->mutex); + db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK; + if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE; + tdsqlite3_mutex_leave(db->mutex); return pOld; } #endif /* SQLITE_OMIT_DEPRECATED */ @@ -142851,24 +164816,24 @@ SQLITE_API void *sqlite3_profile( ** If the invoked function returns non-zero, then the commit becomes a ** rollback. */ -SQLITE_API void *sqlite3_commit_hook( - sqlite3 *db, /* Attach the hook to this database */ +SQLITE_API void *tdsqlite3_commit_hook( + tdsqlite3 *db, /* Attach the hook to this database */ int (*xCallback)(void*), /* Function to invoke on each commit */ void *pArg /* Argument to the function */ ){ void *pOld; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); pOld = db->pCommitArg; db->xCommitCallback = xCallback; db->pCommitArg = pArg; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return pOld; } @@ -142876,24 +164841,24 @@ SQLITE_API void *sqlite3_commit_hook( ** Register a callback to be invoked each time a row is updated, ** inserted or deleted using this database connection. */ -SQLITE_API void *sqlite3_update_hook( - sqlite3 *db, /* Attach the hook to this database */ +SQLITE_API void *tdsqlite3_update_hook( + tdsqlite3 *db, /* Attach the hook to this database */ void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), void *pArg /* Argument to the function */ ){ void *pRet; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); pRet = db->pUpdateArg; db->xUpdateCallback = xCallback; db->pUpdateArg = pArg; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return pRet; } @@ -142901,24 +164866,24 @@ SQLITE_API void *sqlite3_update_hook( ** Register a callback to be invoked each time a transaction is rolled ** back by this database connection. */ -SQLITE_API void *sqlite3_rollback_hook( - sqlite3 *db, /* Attach the hook to this database */ +SQLITE_API void *tdsqlite3_rollback_hook( + tdsqlite3 *db, /* Attach the hook to this database */ void (*xCallback)(void*), /* Callback function */ void *pArg /* Argument to the function */ ){ void *pRet; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); pRet = db->pRollbackArg; db->xRollbackCallback = xCallback; db->pRollbackArg = pArg; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return pRet; } @@ -142927,67 +164892,67 @@ SQLITE_API void *sqlite3_rollback_hook( ** Register a callback to be invoked each time a row is updated, ** inserted or deleted using this database connection. */ -SQLITE_API void *sqlite3_preupdate_hook( - sqlite3 *db, /* Attach the hook to this database */ +SQLITE_API void *tdsqlite3_preupdate_hook( + tdsqlite3 *db, /* Attach the hook to this database */ void(*xCallback)( /* Callback function */ - void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64), + void*,tdsqlite3*,int,char const*,char const*,tdsqlite3_int64,tdsqlite3_int64), void *pArg /* First callback argument */ ){ void *pRet; - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); pRet = db->pPreUpdateArg; db->xPreUpdateCallback = xCallback; db->pPreUpdateArg = pArg; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return pRet; } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ #ifndef SQLITE_OMIT_WAL /* -** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). -** Invoke sqlite3_wal_checkpoint if the number of frames in the log file +** The tdsqlite3_wal_hook() callback registered by tdsqlite3_wal_autocheckpoint(). +** Invoke tdsqlite3_wal_checkpoint if the number of frames in the log file ** is greater than sqlite3.pWalArg cast to an integer (the value configured by ** wal_autocheckpoint()). */ -SQLITE_PRIVATE int sqlite3WalDefaultHook( +SQLITE_PRIVATE int tdsqlite3WalDefaultHook( void *pClientData, /* Argument */ - sqlite3 *db, /* Connection */ + tdsqlite3 *db, /* Connection */ const char *zDb, /* Database */ int nFrame /* Size of WAL */ ){ if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ - sqlite3BeginBenignMalloc(); - sqlite3_wal_checkpoint(db, zDb); - sqlite3EndBenignMalloc(); + tdsqlite3BeginBenignMalloc(); + tdsqlite3_wal_checkpoint(db, zDb); + tdsqlite3EndBenignMalloc(); } return SQLITE_OK; } #endif /* SQLITE_OMIT_WAL */ /* -** Configure an sqlite3_wal_hook() callback to automatically checkpoint +** Configure an tdsqlite3_wal_hook() callback to automatically checkpoint ** a database after committing a transaction if there are nFrame or ** more frames in the log file. Passing zero or a negative value as the ** nFrame parameter disables automatic checkpoints entirely. ** ** The callback registered by this function replaces any existing callback -** registered using sqlite3_wal_hook(). Likewise, registering a callback -** using sqlite3_wal_hook() disables the automatic checkpoint mechanism +** registered using tdsqlite3_wal_hook(). Likewise, registering a callback +** using tdsqlite3_wal_hook() disables the automatic checkpoint mechanism ** configured by this function. */ -SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ +SQLITE_API int tdsqlite3_wal_autocheckpoint(tdsqlite3 *db, int nFrame){ #ifdef SQLITE_OMIT_WAL UNUSED_PARAMETER(db); UNUSED_PARAMETER(nFrame); #else #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif if( nFrame>0 ){ - sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); + tdsqlite3_wal_hook(db, tdsqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); }else{ - sqlite3_wal_hook(db, 0, 0); + tdsqlite3_wal_hook(db, 0, 0); } #endif return SQLITE_OK; @@ -142997,24 +164962,24 @@ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ ** Register a callback to be invoked each time a transaction is written ** into the write-ahead-log by this database connection. */ -SQLITE_API void *sqlite3_wal_hook( - sqlite3 *db, /* Attach the hook to this db handle */ - int(*xCallback)(void *, sqlite3*, const char*, int), +SQLITE_API void *tdsqlite3_wal_hook( + tdsqlite3 *db, /* Attach the hook to this db handle */ + int(*xCallback)(void *, tdsqlite3*, const char*, int), void *pArg /* First argument passed to xCallback() */ ){ #ifndef SQLITE_OMIT_WAL void *pRet; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); pRet = db->pWalArg; db->xWalCallback = xCallback; db->pWalArg = pArg; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return pRet; #else return 0; @@ -143024,8 +164989,8 @@ SQLITE_API void *sqlite3_wal_hook( /* ** Checkpoint database zDb. */ -SQLITE_API int sqlite3_wal_checkpoint_v2( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_wal_checkpoint_v2( + tdsqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ @@ -143038,7 +165003,7 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif /* Initialize the output variables to -1 in case an error occurs. */ @@ -143055,20 +165020,27 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( return SQLITE_MISUSE; } - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); if( zDb && zDb[0] ){ - iDb = sqlite3FindDbName(db, zDb); + iDb = tdsqlite3FindDbName(db, zDb); } if( iDb<0 ){ rc = SQLITE_ERROR; - sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb); + tdsqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb); }else{ db->busyHandler.nBusy = 0; - rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); - sqlite3Error(db, rc); + rc = tdsqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); + tdsqlite3Error(db, rc); } - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + rc = tdsqlite3ApiExit(db, rc); + + /* If there are no active statements, clear the interrupt flag at this + ** point. */ + if( db->nVdbeActive==0 ){ + db->u1.isInterrupted = 0; + } + + tdsqlite3_mutex_leave(db->mutex); return rc; #endif } @@ -143079,10 +165051,10 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( ** to contains a zero-length string, all attached databases are ** checkpointed. */ -SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ - /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to - ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */ - return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0); +SQLITE_API int tdsqlite3_wal_checkpoint(tdsqlite3 *db, const char *zDb){ + /* EVIDENCE-OF: R-41613-20553 The tdsqlite3_wal_checkpoint(D,X) is equivalent to + ** tdsqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */ + return tdsqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0); } #ifndef SQLITE_OMIT_WAL @@ -143103,20 +165075,21 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ ** checkpointed. If an error is encountered it is returned immediately - ** no attempt is made to checkpoint any remaining databases. ** -** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. +** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART +** or TRUNCATE. */ -SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ +SQLITE_PRIVATE int tdsqlite3Checkpoint(tdsqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ int rc = SQLITE_OK; /* Return code */ int i; /* Used to iterate through attached dbs */ int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); assert( !pnLog || *pnLog==-1 ); assert( !pnCkpt || *pnCkpt==-1 ); for(i=0; i<db->nDb && rc==SQLITE_OK; i++){ if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ - rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); + rc = tdsqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); pnLog = 0; pnCkpt = 0; if( rc==SQLITE_BUSY ){ @@ -143149,7 +165122,7 @@ SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog ** 2 0 memory (return 1) ** 3 any memory (return 1) */ -SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){ +SQLITE_PRIVATE int tdsqlite3TempInMemory(const tdsqlite3 *db){ #if SQLITE_TEMP_STORE==1 return ( db->temp_store==2 ); #endif @@ -143170,26 +165143,26 @@ SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){ ** Return UTF-8 encoded English language explanation of the most recent ** error. */ -SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ +SQLITE_API const char *tdsqlite3_errmsg(tdsqlite3 *db){ const char *z; if( !db ){ - return sqlite3ErrStr(SQLITE_NOMEM_BKPT); + return tdsqlite3ErrStr(SQLITE_NOMEM_BKPT); } - if( !sqlite3SafetyCheckSickOrOk(db) ){ - return sqlite3ErrStr(SQLITE_MISUSE_BKPT); + if( !tdsqlite3SafetyCheckSickOrOk(db) ){ + return tdsqlite3ErrStr(SQLITE_MISUSE_BKPT); } - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); if( db->mallocFailed ){ - z = sqlite3ErrStr(SQLITE_NOMEM_BKPT); + z = tdsqlite3ErrStr(SQLITE_NOMEM_BKPT); }else{ testcase( db->pErr==0 ); - z = (char*)sqlite3_value_text(db->pErr); + z = db->errCode ? (char*)tdsqlite3_value_text(db->pErr) : 0; assert( !db->mallocFailed ); if( z==0 ){ - z = sqlite3ErrStr(db->errCode); + z = tdsqlite3ErrStr(db->errCode); } } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return z; } @@ -143198,53 +165171,50 @@ SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ ** Return UTF-16 encoded English language explanation of the most recent ** error. */ -SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ +SQLITE_API const void *tdsqlite3_errmsg16(tdsqlite3 *db){ static const u16 outOfMem[] = { 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 }; static const u16 misuse[] = { - 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', - 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', - 'c', 'a', 'l', 'l', 'e', 'd', ' ', - 'o', 'u', 't', ' ', - 'o', 'f', ' ', - 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 + 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ', + 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ', + 'm', 'i', 's', 'u', 's', 'e', 0 }; const void *z; if( !db ){ return (void *)outOfMem; } - if( !sqlite3SafetyCheckSickOrOk(db) ){ + if( !tdsqlite3SafetyCheckSickOrOk(db) ){ return (void *)misuse; } - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); if( db->mallocFailed ){ z = (void *)outOfMem; }else{ - z = sqlite3_value_text16(db->pErr); + z = tdsqlite3_value_text16(db->pErr); if( z==0 ){ - sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode)); - z = sqlite3_value_text16(db->pErr); + tdsqlite3ErrorWithMsg(db, db->errCode, tdsqlite3ErrStr(db->errCode)); + z = tdsqlite3_value_text16(db->pErr); } - /* A malloc() may have failed within the call to sqlite3_value_text16() + /* A malloc() may have failed within the call to tdsqlite3_value_text16() ** above. If this is the case, then the db->mallocFailed flag needs to ** be cleared before returning. Do this directly, instead of via - ** sqlite3ApiExit(), to avoid setting the database handle error message. + ** tdsqlite3ApiExit(), to avoid setting the database handle error message. */ - sqlite3OomClear(db); + tdsqlite3OomClear(db); } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return z; } #endif /* SQLITE_OMIT_UTF16 */ /* ** Return the most recent error code generated by an SQLite routine. If NULL is -** passed to this function, we assume a malloc() failed during sqlite3_open(). +** passed to this function, we assume a malloc() failed during tdsqlite3_open(). */ -SQLITE_API int sqlite3_errcode(sqlite3 *db){ - if( db && !sqlite3SafetyCheckSickOrOk(db) ){ +SQLITE_API int tdsqlite3_errcode(tdsqlite3 *db){ + if( db && !tdsqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } if( !db || db->mallocFailed ){ @@ -143252,8 +165222,8 @@ SQLITE_API int sqlite3_errcode(sqlite3 *db){ } return db->errCode & db->errMask; } -SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){ - if( db && !sqlite3SafetyCheckSickOrOk(db) ){ +SQLITE_API int tdsqlite3_extended_errcode(tdsqlite3 *db){ + if( db && !tdsqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } if( !db || db->mallocFailed ){ @@ -143261,17 +165231,17 @@ SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){ } return db->errCode; } -SQLITE_API int sqlite3_system_errno(sqlite3 *db){ +SQLITE_API int tdsqlite3_system_errno(tdsqlite3 *db){ return db ? db->iSysErrno : 0; } /* ** Return a string that describes the kind of error specified in the -** argument. For now, this simply calls the internal sqlite3ErrStr() +** argument. For now, this simply calls the internal tdsqlite3ErrStr() ** function. */ -SQLITE_API const char *sqlite3_errstr(int rc){ - return sqlite3ErrStr(rc); +SQLITE_API const char *tdsqlite3_errstr(int rc){ + return tdsqlite3ErrStr(rc); } /* @@ -143279,7 +165249,7 @@ SQLITE_API const char *sqlite3_errstr(int rc){ ** and the encoding is enc. */ static int createCollation( - sqlite3* db, + tdsqlite3* db, const char *zName, u8 enc, void* pCtx, @@ -143289,7 +165259,7 @@ static int createCollation( CollSeq *pColl; int enc2; - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); /* If SQLITE_UTF16 is specified as the encoding type, transform this ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the @@ -143309,23 +165279,23 @@ static int createCollation( ** sequence. If so, and there are active VMs, return busy. If there ** are no active VMs, invalidate any pre-compiled statements. */ - pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); + pColl = tdsqlite3FindCollSeq(db, (u8)enc2, zName, 0); if( pColl && pColl->xCmp ){ if( db->nVdbeActive ){ - sqlite3ErrorWithMsg(db, SQLITE_BUSY, + tdsqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to delete/modify collation sequence due to active statements"); return SQLITE_BUSY; } - sqlite3ExpirePreparedStatements(db); + tdsqlite3ExpirePreparedStatements(db, 0); /* If collation sequence pColl was created directly by a call to - ** sqlite3_create_collation, and not generated by synthCollSeq(), + ** tdsqlite3_create_collation, and not generated by synthCollSeq(), ** then any copies made by synthCollSeq() need to be invalidated. ** Also, collation destructor - CollSeq.xDel() - function may need ** to be called. */ if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ - CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName); + CollSeq *aColl = tdsqlite3HashFind(&db->aCollSeq, zName); int j; for(j=0; j<3; j++){ CollSeq *p = &aColl[j]; @@ -143339,13 +165309,13 @@ static int createCollation( } } - pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); + pColl = tdsqlite3FindCollSeq(db, (u8)enc2, zName, 1); if( pColl==0 ) return SQLITE_NOMEM_BKPT; pColl->xCmp = xCompare; pColl->pUser = pCtx; pColl->xDel = xDel; pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); - sqlite3Error(db, SQLITE_OK); + tdsqlite3Error(db, SQLITE_OK); return SQLITE_OK; } @@ -143418,11 +165388,11 @@ static const int aHardLimit[] = { ** It merely prevents new constructs that exceed the limit ** from forming. */ -SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ +SQLITE_API int tdsqlite3_limit(tdsqlite3 *db, int limitId, int newLimit){ int oldLimit; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return -1; } @@ -143464,7 +165434,7 @@ SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ /* ** This function is used to parse both URIs and non-URI filenames passed by the -** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database +** user to API functions tdsqlite3_open() or tdsqlite3_open_v2(), and for database ** URIs specified as part of ATTACH statements. ** ** The first argument to this function is the name of the VFS to use (or @@ -143478,19 +165448,19 @@ SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to ** the VFS that should be used to open the database file. *pzFile is set to ** point to a buffer containing the name of the file to open. It is the -** responsibility of the caller to eventually call sqlite3_free() to release +** responsibility of the caller to eventually call tdsqlite3_free() to release ** this buffer. ** ** If an error occurs, then an SQLite error code is returned and *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to eventually release -** this buffer by calling sqlite3_free(). +** this buffer by calling tdsqlite3_free(). */ -SQLITE_PRIVATE int sqlite3ParseUri( +SQLITE_PRIVATE int tdsqlite3ParseUri( const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ const char *zUri, /* Nul-terminated URI to parse */ unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ - sqlite3_vfs **ppVfs, /* OUT: VFS to use */ + tdsqlite3_vfs **ppVfs, /* OUT: VFS to use */ char **pzFile, /* OUT: Filename component of URI */ char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ ){ @@ -143499,12 +165469,12 @@ SQLITE_PRIVATE int sqlite3ParseUri( const char *zVfs = zDefaultVfs; char *zFile; char c; - int nUri = sqlite3Strlen30(zUri); + int nUri = tdsqlite3Strlen30(zUri); assert( *pzErrMsg==0 ); if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */ - || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */ + || tdsqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */ && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */ ){ char *zOpt; @@ -143518,7 +165488,7 @@ SQLITE_PRIVATE int sqlite3ParseUri( flags |= SQLITE_OPEN_URI; for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&'); - zFile = sqlite3_malloc64(nByte); + zFile = tdsqlite3_malloc64(nByte); if( !zFile ) return SQLITE_NOMEM_BKPT; iIn = 5; @@ -143540,7 +165510,7 @@ SQLITE_PRIVATE int sqlite3ParseUri( iIn = 7; while( zUri[iIn] && zUri[iIn]!='/' ) iIn++; if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){ - *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", + *pzErrMsg = tdsqlite3_mprintf("invalid uri authority: %.*s", iIn-7, &zUri[7]); rc = SQLITE_ERROR; goto parse_uri_out; @@ -143562,14 +165532,15 @@ SQLITE_PRIVATE int sqlite3ParseUri( while( (c = zUri[iIn])!=0 && c!='#' ){ iIn++; if( c=='%' - && sqlite3Isxdigit(zUri[iIn]) - && sqlite3Isxdigit(zUri[iIn+1]) + && tdsqlite3Isxdigit(zUri[iIn]) + && tdsqlite3Isxdigit(zUri[iIn+1]) ){ - int octet = (sqlite3HexToInt(zUri[iIn++]) << 4); - octet += sqlite3HexToInt(zUri[iIn++]); + int octet = (tdsqlite3HexToInt(zUri[iIn++]) << 4); + octet += tdsqlite3HexToInt(zUri[iIn++]); assert( octet>=0 && octet<256 ); if( octet==0 ){ +#ifndef SQLITE_ENABLE_URI_00_ERROR /* This branch is taken when "%00" appears within the URI. In this ** case we ignore all text in the remainder of the path, name or ** value currently being parsed. So ignore the current character @@ -143582,6 +165553,12 @@ SQLITE_PRIVATE int sqlite3ParseUri( iIn++; } continue; +#else + /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */ + *pzErrMsg = tdsqlite3_mprintf("unexpected %%00 in uri"); + rc = SQLITE_ERROR; + goto parse_uri_out; +#endif } c = octet; }else if( eState==1 && (c=='&' || c=='=') ){ @@ -143608,13 +165585,13 @@ SQLITE_PRIVATE int sqlite3ParseUri( /* Check if there were any options specified that should be interpreted ** here. Options that are interpreted here include "vfs" and those that - ** correspond to flags that may be passed to the sqlite3_open_v2() + ** correspond to flags that may be passed to the tdsqlite3_open_v2() ** method. */ - zOpt = &zFile[sqlite3Strlen30(zFile)+1]; + zOpt = &zFile[tdsqlite3Strlen30(zFile)+1]; while( zOpt[0] ){ - int nOpt = sqlite3Strlen30(zOpt); + int nOpt = tdsqlite3Strlen30(zOpt); char *zVal = &zOpt[nOpt+1]; - int nVal = sqlite3Strlen30(zVal); + int nVal = tdsqlite3Strlen30(zVal); if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ zVfs = zVal; @@ -143660,18 +165637,18 @@ SQLITE_PRIVATE int sqlite3ParseUri( int mode = 0; for(i=0; aMode[i].z; i++){ const char *z = aMode[i].z; - if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ + if( nVal==tdsqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ mode = aMode[i].mode; break; } } if( mode==0 ){ - *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); + *pzErrMsg = tdsqlite3_mprintf("no such %s mode: %s", zModeType, zVal); rc = SQLITE_ERROR; goto parse_uri_out; } if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ - *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", + *pzErrMsg = tdsqlite3_mprintf("%s mode not allowed: %s", zModeType, zVal); rc = SQLITE_PERM; goto parse_uri_out; @@ -143684,22 +165661,24 @@ SQLITE_PRIVATE int sqlite3ParseUri( } }else{ - zFile = sqlite3_malloc64(nUri+2); + zFile = tdsqlite3_malloc64(nUri+2); if( !zFile ) return SQLITE_NOMEM_BKPT; - memcpy(zFile, zUri, nUri); + if( nUri ){ + memcpy(zFile, zUri, nUri); + } zFile[nUri] = '\0'; zFile[nUri+1] = '\0'; flags &= ~SQLITE_OPEN_URI; } - *ppVfs = sqlite3_vfs_find(zVfs); + *ppVfs = tdsqlite3_vfs_find(zVfs); if( *ppVfs==0 ){ - *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); + *pzErrMsg = tdsqlite3_mprintf("no such vfs: %s", zVfs); rc = SQLITE_ERROR; } parse_uri_out: if( rc!=SQLITE_OK ){ - sqlite3_free(zFile); + tdsqlite3_free(zFile); zFile = 0; } *pFlags = flags; @@ -143707,65 +165686,80 @@ SQLITE_PRIVATE int sqlite3ParseUri( return rc; } +#if defined(SQLITE_HAS_CODEC) +/* +** Process URI filename query parameters relevant to the SQLite Encryption +** Extension. Return true if any of the relevant query parameters are +** seen and return false if not. +*/ +SQLITE_PRIVATE int tdsqlite3CodecQueryParameters( + tdsqlite3 *db, /* Database connection */ + const char *zDb, /* Which schema is being created/attached */ + const char *zUri /* URI filename */ +){ + const char *zKey; + if( (zKey = tdsqlite3_uri_parameter(zUri, "hexkey"))!=0 && zKey[0] ){ + u8 iByte; + int i; + char zDecoded[40]; + for(i=0, iByte=0; i<sizeof(zDecoded)*2 && tdsqlite3Isxdigit(zKey[i]); i++){ + iByte = (iByte<<4) + tdsqlite3HexToInt(zKey[i]); + if( (i&1)!=0 ) zDecoded[i/2] = iByte; + } + tdsqlite3_key_v2(db, zDb, zDecoded, i/2); + return 1; + }else if( (zKey = tdsqlite3_uri_parameter(zUri, "key"))!=0 ){ + tdsqlite3_key_v2(db, zDb, zKey, tdsqlite3Strlen30(zKey)); + return 1; + }else if( (zKey = tdsqlite3_uri_parameter(zUri, "textkey"))!=0 ){ + tdsqlite3_key_v2(db, zDb, zKey, -1); + return 1; + }else{ + return 0; + } +} +#endif + /* ** This routine does the work of opening a database on behalf of -** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" +** tdsqlite3_open() and tdsqlite3_open16(). The database filename "zFilename" ** is UTF-8 encoded. */ static int openDatabase( const char *zFilename, /* Database filename UTF-8 encoded */ - sqlite3 **ppDb, /* OUT: Returned database handle */ + tdsqlite3 **ppDb, /* OUT: Returned database handle */ unsigned int flags, /* Operational flags */ const char *zVfs /* Name of the VFS to use */ ){ - sqlite3 *db; /* Store allocated handle here */ + tdsqlite3 *db; /* Store allocated handle here */ int rc; /* Return code */ int isThreadsafe; /* True for threadsafe connections */ char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ - char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ + char *zErrMsg = 0; /* Error message from tdsqlite3ParseUri() */ #ifdef SQLITE_ENABLE_API_ARMOR if( ppDb==0 ) return SQLITE_MISUSE_BKPT; #endif *ppDb = 0; #ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); + rc = tdsqlite3_initialize(); if( rc ) return rc; #endif - /* Only allow sensible combinations of bits in the flags argument. - ** Throw an error if any non-sense combination is used. If we - ** do not block illegal combinations here, it could trigger - ** assert() statements in deeper layers. Sensible combinations - ** are: - ** - ** 1: SQLITE_OPEN_READONLY - ** 2: SQLITE_OPEN_READWRITE - ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE - */ - assert( SQLITE_OPEN_READONLY == 0x01 ); - assert( SQLITE_OPEN_READWRITE == 0x02 ); - assert( SQLITE_OPEN_CREATE == 0x04 ); - testcase( (1<<(flags&7))==0x02 ); /* READONLY */ - testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ - testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ - if( ((1<<(flags&7)) & 0x46)==0 ){ - return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */ - } - - if( sqlite3GlobalConfig.bCoreMutex==0 ){ + if( tdsqlite3GlobalConfig.bCoreMutex==0 ){ isThreadsafe = 0; }else if( flags & SQLITE_OPEN_NOMUTEX ){ isThreadsafe = 0; }else if( flags & SQLITE_OPEN_FULLMUTEX ){ isThreadsafe = 1; }else{ - isThreadsafe = sqlite3GlobalConfig.bFullMutex; + isThreadsafe = tdsqlite3GlobalConfig.bFullMutex; } + if( flags & SQLITE_OPEN_PRIVATECACHE ){ flags &= ~SQLITE_OPEN_SHAREDCACHE; - }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ + }else if( tdsqlite3GlobalConfig.sharedCacheEnabled ){ flags |= SQLITE_OPEN_SHAREDCACHE; } @@ -143773,7 +165767,7 @@ static int openDatabase( ** ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were ** dealt with in the previous code block. Besides these, the only - ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, + ** valid input flags for tdsqlite3_open_v2() are SQLITE_OPEN_READONLY, ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask ** off all other flags. @@ -143793,31 +165787,71 @@ static int openDatabase( ); /* Allocate the sqlite data structure */ - db = sqlite3MallocZero( sizeof(sqlite3) ); + db = tdsqlite3MallocZero( sizeof(tdsqlite3) ); if( db==0 ) goto opendb_out; - if( isThreadsafe ){ - db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); + if( isThreadsafe +#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS + || tdsqlite3GlobalConfig.bCoreMutex +#endif + ){ + db->mutex = tdsqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); if( db->mutex==0 ){ - sqlite3_free(db); + tdsqlite3_free(db); db = 0; goto opendb_out; } + if( isThreadsafe==0 ){ + tdsqlite3MutexWarnOnContention(db->mutex); + } } - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); db->errMask = 0xff; db->nDb = 2; db->magic = SQLITE_MAGIC_BUSY; db->aDb = db->aDbStatic; + db->lookaside.bDisable = 1; + db->lookaside.sz = 0; assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS; db->autoCommit = 1; db->nextAutovac = -1; - db->szMmap = sqlite3GlobalConfig.szMmap; + db->szMmap = tdsqlite3GlobalConfig.szMmap; db->nextPagesize = 0; db->nMaxSorterMmap = 0x7FFFFFFF; - db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill + db->flags |= SQLITE_ShortColNames + | SQLITE_EnableTrigger + | SQLITE_EnableView + | SQLITE_CacheSpill +#if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0 + | SQLITE_TrustedSchema +#endif +/* The SQLITE_DQS compile-time option determines the default settings +** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML. +** +** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML +** ---------- ----------------------- ----------------------- +** undefined on on +** 3 on on +** 2 on off +** 1 off on +** 0 off off +** +** Legacy behavior is 3 (double-quoted string literals are allowed anywhere) +** and so that is the default. But developers are encouranged to use +** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible. +*/ +#if !defined(SQLITE_DQS) +# define SQLITE_DQS 3 +#endif +#if (SQLITE_DQS&1)==1 + | SQLITE_DqsDML +#endif +#if (SQLITE_DQS&2)==2 + | SQLITE_DqsDDL +#endif + #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX | SQLITE_AutoIndex #endif @@ -143845,10 +165879,16 @@ static int openDatabase( #if defined(SQLITE_ENABLE_FTS3_TOKENIZER) | SQLITE_Fts3Tokenizer #endif +#if defined(SQLITE_ENABLE_QPSG) + | SQLITE_EnableQPSG +#endif +#if defined(SQLITE_DEFAULT_DEFENSIVE) + | SQLITE_Defensive +#endif ; - sqlite3HashInit(&db->aCollSeq); + tdsqlite3HashInit(&db->aCollSeq); #ifndef SQLITE_OMIT_VIRTUALTABLE - sqlite3HashInit(&db->aModule); + tdsqlite3HashInit(&db->aModule); #endif /* Add the default collation sequence BINARY. BINARY works for both UTF-8 @@ -143858,45 +165898,66 @@ static int openDatabase( ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating ** functions: */ - createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0); - createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0); - createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0); + createCollation(db, tdsqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0); + createCollation(db, tdsqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0); + createCollation(db, tdsqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0); createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); - createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); + createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0); if( db->mallocFailed ){ goto opendb_out; } /* EVIDENCE-OF: R-08308-17224 The default collating function for all ** strings is BINARY. */ - db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0); + db->pDfltColl = tdsqlite3FindCollSeq(db, SQLITE_UTF8, tdsqlite3StrBINARY, 0); assert( db->pDfltColl!=0 ); - /* Parse the filename/URI argument. */ + /* Parse the filename/URI argument + ** + ** Only allow sensible combinations of bits in the flags argument. + ** Throw an error if any non-sense combination is used. If we + ** do not block illegal combinations here, it could trigger + ** assert() statements in deeper layers. Sensible combinations + ** are: + ** + ** 1: SQLITE_OPEN_READONLY + ** 2: SQLITE_OPEN_READWRITE + ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE + */ db->openFlags = flags; - rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); + assert( SQLITE_OPEN_READONLY == 0x01 ); + assert( SQLITE_OPEN_READWRITE == 0x02 ); + assert( SQLITE_OPEN_CREATE == 0x04 ); + testcase( (1<<(flags&7))==0x02 ); /* READONLY */ + testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ + testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ + if( ((1<<(flags&7)) & 0x46)==0 ){ + rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */ + }else{ + rc = tdsqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); + } if( rc!=SQLITE_OK ){ - if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); - sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg); - sqlite3_free(zErrMsg); + if( rc==SQLITE_NOMEM ) tdsqlite3OomFault(db); + tdsqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg); + tdsqlite3_free(zErrMsg); goto opendb_out; } /* Open the backend database driver */ - rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, + rc = tdsqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, flags | SQLITE_OPEN_MAIN_DB); if( rc!=SQLITE_OK ){ if( rc==SQLITE_IOERR_NOMEM ){ rc = SQLITE_NOMEM_BKPT; } - sqlite3Error(db, rc); + tdsqlite3Error(db, rc); goto opendb_out; } - sqlite3BtreeEnter(db->aDb[0].pBt); - db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); + tdsqlite3BtreeEnter(db->aDb[0].pBt); + db->aDb[0].pSchema = tdsqlite3SchemaGet(db, db->aDb[0].pBt); if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db); - sqlite3BtreeLeave(db->aDb[0].pBt); - db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); + tdsqlite3BtreeLeave(db->aDb[0].pBt); + db->aDb[1].pSchema = tdsqlite3SchemaGet(db, 0); /* The default safety_level for the main database is FULL; for the temp ** database it is OFF. This matches the pager layer defaults. @@ -143915,25 +165976,25 @@ static int openDatabase( ** database schema yet. This is delayed until the first time the database ** is accessed. */ - sqlite3Error(db, SQLITE_OK); - sqlite3RegisterPerConnectionBuiltinFunctions(db); - rc = sqlite3_errcode(db); + tdsqlite3Error(db, SQLITE_OK); + tdsqlite3RegisterPerConnectionBuiltinFunctions(db); + rc = tdsqlite3_errcode(db); #ifdef SQLITE_ENABLE_FTS5 /* Register any built-in FTS5 module before loading the automatic ** extensions. This allows automatic extensions to register FTS5 ** tokenizers and auxiliary functions. */ if( !db->mallocFailed && rc==SQLITE_OK ){ - rc = sqlite3Fts5Init(db); + rc = tdsqlite3Fts5Init(db); } #endif /* Load automatic extensions - extensions that have been registered - ** using the sqlite3_automatic_extension() API. + ** using the tdsqlite3_automatic_extension() API. */ if( rc==SQLITE_OK ){ - sqlite3AutoLoadExtensions(db); - rc = sqlite3_errcode(db); + tdsqlite3AutoLoadExtensions(db); + rc = tdsqlite3_errcode(db); if( rc!=SQLITE_OK ){ goto opendb_out; } @@ -143941,120 +166002,135 @@ static int openDatabase( #ifdef SQLITE_ENABLE_FTS1 if( !db->mallocFailed ){ - extern int sqlite3Fts1Init(sqlite3*); - rc = sqlite3Fts1Init(db); + extern int tdsqlite3Fts1Init(tdsqlite3*); + rc = tdsqlite3Fts1Init(db); } #endif #ifdef SQLITE_ENABLE_FTS2 if( !db->mallocFailed && rc==SQLITE_OK ){ - extern int sqlite3Fts2Init(sqlite3*); - rc = sqlite3Fts2Init(db); + extern int tdsqlite3Fts2Init(tdsqlite3*); + rc = tdsqlite3Fts2Init(db); } #endif #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */ if( !db->mallocFailed && rc==SQLITE_OK ){ - rc = sqlite3Fts3Init(db); + rc = tdsqlite3Fts3Init(db); } #endif -#ifdef SQLITE_ENABLE_ICU +#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS) if( !db->mallocFailed && rc==SQLITE_OK ){ - rc = sqlite3IcuInit(db); + rc = tdsqlite3IcuInit(db); } #endif #ifdef SQLITE_ENABLE_RTREE if( !db->mallocFailed && rc==SQLITE_OK){ - rc = sqlite3RtreeInit(db); + rc = tdsqlite3RtreeInit(db); + } +#endif + +#ifdef SQLITE_ENABLE_DBPAGE_VTAB + if( !db->mallocFailed && rc==SQLITE_OK){ + rc = tdsqlite3DbpageRegister(db); } #endif #ifdef SQLITE_ENABLE_DBSTAT_VTAB if( !db->mallocFailed && rc==SQLITE_OK){ - rc = sqlite3DbstatRegister(db); + rc = tdsqlite3DbstatRegister(db); } #endif #ifdef SQLITE_ENABLE_JSON1 if( !db->mallocFailed && rc==SQLITE_OK){ - rc = sqlite3Json1Init(db); + rc = tdsqlite3Json1Init(db); + } +#endif + +#ifdef SQLITE_ENABLE_STMTVTAB + if( !db->mallocFailed && rc==SQLITE_OK){ + rc = tdsqlite3StmtVtabInit(db); + } +#endif + +#ifdef SQLCIPHER_EXT + if( !db->mallocFailed && rc==SQLITE_OK ){ + extern int sqlcipherVtabInit(tdsqlite3 *); + rc = sqlcipherVtabInit(db); } #endif +#ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS + /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time + ** option gives access to internal functions by default. + ** Testing use only!!! */ + db->mDbFlags |= DBFLAG_InternalFunc; +#endif + /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking ** mode. Doing nothing at all also makes NORMAL the default. */ #ifdef SQLITE_DEFAULT_LOCKING_MODE db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; - sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), + tdsqlite3PagerLockingMode(tdsqlite3BtreePager(db->aDb[0].pBt), SQLITE_DEFAULT_LOCKING_MODE); #endif - if( rc ) sqlite3Error(db, rc); + if( rc ) tdsqlite3Error(db, rc); /* Enable the lookaside-malloc subsystem */ - setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, - sqlite3GlobalConfig.nLookaside); + setupLookaside(db, 0, tdsqlite3GlobalConfig.szLookaside, + tdsqlite3GlobalConfig.nLookaside); - sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); + tdsqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); opendb_out: if( db ){ assert( db->mutex!=0 || isThreadsafe==0 - || sqlite3GlobalConfig.bFullMutex==0 ); - sqlite3_mutex_leave(db->mutex); + || tdsqlite3GlobalConfig.bFullMutex==0 ); + tdsqlite3_mutex_leave(db->mutex); } - rc = sqlite3_errcode(db); + rc = tdsqlite3_errcode(db); assert( db!=0 || rc==SQLITE_NOMEM ); if( rc==SQLITE_NOMEM ){ - sqlite3_close(db); + tdsqlite3_close(db); db = 0; }else if( rc!=SQLITE_OK ){ db->magic = SQLITE_MAGIC_SICK; } *ppDb = db; #ifdef SQLITE_ENABLE_SQLLOG - if( sqlite3GlobalConfig.xSqllog ){ + if( tdsqlite3GlobalConfig.xSqllog ){ /* Opening a db handle. Fourth parameter is passed 0. */ - void *pArg = sqlite3GlobalConfig.pSqllogArg; - sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); + void *pArg = tdsqlite3GlobalConfig.pSqllogArg; + tdsqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); } #endif #if defined(SQLITE_HAS_CODEC) - if( rc==SQLITE_OK ){ - const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey"); - if( zHexKey && zHexKey[0] ){ - u8 iByte; - int i; - char zKey[40]; - for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){ - iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]); - if( (i&1)!=0 ) zKey[i/2] = iByte; - } - sqlite3_key_v2(db, 0, zKey, i/2); - } - } + if( rc==SQLITE_OK ) tdsqlite3CodecQueryParameters(db, 0, zOpen); #endif - sqlite3_free(zOpen); + tdsqlite3_free(zOpen); return rc & 0xff; } + /* ** Open a new database handle. */ -SQLITE_API int sqlite3_open( +SQLITE_API int tdsqlite3_open( const char *zFilename, - sqlite3 **ppDb + tdsqlite3 **ppDb ){ return openDatabase(zFilename, ppDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); } -SQLITE_API int sqlite3_open_v2( +SQLITE_API int tdsqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ - sqlite3 **ppDb, /* OUT: SQLite db handle */ + tdsqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ){ @@ -144065,12 +166141,12 @@ SQLITE_API int sqlite3_open_v2( /* ** Open a new database handle. */ -SQLITE_API int sqlite3_open16( +SQLITE_API int tdsqlite3_open16( const void *zFilename, - sqlite3 **ppDb + tdsqlite3 **ppDb ){ char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ - sqlite3_value *pVal; + tdsqlite3_value *pVal; int rc; #ifdef SQLITE_ENABLE_API_ARMOR @@ -144078,13 +166154,13 @@ SQLITE_API int sqlite3_open16( #endif *ppDb = 0; #ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); + rc = tdsqlite3_initialize(); if( rc ) return rc; #endif if( zFilename==0 ) zFilename = "\000\000"; - pVal = sqlite3ValueNew(0); - sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); - zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); + pVal = tdsqlite3ValueNew(0); + tdsqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); + zFilename8 = tdsqlite3ValueText(pVal, SQLITE_UTF8); if( zFilename8 ){ rc = openDatabase(zFilename8, ppDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); @@ -144095,7 +166171,7 @@ SQLITE_API int sqlite3_open16( }else{ rc = SQLITE_NOMEM_BKPT; } - sqlite3ValueFree(pVal); + tdsqlite3ValueFree(pVal); return rc & 0xff; } @@ -144104,21 +166180,21 @@ SQLITE_API int sqlite3_open16( /* ** Register a new collation sequence with the database handle db. */ -SQLITE_API int sqlite3_create_collation( - sqlite3* db, +SQLITE_API int tdsqlite3_create_collation( + tdsqlite3* db, const char *zName, int enc, void* pCtx, int(*xCompare)(void*,int,const void*,int,const void*) ){ - return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0); + return tdsqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0); } /* ** Register a new collation sequence with the database handle db. */ -SQLITE_API int sqlite3_create_collation_v2( - sqlite3* db, +SQLITE_API int tdsqlite3_create_collation_v2( + tdsqlite3* db, const char *zName, int enc, void* pCtx, @@ -144128,13 +166204,13 @@ SQLITE_API int sqlite3_create_collation_v2( int rc; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -144142,8 +166218,8 @@ SQLITE_API int sqlite3_create_collation_v2( /* ** Register a new collation sequence with the database handle db. */ -SQLITE_API int sqlite3_create_collation16( - sqlite3* db, +SQLITE_API int tdsqlite3_create_collation16( + tdsqlite3* db, const void *zName, int enc, void* pCtx, @@ -144153,17 +166229,17 @@ SQLITE_API int sqlite3_create_collation16( char *zName8; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); - zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); + zName8 = tdsqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); if( zName8 ){ rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); - sqlite3DbFree(db, zName8); + tdsqlite3DbFree(db, zName8); } - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } #endif /* SQLITE_OMIT_UTF16 */ @@ -144172,19 +166248,19 @@ SQLITE_API int sqlite3_create_collation16( ** Register a collation sequence factory callback with the database handle ** db. Replace any previously installed collation sequence factory. */ -SQLITE_API int sqlite3_collation_needed( - sqlite3 *db, +SQLITE_API int tdsqlite3_collation_needed( + tdsqlite3 *db, void *pCollNeededArg, - void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) + void(*xCollNeeded)(void*,tdsqlite3*,int eTextRep,const char*) ){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); db->xCollNeeded = xCollNeeded; db->xCollNeeded16 = 0; db->pCollNeededArg = pCollNeededArg; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_OK; } @@ -144193,19 +166269,19 @@ SQLITE_API int sqlite3_collation_needed( ** Register a collation sequence factory callback with the database handle ** db. Replace any previously installed collation sequence factory. */ -SQLITE_API int sqlite3_collation_needed16( - sqlite3 *db, +SQLITE_API int tdsqlite3_collation_needed16( + tdsqlite3 *db, void *pCollNeededArg, - void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) + void(*xCollNeeded16)(void*,tdsqlite3*,int eTextRep,const void*) ){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); db->xCollNeeded = 0; db->xCollNeeded16 = xCollNeeded16; db->pCollNeededArg = pCollNeededArg; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_OK; } #endif /* SQLITE_OMIT_UTF16 */ @@ -144215,7 +166291,7 @@ SQLITE_API int sqlite3_collation_needed16( ** This function is now an anachronism. It used to be used to recover from a ** malloc() failure, but SQLite now does this automatically. */ -SQLITE_API int sqlite3_global_recover(void){ +SQLITE_API int tdsqlite3_global_recover(void){ return SQLITE_OK; } #endif @@ -144226,9 +166302,9 @@ SQLITE_API int sqlite3_global_recover(void){ ** by default. Autocommit is disabled by a BEGIN statement and reenabled ** by the next COMMIT or ROLLBACK. */ -SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){ +SQLITE_API int tdsqlite3_get_autocommit(tdsqlite3 *db){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } @@ -144244,34 +166320,40 @@ SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){ ** 1. Serve as a convenient place to set a breakpoint in a debugger ** to detect when version error conditions occurs. ** -** 2. Invoke sqlite3_log() to provide the source code location where +** 2. Invoke tdsqlite3_log() to provide the source code location where ** a low-level error is first detected. */ -static int reportError(int iErr, int lineno, const char *zType){ - sqlite3_log(iErr, "%s at line %d of [%.10s]", - zType, lineno, 20+sqlite3_sourceid()); +SQLITE_PRIVATE int tdsqlite3ReportError(int iErr, int lineno, const char *zType){ + tdsqlite3_log(iErr, "%s at line %d of [%.10s]", + zType, lineno, 20+tdsqlite3_sourceid()); return iErr; } -SQLITE_PRIVATE int sqlite3CorruptError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return reportError(SQLITE_CORRUPT, lineno, "database corruption"); +SQLITE_PRIVATE int tdsqlite3CorruptError(int lineno){ + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + return tdsqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption"); } -SQLITE_PRIVATE int sqlite3MisuseError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return reportError(SQLITE_MISUSE, lineno, "misuse"); +SQLITE_PRIVATE int tdsqlite3MisuseError(int lineno){ + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + return tdsqlite3ReportError(SQLITE_MISUSE, lineno, "misuse"); } -SQLITE_PRIVATE int sqlite3CantopenError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return reportError(SQLITE_CANTOPEN, lineno, "cannot open file"); +SQLITE_PRIVATE int tdsqlite3CantopenError(int lineno){ + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + return tdsqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file"); } #ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3NomemError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return reportError(SQLITE_NOMEM, lineno, "OOM"); +SQLITE_PRIVATE int tdsqlite3CorruptPgnoError(int lineno, Pgno pgno){ + char zMsg[100]; + tdsqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno); + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + return tdsqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg); } -SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error"); +SQLITE_PRIVATE int tdsqlite3NomemError(int lineno){ + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + return tdsqlite3ReportError(SQLITE_NOMEM, lineno, "OOM"); +} +SQLITE_PRIVATE int tdsqlite3IoerrnomemError(int lineno){ + testcase( tdsqlite3GlobalConfig.xLog!=0 ); + return tdsqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error"); } #endif @@ -144283,7 +166365,7 @@ SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){ ** SQLite no longer uses thread-specific data so this routine is now a ** no-op. It is retained for historical compatibility. */ -SQLITE_API void sqlite3_thread_cleanup(void){ +SQLITE_API void tdsqlite3_thread_cleanup(void){ } #endif @@ -144291,8 +166373,8 @@ SQLITE_API void sqlite3_thread_cleanup(void){ ** Return meta information about a specific column of a database table. ** See comment in sqlite3.h (sqlite.h.in) for details. */ -SQLITE_API int sqlite3_table_column_metadata( - sqlite3 *db, /* Connection handle */ +SQLITE_API int tdsqlite3_table_column_metadata( + tdsqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ @@ -144315,21 +166397,21 @@ SQLITE_API int sqlite3_table_column_metadata( #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){ + if( !tdsqlite3SafetyCheckOk(db) || zTableName==0 ){ return SQLITE_MISUSE_BKPT; } #endif /* Ensure the database schema has been loaded */ - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeEnterAll(db); - rc = sqlite3Init(db, &zErrMsg); + tdsqlite3_mutex_enter(db->mutex); + tdsqlite3BtreeEnterAll(db); + rc = tdsqlite3Init(db, &zErrMsg); if( SQLITE_OK!=rc ){ goto error_out; } /* Locate the table in question */ - pTab = sqlite3FindTable(db, zTableName, zDbName); + pTab = tdsqlite3FindTable(db, zTableName, zDbName); if( !pTab || pTab->pSelect ){ pTab = 0; goto error_out; @@ -144341,12 +166423,12 @@ SQLITE_API int sqlite3_table_column_metadata( }else{ for(iCol=0; iCol<pTab->nCol; iCol++){ pCol = &pTab->aCol[iCol]; - if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ + if( 0==tdsqlite3StrICmp(pCol->zName, zColumnName) ){ break; } } if( iCol==pTab->nCol ){ - if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){ + if( HasRowid(pTab) && tdsqlite3IsRowid(zColumnName) ){ iCol = pTab->iPKey; pCol = iCol>=0 ? &pTab->aCol[iCol] : 0; }else{ @@ -144367,7 +166449,7 @@ SQLITE_API int sqlite3_table_column_metadata( ** explicitly declared column. Copy meta information from *pCol. */ if( pCol ){ - zDataType = sqlite3ColumnType(pCol,0); + zDataType = tdsqlite3ColumnType(pCol,0); zCollSeq = pCol->zColl; notnull = pCol->notNull!=0; primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; @@ -144377,11 +166459,11 @@ SQLITE_API int sqlite3_table_column_metadata( primarykey = 1; } if( !zCollSeq ){ - zCollSeq = sqlite3StrBINARY; + zCollSeq = tdsqlite3StrBINARY; } error_out: - sqlite3BtreeLeaveAll(db); + tdsqlite3BtreeLeaveAll(db); /* Whether the function call succeeded or failed, set the output parameters ** to whatever their local counterparts contain. If an error did occur, @@ -144394,93 +166476,94 @@ error_out: if( pAutoinc ) *pAutoinc = autoinc; if( SQLITE_OK==rc && !pTab ){ - sqlite3DbFree(db, zErrMsg); - zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, + tdsqlite3DbFree(db, zErrMsg); + zErrMsg = tdsqlite3MPrintf(db, "no such table column: %s.%s", zTableName, zColumnName); rc = SQLITE_ERROR; } - sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg); - sqlite3DbFree(db, zErrMsg); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); + tdsqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg); + tdsqlite3DbFree(db, zErrMsg); + rc = tdsqlite3ApiExit(db, rc); + tdsqlite3_mutex_leave(db->mutex); return rc; } /* ** Sleep for a little while. Return the amount of time slept. */ -SQLITE_API int sqlite3_sleep(int ms){ - sqlite3_vfs *pVfs; +SQLITE_API int tdsqlite3_sleep(int ms){ + tdsqlite3_vfs *pVfs; int rc; - pVfs = sqlite3_vfs_find(0); + pVfs = tdsqlite3_vfs_find(0); if( pVfs==0 ) return 0; /* This function works in milliseconds, but the underlying OsSleep() ** API uses microseconds. Hence the 1000's. */ - rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); + rc = (tdsqlite3OsSleep(pVfs, 1000*ms)/1000); return rc; } /* ** Enable or disable the extended result codes. */ -SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ +SQLITE_API int tdsqlite3_extended_result_codes(tdsqlite3 *db, int onoff){ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); db->errMask = onoff ? 0xffffffff : 0xff; - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return SQLITE_OK; } /* ** Invoke the xFileControl method on a particular database. */ -SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ +SQLITE_API int tdsqlite3_file_control(tdsqlite3 *db, const char *zDbName, int op, void *pArg){ int rc = SQLITE_ERROR; Btree *pBtree; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; + if( !tdsqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif - sqlite3_mutex_enter(db->mutex); - pBtree = sqlite3DbNameToBtree(db, zDbName); + tdsqlite3_mutex_enter(db->mutex); + pBtree = tdsqlite3DbNameToBtree(db, zDbName); if( pBtree ){ Pager *pPager; - sqlite3_file *fd; - sqlite3BtreeEnter(pBtree); - pPager = sqlite3BtreePager(pBtree); + tdsqlite3_file *fd; + tdsqlite3BtreeEnter(pBtree); + pPager = tdsqlite3BtreePager(pBtree); assert( pPager!=0 ); - fd = sqlite3PagerFile(pPager); + fd = tdsqlite3PagerFile(pPager); assert( fd!=0 ); if( op==SQLITE_FCNTL_FILE_POINTER ){ - *(sqlite3_file**)pArg = fd; + *(tdsqlite3_file**)pArg = fd; rc = SQLITE_OK; }else if( op==SQLITE_FCNTL_VFS_POINTER ){ - *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager); + *(tdsqlite3_vfs**)pArg = tdsqlite3PagerVfs(pPager); rc = SQLITE_OK; }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){ - *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager); + *(tdsqlite3_file**)pArg = tdsqlite3PagerJrnlFile(pPager); + rc = SQLITE_OK; + }else if( op==SQLITE_FCNTL_DATA_VERSION ){ + *(unsigned int*)pArg = tdsqlite3PagerDataVersion(pPager); rc = SQLITE_OK; - }else if( fd->pMethods ){ - rc = sqlite3OsFileControl(fd, op, pArg); }else{ - rc = SQLITE_NOTFOUND; + rc = tdsqlite3OsFileControl(fd, op, pArg); } - sqlite3BtreeLeave(pBtree); + tdsqlite3BtreeLeave(pBtree); } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); return rc; } /* ** Interface to the testing logic. */ -SQLITE_API int sqlite3_test_control(int op, ...){ +SQLITE_API int tdsqlite3_test_control(int op, ...){ int rc = 0; -#ifdef SQLITE_OMIT_BUILTIN_TEST +#ifdef SQLITE_UNTESTABLE UNUSED_PARAMETER(op); #else va_list ap; @@ -144491,7 +166574,7 @@ SQLITE_API int sqlite3_test_control(int op, ...){ ** Save the current state of the PRNG. */ case SQLITE_TESTCTRL_PRNG_SAVE: { - sqlite3PrngSaveState(); + tdsqlite3PrngSaveState(); break; } @@ -144501,59 +166584,82 @@ SQLITE_API int sqlite3_test_control(int op, ...){ ** this verb acts like PRNG_RESET. */ case SQLITE_TESTCTRL_PRNG_RESTORE: { - sqlite3PrngRestoreState(); + tdsqlite3PrngRestoreState(); break; } - /* - ** Reset the PRNG back to its uninitialized state. The next call - ** to sqlite3_randomness() will reseed the PRNG using a single call - ** to the xRandomness method of the default VFS. + /* tdsqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, tdsqlite3 *db); + ** + ** Control the seed for the pseudo-random number generator (PRNG) that + ** is built into SQLite. Cases: + ** + ** x!=0 && db!=0 Seed the PRNG to the current value of the + ** schema cookie in the main database for db, or + ** x if the schema cookie is zero. This case + ** is convenient to use with database fuzzers + ** as it allows the fuzzer some control over the + ** the PRNG seed. + ** + ** x!=0 && db==0 Seed the PRNG to the value of x. + ** + ** x==0 && db==0 Revert to default behavior of using the + ** xRandomness method on the primary VFS. + ** + ** This test-control also resets the PRNG so that the new seed will + ** be used for the next call to tdsqlite3_randomness(). */ - case SQLITE_TESTCTRL_PRNG_RESET: { - sqlite3_randomness(0,0); +#ifndef SQLITE_OMIT_WSD + case SQLITE_TESTCTRL_PRNG_SEED: { + int x = va_arg(ap, int); + int y; + tdsqlite3 *db = va_arg(ap, tdsqlite3*); + assert( db==0 || db->aDb[0].pSchema!=0 ); + if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; } + tdsqlite3Config.iPrngSeed = x; + tdsqlite3_randomness(0,0); break; } +#endif /* - ** sqlite3_test_control(BITVEC_TEST, size, program) + ** tdsqlite3_test_control(BITVEC_TEST, size, program) ** ** Run a test against a Bitvec object of size. The program argument ** is an array of integers that defines the test. Return -1 on a ** memory allocation error, 0 on success, or non-zero for an error. - ** See the sqlite3BitvecBuiltinTest() for additional information. + ** See the tdsqlite3BitvecBuiltinTest() for additional information. */ case SQLITE_TESTCTRL_BITVEC_TEST: { int sz = va_arg(ap, int); int *aProg = va_arg(ap, int*); - rc = sqlite3BitvecBuiltinTest(sz, aProg); + rc = tdsqlite3BitvecBuiltinTest(sz, aProg); break; } /* - ** sqlite3_test_control(FAULT_INSTALL, xCallback) + ** tdsqlite3_test_control(FAULT_INSTALL, xCallback) ** - ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called, + ** Arrange to invoke xCallback() whenever tdsqlite3FaultSim() is called, ** if xCallback is not NULL. ** - ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0) + ** As a test of the fault simulator mechanism itself, tdsqlite3FaultSim(0) ** is called immediately after installing the new callback and the return - ** value from sqlite3FaultSim(0) becomes the return from - ** sqlite3_test_control(). + ** value from tdsqlite3FaultSim(0) becomes the return from + ** tdsqlite3_test_control(). */ case SQLITE_TESTCTRL_FAULT_INSTALL: { /* MSVC is picky about pulling func ptrs from va lists. ** http://support.microsoft.com/kb/47961 - ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int)); + ** tdsqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int)); */ typedef int(*TESTCALLBACKFUNC_t)(int); - sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t); - rc = sqlite3FaultSim(0); + tdsqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t); + rc = tdsqlite3FaultSim(0); break; } /* - ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) + ** tdsqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) ** ** Register hooks to call to indicate which malloc() failures ** are benign. @@ -144564,12 +166670,12 @@ SQLITE_API int sqlite3_test_control(int op, ...){ void_function xBenignEnd; xBenignBegin = va_arg(ap, void_function); xBenignEnd = va_arg(ap, void_function); - sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); + tdsqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); break; } /* - ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) + ** tdsqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) ** ** Set the PENDING byte to the value in the argument, if X>0. ** Make no changes if X==0. Return the value of the pending byte @@ -144585,14 +166691,14 @@ SQLITE_API int sqlite3_test_control(int op, ...){ #ifndef SQLITE_OMIT_WSD { unsigned int newVal = va_arg(ap, unsigned int); - if( newVal ) sqlite3PendingByte = newVal; + if( newVal ) tdsqlite3PendingByte = newVal; } #endif break; } /* - ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) + ** tdsqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) ** ** This action provides a run-time test to see whether or not ** assert() was enabled at compile-time. If X is true and assert() @@ -144611,12 +166717,12 @@ SQLITE_API int sqlite3_test_control(int op, ...){ /* - ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) + ** tdsqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) ** ** This action provides a run-time test to see how the ALWAYS and ** NEVER macros were defined at compile-time. ** - ** The return value is ALWAYS(X). + ** The return value is ALWAYS(X) if X is true, or 0 if X is false. ** ** The recommended test is X==2. If the return value is 2, that means ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the @@ -144629,9 +166735,9 @@ SQLITE_API int sqlite3_test_control(int op, ...){ ** ** The run-time test procedure might look something like this: ** - ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ + ** if( tdsqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ ** // ALWAYS() and NEVER() are no-op pass-through macros - ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ + ** }else if( tdsqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. ** }else{ ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. @@ -144639,12 +166745,12 @@ SQLITE_API int sqlite3_test_control(int op, ...){ */ case SQLITE_TESTCTRL_ALWAYS: { int x = va_arg(ap,int); - rc = ALWAYS(x); + rc = x ? ALWAYS(x) : 0; break; } /* - ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER); + ** tdsqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER); ** ** The integer returned reveals the byte-order of the computer on which ** SQLite is running: @@ -144659,21 +166765,21 @@ SQLITE_API int sqlite3_test_control(int op, ...){ break; } - /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) + /* tdsqlite3_test_control(SQLITE_TESTCTRL_RESERVE, tdsqlite3 *db, int N) ** ** Set the nReserve size to N for the main database on the database ** connection db. */ case SQLITE_TESTCTRL_RESERVE: { - sqlite3 *db = va_arg(ap, sqlite3*); + tdsqlite3 *db = va_arg(ap, tdsqlite3*); int x = va_arg(ap,int); - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_enter(db->mutex); + tdsqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); + tdsqlite3_mutex_leave(db->mutex); break; } - /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) + /* tdsqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, tdsqlite3 *db, int N) ** ** Enable or disable various optimizations for testing purposes. The ** argument N is a bitmask of optimizations to be disabled. For normal @@ -144683,57 +166789,33 @@ SQLITE_API int sqlite3_test_control(int op, ...){ ** is obtained in every case. */ case SQLITE_TESTCTRL_OPTIMIZATIONS: { - sqlite3 *db = va_arg(ap, sqlite3*); + tdsqlite3 *db = va_arg(ap, tdsqlite3*); db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); break; } -#ifdef SQLITE_N_KEYWORD - /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) + /* tdsqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); ** - ** If zWord is a keyword recognized by the parser, then return the - ** number of keywords. Or if zWord is not a keyword, return 0. - ** - ** This test feature is only available in the amalgamation since - ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite - ** is built using separate source files. + ** If parameter onoff is non-zero, subsequent calls to localtime() + ** and its variants fail. If onoff is zero, undo this setting. */ - case SQLITE_TESTCTRL_ISKEYWORD: { - const char *zWord = va_arg(ap, const char*); - int n = sqlite3Strlen30(zWord); - rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; - break; - } -#endif - - /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); - ** - ** Pass pFree into sqlite3ScratchFree(). - ** If sz>0 then allocate a scratch buffer into pNew. - */ - case SQLITE_TESTCTRL_SCRATCHMALLOC: { - void *pFree, **ppNew; - int sz; - sz = va_arg(ap, int); - ppNew = va_arg(ap, void**); - pFree = va_arg(ap, void*); - if( sz ) *ppNew = sqlite3ScratchMalloc(sz); - sqlite3ScratchFree(pFree); + case SQLITE_TESTCTRL_LOCALTIME_FAULT: { + tdsqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); break; } - /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); + /* tdsqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, tdsqlite3*); ** - ** If parameter onoff is non-zero, configure the wrappers so that all - ** subsequent calls to localtime() and variants fail. If onoff is zero, - ** undo this setting. + ** Toggle the ability to use internal functions on or off for + ** the database connection given in the argument. */ - case SQLITE_TESTCTRL_LOCALTIME_FAULT: { - sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); + case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: { + tdsqlite3 *db = va_arg(ap, tdsqlite3*); + db->mDbFlags ^= DBFLAG_InternalFunc; break; } - /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int); + /* tdsqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int); ** ** Set or clear a flag that indicates that the database file is always well- ** formed and never corrupt. This flag is clear by default, indicating that @@ -144742,7 +166824,18 @@ SQLITE_API int sqlite3_test_control(int op, ...){ ** that demonstrat invariants on well-formed database files. */ case SQLITE_TESTCTRL_NEVER_CORRUPT: { - sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int); + tdsqlite3GlobalConfig.neverCorrupt = va_arg(ap, int); + break; + } + + /* tdsqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int); + ** + ** Set or clear a flag that causes SQLite to verify that type, name, + ** and tbl_name fields of the sqlite_master table. This is normally + ** on, but it is sometimes useful to turn it off for testing. + */ + case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: { + tdsqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int); break; } @@ -144752,42 +166845,43 @@ SQLITE_API int sqlite3_test_control(int op, ...){ ** provided to set a small and easily reachable reset value. */ case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: { - sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int); + tdsqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int); break; } - /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr); + /* tdsqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr); ** ** Set the VDBE coverage callback function to xCallback with context ** pointer ptr. */ case SQLITE_TESTCTRL_VDBE_COVERAGE: { #ifdef SQLITE_VDBE_COVERAGE - typedef void (*branch_callback)(void*,int,u8,u8); - sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback); - sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*); + typedef void (*branch_callback)(void*,unsigned int, + unsigned char,unsigned char); + tdsqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback); + tdsqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*); #endif break; } - /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */ + /* tdsqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */ case SQLITE_TESTCTRL_SORTER_MMAP: { - sqlite3 *db = va_arg(ap, sqlite3*); + tdsqlite3 *db = va_arg(ap, tdsqlite3*); db->nMaxSorterMmap = va_arg(ap, int); break; } - /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT); + /* tdsqlite3_test_control(SQLITE_TESTCTRL_ISINIT); ** ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if ** not. */ case SQLITE_TESTCTRL_ISINIT: { - if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR; + if( tdsqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR; break; } - /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum); + /* tdsqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum); ** ** This test control is used to create imposter tables. "db" is a pointer ** to the database connection. dbName is the database name (ex: "main" or @@ -144804,20 +166898,52 @@ SQLITE_API int sqlite3_test_control(int op, ...){ ** effect of erasing all imposter tables. */ case SQLITE_TESTCTRL_IMPOSTER: { - sqlite3 *db = va_arg(ap, sqlite3*); - sqlite3_mutex_enter(db->mutex); - db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*)); + tdsqlite3 *db = va_arg(ap, tdsqlite3*); + tdsqlite3_mutex_enter(db->mutex); + db->init.iDb = tdsqlite3FindDbName(db, va_arg(ap,const char*)); db->init.busy = db->init.imposterTable = va_arg(ap,int); db->init.newTnum = va_arg(ap,int); if( db->init.busy==0 && db->init.newTnum>0 ){ - sqlite3ResetAllSchemasOfConnection(db); + tdsqlite3ResetAllSchemasOfConnection(db); } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); + break; + } + +#if defined(YYCOVERAGE) + /* tdsqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out) + ** + ** This test control (only available when SQLite is compiled with + ** -DYYCOVERAGE) writes a report onto "out" that shows all + ** state/lookahead combinations in the parser state machine + ** which are never exercised. If any state is missed, make the + ** return code SQLITE_ERROR. + */ + case SQLITE_TESTCTRL_PARSER_COVERAGE: { + FILE *out = va_arg(ap, FILE*); + if( tdsqlite3ParserCoverage(out) ) rc = SQLITE_ERROR; + break; + } +#endif /* defined(YYCOVERAGE) */ + + /* tdsqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, tdsqlite3_context*); + ** + ** This test-control causes the most recent tdsqlite3_result_int64() value + ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally, + ** MEM_IntReal values only arise during an INSERT operation of integer + ** values into a REAL column, so they can be challenging to test. This + ** test-control enables us to write an intreal() SQL function that can + ** inject an intreal() value at arbitrary places in an SQL statement, + ** for testing purposes. + */ + case SQLITE_TESTCTRL_RESULT_INTREAL: { + tdsqlite3_context *pCtx = va_arg(ap, tdsqlite3_context*); + tdsqlite3ResultIntReal(pCtx); break; } } va_end(ap); -#endif /* SQLITE_OMIT_BUILTIN_TEST */ +#endif /* SQLITE_UNTESTABLE */ return rc; } @@ -144832,88 +166958,134 @@ SQLITE_API int sqlite3_test_control(int op, ...){ ** parameter if it exists. If the parameter does not exist, this routine ** returns a NULL pointer. */ -SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ +SQLITE_API const char *tdsqlite3_uri_parameter(const char *zFilename, const char *zParam){ if( zFilename==0 || zParam==0 ) return 0; - zFilename += sqlite3Strlen30(zFilename) + 1; + zFilename += tdsqlite3Strlen30(zFilename) + 1; while( zFilename[0] ){ int x = strcmp(zFilename, zParam); - zFilename += sqlite3Strlen30(zFilename) + 1; + zFilename += tdsqlite3Strlen30(zFilename) + 1; if( x==0 ) return zFilename; - zFilename += sqlite3Strlen30(zFilename) + 1; + zFilename += tdsqlite3Strlen30(zFilename) + 1; } return 0; } /* +** Return a pointer to the name of Nth query parameter of the filename. +*/ +SQLITE_API const char *tdsqlite3_uri_key(const char *zFilename, int N){ + if( zFilename==0 || N<0 ) return 0; + zFilename += tdsqlite3Strlen30(zFilename) + 1; + while( zFilename[0] && (N--)>0 ){ + zFilename += tdsqlite3Strlen30(zFilename) + 1; + zFilename += tdsqlite3Strlen30(zFilename) + 1; + } + return zFilename[0] ? zFilename : 0; +} + +/* ** Return a boolean value for a query parameter. */ -SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ - const char *z = sqlite3_uri_parameter(zFilename, zParam); +SQLITE_API int tdsqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ + const char *z = tdsqlite3_uri_parameter(zFilename, zParam); bDflt = bDflt!=0; - return z ? sqlite3GetBoolean(z, bDflt) : bDflt; + return z ? tdsqlite3GetBoolean(z, bDflt) : bDflt; } /* ** Return a 64-bit integer value for a query parameter. */ -SQLITE_API sqlite3_int64 sqlite3_uri_int64( +SQLITE_API tdsqlite3_int64 tdsqlite3_uri_int64( const char *zFilename, /* Filename as passed to xOpen */ const char *zParam, /* URI parameter sought */ - sqlite3_int64 bDflt /* return if parameter is missing */ + tdsqlite3_int64 bDflt /* return if parameter is missing */ ){ - const char *z = sqlite3_uri_parameter(zFilename, zParam); - sqlite3_int64 v; - if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){ + const char *z = tdsqlite3_uri_parameter(zFilename, zParam); + tdsqlite3_int64 v; + if( z && tdsqlite3DecOrHexToI64(z, &v)==0 ){ bDflt = v; } return bDflt; } /* -** Return the Btree pointer identified by zDbName. Return NULL if not found. +** The Pager stores the Journal filename, WAL filename, and Database filename +** consecutively in memory, in that order, with prefixes \000\001\000, +** \002\000, and \003\000, in that order. Thus the three names look like query +** parameters if you start at the first prefix. +** +** This routine backs up a filename to the start of the first prefix. +** +** This only works if the filenamed passed in was obtained from the Pager. */ -SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ - int i; - for(i=0; i<db->nDb; i++){ - if( db->aDb[i].pBt - && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zDbSName)==0) - ){ - return db->aDb[i].pBt; - } +static const char *startOfNameList(const char *zName){ + while( zName[0]!='\001' || zName[1]!=0 ){ + zName -= 3; + while( zName[0]!='\000' ){ zName--; } + zName++; } - return 0; + return zName-1; +} + +/* +** Translate a filename that was handed to a VFS routine into the corresponding +** database, journal, or WAL file. +** +** It is an error to pass this routine a filename string that was not +** passed into the VFS from the SQLite core. Doing so is similar to +** passing free() a pointer that was not obtained from malloc() - it is +** an error that we cannot easily detect but that will likely cause memory +** corruption. +*/ +SQLITE_API const char *tdsqlite3_filename_database(const char *zFilename){ + return tdsqlite3_uri_parameter(zFilename - 3, "\003"); +} +SQLITE_API const char *tdsqlite3_filename_journal(const char *zFilename){ + const char *z = tdsqlite3_uri_parameter(startOfNameList(zFilename), "\001"); + return ALWAYS(z) && z[0] ? z : 0; +} +SQLITE_API const char *tdsqlite3_filename_wal(const char *zFilename){ + return tdsqlite3_uri_parameter(startOfNameList(zFilename), "\002"); +} + +/* +** Return the Btree pointer identified by zDbName. Return NULL if not found. +*/ +SQLITE_PRIVATE Btree *tdsqlite3DbNameToBtree(tdsqlite3 *db, const char *zDbName){ + int iDb = zDbName ? tdsqlite3FindDbName(db, zDbName) : 0; + return iDb<0 ? 0 : db->aDb[iDb].pBt; } /* ** Return the filename of the database associated with a database ** connection. */ -SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ +SQLITE_API const char *tdsqlite3_db_filename(tdsqlite3 *db, const char *zDbName){ Btree *pBt; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - pBt = sqlite3DbNameToBtree(db, zDbName); - return pBt ? sqlite3BtreeGetFilename(pBt) : 0; + pBt = tdsqlite3DbNameToBtree(db, zDbName); + return pBt ? tdsqlite3BtreeGetFilename(pBt) : 0; } /* ** Return 1 if database is read-only or 0 if read/write. Return -1 if ** no such database exists. */ -SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ +SQLITE_API int tdsqlite3_db_readonly(tdsqlite3 *db, const char *zDbName){ Btree *pBt; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return -1; } #endif - pBt = sqlite3DbNameToBtree(db, zDbName); - return pBt ? sqlite3BtreeIsReadonly(pBt) : -1; + pBt = tdsqlite3DbNameToBtree(db, zDbName); + return pBt ? tdsqlite3BtreeIsReadonly(pBt) : -1; } #ifdef SQLITE_ENABLE_SNAPSHOT @@ -144921,34 +167093,35 @@ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ ** Obtain a snapshot handle for the snapshot of database zDb currently ** being read by handle db. */ -SQLITE_API int sqlite3_snapshot_get( - sqlite3 *db, +SQLITE_API int tdsqlite3_snapshot_get( + tdsqlite3 *db, const char *zDb, - sqlite3_snapshot **ppSnapshot + tdsqlite3_snapshot **ppSnapshot ){ int rc = SQLITE_ERROR; #ifndef SQLITE_OMIT_WAL - int iDb; #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); - iDb = sqlite3FindDbName(db, zDb); - if( iDb==0 || iDb>1 ){ - Btree *pBt = db->aDb[iDb].pBt; - if( 0==sqlite3BtreeIsInTrans(pBt) ){ - rc = sqlite3BtreeBeginTrans(pBt, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot); + if( db->autoCommit==0 ){ + int iDb = tdsqlite3FindDbName(db, zDb); + if( iDb==0 || iDb>1 ){ + Btree *pBt = db->aDb[iDb].pBt; + if( 0==tdsqlite3BtreeIsInTrans(pBt) ){ + rc = tdsqlite3BtreeBeginTrans(pBt, 0, 0); + if( rc==SQLITE_OK ){ + rc = tdsqlite3PagerSnapshotGet(tdsqlite3BtreePager(pBt), ppSnapshot); + } } } } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); #endif /* SQLITE_OMIT_WAL */ return rc; } @@ -144956,48 +167129,150 @@ SQLITE_API int sqlite3_snapshot_get( /* ** Open a read-transaction on the snapshot idendified by pSnapshot. */ -SQLITE_API int sqlite3_snapshot_open( - sqlite3 *db, +SQLITE_API int tdsqlite3_snapshot_open( + tdsqlite3 *db, const char *zDb, - sqlite3_snapshot *pSnapshot + tdsqlite3_snapshot *pSnapshot ){ int rc = SQLITE_ERROR; #ifndef SQLITE_OMIT_WAL #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ + if( !tdsqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE_BKPT; } #endif - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); if( db->autoCommit==0 ){ int iDb; - iDb = sqlite3FindDbName(db, zDb); + iDb = tdsqlite3FindDbName(db, zDb); if( iDb==0 || iDb>1 ){ Btree *pBt = db->aDb[iDb].pBt; - if( 0==sqlite3BtreeIsInReadTrans(pBt) ){ - rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot); + if( tdsqlite3BtreeIsInTrans(pBt)==0 ){ + Pager *pPager = tdsqlite3BtreePager(pBt); + int bUnlock = 0; + if( tdsqlite3BtreeIsInReadTrans(pBt) ){ + if( db->nVdbeActive==0 ){ + rc = tdsqlite3PagerSnapshotCheck(pPager, pSnapshot); + if( rc==SQLITE_OK ){ + bUnlock = 1; + rc = tdsqlite3BtreeCommit(pBt); + } + } + }else{ + rc = SQLITE_OK; + } if( rc==SQLITE_OK ){ - rc = sqlite3BtreeBeginTrans(pBt, 0); - sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0); + rc = tdsqlite3PagerSnapshotOpen(pPager, pSnapshot); + } + if( rc==SQLITE_OK ){ + rc = tdsqlite3BtreeBeginTrans(pBt, 0, 0); + tdsqlite3PagerSnapshotOpen(pPager, 0); + } + if( bUnlock ){ + tdsqlite3PagerSnapshotUnlock(pPager); } } } } - sqlite3_mutex_leave(db->mutex); + tdsqlite3_mutex_leave(db->mutex); +#endif /* SQLITE_OMIT_WAL */ + return rc; +} + +/* +** Recover as many snapshots as possible from the wal file associated with +** schema zDb of database db. +*/ +SQLITE_API int tdsqlite3_snapshot_recover(tdsqlite3 *db, const char *zDb){ + int rc = SQLITE_ERROR; + int iDb; +#ifndef SQLITE_OMIT_WAL + +#ifdef SQLITE_ENABLE_API_ARMOR + if( !tdsqlite3SafetyCheckOk(db) ){ + return SQLITE_MISUSE_BKPT; + } +#endif + + tdsqlite3_mutex_enter(db->mutex); + iDb = tdsqlite3FindDbName(db, zDb); + if( iDb==0 || iDb>1 ){ + Btree *pBt = db->aDb[iDb].pBt; + if( 0==tdsqlite3BtreeIsInReadTrans(pBt) ){ + rc = tdsqlite3BtreeBeginTrans(pBt, 0, 0); + if( rc==SQLITE_OK ){ + rc = tdsqlite3PagerSnapshotRecover(tdsqlite3BtreePager(pBt)); + tdsqlite3BtreeCommit(pBt); + } + } + } + tdsqlite3_mutex_leave(db->mutex); #endif /* SQLITE_OMIT_WAL */ return rc; } /* -** Free a snapshot handle obtained from sqlite3_snapshot_get(). +** Free a snapshot handle obtained from tdsqlite3_snapshot_get(). */ -SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){ - sqlite3_free(pSnapshot); +SQLITE_API void tdsqlite3_snapshot_free(tdsqlite3_snapshot *pSnapshot){ + tdsqlite3_free(pSnapshot); } #endif /* SQLITE_ENABLE_SNAPSHOT */ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +/* +** Given the name of a compile-time option, return true if that option +** was used and false if not. +** +** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix +** is not required for a match. +*/ +SQLITE_API int tdsqlite3_compileoption_used(const char *zOptName){ + int i, n; + int nOpt; + const char **azCompileOpt; + +#if SQLITE_ENABLE_API_ARMOR + if( zOptName==0 ){ + (void)SQLITE_MISUSE_BKPT; + return 0; + } +#endif + + azCompileOpt = tdsqlite3CompileOptions(&nOpt); + + if( tdsqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7; + n = tdsqlite3Strlen30(zOptName); + + /* Since nOpt is normally in single digits, a linear search is + ** adequate. No need for a binary search. */ + for(i=0; i<nOpt; i++){ + if( tdsqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0 + && tdsqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0 + ){ + return 1; + } + } + return 0; +} + +/* +** Return the N-th compile-time option string. If N is out of range, +** return a NULL pointer. +*/ +SQLITE_API const char *tdsqlite3_compileoption_get(int N){ + int nOpt; + const char **azCompileOpt; + azCompileOpt = tdsqlite3CompileOptions(&nOpt); + if( N>=0 && N<nOpt ){ + return azCompileOpt[N]; + } + return 0; +} +#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ + /************** End of main.c ************************************************/ /************** Begin file notify.c ******************************************/ /* @@ -145012,7 +167287,7 @@ SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){ ** ************************************************************************* ** -** This file contains the implementation of the sqlite3_unlock_notify() +** This file contains the implementation of the tdsqlite3_unlock_notify() ** API method and its associated functionality. */ /* #include "sqliteInt.h" */ @@ -145024,22 +167299,22 @@ SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){ /* ** Public interfaces: ** -** sqlite3ConnectionBlocked() -** sqlite3ConnectionUnlocked() -** sqlite3ConnectionClosed() -** sqlite3_unlock_notify() +** tdsqlite3ConnectionBlocked() +** tdsqlite3ConnectionUnlocked() +** tdsqlite3ConnectionClosed() +** tdsqlite3_unlock_notify() */ #define assertMutexHeld() \ - assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) + assert( tdsqlite3_mutex_held(tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ) /* -** Head of a linked list of all sqlite3 objects created by this process +** Head of a linked list of all tdsqlite3 objects created by this process ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection ** is not NULL. This variable may only accessed while the STATIC_MASTER ** mutex is held. */ -static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; +static tdsqlite3 *SQLITE_WSD tdsqlite3BlockedList = 0; #ifndef NDEBUG /* @@ -145056,17 +167331,17 @@ static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0; ** blocked connections list have pUnlockConnection or pBlockingConnection ** set to db. This is used when closing connection db. */ -static void checkListProperties(sqlite3 *db){ - sqlite3 *p; - for(p=sqlite3BlockedList; p; p=p->pNextBlocked){ +static void checkListProperties(tdsqlite3 *db){ + tdsqlite3 *p; + for(p=tdsqlite3BlockedList; p; p=p->pNextBlocked){ int seen = 0; - sqlite3 *p2; + tdsqlite3 *p2; /* Verify property (1) */ assert( p->pUnlockConnection || p->pBlockingConnection ); /* Verify property (2) */ - for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ + for(p2=tdsqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); assert( db==0 || p->pUnlockConnection!=db ); @@ -145082,10 +167357,10 @@ static void checkListProperties(sqlite3 *db){ ** Remove connection db from the blocked connections list. If connection ** db is not currently a part of the list, this function is a no-op. */ -static void removeFromBlockedList(sqlite3 *db){ - sqlite3 **pp; +static void removeFromBlockedList(tdsqlite3 *db){ + tdsqlite3 **pp; assertMutexHeld(); - for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ + for(pp=&tdsqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ if( *pp==db ){ *pp = (*pp)->pNextBlocked; break; @@ -145097,11 +167372,11 @@ static void removeFromBlockedList(sqlite3 *db){ ** Add connection db to the blocked connections list. It is assumed ** that it is not already a part of the list. */ -static void addToBlockedList(sqlite3 *db){ - sqlite3 **pp; +static void addToBlockedList(tdsqlite3 *db){ + tdsqlite3 **pp; assertMutexHeld(); for( - pp=&sqlite3BlockedList; + pp=&tdsqlite3BlockedList; *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; pp=&(*pp)->pNextBlocked ); @@ -145113,7 +167388,7 @@ static void addToBlockedList(sqlite3 *db){ ** Obtain the STATIC_MASTER mutex. */ static void enterMutex(void){ - sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); + tdsqlite3_mutex_enter(tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); checkListProperties(0); } @@ -145123,7 +167398,7 @@ static void enterMutex(void){ static void leaveMutex(void){ assertMutexHeld(); checkListProperties(0); - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); + tdsqlite3_mutex_leave(tdsqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); } /* @@ -145147,14 +167422,14 @@ static void leaveMutex(void){ ** on the same "db". If xNotify==0 then any prior callbacks are immediately ** cancelled. */ -SQLITE_API int sqlite3_unlock_notify( - sqlite3 *db, +SQLITE_API int tdsqlite3_unlock_notify( + tdsqlite3 *db, void (*xNotify)(void **, int), void *pArg ){ int rc = SQLITE_OK; - sqlite3_mutex_enter(db->mutex); + tdsqlite3_mutex_enter(db->mutex); enterMutex(); if( xNotify==0 ){ @@ -145170,7 +167445,7 @@ SQLITE_API int sqlite3_unlock_notify( */ xNotify(&pArg, 1); }else{ - sqlite3 *p; + tdsqlite3 *p; for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} if( p ){ @@ -145186,8 +167461,8 @@ SQLITE_API int sqlite3_unlock_notify( leaveMutex(); assert( !db->mallocFailed ); - sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0)); - sqlite3_mutex_leave(db->mutex); + tdsqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0)); + tdsqlite3_mutex_leave(db->mutex); return rc; } @@ -145197,7 +167472,7 @@ SQLITE_API int sqlite3_unlock_notify( ** to the user because it requires a lock that will not be available ** until connection pBlocker concludes its current transaction. */ -SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ +SQLITE_PRIVATE void tdsqlite3ConnectionBlocked(tdsqlite3 *db, tdsqlite3 *pBlocker){ enterMutex(); if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ addToBlockedList(db); @@ -145225,10 +167500,10 @@ SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ ** pUnlockConnection==0, remove the entry from the blocked connections ** list. */ -SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ +SQLITE_PRIVATE void tdsqlite3ConnectionUnlocked(tdsqlite3 *db){ void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ int nArg = 0; /* Number of entries in aArg[] */ - sqlite3 **pp; /* Iterator variable */ + tdsqlite3 **pp; /* Iterator variable */ void **aArg; /* Arguments to the unlock callback */ void **aDyn = 0; /* Dynamically allocated space for aArg[] */ void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ @@ -145237,8 +167512,8 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ enterMutex(); /* Enter STATIC_MASTER mutex */ /* This loop runs once for each entry in the blocked-connections list. */ - for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ - sqlite3 *p = *pp; + for(pp=&tdsqlite3BlockedList; *pp; /* no-op */ ){ + tdsqlite3 *p = *pp; /* Step 1. */ if( p->pBlockingConnection==db ){ @@ -145253,17 +167528,17 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ nArg = 0; } - sqlite3BeginBenignMalloc(); + tdsqlite3BeginBenignMalloc(); assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); if( (!aDyn && nArg==(int)ArraySize(aStatic)) - || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*))) + || (aDyn && nArg==(int)(tdsqlite3MallocSize(aDyn)/sizeof(void*))) ){ /* The aArg[] array needs to grow. */ - void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); + void **pNew = (void **)tdsqlite3Malloc(nArg*sizeof(void *)*2); if( pNew ){ memcpy(pNew, aArg, nArg*sizeof(void *)); - sqlite3_free(aDyn); + tdsqlite3_free(aDyn); aDyn = aArg = pNew; }else{ /* This occurs when the array of context pointers that need to @@ -145294,7 +167569,7 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ nArg = 0; } } - sqlite3EndBenignMalloc(); + tdsqlite3EndBenignMalloc(); aArg[nArg++] = p->pUnlockArg; xUnlockNotify = p->xUnlockNotify; @@ -145316,7 +167591,7 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ if( nArg!=0 ){ xUnlockNotify(aArg, nArg); } - sqlite3_free(aDyn); + tdsqlite3_free(aDyn); leaveMutex(); /* Leave STATIC_MASTER mutex */ } @@ -145324,8 +167599,8 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ ** This is called when the database connection passed as an argument is ** being closed. The connection is removed from the blocked list. */ -SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){ - sqlite3ConnectionUnlocked(db); +SQLITE_PRIVATE void tdsqlite3ConnectionClosed(tdsqlite3 *db){ + tdsqlite3ConnectionUnlocked(db); enterMutex(); removeFromBlockedList(db); checkListProperties(db); @@ -145664,9 +167939,9 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -/* If not building as part of the core, include sqlite3ext.h. */ +/* If not building as part of the core, include tdsqlite3ext.h. */ #ifndef SQLITE_CORE -/* # include "sqlite3ext.h" */ +/* # include "tdsqlite3ext.h" */ SQLITE_EXTENSION_INIT3 #endif @@ -145682,21 +167957,21 @@ SQLITE_EXTENSION_INIT3 ** Defines the interface to tokenizers used by fulltext-search. There ** are three basic components: ** -** sqlite3_tokenizer_module is a singleton defining the tokenizer +** tdsqlite3_tokenizer_module is a singleton defining the tokenizer ** interface functions. This is essentially the class structure for ** tokenizers. ** -** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** tdsqlite3_tokenizer is used to define a particular tokenizer, perhaps ** including customization information defined at creation time. ** -** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tdsqlite3_tokenizer_cursor is generated by a tokenizer to generate ** tokens from a particular input. */ #ifndef _FTS3_TOKENIZER_H_ #define _FTS3_TOKENIZER_H_ /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. -** If tokenizers are to be allowed to call sqlite3_*() functions, then +** If tokenizers are to be allowed to call tdsqlite3_*() functions, then ** we will need a way to register the API consistently. */ /* #include "sqlite3.h" */ @@ -145704,27 +167979,27 @@ SQLITE_EXTENSION_INIT3 /* ** Structures used by the tokenizer interface. When a new tokenizer ** implementation is registered, the caller provides a pointer to -** an sqlite3_tokenizer_module containing pointers to the callback +** an tdsqlite3_tokenizer_module containing pointers to the callback ** functions that make up an implementation. ** ** When an fts3 table is created, it passes any arguments passed to ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the -** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer +** tdsqlite3_tokenizer_module.xCreate() function of the requested tokenizer ** implementation. The xCreate() function in turn returns an -** sqlite3_tokenizer structure representing the specific tokenizer to +** tdsqlite3_tokenizer structure representing the specific tokenizer to ** be used for the fts3 table (customized by the tokenizer clause arguments). ** -** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() -** method is called. It returns an sqlite3_tokenizer_cursor object +** To tokenize an input buffer, the tdsqlite3_tokenizer_module.xOpen() +** method is called. It returns an tdsqlite3_tokenizer_cursor object ** that may be used to tokenize a specific input buffer based on -** the tokenization rules supplied by a specific sqlite3_tokenizer +** the tokenization rules supplied by a specific tdsqlite3_tokenizer ** object. */ -typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; -typedef struct sqlite3_tokenizer sqlite3_tokenizer; -typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; +typedef struct tdsqlite3_tokenizer_module tdsqlite3_tokenizer_module; +typedef struct tdsqlite3_tokenizer tdsqlite3_tokenizer; +typedef struct tdsqlite3_tokenizer_cursor tdsqlite3_tokenizer_cursor; -struct sqlite3_tokenizer_module { +struct tdsqlite3_tokenizer_module { /* ** Structure version. Should always be set to 0 or 1. @@ -145745,20 +168020,20 @@ struct sqlite3_tokenizer_module { ** This method should return either SQLITE_OK (0), or an SQLite error ** code. If SQLITE_OK is returned, then *ppTokenizer should be set ** to point at the newly created tokenizer structure. The generic - ** sqlite3_tokenizer.pModule variable should not be initialized by + ** tdsqlite3_tokenizer.pModule variable should not be initialized by ** this callback. The caller will do so. */ int (*xCreate)( int argc, /* Size of argv array */ const char *const*argv, /* Tokenizer argument strings */ - sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + tdsqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ ); /* ** Destroy an existing tokenizer. The fts3 module calls this method ** exactly once for each successful call to xCreate(). */ - int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + int (*xDestroy)(tdsqlite3_tokenizer *pTokenizer); /* ** Create a tokenizer cursor to tokenize an input buffer. The caller @@ -145766,16 +168041,16 @@ struct sqlite3_tokenizer_module { ** until the cursor is closed (using the xClose() method). */ int (*xOpen)( - sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ + tdsqlite3_tokenizer *pTokenizer, /* Tokenizer object */ const char *pInput, int nBytes, /* Input buffer */ - sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ + tdsqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ ); /* ** Destroy an existing tokenizer cursor. The fts3 module calls this ** method exactly once for each successful call to xOpen(). */ - int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + int (*xClose)(tdsqlite3_tokenizer_cursor *pCursor); /* ** Retrieve the next token from the tokenizer cursor pCursor. This @@ -145802,7 +168077,7 @@ struct sqlite3_tokenizer_module { ** should be converted to zInput. */ int (*xNext)( - sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ + tdsqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ int *piStartOffset, /* OUT: Byte offset of token in input buffer */ int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ @@ -145816,16 +168091,16 @@ struct sqlite3_tokenizer_module { /* ** Configure the language id of a tokenizer cursor. */ - int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid); + int (*xLanguageid)(tdsqlite3_tokenizer_cursor *pCsr, int iLangid); }; -struct sqlite3_tokenizer { - const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ +struct tdsqlite3_tokenizer { + const tdsqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ /* Tokenizer implementations will typically add additional fields */ }; -struct sqlite3_tokenizer_cursor { - sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ +struct tdsqlite3_tokenizer_cursor { + tdsqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ /* Tokenizer implementations will typically add additional fields */ }; @@ -145912,20 +168187,20 @@ struct Fts3HashElem { /* ** Access routines. To delete, insert a NULL pointer. */ -SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey); -SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData); -SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey); -SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*); -SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int); +SQLITE_PRIVATE void tdsqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey); +SQLITE_PRIVATE void *tdsqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData); +SQLITE_PRIVATE void *tdsqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey); +SQLITE_PRIVATE void tdsqlite3Fts3HashClear(Fts3Hash*); +SQLITE_PRIVATE Fts3HashElem *tdsqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int); /* ** Shorthand for the functions above */ -#define fts3HashInit sqlite3Fts3HashInit -#define fts3HashInsert sqlite3Fts3HashInsert -#define fts3HashFind sqlite3Fts3HashFind -#define fts3HashClear sqlite3Fts3HashClear -#define fts3HashFindElem sqlite3Fts3HashFindElem +#define fts3HashInit tdsqlite3Fts3HashInit +#define fts3HashInsert tdsqlite3Fts3HashInsert +#define fts3HashFind tdsqlite3Fts3HashFind +#define fts3HashClear tdsqlite3Fts3HashClear +#define fts3HashFindElem tdsqlite3Fts3HashFindElem /* ** Macros for looping over all elements of a hash table. The idiom is @@ -146005,6 +168280,8 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const voi */ #define FTS3_VARINT_MAX 10 +#define FTS3_BUFFER_PADDING 8 + /* ** FTS4 virtual tables may maintain multiple indexes - one index of all terms ** in the document set and zero or more prefix indexes. All indexes are stored @@ -146038,6 +168315,18 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const voi #define POS_END (0) /* Position-list terminator */ /* +** The assert_fts3_nc() macro is similar to the assert() macro, except that it +** is used for assert() conditions that are true only if it can be +** guranteed that the database is not corrupt. +*/ +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) +SQLITE_API extern int tdsqlite3_fts3_may_be_corrupt; +# define assert_fts3_nc(x) assert(tdsqlite3_fts3_may_be_corrupt || (x)) +#else +# define assert_fts3_nc(x) assert(x) +#endif + +/* ** This section provides definitions to allow the ** FTS3 extension to be compiled outside of the ** amalgamation. @@ -146051,10 +168340,10 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const voi # define ALWAYS(x) (1) # define NEVER(X) (0) #elif defined(SQLITE_DEBUG) -# define ALWAYS(x) sqlite3Fts3Always((x)!=0) -# define NEVER(x) sqlite3Fts3Never((x)!=0) -SQLITE_PRIVATE int sqlite3Fts3Always(int b); -SQLITE_PRIVATE int sqlite3Fts3Never(int b); +# define ALWAYS(x) tdsqlite3Fts3Always((x)!=0) +# define NEVER(x) tdsqlite3Fts3Never((x)!=0) +SQLITE_PRIVATE int tdsqlite3Fts3Always(int b); +SQLITE_PRIVATE int tdsqlite3Fts3Never(int b); #else # define ALWAYS(x) (x) # define NEVER(x) (x) @@ -146066,8 +168355,8 @@ SQLITE_PRIVATE int sqlite3Fts3Never(int b); typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */ typedef short int i16; /* 2-byte (or larger) signed integer */ typedef unsigned int u32; /* 4-byte unsigned integer */ -typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */ -typedef sqlite3_int64 i64; /* 8-byte signed integer */ +typedef tdsqlite3_uint64 u64; /* 8-byte unsigned integer */ +typedef tdsqlite3_int64 i64; /* 8-byte signed integer */ /* ** Macro used to suppress compiler warnings for unused parameters. @@ -146092,11 +168381,14 @@ typedef sqlite3_int64 i64; /* 8-byte signed integer */ # define TESTONLY(X) #endif +#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) +#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) + #endif /* SQLITE_AMALGAMATION */ #ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3Fts3Corrupt(void); -# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt() +SQLITE_PRIVATE int tdsqlite3Fts3Corrupt(void); +# define FTS_CORRUPT_VTAB tdsqlite3Fts3Corrupt() #else # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB #endif @@ -146123,23 +168415,25 @@ typedef struct MatchinfoBuffer MatchinfoBuffer; ** arguments. */ struct Fts3Table { - sqlite3_vtab base; /* Base class used by SQLite core */ - sqlite3 *db; /* The database connection */ + tdsqlite3_vtab base; /* Base class used by SQLite core */ + tdsqlite3 *db; /* The database connection */ const char *zDb; /* logical database name */ const char *zName; /* virtual table name */ int nColumn; /* number of named columns in virtual table */ char **azColumn; /* column names. malloced */ u8 *abNotindexed; /* True for 'notindexed' columns */ - sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ + tdsqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ char *zContentTbl; /* content=xxx option, or NULL */ char *zLanguageid; /* languageid=xxx option, or NULL */ int nAutoincrmerge; /* Value configured by 'automerge' */ u32 nLeafAdd; /* Number of leaf blocks added this trans */ + int bLock; /* Used to prevent recursive content= tbls */ /* Precompiled statements used by the implementation. Each of these ** statements is run and reset within a single virtual table API call. */ - sqlite3_stmt *aStmt[40]; + tdsqlite3_stmt *aStmt[40]; + tdsqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */ char *zReadExprlist; char *zWriteExprlist; @@ -146152,7 +168446,7 @@ struct Fts3Table { u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */ int nPgsz; /* Page size for host database */ char *zSegmentsTbl; /* Name of %_segments table */ - sqlite3_blob *pSegments; /* Blob handle open on %_segments table */ + tdsqlite3_blob *pSegments; /* Blob handle open on %_segments table */ /* ** The following array of hash tables is used to buffer pending index @@ -146192,36 +168486,47 @@ struct Fts3Table { int mxSavepoint; /* Largest valid xSavepoint integer */ #endif -#ifdef SQLITE_TEST +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* True to disable the incremental doclist optimization. This is controled ** by special insert command 'test-no-incr-doclist'. */ int bNoIncrDoclist; + + /* Number of segments in a level */ + int nMergeCount; #endif }; +/* Macro to find the number of segments to merge */ +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) +# define MergeCount(P) ((P)->nMergeCount) +#else +# define MergeCount(P) FTS3_MERGE_COUNT +#endif + /* ** When the core wants to read from the virtual table, it creates a ** virtual table cursor (an instance of the following structure) using ** the xOpen method. Cursors are destroyed using the xClose method. */ struct Fts3Cursor { - sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + tdsqlite3_vtab_cursor base; /* Base class used by SQLite core */ i16 eSearch; /* Search strategy (see below) */ u8 isEof; /* True if at End Of Results */ u8 isRequireSeek; /* True if must seek pStmt to %_content row */ - sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ + u8 bSeekStmt; /* True if pStmt is a seek */ + tdsqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ Fts3Expr *pExpr; /* Parsed MATCH query string */ int iLangid; /* Language being queried for */ int nPhrase; /* Number of matchable phrases in query */ Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */ - sqlite3_int64 iPrevId; /* Previous id read from aDoclist */ + tdsqlite3_int64 iPrevId; /* Previous id read from aDoclist */ char *pNextId; /* Pointer into the body of aDoclist */ char *aDoclist; /* List of docids for full-text queries */ int nDoclist; /* Size of buffer at aDoclist */ u8 bDesc; /* True to sort in descending order */ int eEvalmode; /* An FTS3_EVAL_XX constant */ int nRowAvg; /* Average size of database rows, in pages */ - sqlite3_int64 nDoc; /* Documents in table */ + tdsqlite3_int64 nDoc; /* Documents in table */ i64 iMinDocid; /* Minimum docid to return */ i64 iMaxDocid; /* Maximum docid to return */ int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */ @@ -146252,7 +168557,7 @@ struct Fts3Cursor { #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */ /* -** The lower 16-bits of the sqlite3_index_info.idxNum value set by +** The lower 16-bits of the tdsqlite3_index_info.idxNum value set by ** the xBestIndex() method contains the Fts3Cursor.eSearch value described ** above. The upper 16-bits contain a combination of the following ** bits, used to describe extra constraints on full-text searches. @@ -146266,8 +168571,8 @@ struct Fts3Doclist { int nAll; /* Size of a[] in bytes */ char *pNextDocid; /* Pointer to next docid */ - sqlite3_int64 iDocid; /* Current docid (if pList!=0) */ - int bFreeList; /* True if pList should be sqlite3_free()d */ + tdsqlite3_int64 iDocid; /* Current docid (if pList!=0) */ + int bFreeList; /* True if pList should be tdsqlite3_free()d */ char *pList; /* Pointer to position list following iDocid */ int nList; /* Length of position list */ }; @@ -146297,7 +168602,7 @@ struct Fts3Phrase { int bIncr; /* True if doclist is loaded incrementally */ int iDoclistToken; - /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an + /* Used by tdsqlite3Fts3EvalPhrasePoslist() if this is a descendent of an ** OR condition. */ char *pOrPoslist; i64 iOrDocid; @@ -146328,7 +168633,7 @@ struct Fts3Phrase { ** aMI[iCol*3 + 1] = Number of occurrences ** aMI[iCol*3 + 2] = Number of rows containing at least one instance ** -** The aMI array is allocated using sqlite3_malloc(). It should be freed +** The aMI array is allocated using tdsqlite3_malloc(). It should be freed ** when the expression node is. */ struct Fts3Expr { @@ -146340,7 +168645,7 @@ struct Fts3Expr { Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */ /* The following are used by the fts3_eval.c module. */ - sqlite3_int64 iDocid; /* Current docid */ + tdsqlite3_int64 iDocid; /* Current docid */ u8 bEof; /* True this expression is at EOF already */ u8 bStart; /* True if iDocid is valid */ u8 bDeferred; /* True if this expression is entirely deferred */ @@ -146369,47 +168674,47 @@ struct Fts3Expr { /* fts3_write.c */ -SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*); -SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *); -SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *); -SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *); -SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64, - sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**); -SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( +SQLITE_PRIVATE int tdsqlite3Fts3UpdateMethod(tdsqlite3_vtab*,int,tdsqlite3_value**,tdsqlite3_int64*); +SQLITE_PRIVATE int tdsqlite3Fts3PendingTermsFlush(Fts3Table *); +SQLITE_PRIVATE void tdsqlite3Fts3PendingTermsClear(Fts3Table *); +SQLITE_PRIVATE int tdsqlite3Fts3Optimize(Fts3Table *); +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderNew(int, int, tdsqlite3_int64, + tdsqlite3_int64, tdsqlite3_int64, const char *, int, Fts3SegReader**); +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderPending( Fts3Table*,int,const char*,int,int,Fts3SegReader**); -SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *); -SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **); -SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*); +SQLITE_PRIVATE void tdsqlite3Fts3SegReaderFree(Fts3SegReader *); +SQLITE_PRIVATE int tdsqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, tdsqlite3_stmt **); +SQLITE_PRIVATE int tdsqlite3Fts3ReadBlock(Fts3Table*, tdsqlite3_int64, char **, int*, int*); -SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **); -SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **); +SQLITE_PRIVATE int tdsqlite3Fts3SelectDoctotal(Fts3Table *, tdsqlite3_stmt **); +SQLITE_PRIVATE int tdsqlite3Fts3SelectDocsize(Fts3Table *, tdsqlite3_int64, tdsqlite3_stmt **); #ifndef SQLITE_DISABLE_FTS4_DEFERRED -SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *); -SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int); -SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *); -SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *); -SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *); +SQLITE_PRIVATE void tdsqlite3Fts3FreeDeferredTokens(Fts3Cursor *); +SQLITE_PRIVATE int tdsqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int); +SQLITE_PRIVATE int tdsqlite3Fts3CacheDeferredDoclists(Fts3Cursor *); +SQLITE_PRIVATE void tdsqlite3Fts3FreeDeferredDoclists(Fts3Cursor *); +SQLITE_PRIVATE int tdsqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *); #else -# define sqlite3Fts3FreeDeferredTokens(x) -# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK -# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK -# define sqlite3Fts3FreeDeferredDoclists(x) -# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK +# define tdsqlite3Fts3FreeDeferredTokens(x) +# define tdsqlite3Fts3DeferToken(x,y,z) SQLITE_OK +# define tdsqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK +# define tdsqlite3Fts3FreeDeferredDoclists(x) +# define tdsqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK #endif -SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *); -SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *); +SQLITE_PRIVATE void tdsqlite3Fts3SegmentsClose(Fts3Table *); +SQLITE_PRIVATE int tdsqlite3Fts3MaxLevel(Fts3Table *, int *); -/* Special values interpreted by sqlite3SegReaderCursor() */ +/* Special values interpreted by tdsqlite3SegReaderCursor() */ #define FTS3_SEGCURSOR_PENDING -1 #define FTS3_SEGCURSOR_ALL -2 -SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*); -SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *); -SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *); +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*); +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *); +SQLITE_PRIVATE void tdsqlite3Fts3SegReaderFinish(Fts3MultiSegReader *); -SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderCursor(Fts3Table *, int, int, int, const char *, int, int, int, Fts3MultiSegReader *); /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */ @@ -146429,7 +168734,7 @@ struct Fts3SegFilter { }; struct Fts3MultiSegReader { - /* Used internally by sqlite3Fts3SegReaderXXX() calls */ + /* Used internally by tdsqlite3Fts3SegReaderXXX() calls */ Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */ int nSegment; /* Size of apSegment array */ int nAdvance; /* How many seg-readers to advance */ @@ -146451,76 +168756,78 @@ struct Fts3MultiSegReader { int nDoclist; /* Size of aDoclist[] in bytes */ }; -SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int); +SQLITE_PRIVATE int tdsqlite3Fts3Incrmerge(Fts3Table*,int,int); #define fts3GetVarint32(p, piVal) ( \ - (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \ + (*(u8*)(p)&0x80) ? tdsqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \ ) /* fts3.c */ -SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...); -SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64); -SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *); -SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *); -SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64); -SQLITE_PRIVATE void sqlite3Fts3Dequote(char *); -SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*); -SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *); -SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *); -SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*); -SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc); +SQLITE_PRIVATE void tdsqlite3Fts3ErrMsg(char**,const char*,...); +SQLITE_PRIVATE int tdsqlite3Fts3PutVarint(char *, tdsqlite3_int64); +SQLITE_PRIVATE int tdsqlite3Fts3GetVarint(const char *, sqlite_int64 *); +SQLITE_PRIVATE int tdsqlite3Fts3GetVarintU(const char *, sqlite_uint64 *); +SQLITE_PRIVATE int tdsqlite3Fts3GetVarintBounded(const char*,const char*,tdsqlite3_int64*); +SQLITE_PRIVATE int tdsqlite3Fts3GetVarint32(const char *, int *); +SQLITE_PRIVATE int tdsqlite3Fts3VarintLen(tdsqlite3_uint64); +SQLITE_PRIVATE void tdsqlite3Fts3Dequote(char *); +SQLITE_PRIVATE void tdsqlite3Fts3DoclistPrev(int,char*,int,char**,tdsqlite3_int64*,int*,u8*); +SQLITE_PRIVATE int tdsqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *); +SQLITE_PRIVATE int tdsqlite3Fts3FirstFilter(tdsqlite3_int64, char *, int, char *); +SQLITE_PRIVATE void tdsqlite3Fts3CreateStatTable(int*, Fts3Table*); +SQLITE_PRIVATE int tdsqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc); /* fts3_tokenizer.c */ -SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *); -SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *); -SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, - sqlite3_tokenizer **, char ** +SQLITE_PRIVATE const char *tdsqlite3Fts3NextToken(const char *, int *); +SQLITE_PRIVATE int tdsqlite3Fts3InitHashTable(tdsqlite3 *, Fts3Hash *, const char *); +SQLITE_PRIVATE int tdsqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, + tdsqlite3_tokenizer **, char ** ); -SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char); +SQLITE_PRIVATE int tdsqlite3Fts3IsIdChar(char); /* fts3_snippet.c */ -SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*); -SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *, +SQLITE_PRIVATE void tdsqlite3Fts3Offsets(tdsqlite3_context*, Fts3Cursor*); +SQLITE_PRIVATE void tdsqlite3Fts3Snippet(tdsqlite3_context *, Fts3Cursor *, const char *, const char *, const char *, int, int ); -SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *); -SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p); +SQLITE_PRIVATE void tdsqlite3Fts3Matchinfo(tdsqlite3_context *, Fts3Cursor *, const char *); +SQLITE_PRIVATE void tdsqlite3Fts3MIBufferFree(MatchinfoBuffer *p); /* fts3_expr.c */ -SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int, +SQLITE_PRIVATE int tdsqlite3Fts3ExprParse(tdsqlite3_tokenizer *, int, char **, int, int, int, const char *, int, Fts3Expr **, char ** ); -SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *); +SQLITE_PRIVATE void tdsqlite3Fts3ExprFree(Fts3Expr *); #ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db); -SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db); +SQLITE_PRIVATE int tdsqlite3Fts3ExprInitTestInterface(tdsqlite3 *db, Fts3Hash*); +SQLITE_PRIVATE int tdsqlite3Fts3InitTerm(tdsqlite3 *db); #endif -SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int, - sqlite3_tokenizer_cursor ** +SQLITE_PRIVATE int tdsqlite3Fts3OpenTokenizer(tdsqlite3_tokenizer *, int, const char *, int, + tdsqlite3_tokenizer_cursor ** ); /* fts3_aux.c */ -SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db); +SQLITE_PRIVATE int tdsqlite3Fts3InitAux(tdsqlite3 *db); -SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *); +SQLITE_PRIVATE void tdsqlite3Fts3EvalPhraseCleanup(Fts3Phrase *); -SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( +SQLITE_PRIVATE int tdsqlite3Fts3MsrIncrStart( Fts3Table*, Fts3MultiSegReader*, int, const char*, int); -SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( - Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *); -SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); -SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *); -SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr); +SQLITE_PRIVATE int tdsqlite3Fts3MsrIncrNext( + Fts3Table *, Fts3MultiSegReader *, tdsqlite3_int64 *, char **, int *); +SQLITE_PRIVATE int tdsqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); +SQLITE_PRIVATE int tdsqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *); +SQLITE_PRIVATE int tdsqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr); /* fts3_tokenize_vtab.c */ -SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *); +SQLITE_PRIVATE int tdsqlite3Fts3InitTok(tdsqlite3*, Fts3Hash *); /* fts3_unicode2.c (functions generated by parsing unicode text files) */ #ifndef SQLITE_DISABLE_FTS3_UNICODE -SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int); -SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int); -SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int); +SQLITE_PRIVATE int tdsqlite3FtsUnicodeFold(int, int); +SQLITE_PRIVATE int tdsqlite3FtsUnicodeIsalnum(int); +SQLITE_PRIVATE int tdsqlite3FtsUnicodeIsdiacritic(int); #endif #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */ @@ -146543,7 +168850,7 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int); /* #include "fts3.h" */ #ifndef SQLITE_CORE -/* # include "sqlite3ext.h" */ +/* # include "tdsqlite3ext.h" */ SQLITE_EXTENSION_INIT1 #endif @@ -146554,17 +168861,25 @@ static int fts3TermSegReaderCursor( #ifndef SQLITE_AMALGAMATION # if defined(SQLITE_DEBUG) -SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; } -SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; } +SQLITE_PRIVATE int tdsqlite3Fts3Always(int b) { assert( b ); return b; } +SQLITE_PRIVATE int tdsqlite3Fts3Never(int b) { assert( !b ); return b; } # endif #endif +/* +** This variable is set to false when running tests for which the on disk +** structures should not be corrupt. Otherwise, true. If it is false, extra +** assert() conditions in the fts3 code are activated - conditions that are +** only true if it is guaranteed that the fts3 database is not corrupt. +*/ +SQLITE_API int tdsqlite3_fts3_may_be_corrupt = 1; + /* ** Write a 64-bit variable-length integer to memory starting at p[0]. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes. ** The number of bytes written is returned. */ -SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){ +SQLITE_PRIVATE int tdsqlite3Fts3PutVarint(char *p, sqlite_int64 v){ unsigned char *q = (unsigned char *) p; sqlite_uint64 vu = v; do{ @@ -146577,19 +168892,15 @@ SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){ } #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \ - v = (v & mask1) | ( (*ptr++) << shift ); \ + v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift ); \ if( (v & mask2)==0 ){ var = v; return ret; } #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \ v = (*ptr++); \ if( (v & mask2)==0 ){ var = v; return ret; } -/* -** Read a 64-bit variable-length integer from memory starting at p[0]. -** Return the number of bytes read, or 0 on error. -** The value is stored in *v. -*/ -SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){ - const char *pStart = p; +SQLITE_PRIVATE int tdsqlite3Fts3GetVarintU(const char *pBuf, sqlite_uint64 *v){ + const unsigned char *p = (const unsigned char*)pBuf; + const unsigned char *pStart = p; u32 a; u64 b; int shift; @@ -146609,32 +168920,70 @@ SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){ return (int)(p - pStart); } +/* +** Read a 64-bit variable-length integer from memory starting at p[0]. +** Return the number of bytes read, or 0 on error. +** The value is stored in *v. +*/ +SQLITE_PRIVATE int tdsqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){ + return tdsqlite3Fts3GetVarintU(pBuf, (tdsqlite3_uint64*)v); +} + +/* +** Read a 64-bit variable-length integer from memory starting at p[0] and +** not extending past pEnd[-1]. +** Return the number of bytes read, or 0 on error. +** The value is stored in *v. +*/ +SQLITE_PRIVATE int tdsqlite3Fts3GetVarintBounded( + const char *pBuf, + const char *pEnd, + sqlite_int64 *v +){ + const unsigned char *p = (const unsigned char*)pBuf; + const unsigned char *pStart = p; + const unsigned char *pX = (const unsigned char*)pEnd; + u64 b = 0; + int shift; + for(shift=0; shift<=63; shift+=7){ + u64 c = p<pX ? *p : 0; + p++; + b += (c&0x7F) << shift; + if( (c & 0x80)==0 ) break; + } + *v = b; + return (int)(p - pStart); +} + /* -** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a -** 32-bit integer before it is returned. +** Similar to tdsqlite3Fts3GetVarint(), except that the output is truncated to +** a non-negative 32-bit integer before it is returned. */ -SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){ +SQLITE_PRIVATE int tdsqlite3Fts3GetVarint32(const char *p, int *pi){ + const unsigned char *ptr = (const unsigned char*)p; u32 a; #ifndef fts3GetVarint32 - GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1); + GETVARINT_INIT(a, ptr, 0, 0x00, 0x80, *pi, 1); #else - a = (*p++); + a = (*ptr++); assert( a & 0x80 ); #endif - GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2); - GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3); - GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4); + GETVARINT_STEP(a, ptr, 7, 0x7F, 0x4000, *pi, 2); + GETVARINT_STEP(a, ptr, 14, 0x3FFF, 0x200000, *pi, 3); + GETVARINT_STEP(a, ptr, 21, 0x1FFFFF, 0x10000000, *pi, 4); a = (a & 0x0FFFFFFF ); - *pi = (int)(a | ((u32)(*p & 0x0F) << 28)); + *pi = (int)(a | ((u32)(*ptr & 0x07) << 28)); + assert( 0==(a & 0x80000000) ); + assert( *pi>=0 ); return 5; } /* ** Return the number of bytes required to encode v as a varint */ -SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){ +SQLITE_PRIVATE int tdsqlite3Fts3VarintLen(tdsqlite3_uint64 v){ int i = 0; do{ i++; @@ -146657,7 +169006,7 @@ SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){ ** `mno` becomes mno ** */ -SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){ +SQLITE_PRIVATE void tdsqlite3Fts3Dequote(char *z){ char quote; /* Quote character (if any ) */ quote = z[0]; @@ -146686,9 +169035,9 @@ SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){ ** to the first byte past the end of the varint. Add the value of the varint ** to *pVal. */ -static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){ - sqlite3_int64 iVal; - *pp += sqlite3Fts3GetVarint(*pp, &iVal); +static void fts3GetDeltaVarint(char **pp, tdsqlite3_int64 *pVal){ + tdsqlite3_int64 iVal; + *pp += tdsqlite3Fts3GetVarint(*pp, &iVal); *pVal += iVal; } @@ -146704,9 +169053,9 @@ static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){ static void fts3GetReverseVarint( char **pp, char *pStart, - sqlite3_int64 *pVal + tdsqlite3_int64 *pVal ){ - sqlite3_int64 iVal; + tdsqlite3_int64 iVal; char *p; /* Pointer p now points at the first byte past the varint we are @@ -146716,14 +169065,14 @@ static void fts3GetReverseVarint( p++; *pp = p; - sqlite3Fts3GetVarint(p, &iVal); + tdsqlite3Fts3GetVarint(p, &iVal); *pVal = iVal; } /* ** The xDisconnect() virtual table method. */ -static int fts3DisconnectMethod(sqlite3_vtab *pVtab){ +static int fts3DisconnectMethod(tdsqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table *)pVtab; int i; @@ -146731,30 +169080,31 @@ static int fts3DisconnectMethod(sqlite3_vtab *pVtab){ assert( p->pSegments==0 ); /* Free any prepared statements held */ + tdsqlite3_finalize(p->pSeekStmt); for(i=0; i<SizeofArray(p->aStmt); i++){ - sqlite3_finalize(p->aStmt[i]); + tdsqlite3_finalize(p->aStmt[i]); } - sqlite3_free(p->zSegmentsTbl); - sqlite3_free(p->zReadExprlist); - sqlite3_free(p->zWriteExprlist); - sqlite3_free(p->zContentTbl); - sqlite3_free(p->zLanguageid); + tdsqlite3_free(p->zSegmentsTbl); + tdsqlite3_free(p->zReadExprlist); + tdsqlite3_free(p->zWriteExprlist); + tdsqlite3_free(p->zContentTbl); + tdsqlite3_free(p->zLanguageid); /* Invoke the tokenizer destructor to free the tokenizer. */ p->pTokenizer->pModule->xDestroy(p->pTokenizer); - sqlite3_free(p); + tdsqlite3_free(p); return SQLITE_OK; } /* ** Write an error message into *pzErr */ -SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){ +SQLITE_PRIVATE void tdsqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){ va_list ap; - sqlite3_free(*pzErr); + tdsqlite3_free(*pzErr); va_start(ap, zFormat); - *pzErr = sqlite3_vmprintf(zFormat, ap); + *pzErr = tdsqlite3_vmprintf(zFormat, ap); va_end(ap); } @@ -146767,7 +169117,7 @@ SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){ */ static void fts3DbExec( int *pRc, /* Success code */ - sqlite3 *db, /* Database in which to run SQL */ + tdsqlite3 *db, /* Database in which to run SQL */ const char *zFormat, /* Format string for SQL */ ... /* Arguments to the format string */ ){ @@ -146775,33 +169125,38 @@ static void fts3DbExec( char *zSql; if( *pRc ) return; va_start(ap, zFormat); - zSql = sqlite3_vmprintf(zFormat, ap); + zSql = tdsqlite3_vmprintf(zFormat, ap); va_end(ap); if( zSql==0 ){ *pRc = SQLITE_NOMEM; }else{ - *pRc = sqlite3_exec(db, zSql, 0, 0, 0); - sqlite3_free(zSql); + *pRc = tdsqlite3_exec(db, zSql, 0, 0, 0); + tdsqlite3_free(zSql); } } /* ** The xDestroy() virtual table method. */ -static int fts3DestroyMethod(sqlite3_vtab *pVtab){ +static int fts3DestroyMethod(tdsqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table *)pVtab; int rc = SQLITE_OK; /* Return code */ const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */ - sqlite3 *db = p->db; /* Database handle */ + tdsqlite3 *db = p->db; /* Database handle */ /* Drop the shadow tables */ - if( p->zContentTbl==0 ){ - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName); - } - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName); - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName); - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName); - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName); + fts3DbExec(&rc, db, + "DROP TABLE IF EXISTS %Q.'%q_segments';" + "DROP TABLE IF EXISTS %Q.'%q_segdir';" + "DROP TABLE IF EXISTS %Q.'%q_docsize';" + "DROP TABLE IF EXISTS %Q.'%q_stat';" + "%s DROP TABLE IF EXISTS %Q.'%q_content';", + zDb, p->zName, + zDb, p->zName, + zDb, p->zName, + zDb, p->zName, + (p->zContentTbl ? "--" : ""), zDb,p->zName + ); /* If everything has worked, invoke fts3DisconnectMethod() to free the ** memory associated with the Fts3Table structure and return SQLITE_OK. @@ -146812,7 +169167,7 @@ static int fts3DestroyMethod(sqlite3_vtab *pVtab){ /* -** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table +** Invoke tdsqlite3_declare_vtab() to declare the schema for the FTS3 table ** passed as the first argument. This is done as part of the xConnect() ** and xCreate() methods. ** @@ -146829,27 +169184,27 @@ static void fts3DeclareVtab(int *pRc, Fts3Table *p){ const char *zLanguageid; zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid"); - sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); + tdsqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); /* Create a list of user columns for the virtual table */ - zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]); + zCols = tdsqlite3_mprintf("%Q, ", p->azColumn[0]); for(i=1; zCols && i<p->nColumn; i++){ - zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]); + zCols = tdsqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]); } /* Create the whole "CREATE TABLE" statement to pass to SQLite */ - zSql = sqlite3_mprintf( + zSql = tdsqlite3_mprintf( "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", zCols, p->zName, zLanguageid ); if( !zCols || !zSql ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_declare_vtab(p->db, zSql); + rc = tdsqlite3_declare_vtab(p->db, zSql); } - sqlite3_free(zSql); - sqlite3_free(zCols); + tdsqlite3_free(zSql); + tdsqlite3_free(zCols); *pRc = rc; } } @@ -146857,7 +169212,7 @@ static void fts3DeclareVtab(int *pRc, Fts3Table *p){ /* ** Create the %_stat table if it does not already exist. */ -SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){ +SQLITE_PRIVATE void tdsqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){ fts3DbExec(pRc, p->db, "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'" "(id INTEGER PRIMARY KEY, value BLOB);", @@ -146878,20 +169233,20 @@ SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){ static int fts3CreateTables(Fts3Table *p){ int rc = SQLITE_OK; /* Return code */ int i; /* Iterator variable */ - sqlite3 *db = p->db; /* The database connection */ + tdsqlite3 *db = p->db; /* The database connection */ if( p->zContentTbl==0 ){ const char *zLanguageid = p->zLanguageid; char *zContentCols; /* Columns of %_content table */ /* Create a list of user columns for the content table */ - zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY"); + zContentCols = tdsqlite3_mprintf("docid INTEGER PRIMARY KEY"); for(i=0; zContentCols && i<p->nColumn; i++){ char *z = p->azColumn[i]; - zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z); + zContentCols = tdsqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z); } if( zLanguageid && zContentCols ){ - zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid); + zContentCols = tdsqlite3_mprintf("%z, langid", zContentCols, zLanguageid); } if( zContentCols==0 ) rc = SQLITE_NOMEM; @@ -146900,7 +169255,7 @@ static int fts3CreateTables(Fts3Table *p){ "CREATE TABLE %Q.'%q_content'(%s)", p->zDb, p->zName, zContentCols ); - sqlite3_free(zContentCols); + tdsqlite3_free(zContentCols); } /* Create other tables */ @@ -146928,7 +169283,7 @@ static int fts3CreateTables(Fts3Table *p){ } assert( p->bHasStat==p->bFts4 ); if( p->bHasStat ){ - sqlite3Fts3CreateStatTable(&rc, p); + tdsqlite3Fts3CreateStatTable(&rc, p); } return rc; } @@ -146944,24 +169299,24 @@ static void fts3DatabasePageSize(int *pRc, Fts3Table *p){ if( *pRc==SQLITE_OK ){ int rc; /* Return code */ char *zSql; /* SQL text "PRAGMA %Q.page_size" */ - sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */ + tdsqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */ - zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb); + zSql = tdsqlite3_mprintf("PRAGMA %Q.page_size", p->zDb); if( !zSql ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); + rc = tdsqlite3_prepare(p->db, zSql, -1, &pStmt, 0); if( rc==SQLITE_OK ){ - sqlite3_step(pStmt); - p->nPgsz = sqlite3_column_int(pStmt, 0); - rc = sqlite3_finalize(pStmt); + tdsqlite3_step(pStmt); + p->nPgsz = tdsqlite3_column_int(pStmt, 0); + rc = tdsqlite3_finalize(pStmt); }else if( rc==SQLITE_AUTH ){ p->nPgsz = 1024; rc = SQLITE_OK; } } assert( p->nPgsz>0 || rc!=SQLITE_OK ); - sqlite3_free(zSql); + tdsqlite3_free(zSql); *pRc = rc; } } @@ -146988,9 +169343,9 @@ static int fts3IsSpecialColumn( } *pnKey = (int)(zCsr-z); - zValue = sqlite3_mprintf("%s", &zCsr[1]); + zValue = tdsqlite3_mprintf("%s", &zCsr[1]); if( zValue ){ - sqlite3Fts3Dequote(zValue); + tdsqlite3Fts3Dequote(zValue); } *pzValue = zValue; return 1; @@ -147009,15 +169364,15 @@ static void fts3Appendf( va_list ap; char *z; va_start(ap, zFormat); - z = sqlite3_vmprintf(zFormat, ap); + z = tdsqlite3_vmprintf(zFormat, ap); va_end(ap); if( z && *pz ){ - char *z2 = sqlite3_mprintf("%s%s", *pz, z); - sqlite3_free(z); + char *z2 = tdsqlite3_mprintf("%s%s", *pz, z); + tdsqlite3_free(z); z = z2; } if( z==0 ) *pRc = SQLITE_NOMEM; - sqlite3_free(*pz); + tdsqlite3_free(*pz); *pz = z; } } @@ -147028,15 +169383,15 @@ static void fts3Appendf( ** ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\"" ** -** The pointer returned points to memory obtained from sqlite3_malloc(). It -** is the callers responsibility to call sqlite3_free() to release this +** The pointer returned points to memory obtained from tdsqlite3_malloc(). It +** is the callers responsibility to call tdsqlite3_free() to release this ** memory. */ static char *fts3QuoteId(char const *zInput){ - int nRet; + tdsqlite3_int64 nRet; char *zRet; nRet = 2 + (int)strlen(zInput)*2 + 1; - zRet = sqlite3_malloc(nRet); + zRet = tdsqlite3_malloc64(nRet); if( zRet ){ int i; char *z = zRet; @@ -147066,7 +169421,7 @@ static char *fts3QuoteId(char const *zInput){ ** ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x" ** -** The pointer returned points to a buffer allocated by sqlite3_malloc(). It +** The pointer returned points to a buffer allocated by tdsqlite3_malloc(). It ** is the responsibility of the caller to eventually free it. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and @@ -147093,7 +169448,7 @@ static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){ if( p->zLanguageid ){ fts3Appendf(pRc, &zRet, ", x.%Q", "langid"); } - sqlite3_free(zFree); + tdsqlite3_free(zFree); }else{ fts3Appendf(pRc, &zRet, "rowid"); for(i=0; i<p->nColumn; i++){ @@ -147123,7 +169478,7 @@ static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){ ** ** "?, zip(?), zip(?), zip(?)" ** -** The pointer returned points to a buffer allocated by sqlite3_malloc(). It +** The pointer returned points to a buffer allocated by tdsqlite3_malloc(). It ** is the responsibility of the caller to eventually free it. ** ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and @@ -147149,7 +169504,7 @@ static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){ if( p->zLanguageid ){ fts3Appendf(pRc, &zRet, ", ?"); } - sqlite3_free(zFree); + tdsqlite3_free(zFree); return zRet; } @@ -147199,7 +169554,7 @@ static int fts3GobbleInt(const char **pp, int *pnOut){ ** array. If an error does occur, an SQLite error code is returned. ** ** Regardless of whether or not an error is returned, it is the responsibility -** of the caller to call sqlite3_free() on the output array to free it. +** of the caller to call tdsqlite3_free() on the output array to free it. */ static int fts3PrefixParameter( const char *zParam, /* ABC in prefix=ABC parameter to parse */ @@ -147217,7 +169572,7 @@ static int fts3PrefixParameter( } } - aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex); + aIndex = tdsqlite3_malloc64(sizeof(struct Fts3Index) * nIndex); *apIndex = aIndex; if( !aIndex ){ return SQLITE_NOMEM; @@ -147264,14 +169619,14 @@ static int fts3PrefixParameter( ** the name of the corresponding column in table xxx. The array ** and its contents are allocated using a single allocation. It ** is the responsibility of the caller to free this allocation -** by eventually passing the *pazCol value to sqlite3_free(). +** by eventually passing the *pazCol value to tdsqlite3_free(). ** ** If the table cannot be found, an error code is returned and the output ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is ** returned (and the output variables are undefined). */ static int fts3ContentColumns( - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */ const char *zTbl, /* Name of content table */ const char ***pazCol, /* OUT: Malloc'd array of column names */ @@ -147281,49 +169636,49 @@ static int fts3ContentColumns( ){ int rc = SQLITE_OK; /* Return code */ char *zSql; /* "SELECT *" statement on zTbl */ - sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */ + tdsqlite3_stmt *pStmt = 0; /* Compiled version of zSql */ - zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl); + zSql = tdsqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl); if( !zSql ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + rc = tdsqlite3_prepare(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ - sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db)); + tdsqlite3Fts3ErrMsg(pzErr, "%s", tdsqlite3_errmsg(db)); } } - sqlite3_free(zSql); + tdsqlite3_free(zSql); if( rc==SQLITE_OK ){ const char **azCol; /* Output array */ - int nStr = 0; /* Size of all column names (incl. 0x00) */ + tdsqlite3_int64 nStr = 0; /* Size of all column names (incl. 0x00) */ int nCol; /* Number of table columns */ int i; /* Used to iterate through columns */ /* Loop through the returned columns. Set nStr to the number of bytes of ** space required to store a copy of each column name, including the ** nul-terminator byte. */ - nCol = sqlite3_column_count(pStmt); + nCol = tdsqlite3_column_count(pStmt); for(i=0; i<nCol; i++){ - const char *zCol = sqlite3_column_name(pStmt, i); - nStr += (int)strlen(zCol) + 1; + const char *zCol = tdsqlite3_column_name(pStmt, i); + nStr += strlen(zCol) + 1; } /* Allocate and populate the array to return. */ - azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr); + azCol = (const char **)tdsqlite3_malloc64(sizeof(char *) * nCol + nStr); if( azCol==0 ){ rc = SQLITE_NOMEM; }else{ char *p = (char *)&azCol[nCol]; for(i=0; i<nCol; i++){ - const char *zCol = sqlite3_column_name(pStmt, i); + const char *zCol = tdsqlite3_column_name(pStmt, i); int n = (int)strlen(zCol)+1; memcpy(p, zCol, n); azCol[i] = p; p += n; } } - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); /* Set the output variables. */ *pnCol = nCol; @@ -147347,18 +169702,18 @@ static int fts3ContentColumns( */ static int fts3InitVtab( int isCreate, /* True for xCreate, false for xConnect */ - sqlite3 *db, /* The SQLite database connection */ + tdsqlite3 *db, /* The SQLite database connection */ void *pAux, /* Hash table containing tokenizers */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ + tdsqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ char **pzErr /* Write any error message here */ ){ Fts3Hash *pHash = (Fts3Hash *)pAux; Fts3Table *p = 0; /* Pointer to allocated vtab */ int rc = SQLITE_OK; /* Return code */ int i; /* Iterator variable */ - int nByte; /* Size of allocation used for *p */ + tdsqlite3_int64 nByte; /* Size of allocation used for *p */ int iCol; /* Column index */ int nString = 0; /* Bytes required to hold all column names */ int nCol = 0; /* Number of columns in the FTS table */ @@ -147367,7 +169722,7 @@ static int fts3InitVtab( int nName; /* Bytes required to hold table name */ int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */ const char **aCol; /* Array of column names */ - sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */ + tdsqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */ int nIndex = 0; /* Size of aIndex[] array */ struct Fts3Index *aIndex = 0; /* Array of indexes for this table */ @@ -147384,18 +169739,18 @@ static int fts3InitVtab( int nNotindexed = 0; /* Size of azNotindexed[] array */ assert( strlen(argv[0])==4 ); - assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4) - || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4) + assert( (tdsqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4) + || (tdsqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4) ); nDb = (int)strlen(argv[1]) + 1; nName = (int)strlen(argv[2]) + 1; nByte = sizeof(const char *) * (argc-2); - aCol = (const char **)sqlite3_malloc(nByte); + aCol = (const char **)tdsqlite3_malloc64(nByte); if( aCol ){ memset((void*)aCol, 0, nByte); - azNotindexed = (char **)sqlite3_malloc(nByte); + azNotindexed = (char **)tdsqlite3_malloc64(nByte); } if( azNotindexed ){ memset(azNotindexed, 0, nByte); @@ -147424,10 +169779,10 @@ static int fts3InitVtab( /* Check if this is a tokenizer specification */ if( !pTokenizer && strlen(z)>8 - && 0==sqlite3_strnicmp(z, "tokenize", 8) - && 0==sqlite3Fts3IsIdChar(z[8]) + && 0==tdsqlite3_strnicmp(z, "tokenize", 8) + && 0==tdsqlite3Fts3IsIdChar(z[8]) ){ - rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr); + rc = tdsqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr); } /* Check if it is an FTS4 special argument. */ @@ -147452,71 +169807,72 @@ static int fts3InitVtab( }else{ for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){ struct Fts4Option *pOp = &aFts4Opt[iOpt]; - if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){ + if( nKey==pOp->nOpt && !tdsqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){ break; } } - if( iOpt==SizeofArray(aFts4Opt) ){ - sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z); - rc = SQLITE_ERROR; - }else{ - switch( iOpt ){ - case 0: /* MATCHINFO */ - if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){ - sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal); - rc = SQLITE_ERROR; - } - bNoDocsize = 1; - break; + switch( iOpt ){ + case 0: /* MATCHINFO */ + if( strlen(zVal)!=4 || tdsqlite3_strnicmp(zVal, "fts3", 4) ){ + tdsqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal); + rc = SQLITE_ERROR; + } + bNoDocsize = 1; + break; - case 1: /* PREFIX */ - sqlite3_free(zPrefix); - zPrefix = zVal; - zVal = 0; - break; + case 1: /* PREFIX */ + tdsqlite3_free(zPrefix); + zPrefix = zVal; + zVal = 0; + break; - case 2: /* COMPRESS */ - sqlite3_free(zCompress); - zCompress = zVal; - zVal = 0; - break; + case 2: /* COMPRESS */ + tdsqlite3_free(zCompress); + zCompress = zVal; + zVal = 0; + break; - case 3: /* UNCOMPRESS */ - sqlite3_free(zUncompress); - zUncompress = zVal; - zVal = 0; - break; + case 3: /* UNCOMPRESS */ + tdsqlite3_free(zUncompress); + zUncompress = zVal; + zVal = 0; + break; - case 4: /* ORDER */ - if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) - && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) - ){ - sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal); - rc = SQLITE_ERROR; - } - bDescIdx = (zVal[0]=='d' || zVal[0]=='D'); - break; + case 4: /* ORDER */ + if( (strlen(zVal)!=3 || tdsqlite3_strnicmp(zVal, "asc", 3)) + && (strlen(zVal)!=4 || tdsqlite3_strnicmp(zVal, "desc", 4)) + ){ + tdsqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal); + rc = SQLITE_ERROR; + } + bDescIdx = (zVal[0]=='d' || zVal[0]=='D'); + break; - case 5: /* CONTENT */ - sqlite3_free(zContent); - zContent = zVal; - zVal = 0; - break; + case 5: /* CONTENT */ + tdsqlite3_free(zContent); + zContent = zVal; + zVal = 0; + break; - case 6: /* LANGUAGEID */ - assert( iOpt==6 ); - sqlite3_free(zLanguageid); - zLanguageid = zVal; - zVal = 0; - break; + case 6: /* LANGUAGEID */ + assert( iOpt==6 ); + tdsqlite3_free(zLanguageid); + zLanguageid = zVal; + zVal = 0; + break; - case 7: /* NOTINDEXED */ - azNotindexed[nNotindexed++] = zVal; - zVal = 0; - break; - } + case 7: /* NOTINDEXED */ + azNotindexed[nNotindexed++] = zVal; + zVal = 0; + break; + + default: + assert( iOpt==SizeofArray(aFts4Opt) ); + tdsqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z); + rc = SQLITE_ERROR; + break; } - sqlite3_free(zVal); + tdsqlite3_free(zVal); } } @@ -147535,12 +169891,12 @@ static int fts3InitVtab( ** TABLE statement, use all columns from the content table. */ if( rc==SQLITE_OK && zContent ){ - sqlite3_free(zCompress); - sqlite3_free(zUncompress); + tdsqlite3_free(zCompress); + tdsqlite3_free(zUncompress); zCompress = 0; zUncompress = 0; if( nCol==0 ){ - sqlite3_free((void*)aCol); + tdsqlite3_free((void*)aCol); aCol = 0; rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr); @@ -147549,7 +169905,7 @@ static int fts3InitVtab( if( rc==SQLITE_OK && zLanguageid ){ int j; for(j=0; j<nCol; j++){ - if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){ + if( tdsqlite3_stricmp(zLanguageid, aCol[j])==0 ){ int k; for(k=j; k<nCol; k++) aCol[k] = aCol[k+1]; nCol--; @@ -147569,7 +169925,7 @@ static int fts3InitVtab( } if( pTokenizer==0 ){ - rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr); + rc = tdsqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr); if( rc!=SQLITE_OK ) goto fts3_init_out; } assert( pTokenizer ); @@ -147577,7 +169933,7 @@ static int fts3InitVtab( rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex); if( rc==SQLITE_ERROR ){ assert( zPrefix ); - sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix); + tdsqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix); } if( rc!=SQLITE_OK ) goto fts3_init_out; @@ -147589,7 +169945,7 @@ static int fts3InitVtab( nName + /* zName */ nDb + /* zDb */ nString; /* Space for azColumn strings */ - p = (Fts3Table*)sqlite3_malloc(nByte); + p = (Fts3Table*)tdsqlite3_malloc64(nByte); if( p==0 ){ rc = SQLITE_NOMEM; goto fts3_init_out; @@ -147602,9 +169958,9 @@ static int fts3InitVtab( p->pTokenizer = pTokenizer; p->nMaxPendingData = FTS3_MAX_PENDING_DATA; p->bHasDocsize = (isFts4 && bNoDocsize==0); - p->bHasStat = isFts4; - p->bFts4 = isFts4; - p->bDescIdx = bDescIdx; + p->bHasStat = (u8)isFts4; + p->bFts4 = (u8)isFts4; + p->bDescIdx = (u8)bDescIdx; p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */ p->zContentTbl = zContent; p->zLanguageid = zLanguageid; @@ -147634,10 +169990,12 @@ static int fts3InitVtab( for(iCol=0; iCol<nCol; iCol++){ char *z; int n = 0; - z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n); - memcpy(zCsr, z, n); + z = (char *)tdsqlite3Fts3NextToken(aCol[iCol], &n); + if( n>0 ){ + memcpy(zCsr, z, n); + } zCsr[n] = '\0'; - sqlite3Fts3Dequote(zCsr); + tdsqlite3Fts3Dequote(zCsr); p->azColumn[iCol] = zCsr; zCsr += n+1; assert( zCsr <= &((char *)p)[nByte] ); @@ -147649,17 +170007,17 @@ static int fts3InitVtab( for(i=0; i<nNotindexed; i++){ char *zNot = azNotindexed[i]; if( zNot && n==(int)strlen(zNot) - && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) + && 0==tdsqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){ p->abNotindexed[iCol] = 1; - sqlite3_free(zNot); + tdsqlite3_free(zNot); azNotindexed[i] = 0; } } } for(i=0; i<nNotindexed; i++){ if( azNotindexed[i] ){ - sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]); + tdsqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]); rc = SQLITE_ERROR; } } @@ -147667,7 +170025,7 @@ static int fts3InitVtab( if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){ char const *zMiss = (zCompress==0 ? "compress" : "uncompress"); rc = SQLITE_ERROR; - sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss); + tdsqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss); } p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc); p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc); @@ -147692,22 +170050,26 @@ static int fts3InitVtab( fts3DatabasePageSize(&rc, p); p->nNodeSize = p->nPgsz-35; +#if defined(SQLITE_DEBUG)||defined(SQLITE_TEST) + p->nMergeCount = FTS3_MERGE_COUNT; +#endif + /* Declare the table schema to SQLite. */ fts3DeclareVtab(&rc, p); fts3_init_out: - sqlite3_free(zPrefix); - sqlite3_free(aIndex); - sqlite3_free(zCompress); - sqlite3_free(zUncompress); - sqlite3_free(zContent); - sqlite3_free(zLanguageid); - for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]); - sqlite3_free((void *)aCol); - sqlite3_free((void *)azNotindexed); + tdsqlite3_free(zPrefix); + tdsqlite3_free(aIndex); + tdsqlite3_free(zCompress); + tdsqlite3_free(zUncompress); + tdsqlite3_free(zContent); + tdsqlite3_free(zLanguageid); + for(i=0; i<nNotindexed; i++) tdsqlite3_free(azNotindexed[i]); + tdsqlite3_free((void *)aCol); + tdsqlite3_free((void *)azNotindexed); if( rc!=SQLITE_OK ){ if( p ){ - fts3DisconnectMethod((sqlite3_vtab *)p); + fts3DisconnectMethod((tdsqlite3_vtab *)p); }else if( pTokenizer ){ pTokenizer->pModule->xDestroy(pTokenizer); } @@ -147723,22 +170085,22 @@ fts3_init_out: ** work is done in function fts3InitVtab(). */ static int fts3ConnectMethod( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ + tdsqlite3_vtab **ppVtab, /* OUT: New tdsqlite3_vtab object */ + char **pzErr /* OUT: tdsqlite3_malloc'd error message */ ){ return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); } static int fts3CreateMethod( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ + tdsqlite3_vtab **ppVtab, /* OUT: New tdsqlite3_vtab object */ + char **pzErr /* OUT: tdsqlite3_malloc'd error message */ ){ return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); } @@ -147748,9 +170110,9 @@ static int fts3CreateMethod( ** extension is currently being used by a version of SQLite too old to ** support estimatedRows. In that case this function is a no-op. */ -static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ +static void fts3SetEstimatedRows(tdsqlite3_index_info *pIdxInfo, i64 nRow){ #if SQLITE_VERSION_NUMBER>=3008002 - if( sqlite3_libversion_number()>=3008002 ){ + if( tdsqlite3_libversion_number()>=3008002 ){ pIdxInfo->estimatedRows = nRow; } #endif @@ -147761,9 +170123,9 @@ static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ ** extension is currently being used by a version of SQLite too old to ** support index-info flags. In that case this function is a no-op. */ -static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){ +static void fts3SetUniqueFlag(tdsqlite3_index_info *pIdxInfo){ #if SQLITE_VERSION_NUMBER>=3008012 - if( sqlite3_libversion_number()>=3008012 ){ + if( tdsqlite3_libversion_number()>=3008012 ){ pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE; } #endif @@ -147777,7 +170139,7 @@ static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){ ** 2. Full-text search using a MATCH operator on a non-docid column. ** 3. Linear scan of %_content table. */ -static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ +static int fts3BestIndexMethod(tdsqlite3_vtab *pVTab, tdsqlite3_index_info *pInfo){ Fts3Table *p = (Fts3Table *)pVTab; int i; /* Iterator variable */ int iCons = -1; /* Index of constraint to use */ @@ -147787,6 +170149,10 @@ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ int iDocidLe = -1; /* Index of docid<=x constraint, if present */ int iIdx; + if( p->bLock ){ + return SQLITE_ERROR; + } + /* By default use a full table scan. This is an expensive option, ** so search through the constraints to see if a more efficient ** strategy is possible. @@ -147795,7 +170161,7 @@ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ pInfo->estimatedCost = 5000000; for(i=0; i<pInfo->nConstraint; i++){ int bDocid; /* True if this constraint is on docid */ - struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; + struct tdsqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; if( pCons->usable==0 ){ if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ /* There exists an unusable MATCH constraint. This means that if @@ -147805,7 +170171,7 @@ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ ** this, return a very high cost here. */ pInfo->idxNum = FTS3_FULLSCAN_SEARCH; pInfo->estimatedCost = 1e50; - fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50); + fts3SetEstimatedRows(pInfo, ((tdsqlite3_int64)1) << 50); return SQLITE_OK; } continue; @@ -147884,7 +170250,7 @@ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ ** docid) order. Both ascending and descending are possible. */ if( pInfo->nOrderBy==1 ){ - struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0]; + struct tdsqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0]; if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){ if( pOrder->desc ){ pInfo->idxStr = "DESC"; @@ -147902,8 +170268,8 @@ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ /* ** Implementation of xOpen method. */ -static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ - sqlite3_vtab_cursor *pCsr; /* Allocated cursor */ +static int fts3OpenMethod(tdsqlite3_vtab *pVTab, tdsqlite3_vtab_cursor **ppCsr){ + tdsqlite3_vtab_cursor *pCsr; /* Allocated cursor */ UNUSED_PARAMETER(pVTab); @@ -147911,7 +170277,7 @@ static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, ** if the allocation fails, return SQLITE_NOMEM. */ - *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor)); + *ppCsr = pCsr = (tdsqlite3_vtab_cursor *)tdsqlite3_malloc(sizeof(Fts3Cursor)); if( !pCsr ){ return SQLITE_NOMEM; } @@ -147920,19 +170286,48 @@ static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ } /* +** Finalize the statement handle at pCsr->pStmt. +** +** Or, if that statement handle is one created by fts3CursorSeekStmt(), +** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement +** pointer there instead of finalizing it. +*/ +static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){ + if( pCsr->bSeekStmt ){ + Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; + if( p->pSeekStmt==0 ){ + p->pSeekStmt = pCsr->pStmt; + tdsqlite3_reset(pCsr->pStmt); + pCsr->pStmt = 0; + } + pCsr->bSeekStmt = 0; + } + tdsqlite3_finalize(pCsr->pStmt); +} + +/* +** Free all resources currently held by the cursor passed as the only +** argument. +*/ +static void fts3ClearCursor(Fts3Cursor *pCsr){ + fts3CursorFinalizeStmt(pCsr); + tdsqlite3Fts3FreeDeferredTokens(pCsr); + tdsqlite3_free(pCsr->aDoclist); + tdsqlite3Fts3MIBufferFree(pCsr->pMIBuffer); + tdsqlite3Fts3ExprFree(pCsr->pExpr); + memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(tdsqlite3_vtab_cursor)); +} + +/* ** Close the cursor. For additional information see the documentation ** on the xClose method of the virtual table interface. */ -static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){ +static int fts3CloseMethod(tdsqlite3_vtab_cursor *pCursor){ Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); - sqlite3_finalize(pCsr->pStmt); - sqlite3Fts3ExprFree(pCsr->pExpr); - sqlite3Fts3FreeDeferredTokens(pCsr); - sqlite3_free(pCsr->aDoclist); - sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); + fts3ClearCursor(pCsr); assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); - sqlite3_free(pCsr); + tdsqlite3_free(pCsr); return SQLITE_OK; } @@ -147944,20 +170339,27 @@ static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){ ** ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to ** it. If an error occurs, return an SQLite error code. -** -** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK. */ -static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){ +static int fts3CursorSeekStmt(Fts3Cursor *pCsr){ int rc = SQLITE_OK; if( pCsr->pStmt==0 ){ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; char *zSql; - zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist); - if( !zSql ) return SQLITE_NOMEM; - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); - sqlite3_free(zSql); + if( p->pSeekStmt ){ + pCsr->pStmt = p->pSeekStmt; + p->pSeekStmt = 0; + }else{ + zSql = tdsqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist); + if( !zSql ) return SQLITE_NOMEM; + p->bLock++; + rc = tdsqlite3_prepare_v3( + p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0 + ); + p->bLock--; + tdsqlite3_free(zSql); + } + if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1; } - *ppStmt = pCsr->pStmt; return rc; } @@ -147966,19 +170368,21 @@ static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){ ** of the %_content table that contains the last match. Return ** SQLITE_OK on success. */ -static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){ +static int fts3CursorSeek(tdsqlite3_context *pContext, Fts3Cursor *pCsr){ int rc = SQLITE_OK; if( pCsr->isRequireSeek ){ - sqlite3_stmt *pStmt = 0; - - rc = fts3CursorSeekStmt(pCsr, &pStmt); + rc = fts3CursorSeekStmt(pCsr); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); + Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab; + pTab->bLock++; + tdsqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); pCsr->isRequireSeek = 0; - if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){ + if( SQLITE_ROW==tdsqlite3_step(pCsr->pStmt) ){ + pTab->bLock--; return SQLITE_OK; }else{ - rc = sqlite3_reset(pCsr->pStmt); + pTab->bLock--; + rc = tdsqlite3_reset(pCsr->pStmt); if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){ /* If no row was found and no error has occurred, then the %_content ** table is missing a row that is present in the full-text index. @@ -147991,7 +170395,7 @@ static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){ } if( rc!=SQLITE_OK && pContext ){ - sqlite3_result_error_code(pContext, rc); + tdsqlite3_result_error_code(pContext, rc); } return rc; } @@ -148016,16 +170420,16 @@ static int fts3ScanInteriorNode( int nTerm, /* Size of term zTerm in bytes */ const char *zNode, /* Buffer containing segment interior node */ int nNode, /* Size of buffer at zNode */ - sqlite3_int64 *piFirst, /* OUT: Selected child node */ - sqlite3_int64 *piLast /* OUT: Selected child node */ + tdsqlite3_int64 *piFirst, /* OUT: Selected child node */ + tdsqlite3_int64 *piLast /* OUT: Selected child node */ ){ int rc = SQLITE_OK; /* Return code */ const char *zCsr = zNode; /* Cursor to iterate through node */ const char *zEnd = &zCsr[nNode];/* End of interior node buffer */ char *zBuffer = 0; /* Buffer to load terms into */ - int nAlloc = 0; /* Size of allocated buffer */ + i64 nAlloc = 0; /* Size of allocated buffer */ int isFirstTerm = 1; /* True when processing first term on page */ - sqlite3_int64 iChild; /* Block id of child node to descend to */ + tdsqlite3_int64 iChild; /* Block id of child node to descend to */ /* Skip over the 'height' varint that occurs at the start of every ** interior node. Then load the blockid of the left-child of the b-tree @@ -148038,10 +170442,10 @@ static int fts3ScanInteriorNode( ** either more than 20 bytes of allocated space following the nNode bytes of ** contents, or two zero bytes. Or, if the node is read from the %_segments ** table, then there are always 20 bytes of zeroed padding following the - ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details). + ** nNode bytes of content (see tdsqlite3Fts3ReadBlock() for details). */ - zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); - zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); + zCsr += tdsqlite3Fts3GetVarint(zCsr, &iChild); + zCsr += tdsqlite3Fts3GetVarint(zCsr, &iChild); if( zCsr>zEnd ){ return FTS_CORRUPT_VTAB; } @@ -148060,14 +170464,15 @@ static int fts3ScanInteriorNode( isFirstTerm = 0; zCsr += fts3GetVarint32(zCsr, &nSuffix); - if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){ + assert( nPrefix>=0 && nSuffix>=0 ); + if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){ rc = FTS_CORRUPT_VTAB; goto finish_scan; } - if( nPrefix+nSuffix>nAlloc ){ + if( (i64)nPrefix+nSuffix>nAlloc ){ char *zNew; - nAlloc = (nPrefix+nSuffix) * 2; - zNew = (char *)sqlite3_realloc(zBuffer, nAlloc); + nAlloc = ((i64)nPrefix+nSuffix) * 2; + zNew = (char *)tdsqlite3_realloc64(zBuffer, nAlloc); if( !zNew ){ rc = SQLITE_NOMEM; goto finish_scan; @@ -148106,7 +170511,7 @@ static int fts3ScanInteriorNode( if( piLast ) *piLast = iChild; finish_scan: - sqlite3_free(zBuffer); + tdsqlite3_free(zBuffer); return rc; } @@ -148138,8 +170543,8 @@ static int fts3SelectLeaf( int nTerm, /* Size of term zTerm in bytes */ const char *zNode, /* Buffer containing segment interior node */ int nNode, /* Size of buffer at zNode */ - sqlite3_int64 *piLeaf, /* Selected leaf node */ - sqlite3_int64 *piLeaf2 /* Selected leaf node */ + tdsqlite3_int64 *piLeaf, /* Selected leaf node */ + tdsqlite3_int64 *piLeaf2 /* Selected leaf node */ ){ int rc = SQLITE_OK; /* Return code */ int iHeight; /* Height of this node in tree */ @@ -148148,29 +170553,35 @@ static int fts3SelectLeaf( fts3GetVarint32(zNode, &iHeight); rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); - assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); + assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); if( rc==SQLITE_OK && iHeight>1 ){ char *zBlob = 0; /* Blob read from %_segments table */ int nBlob = 0; /* Size of zBlob in bytes */ if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){ - rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0); + rc = tdsqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0); if( rc==SQLITE_OK ){ rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0); } - sqlite3_free(zBlob); + tdsqlite3_free(zBlob); piLeaf = 0; zBlob = 0; } if( rc==SQLITE_OK ){ - rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0); + rc = tdsqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0); } if( rc==SQLITE_OK ){ - rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); + int iNewHeight = 0; + fts3GetVarint32(zBlob, &iNewHeight); + if( iNewHeight>=iHeight ){ + rc = FTS_CORRUPT_VTAB; + }else{ + rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); + } } - sqlite3_free(zBlob); + tdsqlite3_free(zBlob); } return rc; @@ -148182,11 +170593,11 @@ static int fts3SelectLeaf( */ static void fts3PutDeltaVarint( char **pp, /* IN/OUT: Output pointer */ - sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ - sqlite3_int64 iVal /* Write this value to the list */ + tdsqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ + tdsqlite3_int64 iVal /* Write this value to the list */ ){ assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) ); - *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); + *pp += tdsqlite3Fts3PutVarint(*pp, iVal-*piPrev); *piPrev = iVal; } @@ -148273,10 +170684,11 @@ static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ } /* -** Value used to signify the end of an position-list. This is safe because -** it is not possible to have a document with 2^31 terms. +** Value used to signify the end of an position-list. This must be +** as large or larger than any value that might appear on the +** position-list, even a position list that has been corrupted. */ -#define POSITION_LIST_END 0x7fffffff +#define POSITION_LIST_END LARGEST_INT64 /* ** This function is used to help parse position-lists. When this function is @@ -148298,7 +170710,7 @@ static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ */ static void fts3ReadNextPos( char **pp, /* IN/OUT: Pointer into position-list buffer */ - sqlite3_int64 *pi /* IN/OUT: Value read from position-list */ + tdsqlite3_int64 *pi /* IN/OUT: Value read from position-list */ ){ if( (**pp)&0xFE ){ fts3GetDeltaVarint(pp, pi); @@ -148321,7 +170733,7 @@ static int fts3PutColNumber(char **pp, int iCol){ int n = 0; /* Number of bytes written */ if( iCol ){ char *p = *pp; /* Output pointer */ - n = 1 + sqlite3Fts3PutVarint(&p[1], iCol); + n = 1 + tdsqlite3Fts3PutVarint(&p[1], iCol); *p = 0x01; *pp = &p[n]; } @@ -148335,7 +170747,7 @@ static int fts3PutColNumber(char **pp, int iCol){ ** updated appropriately. The caller is responsible for insuring ** that there is enough space in *pp to hold the complete output. */ -static void fts3PoslistMerge( +static int fts3PoslistMerge( char **pp, /* Output buffer */ char **pp1, /* Left input list */ char **pp2 /* Right input list */ @@ -148348,18 +170760,24 @@ static void fts3PoslistMerge( int iCol1; /* The current column index in pp1 */ int iCol2; /* The current column index in pp2 */ - if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1); - else if( *p1==POS_END ) iCol1 = POSITION_LIST_END; + if( *p1==POS_COLUMN ){ + fts3GetVarint32(&p1[1], &iCol1); + if( iCol1==0 ) return FTS_CORRUPT_VTAB; + } + else if( *p1==POS_END ) iCol1 = 0x7fffffff; else iCol1 = 0; - if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2); - else if( *p2==POS_END ) iCol2 = POSITION_LIST_END; + if( *p2==POS_COLUMN ){ + fts3GetVarint32(&p2[1], &iCol2); + if( iCol2==0 ) return FTS_CORRUPT_VTAB; + } + else if( *p2==POS_END ) iCol2 = 0x7fffffff; else iCol2 = 0; if( iCol1==iCol2 ){ - sqlite3_int64 i1 = 0; /* Last position from pp1 */ - sqlite3_int64 i2 = 0; /* Last position from pp2 */ - sqlite3_int64 iPrev = 0; + tdsqlite3_int64 i1 = 0; /* Last position from pp1 */ + tdsqlite3_int64 i2 = 0; /* Last position from pp2 */ + tdsqlite3_int64 iPrev = 0; int n = fts3PutColNumber(&p, iCol1); p1 += n; p2 += n; @@ -148400,6 +170818,7 @@ static void fts3PoslistMerge( *pp = p; *pp1 = p1 + 1; *pp2 = p2 + 1; + return SQLITE_OK; } /* @@ -148455,25 +170874,24 @@ static int fts3PoslistPhraseMerge( while( 1 ){ if( iCol1==iCol2 ){ char *pSave = p; - sqlite3_int64 iPrev = 0; - sqlite3_int64 iPos1 = 0; - sqlite3_int64 iPos2 = 0; + tdsqlite3_int64 iPrev = 0; + tdsqlite3_int64 iPos1 = 0; + tdsqlite3_int64 iPos2 = 0; if( iCol1 ){ *p++ = POS_COLUMN; - p += sqlite3Fts3PutVarint(p, iCol1); + p += tdsqlite3Fts3PutVarint(p, iCol1); } - assert( *p1!=POS_END && *p1!=POS_COLUMN ); - assert( *p2!=POS_END && *p2!=POS_COLUMN ); fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; + if( iPos1<0 || iPos2<0 ) break; while( 1 ){ if( iPos2==iPos1+nToken || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) ){ - sqlite3_int64 iSave; + tdsqlite3_int64 iSave; iSave = isSaveLeft ? iPos1 : iPos2; fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2; pSave = 0; @@ -148611,17 +171029,17 @@ static void fts3GetDeltaVarint3( char **pp, /* IN/OUT: Point to read varint from */ char *pEnd, /* End of buffer */ int bDescIdx, /* True if docids are descending */ - sqlite3_int64 *pVal /* IN/OUT: Integer value */ + tdsqlite3_int64 *pVal /* IN/OUT: Integer value */ ){ if( *pp>=pEnd ){ *pp = 0; }else{ - sqlite3_int64 iVal; - *pp += sqlite3Fts3GetVarint(*pp, &iVal); + u64 iVal; + *pp += tdsqlite3Fts3GetVarintU(*pp, &iVal); if( bDescIdx ){ - *pVal -= iVal; + *pVal = (i64)((u64)*pVal - iVal); }else{ - *pVal += iVal; + *pVal = (i64)((u64)*pVal + iVal); } } } @@ -148644,19 +171062,21 @@ static void fts3GetDeltaVarint3( static void fts3PutDeltaVarint3( char **pp, /* IN/OUT: Output pointer */ int bDescIdx, /* True for descending docids */ - sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ + tdsqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ int *pbFirst, /* IN/OUT: True after first int written */ - sqlite3_int64 iVal /* Write this value to the list */ + tdsqlite3_int64 iVal /* Write this value to the list */ ){ - sqlite3_int64 iWrite; + tdsqlite3_uint64 iWrite; if( bDescIdx==0 || *pbFirst==0 ){ - iWrite = iVal - *piPrev; + assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev ); + iWrite = (u64)iVal - (u64)*piPrev; }else{ - iWrite = *piPrev - iVal; + assert_fts3_nc( *piPrev>=iVal ); + iWrite = (u64)*piPrev - (u64)iVal; } assert( *pbFirst || *piPrev==0 ); - assert( *pbFirst==0 || iWrite>0 ); - *pp += sqlite3Fts3PutVarint(*pp, iWrite); + assert_fts3_nc( *pbFirst==0 || iWrite>0 ); + *pp += tdsqlite3Fts3PutVarint(*pp, iWrite); *piPrev = iVal; *pbFirst = 1; } @@ -148671,7 +171091,8 @@ static void fts3PutDeltaVarint3( ** Using this makes it easier to write code that can merge doclists that are ** sorted in either ascending or descending order. */ -#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2)) +/* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */ +#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1))) /* ** This function does an "OR" merge of two doclists (output contains all @@ -148680,7 +171101,7 @@ static void fts3PutDeltaVarint3( ** should be false. If they are sorted in ascending order, it should be ** passed a non-zero value. ** -** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer +** If no error occurs, *paOut is set to point at an tdsqlite3_malloc'd buffer ** containing the output doclist and SQLITE_OK is returned. In this case ** *pnOut is set to the number of bytes in the output doclist. ** @@ -148693,9 +171114,10 @@ static int fts3DoclistOrMerge( char *a2, int n2, /* Second doclist */ char **paOut, int *pnOut /* OUT: Malloc'd doclist */ ){ - sqlite3_int64 i1 = 0; - sqlite3_int64 i2 = 0; - sqlite3_int64 iPrev = 0; + int rc = SQLITE_OK; + tdsqlite3_int64 i1 = 0; + tdsqlite3_int64 i2 = 0; + tdsqlite3_int64 iPrev = 0; char *pEnd1 = &a1[n1]; char *pEnd2 = &a2[n2]; char *p1 = a1; @@ -148736,18 +171158,19 @@ static int fts3DoclistOrMerge( ** A symetric argument may be made if the doclists are in descending ** order. */ - aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1); + aOut = tdsqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING); if( !aOut ) return SQLITE_NOMEM; p = aOut; fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); while( p1 || p2 ){ - sqlite3_int64 iDiff = DOCID_CMP(i1, i2); + tdsqlite3_int64 iDiff = DOCID_CMP(i1, i2); if( p2 && p1 && iDiff==0 ){ fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); - fts3PoslistMerge(&p, &p1, &p2); + rc = fts3PoslistMerge(&p, &p1, &p2); + if( rc ) break; fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); }else if( !p2 || (p1 && iDiff<0) ){ @@ -148759,12 +171182,20 @@ static int fts3DoclistOrMerge( fts3PoslistCopy(&p, &p2); fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); } + + assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) ); } + if( rc!=SQLITE_OK ){ + tdsqlite3_free(aOut); + p = aOut = 0; + }else{ + assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 ); + memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING); + } *paOut = aOut; *pnOut = (int)(p-aOut); - assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 ); - return SQLITE_OK; + return rc; } /* @@ -148785,9 +171216,9 @@ static int fts3DoclistPhraseMerge( char *aLeft, int nLeft, /* Left doclist */ char **paRight, int *pnRight /* IN/OUT: Right/output doclist */ ){ - sqlite3_int64 i1 = 0; - sqlite3_int64 i2 = 0; - sqlite3_int64 iPrev = 0; + tdsqlite3_int64 i1 = 0; + tdsqlite3_int64 i2 = 0; + tdsqlite3_int64 iPrev = 0; char *aRight = *paRight; char *pEnd1 = &aLeft[nLeft]; char *pEnd2 = &aRight[*pnRight]; @@ -148799,7 +171230,7 @@ static int fts3DoclistPhraseMerge( assert( nDist>0 ); if( bDescDoclist ){ - aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX); + aOut = tdsqlite3_malloc64((tdsqlite3_int64)*pnRight + FTS3_VARINT_MAX); if( aOut==0 ) return SQLITE_NOMEM; }else{ aOut = aRight; @@ -148810,10 +171241,10 @@ static int fts3DoclistPhraseMerge( fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); while( p1 && p2 ){ - sqlite3_int64 iDiff = DOCID_CMP(i1, i2); + tdsqlite3_int64 iDiff = DOCID_CMP(i1, i2); if( iDiff==0 ){ char *pSave = p; - sqlite3_int64 iPrevSave = iPrev; + tdsqlite3_int64 iPrevSave = iPrev; int bFirstOutSave = bFirstOut; fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); @@ -148835,7 +171266,7 @@ static int fts3DoclistPhraseMerge( *pnRight = (int)(p - aOut); if( bDescDoclist ){ - sqlite3_free(aRight); + tdsqlite3_free(aRight); *paRight = aOut; } @@ -148850,8 +171281,8 @@ static int fts3DoclistPhraseMerge( ** of the entries from pList at position 0, and terminated by an 0x00 byte. ** The value returned is the number of bytes written to pOut (if any). */ -SQLITE_PRIVATE int sqlite3Fts3FirstFilter( - sqlite3_int64 iDelta, /* Varint that may be written to pOut */ +SQLITE_PRIVATE int tdsqlite3Fts3FirstFilter( + tdsqlite3_int64 iDelta, /* Varint that may be written to pOut */ char *pList, /* Position list (no 0x00 term) */ int nList, /* Size of pList in bytes */ char *pOut /* Write output here */ @@ -148863,24 +171294,24 @@ SQLITE_PRIVATE int sqlite3Fts3FirstFilter( if( *p!=0x01 ){ if( *p==0x02 ){ - nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta); + nOut += tdsqlite3Fts3PutVarint(&pOut[nOut], iDelta); pOut[nOut++] = 0x02; bWritten = 1; } fts3ColumnlistCopy(0, &p); } - while( p<pEnd && *p==0x01 ){ - sqlite3_int64 iCol; + while( p<pEnd ){ + tdsqlite3_int64 iCol; p++; - p += sqlite3Fts3GetVarint(p, &iCol); + p += tdsqlite3Fts3GetVarint(p, &iCol); if( *p==0x02 ){ if( bWritten==0 ){ - nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta); + nOut += tdsqlite3Fts3PutVarint(&pOut[nOut], iDelta); bWritten = 1; } pOut[nOut++] = 0x01; - nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol); + nOut += tdsqlite3Fts3PutVarint(&pOut[nOut], iCol); pOut[nOut++] = 0x02; } fts3ColumnlistCopy(0, &p); @@ -148924,12 +171355,12 @@ static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){ pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew ); if( rc!=SQLITE_OK ){ - sqlite3_free(aOut); + tdsqlite3_free(aOut); return rc; } - sqlite3_free(pTS->aaOutput[i]); - sqlite3_free(aOut); + tdsqlite3_free(pTS->aaOutput[i]); + tdsqlite3_free(aOut); pTS->aaOutput[i] = 0; aOut = aNew; nOut = nNew; @@ -148979,10 +171410,11 @@ static int fts3TermSelectMerge( ** ** Similar padding is added in the fts3DoclistOrMerge() function. */ - pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1); + pTS->aaOutput[0] = tdsqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1); pTS->anOutput[0] = nDoclist; if( pTS->aaOutput[0] ){ memcpy(pTS->aaOutput[0], aDoclist, nDoclist); + memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX); }else{ return SQLITE_NOMEM; } @@ -149005,12 +171437,12 @@ static int fts3TermSelectMerge( pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew ); if( rc!=SQLITE_OK ){ - if( aMerge!=aDoclist ) sqlite3_free(aMerge); + if( aMerge!=aDoclist ) tdsqlite3_free(aMerge); return rc; } - if( aMerge!=aDoclist ) sqlite3_free(aMerge); - sqlite3_free(pTS->aaOutput[iOut]); + if( aMerge!=aDoclist ) tdsqlite3_free(aMerge); + tdsqlite3_free(pTS->aaOutput[iOut]); pTS->aaOutput[iOut] = 0; aMerge = aNew; @@ -149034,10 +171466,10 @@ static int fts3SegReaderCursorAppend( ){ if( (pCsr->nSegment%16)==0 ){ Fts3SegReader **apNew; - int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); - apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte); + tdsqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); + apNew = (Fts3SegReader **)tdsqlite3_realloc64(pCsr->apSegment, nByte); if( !apNew ){ - sqlite3Fts3SegReaderFree(pNew); + tdsqlite3Fts3SegReaderFree(pNew); return SQLITE_NOMEM; } pCsr->apSegment = apNew; @@ -149065,8 +171497,8 @@ static int fts3SegReaderCursor( Fts3MultiSegReader *pCsr /* Cursor object to populate */ ){ int rc = SQLITE_OK; /* Error code */ - sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */ - int rc2; /* Result of sqlite3_reset() */ + tdsqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */ + int rc2; /* Result of tdsqlite3_reset() */ /* If iLevel is less than 0 and this is not a scan, include a seg-reader ** for the pending-terms. If this is a scan, then this call must be being @@ -149074,9 +171506,9 @@ static int fts3SegReaderCursor( ** Fts3SegReaderPending might segfault, as the data structures used by ** fts4aux are not completely populated. So it's easiest to filter these ** calls out here. */ - if( iLevel<0 && p->aIndex ){ + if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){ Fts3SegReader *pSeg = 0; - rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg); + rc = tdsqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg); if( rc==SQLITE_OK && pSeg ){ rc = fts3SegReaderCursorAppend(pCsr, pSeg); } @@ -149084,29 +171516,29 @@ static int fts3SegReaderCursor( if( iLevel!=FTS3_SEGCURSOR_PENDING ){ if( rc==SQLITE_OK ){ - rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt); + rc = tdsqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt); } - while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ + while( rc==SQLITE_OK && SQLITE_ROW==(rc = tdsqlite3_step(pStmt)) ){ Fts3SegReader *pSeg = 0; /* Read the values returned by the SELECT into local variables. */ - sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1); - sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2); - sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3); - int nRoot = sqlite3_column_bytes(pStmt, 4); - char const *zRoot = sqlite3_column_blob(pStmt, 4); + tdsqlite3_int64 iStartBlock = tdsqlite3_column_int64(pStmt, 1); + tdsqlite3_int64 iLeavesEndBlock = tdsqlite3_column_int64(pStmt, 2); + tdsqlite3_int64 iEndBlock = tdsqlite3_column_int64(pStmt, 3); + int nRoot = tdsqlite3_column_bytes(pStmt, 4); + char const *zRoot = tdsqlite3_column_blob(pStmt, 4); /* If zTerm is not NULL, and this segment is not stored entirely on its ** root node, the range of leaves scanned can be reduced. Do this. */ - if( iStartBlock && zTerm ){ - sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0); + if( iStartBlock && zTerm && zRoot ){ + tdsqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0); rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi); if( rc!=SQLITE_OK ) goto finished; if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock; } - rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, + rc = tdsqlite3Fts3SegReaderNew(pCsr->nSegment+1, (isPrefix==0 && isScan==0), iStartBlock, iLeavesEndBlock, iEndBlock, zRoot, nRoot, &pSeg @@ -149117,7 +171549,7 @@ static int fts3SegReaderCursor( } finished: - rc2 = sqlite3_reset(pStmt); + rc2 = tdsqlite3_reset(pStmt); if( rc==SQLITE_DONE ) rc = rc2; return rc; @@ -149127,7 +171559,7 @@ static int fts3SegReaderCursor( ** Set up a cursor object for iterating through a full-text index or a ** single level therein. */ -SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor( +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderCursor( Fts3Table *p, /* FTS3 table handle */ int iLangid, /* Language-id to search */ int iIndex, /* Index to search (from 0 to p->nIndex-1) */ @@ -149194,7 +171626,7 @@ static int fts3TermSegReaderCursor( Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */ int rc = SQLITE_NOMEM; /* Return code */ - pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader)); + pSegcsr = tdsqlite3_malloc(sizeof(Fts3MultiSegReader)); if( pSegcsr ){ int i; int bFound = 0; /* True once an index has been found */ @@ -149204,7 +171636,7 @@ static int fts3TermSegReaderCursor( for(i=1; bFound==0 && i<p->nIndex; i++){ if( p->aIndex[i].nPrefix==nTerm ){ bFound = 1; - rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, + rc = tdsqlite3Fts3SegReaderCursor(p, pCsr->iLangid, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr ); pSegcsr->bLookup = 1; @@ -149214,7 +171646,7 @@ static int fts3TermSegReaderCursor( for(i=1; bFound==0 && i<p->nIndex; i++){ if( p->aIndex[i].nPrefix==nTerm+1 ){ bFound = 1; - rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, + rc = tdsqlite3Fts3SegReaderCursor(p, pCsr->iLangid, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr ); if( rc==SQLITE_OK ){ @@ -149227,7 +171659,7 @@ static int fts3TermSegReaderCursor( } if( bFound==0 ){ - rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, + rc = tdsqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr ); pSegcsr->bLookup = !isPrefix; @@ -149242,8 +171674,8 @@ static int fts3TermSegReaderCursor( ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor(). */ static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){ - sqlite3Fts3SegReaderFinish(pSegcsr); - sqlite3_free(pSegcsr); + tdsqlite3Fts3SegReaderFinish(pSegcsr); + tdsqlite3_free(pSegcsr); } /* @@ -149273,9 +171705,9 @@ static int fts3TermSelect( filter.zTerm = pTok->z; filter.nTerm = pTok->n; - rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter); + rc = tdsqlite3Fts3SegReaderStart(p, pSegcsr, &filter); while( SQLITE_OK==rc - && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) + && SQLITE_ROW==(rc = tdsqlite3Fts3SegReaderStep(p, pSegcsr)) ){ rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist); } @@ -149289,7 +171721,7 @@ static int fts3TermSelect( }else{ int i; for(i=0; i<SizeofArray(tsc.aaOutput); i++){ - sqlite3_free(tsc.aaOutput[i]); + tdsqlite3_free(tsc.aaOutput[i]); } } @@ -149333,17 +171765,20 @@ static int fts3DoclistCountDocids(char *aList, int nList){ ** even if we reach end-of-file. The fts3EofMethod() will be called ** subsequently to determine whether or not an EOF was hit. */ -static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){ +static int fts3NextMethod(tdsqlite3_vtab_cursor *pCursor){ int rc; Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){ - if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){ + Fts3Table *pTab = (Fts3Table*)pCursor->pVtab; + pTab->bLock++; + if( SQLITE_ROW!=tdsqlite3_step(pCsr->pStmt) ){ pCsr->isEof = 1; - rc = sqlite3_reset(pCsr->pStmt); + rc = tdsqlite3_reset(pCsr->pStmt); }else{ - pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0); + pCsr->iPrevId = tdsqlite3_column_int64(pCsr->pStmt, 0); rc = SQLITE_OK; } + pTab->bLock--; }else{ rc = fts3EvalNext((Fts3Cursor *)pCursor); } @@ -149352,27 +171787,15 @@ static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){ } /* -** The following are copied from sqliteInt.h. -** -** Constants for the largest and smallest possible 64-bit signed integers. -** These macros are designed to work correctly on both 32-bit and 64-bit -** compilers. -*/ -#ifndef SQLITE_AMALGAMATION -# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) -# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) -#endif - -/* ** If the numeric type of argument pVal is "integer", then return it ** converted to a 64-bit signed integer. Otherwise, return a copy of ** the second parameter, iDefault. */ -static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){ +static tdsqlite3_int64 fts3DocidRange(tdsqlite3_value *pVal, i64 iDefault){ if( pVal ){ - int eType = sqlite3_value_numeric_type(pVal); + int eType = tdsqlite3_value_numeric_type(pVal); if( eType==SQLITE_INTEGER ){ - return sqlite3_value_int64(pVal); + return tdsqlite3_value_int64(pVal); } } return iDefault; @@ -149395,11 +171818,11 @@ static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){ ** side of the MATCH operator. */ static int fts3FilterMethod( - sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + tdsqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ - sqlite3_value **apVal /* Arguments for the indexing scheme */ + tdsqlite3_value **apVal /* Arguments for the indexing scheme */ ){ int rc = SQLITE_OK; char *zSql; /* SQL statement used to access %_content */ @@ -149407,15 +171830,19 @@ static int fts3FilterMethod( Fts3Table *p = (Fts3Table *)pCursor->pVtab; Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; - sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */ - sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */ - sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */ - sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */ + tdsqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */ + tdsqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */ + tdsqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */ + tdsqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */ int iIdx; UNUSED_PARAMETER(idxStr); UNUSED_PARAMETER(nVal); + if( p->bLock ){ + return SQLITE_ERROR; + } + eSearch = (idxNum & 0x0000FFFF); assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) ); assert( p->pSegments==0 ); @@ -149429,11 +171856,7 @@ static int fts3FilterMethod( assert( iIdx==nVal ); /* In case the cursor has been used before, clear it now. */ - sqlite3_finalize(pCsr->pStmt); - sqlite3_free(pCsr->aDoclist); - sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); - sqlite3Fts3ExprFree(pCsr->pExpr); - memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor)); + fts3ClearCursor(pCsr); /* Set the lower and upper bounds on docids to return */ pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64); @@ -149448,17 +171871,17 @@ static int fts3FilterMethod( if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){ int iCol = eSearch-FTS3_FULLTEXT_SEARCH; - const char *zQuery = (const char *)sqlite3_value_text(pCons); + const char *zQuery = (const char *)tdsqlite3_value_text(pCons); - if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){ + if( zQuery==0 && tdsqlite3_value_type(pCons)!=SQLITE_NULL ){ return SQLITE_NOMEM; } pCsr->iLangid = 0; - if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid); + if( pLangid ) pCsr->iLangid = tdsqlite3_value_int(pLangid); assert( p->base.zErrMsg==0 ); - rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid, + rc = tdsqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid, p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, &p->base.zErrMsg ); @@ -149467,7 +171890,7 @@ static int fts3FilterMethod( } rc = fts3EvalStart(pCsr); - sqlite3Fts3SegmentsClose(p); + tdsqlite3Fts3SegmentsClose(p); if( rc!=SQLITE_OK ) return rc; pCsr->pNextId = pCsr->aDoclist; pCsr->iPrevId = 0; @@ -149480,26 +171903,30 @@ static int fts3FilterMethod( */ if( eSearch==FTS3_FULLSCAN_SEARCH ){ if( pDocidGe || pDocidLe ){ - zSql = sqlite3_mprintf( + zSql = tdsqlite3_mprintf( "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s", p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid, (pCsr->bDesc ? "DESC" : "ASC") ); }else{ - zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", + zSql = tdsqlite3_mprintf("SELECT %s ORDER BY rowid %s", p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC") ); } if( zSql ){ - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0); - sqlite3_free(zSql); + p->bLock++; + rc = tdsqlite3_prepare_v3( + p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0 + ); + p->bLock--; + tdsqlite3_free(zSql); }else{ rc = SQLITE_NOMEM; } }else if( eSearch==FTS3_DOCID_SEARCH ){ - rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt); + rc = fts3CursorSeekStmt(pCsr); if( rc==SQLITE_OK ){ - rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons); + rc = tdsqlite3_bind_value(pCsr->pStmt, 1, pCons); } } if( rc!=SQLITE_OK ) return rc; @@ -149511,8 +171938,13 @@ static int fts3FilterMethod( ** This is the xEof method of the virtual table. SQLite calls this ** routine to find out if it has reached the end of a result set. */ -static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){ - return ((Fts3Cursor *)pCursor)->isEof; +static int fts3EofMethod(tdsqlite3_vtab_cursor *pCursor){ + Fts3Cursor *pCsr = (Fts3Cursor*)pCursor; + if( pCsr->isEof ){ + fts3ClearCursor(pCsr); + pCsr->isEof = 1; + } + return pCsr->isEof; } /* @@ -149521,7 +171953,7 @@ static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){ ** exposes %_content.docid as the rowid for the virtual table. The ** rowid should be written to *pRowid. */ -static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ +static int fts3RowidMethod(tdsqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; *pRowid = pCsr->iPrevId; return SQLITE_OK; @@ -149539,8 +171971,8 @@ static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ ** (iCol == p->nColumn+2) -> Langid column */ static int fts3ColumnMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + tdsqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + tdsqlite3_context *pCtx, /* Context for tdsqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ int rc = SQLITE_OK; /* Return Code */ @@ -149550,33 +171982,37 @@ static int fts3ColumnMethod( /* The column value supplied by SQLite must be in range. */ assert( iCol>=0 && iCol<=p->nColumn+2 ); - if( iCol==p->nColumn+1 ){ - /* This call is a request for the "docid" column. Since "docid" is an - ** alias for "rowid", use the xRowid() method to obtain the value. - */ - sqlite3_result_int64(pCtx, pCsr->iPrevId); - }else if( iCol==p->nColumn ){ - /* The extra column whose name is the same as the table. - ** Return a blob which is a pointer to the cursor. */ - sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT); - }else if( iCol==p->nColumn+2 && pCsr->pExpr ){ - sqlite3_result_int64(pCtx, pCsr->iLangid); - }else{ - /* The requested column is either a user column (one that contains - ** indexed data), or the language-id column. */ - rc = fts3CursorSeek(0, pCsr); + switch( iCol-p->nColumn ){ + case 0: + /* The special 'table-name' column */ + tdsqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0); + break; - if( rc==SQLITE_OK ){ - if( iCol==p->nColumn+2 ){ - int iLangid = 0; - if( p->zLanguageid ){ - iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1); - } - sqlite3_result_int(pCtx, iLangid); - }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){ - sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1)); + case 1: + /* The docid column */ + tdsqlite3_result_int64(pCtx, pCsr->iPrevId); + break; + + case 2: + if( pCsr->pExpr ){ + tdsqlite3_result_int64(pCtx, pCsr->iLangid); + break; + }else if( p->zLanguageid==0 ){ + tdsqlite3_result_int(pCtx, 0); + break; + }else{ + iCol = p->nColumn; + /* fall-through */ } - } + + default: + /* A user column. Or, if this is a full-table scan, possibly the + ** language-id column. Seek the cursor. */ + rc = fts3CursorSeek(0, pCsr); + if( rc==SQLITE_OK && tdsqlite3_data_count(pCsr->pStmt)-1>iCol ){ + tdsqlite3_result_value(pCtx, tdsqlite3_column_value(pCsr->pStmt, iCol+1)); + } + break; } assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); @@ -149589,19 +172025,19 @@ static int fts3ColumnMethod( ** inserted, updated or deleted. */ static int fts3UpdateMethod( - sqlite3_vtab *pVtab, /* Virtual table handle */ + tdsqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Size of argument array */ - sqlite3_value **apVal, /* Array of arguments */ + tdsqlite3_value **apVal, /* Array of arguments */ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ ){ - return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid); + return tdsqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid); } /* ** Implementation of xSync() method. Flush the contents of the pending-terms ** hash-table to the database. */ -static int fts3SyncMethod(sqlite3_vtab *pVtab){ +static int fts3SyncMethod(tdsqlite3_vtab *pVtab){ /* Following an incremental-merge operation, assuming that the input ** segments are not completely consumed (the usual case), they are updated @@ -149625,8 +172061,10 @@ static int fts3SyncMethod(sqlite3_vtab *pVtab){ const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */ Fts3Table *p = (Fts3Table*)pVtab; - int rc = sqlite3Fts3PendingTermsFlush(p); + int rc; + i64 iLastRowid = tdsqlite3_last_insert_rowid(p->db); + rc = tdsqlite3Fts3PendingTermsFlush(p); if( rc==SQLITE_OK && p->nLeafAdd>(nMinMerge/16) && p->nAutoincrmerge && p->nAutoincrmerge!=0xff @@ -149634,13 +172072,14 @@ static int fts3SyncMethod(sqlite3_vtab *pVtab){ int mxLevel = 0; /* Maximum relative level value in db */ int A; /* Incr-merge parameter A */ - rc = sqlite3Fts3MaxLevel(p, &mxLevel); + rc = tdsqlite3Fts3MaxLevel(p, &mxLevel); assert( rc==SQLITE_OK || mxLevel==0 ); A = p->nLeafAdd * mxLevel; A += (A/2); - if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge); + if( A>(int)nMinMerge ) rc = tdsqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge); } - sqlite3Fts3SegmentsClose(p); + tdsqlite3Fts3SegmentsClose(p); + tdsqlite3_set_last_insert_rowid(p->db, iLastRowid); return rc; } @@ -149653,17 +172092,11 @@ static int fts3SyncMethod(sqlite3_vtab *pVtab){ static int fts3SetHasStat(Fts3Table *p){ int rc = SQLITE_OK; if( p->bHasStat==2 ){ - const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'"; - char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName); - if( zSql ){ - sqlite3_stmt *pStmt = 0; - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - if( rc==SQLITE_OK ){ - int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW); - rc = sqlite3_finalize(pStmt); - if( rc==SQLITE_OK ) p->bHasStat = bHasStat; - } - sqlite3_free(zSql); + char *zTbl = tdsqlite3_mprintf("%s_stat", p->zName); + if( zTbl ){ + int res = tdsqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0); + tdsqlite3_free(zTbl); + p->bHasStat = (res==SQLITE_OK); }else{ rc = SQLITE_NOMEM; } @@ -149674,7 +172107,7 @@ static int fts3SetHasStat(Fts3Table *p){ /* ** Implementation of xBegin() method. */ -static int fts3BeginMethod(sqlite3_vtab *pVtab){ +static int fts3BeginMethod(tdsqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table*)pVtab; UNUSED_PARAMETER(pVtab); assert( p->pSegments==0 ); @@ -149691,7 +172124,7 @@ static int fts3BeginMethod(sqlite3_vtab *pVtab){ ** the pending-terms hash-table have already been flushed into the database ** by fts3SyncMethod(). */ -static int fts3CommitMethod(sqlite3_vtab *pVtab){ +static int fts3CommitMethod(tdsqlite3_vtab *pVtab){ TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); UNUSED_PARAMETER(pVtab); assert( p->nPendingData==0 ); @@ -149706,9 +172139,9 @@ static int fts3CommitMethod(sqlite3_vtab *pVtab){ ** Implementation of xRollback(). Discard the contents of the pending-terms ** hash-table. Any changes made to the database are reverted by SQLite. */ -static int fts3RollbackMethod(sqlite3_vtab *pVtab){ +static int fts3RollbackMethod(tdsqlite3_vtab *pVtab){ Fts3Table *p = (Fts3Table*)pVtab; - sqlite3Fts3PendingTermsClear(p); + tdsqlite3Fts3PendingTermsClear(p); assert( p->inTransaction!=0 ); TESTONLY( p->inTransaction = 0 ); TESTONLY( p->mxSavepoint = -1; ); @@ -149765,32 +172198,31 @@ static void fts3ReversePoslist(char *pStart, char **ppPoslist){ ** string passed via zFunc is used as part of the error message. */ static int fts3FunctionArg( - sqlite3_context *pContext, /* SQL function call context */ + tdsqlite3_context *pContext, /* SQL function call context */ const char *zFunc, /* Function name */ - sqlite3_value *pVal, /* argv[0] passed to function */ + tdsqlite3_value *pVal, /* argv[0] passed to function */ Fts3Cursor **ppCsr /* OUT: Store cursor handle here */ ){ - Fts3Cursor *pRet; - if( sqlite3_value_type(pVal)!=SQLITE_BLOB - || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *) - ){ - char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc); - sqlite3_result_error(pContext, zErr, -1); - sqlite3_free(zErr); - return SQLITE_ERROR; + int rc; + *ppCsr = (Fts3Cursor*)tdsqlite3_value_pointer(pVal, "fts3cursor"); + if( (*ppCsr)!=0 ){ + rc = SQLITE_OK; + }else{ + char *zErr = tdsqlite3_mprintf("illegal first argument to %s", zFunc); + tdsqlite3_result_error(pContext, zErr, -1); + tdsqlite3_free(zErr); + rc = SQLITE_ERROR; } - memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *)); - *ppCsr = pRet; - return SQLITE_OK; + return rc; } /* ** Implementation of the snippet() function for FTS3 */ static void fts3SnippetFunc( - sqlite3_context *pContext, /* SQLite function call context */ + tdsqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of apVal[] array */ - sqlite3_value **apVal /* Array of arguments */ + tdsqlite3_value **apVal /* Array of arguments */ ){ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ const char *zStart = "<b>"; @@ -149805,25 +172237,25 @@ static void fts3SnippetFunc( assert( nVal>=1 ); if( nVal>6 ){ - sqlite3_result_error(pContext, + tdsqlite3_result_error(pContext, "wrong number of arguments to function snippet()", -1); return; } if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return; switch( nVal ){ - case 6: nToken = sqlite3_value_int(apVal[5]); - case 5: iCol = sqlite3_value_int(apVal[4]); - case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); - case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]); - case 2: zStart = (const char*)sqlite3_value_text(apVal[1]); + case 6: nToken = tdsqlite3_value_int(apVal[5]); + case 5: iCol = tdsqlite3_value_int(apVal[4]); + case 4: zEllipsis = (const char*)tdsqlite3_value_text(apVal[3]); + case 3: zEnd = (const char*)tdsqlite3_value_text(apVal[2]); + case 2: zStart = (const char*)tdsqlite3_value_text(apVal[1]); } if( !zEllipsis || !zEnd || !zStart ){ - sqlite3_result_error_nomem(pContext); + tdsqlite3_result_error_nomem(pContext); }else if( nToken==0 ){ - sqlite3_result_text(pContext, "", -1, SQLITE_STATIC); + tdsqlite3_result_text(pContext, "", -1, SQLITE_STATIC); }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ - sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); + tdsqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); } } @@ -149831,9 +172263,9 @@ static void fts3SnippetFunc( ** Implementation of the offsets() function for FTS3 */ static void fts3OffsetsFunc( - sqlite3_context *pContext, /* SQLite function call context */ + tdsqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of argument array */ - sqlite3_value **apVal /* Array of arguments */ + tdsqlite3_value **apVal /* Array of arguments */ ){ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ @@ -149843,7 +172275,7 @@ static void fts3OffsetsFunc( if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return; assert( pCsr ); if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ - sqlite3Fts3Offsets(pContext, pCsr); + tdsqlite3Fts3Offsets(pContext, pCsr); } } @@ -149857,9 +172289,9 @@ static void fts3OffsetsFunc( ** where 't' is the name of an FTS3 table. */ static void fts3OptimizeFunc( - sqlite3_context *pContext, /* SQLite function call context */ + tdsqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of argument array */ - sqlite3_value **apVal /* Array of arguments */ + tdsqlite3_value **apVal /* Array of arguments */ ){ int rc; /* Return code */ Fts3Table *p; /* Virtual table handle */ @@ -149872,17 +172304,17 @@ static void fts3OptimizeFunc( p = (Fts3Table *)pCursor->base.pVtab; assert( p ); - rc = sqlite3Fts3Optimize(p); + rc = tdsqlite3Fts3Optimize(p); switch( rc ){ case SQLITE_OK: - sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); + tdsqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); break; case SQLITE_DONE: - sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC); + tdsqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC); break; default: - sqlite3_result_error_code(pContext, rc); + tdsqlite3_result_error_code(pContext, rc); break; } } @@ -149891,18 +172323,18 @@ static void fts3OptimizeFunc( ** Implementation of the matchinfo() function for FTS3 */ static void fts3MatchinfoFunc( - sqlite3_context *pContext, /* SQLite function call context */ + tdsqlite3_context *pContext, /* SQLite function call context */ int nVal, /* Size of argument array */ - sqlite3_value **apVal /* Array of arguments */ + tdsqlite3_value **apVal /* Array of arguments */ ){ Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ assert( nVal==1 || nVal==2 ); if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){ const char *zArg = 0; if( nVal>1 ){ - zArg = (const char *)sqlite3_value_text(apVal[1]); + zArg = (const char *)tdsqlite3_value_text(apVal[1]); } - sqlite3Fts3Matchinfo(pContext, pCsr, zArg); + tdsqlite3Fts3Matchinfo(pContext, pCsr, zArg); } } @@ -149911,15 +172343,15 @@ static void fts3MatchinfoFunc( ** virtual table. */ static int fts3FindFunctionMethod( - sqlite3_vtab *pVtab, /* Virtual table handle */ + tdsqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Number of SQL function arguments */ const char *zName, /* Name of SQL function */ - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ + void (**pxFunc)(tdsqlite3_context*,int,tdsqlite3_value**), /* OUT: Result */ void **ppArg /* Unused */ ){ struct Overloaded { const char *zName; - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**); } aOverload[] = { { "snippet", fts3SnippetFunc }, { "offsets", fts3OffsetsFunc }, @@ -149947,11 +172379,11 @@ static int fts3FindFunctionMethod( ** Implementation of FTS3 xRename method. Rename an fts3 table. */ static int fts3RenameMethod( - sqlite3_vtab *pVtab, /* Virtual table handle */ + tdsqlite3_vtab *pVtab, /* Virtual table handle */ const char *zName /* New name of table */ ){ Fts3Table *p = (Fts3Table *)pVtab; - sqlite3 *db = p->db; /* Database connection */ + tdsqlite3 *db = p->db; /* Database connection */ int rc; /* Return Code */ /* At this point it must be known if the %_stat table exists or not. @@ -149966,7 +172398,7 @@ static int fts3RenameMethod( */ assert( p->nPendingData==0 ); if( rc==SQLITE_OK ){ - rc = sqlite3Fts3PendingTermsFlush(p); + rc = tdsqlite3Fts3PendingTermsFlush(p); } if( p->zContentTbl==0 ){ @@ -150004,11 +172436,11 @@ static int fts3RenameMethod( ** ** Flush the contents of the pending-terms table to disk. */ -static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ +static int fts3SavepointMethod(tdsqlite3_vtab *pVtab, int iSavepoint){ int rc = SQLITE_OK; UNUSED_PARAMETER(iSavepoint); assert( ((Fts3Table *)pVtab)->inTransaction ); - assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint ); + assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint ); TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint ); if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){ rc = fts3SyncMethod(pVtab); @@ -150021,7 +172453,7 @@ static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ ** ** This is a no-op. */ -static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ +static int fts3ReleaseMethod(tdsqlite3_vtab *pVtab, int iSavepoint){ TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); UNUSED_PARAMETER(iSavepoint); UNUSED_PARAMETER(pVtab); @@ -150036,18 +172468,32 @@ static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ ** ** Discard the contents of the pending terms table. */ -static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ +static int fts3RollbackToMethod(tdsqlite3_vtab *pVtab, int iSavepoint){ Fts3Table *p = (Fts3Table*)pVtab; UNUSED_PARAMETER(iSavepoint); assert( p->inTransaction ); - assert( p->mxSavepoint >= iSavepoint ); TESTONLY( p->mxSavepoint = iSavepoint ); - sqlite3Fts3PendingTermsClear(p); + tdsqlite3Fts3PendingTermsClear(p); return SQLITE_OK; } -static const sqlite3_module fts3Module = { - /* iVersion */ 2, +/* +** Return true if zName is the extension on one of the shadow tables used +** by this module. +*/ +static int fts3ShadowName(const char *zName){ + static const char *azName[] = { + "content", "docsize", "segdir", "segments", "stat", + }; + unsigned int i; + for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){ + if( tdsqlite3_stricmp(zName, azName[i])==0 ) return 1; + } + return 0; +} + +static const tdsqlite3_module fts3Module = { + /* iVersion */ 3, /* xCreate */ fts3CreateMethod, /* xConnect */ fts3ConnectMethod, /* xBestIndex */ fts3BestIndexMethod, @@ -150070,6 +172516,7 @@ static const sqlite3_module fts3Module = { /* xSavepoint */ fts3SavepointMethod, /* xRelease */ fts3ReleaseMethod, /* xRollbackTo */ fts3RollbackToMethod, + /* xShadowName */ fts3ShadowName, }; /* @@ -150079,8 +172526,8 @@ static const sqlite3_module fts3Module = { */ static void hashDestroy(void *p){ Fts3Hash *pHash = (Fts3Hash *)p; - sqlite3Fts3HashClear(pHash); - sqlite3_free(pHash); + tdsqlite3Fts3HashClear(pHash); + tdsqlite3_free(pHash); } /* @@ -150089,72 +172536,72 @@ static void hashDestroy(void *p){ ** respectively. The following three forward declarations are for functions ** declared in these files used to retrieve the respective implementations. ** -** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed +** Calling tdsqlite3Fts3SimpleTokenizerModule() sets the value pointed ** to by the argument to point to the "simple" tokenizer implementation. ** And so on. */ -SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); -SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); +SQLITE_PRIVATE void tdsqlite3Fts3SimpleTokenizerModule(tdsqlite3_tokenizer_module const**ppModule); +SQLITE_PRIVATE void tdsqlite3Fts3PorterTokenizerModule(tdsqlite3_tokenizer_module const**ppModule); #ifndef SQLITE_DISABLE_FTS3_UNICODE -SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule); +SQLITE_PRIVATE void tdsqlite3Fts3UnicodeTokenizer(tdsqlite3_tokenizer_module const**ppModule); #endif #ifdef SQLITE_ENABLE_ICU -SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); +SQLITE_PRIVATE void tdsqlite3Fts3IcuTokenizerModule(tdsqlite3_tokenizer_module const**ppModule); #endif /* ** Initialize the fts3 extension. If this extension is built as part ** of the sqlite library, then this function is called directly by ** SQLite. If fts3 is built as a dynamically loadable extension, this -** function is called by the sqlite3_extension_init() entry point. +** function is called by the tdsqlite3_extension_init() entry point. */ -SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ +SQLITE_PRIVATE int tdsqlite3Fts3Init(tdsqlite3 *db){ int rc = SQLITE_OK; Fts3Hash *pHash = 0; - const sqlite3_tokenizer_module *pSimple = 0; - const sqlite3_tokenizer_module *pPorter = 0; + const tdsqlite3_tokenizer_module *pSimple = 0; + const tdsqlite3_tokenizer_module *pPorter = 0; #ifndef SQLITE_DISABLE_FTS3_UNICODE - const sqlite3_tokenizer_module *pUnicode = 0; + const tdsqlite3_tokenizer_module *pUnicode = 0; #endif #ifdef SQLITE_ENABLE_ICU - const sqlite3_tokenizer_module *pIcu = 0; - sqlite3Fts3IcuTokenizerModule(&pIcu); + const tdsqlite3_tokenizer_module *pIcu = 0; + tdsqlite3Fts3IcuTokenizerModule(&pIcu); #endif #ifndef SQLITE_DISABLE_FTS3_UNICODE - sqlite3Fts3UnicodeTokenizer(&pUnicode); + tdsqlite3Fts3UnicodeTokenizer(&pUnicode); #endif #ifdef SQLITE_TEST - rc = sqlite3Fts3InitTerm(db); + rc = tdsqlite3Fts3InitTerm(db); if( rc!=SQLITE_OK ) return rc; #endif - rc = sqlite3Fts3InitAux(db); + rc = tdsqlite3Fts3InitAux(db); if( rc!=SQLITE_OK ) return rc; - sqlite3Fts3SimpleTokenizerModule(&pSimple); - sqlite3Fts3PorterTokenizerModule(&pPorter); + tdsqlite3Fts3SimpleTokenizerModule(&pSimple); + tdsqlite3Fts3PorterTokenizerModule(&pPorter); /* Allocate and initialize the hash-table used to store tokenizers. */ - pHash = sqlite3_malloc(sizeof(Fts3Hash)); + pHash = tdsqlite3_malloc(sizeof(Fts3Hash)); if( !pHash ){ rc = SQLITE_NOMEM; }else{ - sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); + tdsqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); } /* Load the built-in tokenizers into the hash table */ if( rc==SQLITE_OK ){ - if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple) - || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) + if( tdsqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple) + || tdsqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) #ifndef SQLITE_DISABLE_FTS3_UNICODE - || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) + || tdsqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) #endif #ifdef SQLITE_ENABLE_ICU - || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu)) + || (pIcu && tdsqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu)) #endif ){ rc = SQLITE_NOMEM; @@ -150163,32 +172610,32 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ #ifdef SQLITE_TEST if( rc==SQLITE_OK ){ - rc = sqlite3Fts3ExprInitTestInterface(db); + rc = tdsqlite3Fts3ExprInitTestInterface(db, pHash); } #endif /* Create the virtual table wrapper around the hash-table and overload - ** the two scalar functions. If this is successful, register the + ** the four scalar functions. If this is successful, register the ** module with sqlite. */ if( SQLITE_OK==rc - && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer")) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1)) + && SQLITE_OK==(rc = tdsqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer")) + && SQLITE_OK==(rc = tdsqlite3_overload_function(db, "snippet", -1)) + && SQLITE_OK==(rc = tdsqlite3_overload_function(db, "offsets", 1)) + && SQLITE_OK==(rc = tdsqlite3_overload_function(db, "matchinfo", 1)) + && SQLITE_OK==(rc = tdsqlite3_overload_function(db, "matchinfo", 2)) + && SQLITE_OK==(rc = tdsqlite3_overload_function(db, "optimize", 1)) ){ - rc = sqlite3_create_module_v2( + rc = tdsqlite3_create_module_v2( db, "fts3", &fts3Module, (void *)pHash, hashDestroy ); if( rc==SQLITE_OK ){ - rc = sqlite3_create_module_v2( + rc = tdsqlite3_create_module_v2( db, "fts4", &fts3Module, (void *)pHash, 0 ); } if( rc==SQLITE_OK ){ - rc = sqlite3Fts3InitTok(db, (void *)pHash); + rc = tdsqlite3Fts3InitTok(db, (void *)pHash); } return rc; } @@ -150197,8 +172644,8 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ /* An error has occurred. Delete the hash table and return the error code. */ assert( rc!=SQLITE_OK ); if( pHash ){ - sqlite3Fts3HashClear(pHash); - sqlite3_free(pHash); + tdsqlite3Fts3HashClear(pHash); + tdsqlite3_free(pHash); } return rc; } @@ -150255,7 +172702,7 @@ static void fts3EvalAllocateReaders( ** It is merged into the main doclist stored in p->doclist.aAll/nAll. ** ** This function assumes that pList points to a buffer allocated using -** sqlite3_malloc(). This function takes responsibility for eventually +** tdsqlite3_malloc(). This function takes responsibility for eventually ** freeing the buffer. ** ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs. @@ -150271,7 +172718,7 @@ static int fts3EvalPhraseMergeToken( assert( iToken!=p->iDoclistToken ); if( pList==0 ){ - sqlite3_free(p->doclist.aAll); + tdsqlite3_free(p->doclist.aAll); p->doclist.aAll = 0; p->doclist.nAll = 0; } @@ -150282,7 +172729,7 @@ static int fts3EvalPhraseMergeToken( } else if( p->doclist.aAll==0 ){ - sqlite3_free(pList); + tdsqlite3_free(pList); } else { @@ -150309,7 +172756,7 @@ static int fts3EvalPhraseMergeToken( rc = fts3DoclistPhraseMerge( pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight ); - sqlite3_free(pLeft); + tdsqlite3_free(pLeft); p->doclist.aAll = pRight; p->doclist.nAll = nRight; } @@ -150350,6 +172797,7 @@ static int fts3EvalPhraseLoad( return rc; } +#ifndef SQLITE_DISABLE_FTS4_DEFERRED /* ** This function is called on each phrase after the position lists for ** any deferred tokens have been loaded into memory. It updates the phrases @@ -150375,11 +172823,11 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ if( pDeferred ){ char *pList; int nList; - int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList); + int rc = tdsqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList); if( rc!=SQLITE_OK ) return rc; if( pList==0 ){ - sqlite3_free(aPoslist); + tdsqlite3_free(aPoslist); pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; return SQLITE_OK; @@ -150395,11 +172843,11 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ assert( iPrev>=0 ); fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2); - sqlite3_free(aPoslist); + tdsqlite3_free(aPoslist); aPoslist = pList; nPoslist = (int)(aOut - aPoslist); if( nPoslist==0 ){ - sqlite3_free(aPoslist); + tdsqlite3_free(aPoslist); pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; return SQLITE_OK; @@ -150432,9 +172880,9 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ nDistance = iPrev - nMaxUndeferred; } - aOut = (char *)sqlite3_malloc(nPoslist+8); + aOut = (char *)tdsqlite3_malloc(nPoslist+8); if( !aOut ){ - sqlite3_free(aPoslist); + tdsqlite3_free(aPoslist); return SQLITE_NOMEM; } @@ -150443,16 +172891,17 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ pPhrase->doclist.bFreeList = 1; pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList); }else{ - sqlite3_free(aOut); + tdsqlite3_free(aOut); pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; } - sqlite3_free(aPoslist); + tdsqlite3_free(aPoslist); } } return SQLITE_OK; } +#endif /* SQLITE_DISABLE_FTS4_DEFERRED */ /* ** Maximum number of tokens a phrase may have to be considered for the @@ -150486,7 +172935,7 @@ static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ int bIncrOk = (bOptOk && pCsr->bDesc==pTab->bDescIdx && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 -#ifdef SQLITE_TEST +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) && pTab->bNoIncrDoclist==0 #endif ); @@ -150505,7 +172954,7 @@ static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ Fts3PhraseToken *pToken = &p->aToken[i]; Fts3MultiSegReader *pSegcsr = pToken->pSegcsr; if( pSegcsr ){ - rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n); + rc = tdsqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n); } } p->bIncr = 1; @@ -150529,12 +172978,12 @@ static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ ** descending (parameter bDescIdx==1) order of docid. Regardless, this ** function iterates from the end of the doclist to the beginning. */ -SQLITE_PRIVATE void sqlite3Fts3DoclistPrev( +SQLITE_PRIVATE void tdsqlite3Fts3DoclistPrev( int bDescIdx, /* True if the doclist is desc */ char *aDoclist, /* Pointer to entire doclist */ int nDoclist, /* Length of aDoclist in bytes */ char **ppIter, /* IN/OUT: Iterator pointer */ - sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ + tdsqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ int *pnList, /* OUT: List length pointer */ u8 *pbEof /* OUT: End-of-file flag */ ){ @@ -150546,15 +172995,15 @@ SQLITE_PRIVATE void sqlite3Fts3DoclistPrev( assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) ); if( p==0 ){ - sqlite3_int64 iDocid = 0; + tdsqlite3_int64 iDocid = 0; char *pNext = 0; char *pDocid = aDoclist; char *pEnd = &aDoclist[nDoclist]; int iMul = 1; while( pDocid<pEnd ){ - sqlite3_int64 iDelta; - pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta); + tdsqlite3_int64 iDelta; + pDocid += tdsqlite3Fts3GetVarint(pDocid, &iDelta); iDocid += (iMul * iDelta); pNext = pDocid; fts3PoslistCopy(0, &pDocid); @@ -150567,7 +173016,7 @@ SQLITE_PRIVATE void sqlite3Fts3DoclistPrev( *piDocid = iDocid; }else{ int iMul = (bDescIdx ? -1 : 1); - sqlite3_int64 iDelta; + tdsqlite3_int64 iDelta; fts3GetReverseVarint(&p, aDoclist, &iDelta); *piDocid -= (iMul * iDelta); @@ -150585,12 +173034,12 @@ SQLITE_PRIVATE void sqlite3Fts3DoclistPrev( /* ** Iterate forwards through a doclist. */ -SQLITE_PRIVATE void sqlite3Fts3DoclistNext( +SQLITE_PRIVATE void tdsqlite3Fts3DoclistNext( int bDescIdx, /* True if the doclist is desc */ char *aDoclist, /* Pointer to entire doclist */ int nDoclist, /* Length of aDoclist in bytes */ char **ppIter, /* IN/OUT: Iterator pointer */ - sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ + tdsqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ u8 *pbEof /* OUT: End-of-file flag */ ){ char *p = *ppIter; @@ -150602,15 +173051,15 @@ SQLITE_PRIVATE void sqlite3Fts3DoclistNext( if( p==0 ){ p = aDoclist; - p += sqlite3Fts3GetVarint(p, piDocid); + p += tdsqlite3Fts3GetVarint(p, piDocid); }else{ fts3PoslistCopy(0, &p); while( p<&aDoclist[nDoclist] && *p==0 ) p++; if( p>=&aDoclist[nDoclist] ){ *pbEof = 1; }else{ - sqlite3_int64 iVar; - p += sqlite3Fts3GetVarint(p, &iVar); + tdsqlite3_int64 iVar; + p += tdsqlite3Fts3GetVarint(p, &iVar); *piDocid += ((bDescIdx ? -1 : 1) * iVar); } } @@ -150628,20 +173077,21 @@ static void fts3EvalDlPhraseNext( u8 *pbEof ){ char *pIter; /* Used to iterate through aAll */ - char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */ + char *pEnd; /* 1 byte past end of aAll */ if( pDL->pNextDocid ){ pIter = pDL->pNextDocid; + assert( pDL->aAll!=0 || pIter==0 ); }else{ pIter = pDL->aAll; } - if( pIter>=pEnd ){ + if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){ /* We have already reached the end of this doclist. EOF. */ *pbEof = 1; }else{ - sqlite3_int64 iDelta; - pIter += sqlite3Fts3GetVarint(pIter, &iDelta); + tdsqlite3_int64 iDelta; + pIter += tdsqlite3Fts3GetVarint(pIter, &iDelta); if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){ pDL->iDocid += iDelta; }else{ @@ -150671,7 +173121,7 @@ static void fts3EvalDlPhraseNext( typedef struct TokenDoclist TokenDoclist; struct TokenDoclist { int bIgnore; - sqlite3_int64 iDocid; + tdsqlite3_int64 iDocid; char *pList; int nList; }; @@ -150707,7 +173157,7 @@ static int incrPhraseTokenNext( assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 ); if( pToken->pSegcsr ){ assert( p->bIgnore==0 ); - rc = sqlite3Fts3MsrIncrNext( + rc = tdsqlite3Fts3MsrIncrNext( pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList ); if( p->pList==0 ) *pbEof = 1; @@ -150751,8 +173201,8 @@ static int fts3EvalIncrPhraseNext( ** one incremental token. In which case the bIncr flag is set. */ assert( p->bIncr==1 ); - if( p->nToken==1 && p->bIncr ){ - rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, + if( p->nToken==1 ){ + rc = tdsqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, &pDL->iDocid, &pDL->pList, &pDL->nList ); if( pDL->pList==0 ) bEof = 1; @@ -150766,7 +173216,7 @@ static int fts3EvalIncrPhraseNext( while( bEof==0 ){ int bMaxSet = 0; - sqlite3_int64 iMax = 0; /* Largest docid for all iterators */ + tdsqlite3_int64 iMax = 0; /* Largest docid for all iterators */ int i; /* Used to iterate through tokens */ /* Advance the iterator for each token in the phrase once. */ @@ -150797,9 +173247,10 @@ static int fts3EvalIncrPhraseNext( if( bEof==0 ){ int nList = 0; int nByte = a[p->nToken-1].nList; - char *aDoclist = sqlite3_malloc(nByte+1); + char *aDoclist = tdsqlite3_malloc(nByte+FTS3_BUFFER_PADDING); if( !aDoclist ) return SQLITE_NOMEM; memcpy(aDoclist, a[p->nToken-1].pList, nByte+1); + memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING); for(i=0; i<(p->nToken-1); i++){ if( a[i].bIgnore==0 ){ @@ -150819,7 +173270,7 @@ static int fts3EvalIncrPhraseNext( pDL->bFreeList = 1; break; } - sqlite3_free(aDoclist); + tdsqlite3_free(aDoclist); } } } @@ -150849,7 +173300,7 @@ static int fts3EvalPhraseNext( if( p->bIncr ){ rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof); }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){ - sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, + tdsqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof ); pDL->pList = pDL->pNextDocid; @@ -150948,7 +173399,7 @@ static void fts3EvalTokenCosts( pTC->pRoot = pRoot; pTC->pToken = &pPhrase->aToken[i]; pTC->iCol = pPhrase->iColumn; - *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl); + *pRc = tdsqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl); } }else if( pExpr->eType!=FTSQUERY_NOT ){ assert( pExpr->eType==FTSQUERY_OR @@ -150984,6 +173435,7 @@ static void fts3EvalTokenCosts( ** the number of overflow pages consumed by a record B bytes in size. */ static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){ + int rc = SQLITE_OK; if( pCsr->nRowAvg==0 ){ /* The average document size, which is required to calculate the cost ** of each doclist, has not yet been determined. Read the required @@ -150996,38 +173448,37 @@ static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){ ** data stored in all rows of each column of the table, from left ** to right. */ - int rc; Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; - sqlite3_stmt *pStmt; - sqlite3_int64 nDoc = 0; - sqlite3_int64 nByte = 0; + tdsqlite3_stmt *pStmt; + tdsqlite3_int64 nDoc = 0; + tdsqlite3_int64 nByte = 0; const char *pEnd; const char *a; - rc = sqlite3Fts3SelectDoctotal(p, &pStmt); + rc = tdsqlite3Fts3SelectDoctotal(p, &pStmt); if( rc!=SQLITE_OK ) return rc; - a = sqlite3_column_blob(pStmt, 0); - assert( a ); - - pEnd = &a[sqlite3_column_bytes(pStmt, 0)]; - a += sqlite3Fts3GetVarint(a, &nDoc); - while( a<pEnd ){ - a += sqlite3Fts3GetVarint(a, &nByte); + a = tdsqlite3_column_blob(pStmt, 0); + testcase( a==0 ); /* If %_stat.value set to X'' */ + if( a ){ + pEnd = &a[tdsqlite3_column_bytes(pStmt, 0)]; + a += tdsqlite3Fts3GetVarintBounded(a, pEnd, &nDoc); + while( a<pEnd ){ + a += tdsqlite3Fts3GetVarintBounded(a, pEnd, &nByte); + } } if( nDoc==0 || nByte==0 ){ - sqlite3_reset(pStmt); + tdsqlite3_reset(pStmt); return FTS_CORRUPT_VTAB; } pCsr->nDoc = nDoc; pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz); assert( pCsr->nRowAvg>0 ); - rc = sqlite3_reset(pStmt); - if( rc!=SQLITE_OK ) return rc; + rc = tdsqlite3_reset(pStmt); } *pnPage = pCsr->nRowAvg; - return SQLITE_OK; + return rc; } /* @@ -151040,7 +173491,7 @@ static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){ ** the cluster with root node pRoot. See comments above the definition ** of struct Fts3TokenAndCost for more details. ** -** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken() +** If no error occurs, SQLITE_OK is returned and tdsqlite3Fts3DeferToken() ** called on each token to defer. Otherwise, an SQLite error code is ** returned. */ @@ -151127,7 +173578,7 @@ static int fts3EvalSelectDeferred( ** that will be loaded if all subsequent tokens are deferred. */ Fts3PhraseToken *pToken = pTC->pToken; - rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol); + rc = tdsqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol); fts3SegReaderCursorFree(pToken->pSegcsr); pToken->pSegcsr = 0; }else{ @@ -151191,7 +173642,7 @@ static int fts3EvalStart(Fts3Cursor *pCsr){ if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){ Fts3TokenAndCost *aTC; Fts3Expr **apOr; - aTC = (Fts3TokenAndCost *)sqlite3_malloc( + aTC = (Fts3TokenAndCost *)tdsqlite3_malloc64( sizeof(Fts3TokenAndCost) * nToken + sizeof(Fts3Expr *) * nOr * 2 ); @@ -151215,7 +173666,7 @@ static int fts3EvalStart(Fts3Cursor *pCsr){ } } - sqlite3_free(aTC); + tdsqlite3_free(aTC); } } #endif @@ -151229,7 +173680,7 @@ static int fts3EvalStart(Fts3Cursor *pCsr){ */ static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){ if( pPhrase->doclist.bFreeList ){ - sqlite3_free(pPhrase->doclist.pList); + tdsqlite3_free(pPhrase->doclist.pList); } pPhrase->doclist.pList = 0; pPhrase->doclist.nList = 0; @@ -151329,7 +173780,7 @@ static int fts3EvalNearTrim( ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is ** advanced to point to the next row that matches "x AND y". ** -** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is +** See tdsqlite3Fts3EvalTestDeferred() for details on testing if a row is ** really a match, taking into account deferred tokens and NEAR operators. */ static void fts3EvalNextRow( @@ -151366,7 +173817,7 @@ static void fts3EvalNextRow( fts3EvalNextRow(pCsr, pLeft, pRc); fts3EvalNextRow(pCsr, pRight, pRc); while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){ - sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid); + tdsqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid); if( iDiff==0 ) break; if( iDiff<0 ){ fts3EvalNextRow(pCsr, pLeft, pRc); @@ -151377,7 +173828,8 @@ static void fts3EvalNextRow( pExpr->iDocid = pLeft->iDocid; pExpr->bEof = (pLeft->bEof || pRight->bEof); if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){ - if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){ + assert( pRight->eType==FTSQUERY_PHRASE ); + if( pRight->pPhrase->doclist.aAll ){ Fts3Doclist *pDl = &pRight->pPhrase->doclist; while( *pRc==SQLITE_OK && pRight->bEof==0 ){ memset(pDl->pList, 0, pDl->nList); @@ -151399,14 +173851,14 @@ static void fts3EvalNextRow( case FTSQUERY_OR: { Fts3Expr *pLeft = pExpr->pLeft; Fts3Expr *pRight = pExpr->pRight; - sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); + tdsqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid ); assert( pRight->bStart || pLeft->iDocid==pRight->iDocid ); if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ fts3EvalNextRow(pCsr, pLeft, pRc); - }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){ + }else if( pLeft->bEof || iCmp>0 ){ fts3EvalNextRow(pCsr, pRight, pRc); }else{ fts3EvalNextRow(pCsr, pLeft, pRc); @@ -151498,58 +173950,54 @@ static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){ */ if( *pRc==SQLITE_OK && pExpr->eType==FTSQUERY_NEAR - && pExpr->bEof==0 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) ){ Fts3Expr *p; - int nTmp = 0; /* Bytes of temp space */ + tdsqlite3_int64 nTmp = 0; /* Bytes of temp space */ char *aTmp; /* Temp space for PoslistNearMerge() */ /* Allocate temporary working space. */ for(p=pExpr; p->pLeft; p=p->pLeft){ + assert( p->pRight->pPhrase->doclist.nList>0 ); nTmp += p->pRight->pPhrase->doclist.nList; } nTmp += p->pPhrase->doclist.nList; - if( nTmp==0 ){ + aTmp = tdsqlite3_malloc64(nTmp*2); + if( !aTmp ){ + *pRc = SQLITE_NOMEM; res = 0; }else{ - aTmp = sqlite3_malloc(nTmp*2); - if( !aTmp ){ - *pRc = SQLITE_NOMEM; - res = 0; - }else{ - char *aPoslist = p->pPhrase->doclist.pList; - int nToken = p->pPhrase->nToken; - - for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){ - Fts3Phrase *pPhrase = p->pRight->pPhrase; - int nNear = p->nNear; - res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); - } - - aPoslist = pExpr->pRight->pPhrase->doclist.pList; - nToken = pExpr->pRight->pPhrase->nToken; - for(p=pExpr->pLeft; p && res; p=p->pLeft){ - int nNear; - Fts3Phrase *pPhrase; - assert( p->pParent && p->pParent->pLeft==p ); - nNear = p->pParent->nNear; - pPhrase = ( - p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase - ); - res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); - } + char *aPoslist = p->pPhrase->doclist.pList; + int nToken = p->pPhrase->nToken; + + for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){ + Fts3Phrase *pPhrase = p->pRight->pPhrase; + int nNear = p->nNear; + res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); } - sqlite3_free(aTmp); + aPoslist = pExpr->pRight->pPhrase->doclist.pList; + nToken = pExpr->pRight->pPhrase->nToken; + for(p=pExpr->pLeft; p && res; p=p->pLeft){ + int nNear; + Fts3Phrase *pPhrase; + assert( p->pParent && p->pParent->pLeft==p ); + nNear = p->pParent->nNear; + pPhrase = ( + p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase + ); + res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); + } } + + tdsqlite3_free(aTmp); } return res; } /* -** This function is a helper function for sqlite3Fts3EvalTestDeferred(). +** This function is a helper function for tdsqlite3Fts3EvalTestDeferred(). ** Assuming no error occurs or has occurred, It returns non-zero if the ** expression passed as the second argument matches the row that pCsr ** currently points to, or zero if it does not. @@ -151670,7 +174118,7 @@ static int fts3EvalTestExpr( ** Or, if no error occurs and it seems the current row does match the FTS ** query, return 0. */ -SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){ +SQLITE_PRIVATE int tdsqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){ int rc = *pRc; int bMiss = 0; if( rc==SQLITE_OK ){ @@ -151684,13 +174132,13 @@ SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){ if( pCsr->pDeferred ){ rc = fts3CursorSeek(0, pCsr); if( rc==SQLITE_OK ){ - rc = sqlite3Fts3CacheDeferredDoclists(pCsr); + rc = tdsqlite3Fts3CacheDeferredDoclists(pCsr); } } bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc)); /* Free the position-lists accumulated for each deferred token above. */ - sqlite3Fts3FreeDeferredDoclists(pCsr); + tdsqlite3Fts3FreeDeferredDoclists(pCsr); *pRc = rc; } return (rc==SQLITE_OK && bMiss); @@ -151709,15 +174157,15 @@ static int fts3EvalNext(Fts3Cursor *pCsr){ }else{ do { if( pCsr->isRequireSeek==0 ){ - sqlite3_reset(pCsr->pStmt); + tdsqlite3_reset(pCsr->pStmt); } - assert( sqlite3_data_count(pCsr->pStmt)==0 ); + assert( tdsqlite3_data_count(pCsr->pStmt)==0 ); fts3EvalNextRow(pCsr, pExpr, &rc); pCsr->isEof = pExpr->bEof; pCsr->isRequireSeek = 1; pCsr->isMatchinfoNeeded = 1; pCsr->iPrevId = pExpr->iDocid; - }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) ); + }while( pCsr->isEof==0 && tdsqlite3Fts3EvalTestDeferred(pCsr, &rc) ); } /* Check if the cursor is past the end of the docid range specified @@ -151757,7 +174205,7 @@ static void fts3EvalRestart( Fts3PhraseToken *pToken = &pPhrase->aToken[i]; assert( pToken->pDeferred==0 ); if( pToken->pSegcsr ){ - sqlite3Fts3MsrIncrRestart(pToken->pSegcsr); + tdsqlite3Fts3MsrIncrRestart(pToken->pSegcsr); } } *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase); @@ -151784,15 +174232,14 @@ static void fts3EvalRestart( ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase ** expression nodes. */ -static void fts3EvalUpdateCounts(Fts3Expr *pExpr){ +static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){ if( pExpr ){ Fts3Phrase *pPhrase = pExpr->pPhrase; if( pPhrase && pPhrase->doclist.pList ){ int iCol = 0; char *p = pPhrase->doclist.pList; - assert( *p ); - while( 1 ){ + do{ u8 c = 0; int iCnt = 0; while( 0xFE & (*p | c) ){ @@ -151808,11 +174255,11 @@ static void fts3EvalUpdateCounts(Fts3Expr *pExpr){ if( *p==0x00 ) break; p++; p += fts3GetVarint32(p, &iCol); - } + }while( iCol<nCol ); } - fts3EvalUpdateCounts(pExpr->pLeft); - fts3EvalUpdateCounts(pExpr->pRight); + fts3EvalUpdateCounts(pExpr->pLeft, nCol); + fts3EvalUpdateCounts(pExpr->pRight, nCol); } } @@ -151839,8 +174286,8 @@ static int fts3EvalGatherStats( Fts3Expr *pRoot; /* Root of NEAR expression */ Fts3Expr *p; /* Iterator used for several purposes */ - sqlite3_int64 iPrevId = pCsr->iPrevId; - sqlite3_int64 iDocid; + tdsqlite3_int64 iPrevId = pCsr->iPrevId; + tdsqlite3_int64 iDocid; u8 bEof; /* Find the root of the NEAR expression */ @@ -151856,7 +174303,7 @@ static int fts3EvalGatherStats( for(p=pRoot; p; p=p->pLeft){ Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight); assert( pE->aMI==0 ); - pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32)); + pE->aMI = (u32 *)tdsqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32)); if( !pE->aMI ) return SQLITE_NOMEM; memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32)); } @@ -151867,8 +174314,8 @@ static int fts3EvalGatherStats( do { /* Ensure the %_content statement is reset. */ - if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt); - assert( sqlite3_data_count(pCsr->pStmt)==0 ); + if( pCsr->isRequireSeek==0 ) tdsqlite3_reset(pCsr->pStmt); + assert( tdsqlite3_data_count(pCsr->pStmt)==0 ); /* Advance to the next document */ fts3EvalNextRow(pCsr, pRoot, &rc); @@ -151878,11 +174325,11 @@ static int fts3EvalGatherStats( pCsr->iPrevId = pRoot->iDocid; }while( pCsr->isEof==0 && pRoot->eType==FTSQUERY_NEAR - && sqlite3Fts3EvalTestDeferred(pCsr, &rc) + && tdsqlite3Fts3EvalTestDeferred(pCsr, &rc) ); if( rc==SQLITE_OK && pCsr->isEof==0 ){ - fts3EvalUpdateCounts(pRoot); + fts3EvalUpdateCounts(pRoot, pTab->nColumn); } } @@ -151938,7 +174385,7 @@ static int fts3EvalGatherStats( ** * If the phrase is part of a NEAR expression, then only phrase instances ** that meet the NEAR constraint are included in the counts. */ -SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats( +SQLITE_PRIVATE int tdsqlite3Fts3EvalPhraseStats( Fts3Cursor *pCsr, /* FTS cursor handle */ Fts3Expr *pExpr, /* Phrase expression */ u32 *aiOut /* Array to write results into (see above) */ @@ -151986,7 +174433,7 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats( ** This function works regardless of whether or not the phrase is deferred, ** incremental, or neither. */ -SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist( +SQLITE_PRIVATE int tdsqlite3Fts3EvalPhrasePoslist( Fts3Cursor *pCsr, /* FTS3 cursor object */ Fts3Expr *pExpr, /* Phrase to return doclist for */ int iCol, /* Column to return position list for */ @@ -151996,7 +174443,7 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist( Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; char *pIter; int iThis; - sqlite3_int64 iDocid; + tdsqlite3_int64 iDocid; /* If this phrase is applies specifically to some column other than ** column iCol, return a NULL pointer. */ @@ -152065,7 +174512,7 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist( bEof = !pPh->doclist.nAll || (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll)); while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){ - sqlite3Fts3DoclistNext( + tdsqlite3Fts3DoclistNext( bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, &pIter, &iDocid, &bEof ); @@ -152074,7 +174521,7 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist( bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll); while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){ int dummy; - sqlite3Fts3DoclistPrev( + tdsqlite3Fts3DoclistPrev( bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, &pIter, &iDocid, &dummy, &bEof ); @@ -152120,10 +174567,10 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist( ** * the contents of pPhrase->doclist, and ** * any Fts3MultiSegReader objects held by phrase tokens. */ -SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){ +SQLITE_PRIVATE void tdsqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){ if( pPhrase ){ int i; - sqlite3_free(pPhrase->doclist.aAll); + tdsqlite3_free(pPhrase->doclist.aAll); fts3EvalInvalidatePoslist(pPhrase); memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist)); for(i=0; i<pPhrase->nToken; i++){ @@ -152138,7 +174585,7 @@ SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){ ** Return SQLITE_CORRUPT_VTAB. */ #ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3Fts3Corrupt(){ +SQLITE_PRIVATE int tdsqlite3Fts3Corrupt(){ return SQLITE_CORRUPT_VTAB; } #endif @@ -152150,13 +174597,13 @@ SQLITE_PRIVATE int sqlite3Fts3Corrupt(){ #ifdef _WIN32 __declspec(dllexport) #endif -SQLITE_API int sqlite3_fts3_init( - sqlite3 *db, +SQLITE_API int tdsqlite3_fts3_init( + tdsqlite3 *db, char **pzErrMsg, - const sqlite3_api_routines *pApi + const tdsqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) - return sqlite3Fts3Init(db); + return tdsqlite3Fts3Init(db); } #endif @@ -152187,25 +174634,25 @@ typedef struct Fts3auxTable Fts3auxTable; typedef struct Fts3auxCursor Fts3auxCursor; struct Fts3auxTable { - sqlite3_vtab base; /* Base class used by SQLite core */ + tdsqlite3_vtab base; /* Base class used by SQLite core */ Fts3Table *pFts3Tab; }; struct Fts3auxCursor { - sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + tdsqlite3_vtab_cursor base; /* Base class used by SQLite core */ Fts3MultiSegReader csr; /* Must be right after "base" */ Fts3SegFilter filter; char *zStop; int nStop; /* Byte-length of string zStop */ int iLangid; /* Language id to query */ int isEof; /* True if cursor is at EOF */ - sqlite3_int64 iRowid; /* Current rowid */ + tdsqlite3_int64 iRowid; /* Current rowid */ int iCol; /* Current value of 'col' column */ int nStat; /* Size of aStat[] array */ struct Fts3auxColstats { - sqlite3_int64 nDoc; /* 'documents' values for current csr row */ - sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */ + tdsqlite3_int64 nDoc; /* 'documents' values for current csr row */ + tdsqlite3_int64 nOcc; /* 'occurrences' values for current csr row */ } *aStat; }; @@ -152221,18 +174668,18 @@ struct Fts3auxCursor { ** and xCreate are identical operations. */ static int fts3auxConnectMethod( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ void *pUnused, /* Unused */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ + tdsqlite3_vtab **ppVtab, /* OUT: New tdsqlite3_vtab object */ + char **pzErr /* OUT: tdsqlite3_malloc'd error message */ ){ char const *zDb; /* Name of database (e.g. "main") */ char const *zFts3; /* Name of fts3 table */ int nDb; /* Result of strlen(zDb) */ int nFts3; /* Result of strlen(zFts3) */ - int nByte; /* Bytes of space to allocate here */ + tdsqlite3_int64 nByte; /* Bytes of space to allocate here */ int rc; /* value returned by declare_vtab() */ Fts3auxTable *p; /* Virtual table object to return */ @@ -152248,7 +174695,7 @@ static int fts3auxConnectMethod( zDb = argv[1]; nDb = (int)strlen(zDb); if( argc==5 ){ - if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){ + if( nDb==4 && 0==tdsqlite3_strnicmp("temp", zDb, 4) ){ zDb = argv[3]; nDb = (int)strlen(zDb); zFts3 = argv[4]; @@ -152260,11 +174707,11 @@ static int fts3auxConnectMethod( } nFts3 = (int)strlen(zFts3); - rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA); + rc = tdsqlite3_declare_vtab(db, FTS3_AUX_SCHEMA); if( rc!=SQLITE_OK ) return rc; nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2; - p = (Fts3auxTable *)sqlite3_malloc(nByte); + p = (Fts3auxTable *)tdsqlite3_malloc64(nByte); if( !p ) return SQLITE_NOMEM; memset(p, 0, nByte); @@ -152276,13 +174723,13 @@ static int fts3auxConnectMethod( memcpy((char *)p->pFts3Tab->zDb, zDb, nDb); memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3); - sqlite3Fts3Dequote((char *)p->pFts3Tab->zName); + tdsqlite3Fts3Dequote((char *)p->pFts3Tab->zName); - *ppVtab = (sqlite3_vtab *)p; + *ppVtab = (tdsqlite3_vtab *)p; return SQLITE_OK; bad_args: - sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor"); + tdsqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor"); return SQLITE_ERROR; } @@ -152291,17 +174738,17 @@ static int fts3auxConnectMethod( ** These tables have no persistent representation of their own, so xDisconnect ** and xDestroy are identical operations. */ -static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){ +static int fts3auxDisconnectMethod(tdsqlite3_vtab *pVtab){ Fts3auxTable *p = (Fts3auxTable *)pVtab; Fts3Table *pFts3 = p->pFts3Tab; int i; /* Free any prepared statements held */ for(i=0; i<SizeofArray(pFts3->aStmt); i++){ - sqlite3_finalize(pFts3->aStmt[i]); + tdsqlite3_finalize(pFts3->aStmt[i]); } - sqlite3_free(pFts3->zSegmentsTbl); - sqlite3_free(p); + tdsqlite3_free(pFts3->zSegmentsTbl); + tdsqlite3_free(p); return SQLITE_OK; } @@ -152313,8 +174760,8 @@ static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){ ** xBestIndex - Analyze a WHERE and ORDER BY clause. */ static int fts3auxBestIndexMethod( - sqlite3_vtab *pVTab, - sqlite3_index_info *pInfo + tdsqlite3_vtab *pVTab, + tdsqlite3_index_info *pInfo ){ int i; int iEq = -1; @@ -152382,39 +174829,39 @@ static int fts3auxBestIndexMethod( /* ** xOpen - Open a cursor. */ -static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ +static int fts3auxOpenMethod(tdsqlite3_vtab *pVTab, tdsqlite3_vtab_cursor **ppCsr){ Fts3auxCursor *pCsr; /* Pointer to cursor object to return */ UNUSED_PARAMETER(pVTab); - pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor)); + pCsr = (Fts3auxCursor *)tdsqlite3_malloc(sizeof(Fts3auxCursor)); if( !pCsr ) return SQLITE_NOMEM; memset(pCsr, 0, sizeof(Fts3auxCursor)); - *ppCsr = (sqlite3_vtab_cursor *)pCsr; + *ppCsr = (tdsqlite3_vtab_cursor *)pCsr; return SQLITE_OK; } /* ** xClose - Close a cursor. */ -static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){ +static int fts3auxCloseMethod(tdsqlite3_vtab_cursor *pCursor){ Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; - sqlite3Fts3SegmentsClose(pFts3); - sqlite3Fts3SegReaderFinish(&pCsr->csr); - sqlite3_free((void *)pCsr->filter.zTerm); - sqlite3_free(pCsr->zStop); - sqlite3_free(pCsr->aStat); - sqlite3_free(pCsr); + tdsqlite3Fts3SegmentsClose(pFts3); + tdsqlite3Fts3SegReaderFinish(&pCsr->csr); + tdsqlite3_free((void *)pCsr->filter.zTerm); + tdsqlite3_free(pCsr->zStop); + tdsqlite3_free(pCsr->aStat); + tdsqlite3_free(pCsr); return SQLITE_OK; } static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){ if( nSize>pCsr->nStat ){ struct Fts3auxColstats *aNew; - aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, + aNew = (struct Fts3auxColstats *)tdsqlite3_realloc64(pCsr->aStat, sizeof(struct Fts3auxColstats) * nSize ); if( aNew==0 ) return SQLITE_NOMEM; @@ -152430,7 +174877,7 @@ static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){ /* ** xNext - Advance the cursor to the next row, if any. */ -static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ +static int fts3auxNextMethod(tdsqlite3_vtab_cursor *pCursor){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; int rc; @@ -152442,7 +174889,7 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK; } - rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr); + rc = tdsqlite3Fts3SegReaderStep(pFts3, &pCsr->csr); if( rc==SQLITE_ROW ){ int i = 0; int nDoclist = pCsr->csr.nDoclist; @@ -152465,9 +174912,9 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ iCol = 0; while( i<nDoclist ){ - sqlite3_int64 v = 0; + tdsqlite3_int64 v = 0; - i += sqlite3Fts3GetVarint(&aDoclist[i], &v); + i += tdsqlite3Fts3GetVarint(&aDoclist[i], &v); switch( eState ){ /* State 0. In this state the integer just read was a docid. */ case 0: @@ -152525,11 +174972,11 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ ** xFilter - Initialize a cursor to point at the start of its data. */ static int fts3auxFilterMethod( - sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + tdsqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ - sqlite3_value **apVal /* Arguments for the indexing scheme */ + tdsqlite3_value **apVal /* Arguments for the indexing scheme */ ){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; @@ -152569,32 +175016,32 @@ static int fts3auxFilterMethod( /* In case this cursor is being reused, close and zero it. */ testcase(pCsr->filter.zTerm); - sqlite3Fts3SegReaderFinish(&pCsr->csr); - sqlite3_free((void *)pCsr->filter.zTerm); - sqlite3_free(pCsr->aStat); + tdsqlite3Fts3SegReaderFinish(&pCsr->csr); + tdsqlite3_free((void *)pCsr->filter.zTerm); + tdsqlite3_free(pCsr->aStat); memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr); pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN; if( iEq>=0 || iGe>=0 ){ - const unsigned char *zStr = sqlite3_value_text(apVal[0]); + const unsigned char *zStr = tdsqlite3_value_text(apVal[0]); assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) ); if( zStr ){ - pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr); - pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]); + pCsr->filter.zTerm = tdsqlite3_mprintf("%s", zStr); if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM; + pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm); } } if( iLe>=0 ){ - pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe])); - pCsr->nStop = sqlite3_value_bytes(apVal[iLe]); + pCsr->zStop = tdsqlite3_mprintf("%s", tdsqlite3_value_text(apVal[iLe])); if( pCsr->zStop==0 ) return SQLITE_NOMEM; + pCsr->nStop = (int)strlen(pCsr->zStop); } if( iLangid>=0 ){ - iLangVal = sqlite3_value_int(apVal[iLangid]); + iLangVal = tdsqlite3_value_int(apVal[iLangid]); /* If the user specified a negative value for the languageid, use zero ** instead. This works, as the "languageid=?" constraint will also @@ -152605,11 +175052,11 @@ static int fts3auxFilterMethod( } pCsr->iLangid = iLangVal; - rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL, + rc = tdsqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL, pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr ); if( rc==SQLITE_OK ){ - rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter); + rc = tdsqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter); } if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor); @@ -152619,7 +175066,7 @@ static int fts3auxFilterMethod( /* ** xEof - Return true if the cursor is at EOF, or false otherwise. */ -static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){ +static int fts3auxEofMethod(tdsqlite3_vtab_cursor *pCursor){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; return pCsr->isEof; } @@ -152628,8 +175075,8 @@ static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){ ** xColumn - Return a column value. */ static int fts3auxColumnMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + tdsqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + tdsqlite3_context *pCtx, /* Context for tdsqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ Fts3auxCursor *p = (Fts3auxCursor *)pCursor; @@ -152637,28 +175084,28 @@ static int fts3auxColumnMethod( assert( p->isEof==0 ); switch( iCol ){ case 0: /* term */ - sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT); + tdsqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT); break; case 1: /* col */ if( p->iCol ){ - sqlite3_result_int(pCtx, p->iCol-1); + tdsqlite3_result_int(pCtx, p->iCol-1); }else{ - sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC); + tdsqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC); } break; case 2: /* documents */ - sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc); + tdsqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc); break; case 3: /* occurrences */ - sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc); + tdsqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc); break; default: /* languageid */ assert( iCol==4 ); - sqlite3_result_int(pCtx, p->iLangid); + tdsqlite3_result_int(pCtx, p->iLangid); break; } @@ -152669,7 +175116,7 @@ static int fts3auxColumnMethod( ** xRowid - Return the current rowid for the cursor. */ static int fts3auxRowidMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + tdsqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite_int64 *pRowid /* OUT: Rowid value */ ){ Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; @@ -152679,10 +175126,10 @@ static int fts3auxRowidMethod( /* ** Register the fts3aux module with database connection db. Return SQLITE_OK -** if successful or an error code if sqlite3_create_module() fails. +** if successful or an error code if tdsqlite3_create_module() fails. */ -SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){ - static const sqlite3_module fts3aux_module = { +SQLITE_PRIVATE int tdsqlite3Fts3InitAux(tdsqlite3 *db){ + static const tdsqlite3_module fts3aux_module = { 0, /* iVersion */ fts3auxConnectMethod, /* xCreate */ fts3auxConnectMethod, /* xConnect */ @@ -152705,11 +175152,12 @@ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ - 0 /* xRollbackTo */ + 0, /* xRollbackTo */ + 0 /* xShadowName */ }; int rc; /* Return code */ - rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0); + rc = tdsqlite3_create_module(db, "fts4aux", &fts3aux_module, 0); return rc; } @@ -152755,7 +175203,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){ ** AND operators have a higher precedence than OR. ** ** If compiled with SQLITE_TEST defined, then this module exports the -** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable +** symbol "int tdsqlite3_fts3_enable_parentheses". Setting this variable ** to zero causes the module to use the old syntax. If it is set to ** non-zero the new syntax is activated. This is so both syntaxes can ** be tested using a single build of testfixture. @@ -152783,12 +175231,12 @@ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){ */ #ifdef SQLITE_TEST -SQLITE_API int sqlite3_fts3_enable_parentheses = 0; +SQLITE_API int tdsqlite3_fts3_enable_parentheses = 0; #else # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS -# define sqlite3_fts3_enable_parentheses 1 +# define tdsqlite3_fts3_enable_parentheses 1 # else -# define sqlite3_fts3_enable_parentheses 0 +# define tdsqlite3_fts3_enable_parentheses 0 # endif #endif @@ -152810,14 +175258,14 @@ SQLITE_API int sqlite3_fts3_enable_parentheses = 0; */ typedef struct ParseContext ParseContext; struct ParseContext { - sqlite3_tokenizer *pTokenizer; /* Tokenizer module */ + tdsqlite3_tokenizer *pTokenizer; /* Tokenizer module */ int iLangid; /* Language id used with tokenizer */ const char **azCol; /* Array of column names for fts3 table */ int bFts4; /* True to allow FTS4-only syntax */ int nCol; /* Number of entries in azCol[] */ int iDefaultCol; /* Default column to query */ int isNot; /* True if getNextNode() sees a unary - */ - sqlite3_context *pCtx; /* Write error message here */ + tdsqlite3_context *pCtx; /* Write error message here */ int nNest; /* Number of nested brackets */ }; @@ -152837,25 +175285,25 @@ static int fts3isspace(char c){ } /* -** Allocate nByte bytes of memory using sqlite3_malloc(). If successful, +** Allocate nByte bytes of memory using tdsqlite3_malloc(). If successful, ** zero the memory before returning a pointer to it. If unsuccessful, ** return NULL. */ -static void *fts3MallocZero(int nByte){ - void *pRet = sqlite3_malloc(nByte); +static void *fts3MallocZero(tdsqlite3_int64 nByte){ + void *pRet = tdsqlite3_malloc64(nByte); if( pRet ) memset(pRet, 0, nByte); return pRet; } -SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer( - sqlite3_tokenizer *pTokenizer, +SQLITE_PRIVATE int tdsqlite3Fts3OpenTokenizer( + tdsqlite3_tokenizer *pTokenizer, int iLangid, const char *z, int n, - sqlite3_tokenizer_cursor **ppCsr + tdsqlite3_tokenizer_cursor **ppCsr ){ - sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; - sqlite3_tokenizer_cursor *pCsr = 0; + tdsqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + tdsqlite3_tokenizer_cursor *pCsr = 0; int rc; rc = pModule->xOpen(pTokenizer, z, n, &pCsr); @@ -152887,7 +175335,7 @@ static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *); ** single token and set *ppExpr to point to it. If the end of the buffer is ** reached before a token is found, set *ppExpr to zero. It is the ** responsibility of the caller to eventually deallocate the allocated -** Fts3Expr structure (if any) by passing it to sqlite3_free(). +** Fts3Expr structure (if any) by passing it to tdsqlite3_free(). ** ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation ** fails. @@ -152899,25 +175347,25 @@ static int getNextToken( Fts3Expr **ppExpr, /* OUT: expression */ int *pnConsumed /* OUT: Number of bytes consumed */ ){ - sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; - sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + tdsqlite3_tokenizer *pTokenizer = pParse->pTokenizer; + tdsqlite3_tokenizer_module const *pModule = pTokenizer->pModule; int rc; - sqlite3_tokenizer_cursor *pCursor; + tdsqlite3_tokenizer_cursor *pCursor; Fts3Expr *pRet = 0; int i = 0; /* Set variable i to the maximum number of bytes of input to tokenize. */ for(i=0; i<n; i++){ - if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break; + if( tdsqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break; if( z[i]=='"' ) break; } *pnConsumed = i; - rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor); + rc = tdsqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor); if( rc==SQLITE_OK ){ const char *zToken; int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0; - int nByte; /* total space to allocate */ + tdsqlite3_int64 nByte; /* total space to allocate */ rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition); if( rc==SQLITE_OK ){ @@ -152940,7 +175388,7 @@ static int getNextToken( } while( 1 ){ - if( !sqlite3_fts3_enable_parentheses + if( !tdsqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){ pParse->isNot = 1; @@ -152971,10 +175419,10 @@ static int getNextToken( ** Enlarge a memory allocation. If an out-of-memory allocation occurs, ** then free the old allocation. */ -static void *fts3ReallocOrFree(void *pOrig, int nNew){ - void *pRet = sqlite3_realloc(pOrig, nNew); +static void *fts3ReallocOrFree(void *pOrig, tdsqlite3_int64 nNew){ + void *pRet = tdsqlite3_realloc64(pOrig, nNew); if( !pRet ){ - sqlite3_free(pOrig); + tdsqlite3_free(pOrig); } return pRet; } @@ -152996,11 +175444,11 @@ static int getNextString( const char *zInput, int nInput, /* Input string */ Fts3Expr **ppExpr /* OUT: expression */ ){ - sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; - sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + tdsqlite3_tokenizer *pTokenizer = pParse->pTokenizer; + tdsqlite3_tokenizer_module const *pModule = pTokenizer->pModule; int rc; Fts3Expr *p = 0; - sqlite3_tokenizer_cursor *pCursor = 0; + tdsqlite3_tokenizer_cursor *pCursor = 0; char *zTemp = 0; int nTemp = 0; @@ -153010,7 +175458,7 @@ static int getNextString( /* The final Fts3Expr data structure, including the Fts3Phrase, ** Fts3PhraseToken structures token buffers are all stored as a single ** allocation so that the expression can be freed with a single call to - ** sqlite3_free(). Setting this up requires a two pass approach. + ** tdsqlite3_free(). Setting this up requires a two pass approach. ** ** The first pass, in the block below, uses a tokenizer cursor to iterate ** through the tokens in the expression. This pass uses fts3ReallocOrFree() @@ -153026,7 +175474,7 @@ static int getNextString( ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase ** structures. */ - rc = sqlite3Fts3OpenTokenizer( + rc = tdsqlite3Fts3OpenTokenizer( pTokenizer, pParse->iLangid, zInput, nInput, &pCursor); if( rc==SQLITE_OK ){ int ii; @@ -153076,7 +175524,7 @@ static int getNextString( zBuf = (char *)&p->pPhrase->aToken[nToken]; if( zTemp ){ memcpy(zBuf, zTemp, nTemp); - sqlite3_free(zTemp); + tdsqlite3_free(zTemp); }else{ assert( nTemp==0 ); } @@ -153095,8 +175543,8 @@ no_mem: if( pCursor ){ pModule->xClose(pCursor); } - sqlite3_free(zTemp); - sqlite3_free(p); + tdsqlite3_free(zTemp); + tdsqlite3_free(p); *ppExpr = 0; return SQLITE_NOMEM; } @@ -153152,7 +175600,7 @@ static int getNextNode( for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){ const struct Fts3Keyword *pKey = &aKeyword[ii]; - if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){ + if( (pKey->parenOnly & ~tdsqlite3_fts3_enable_parentheses)!=0 ){ continue; } @@ -153211,12 +175659,11 @@ static int getNextNode( return getNextString(pParse, &zInput[1], ii-1, ppExpr); } - if( sqlite3_fts3_enable_parentheses ){ + if( tdsqlite3_fts3_enable_parentheses ){ if( *zInput=='(' ){ int nConsumed = 0; pParse->nNest++; rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed); - if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; } *pnConsumed = (int)(zInput - z) + 1 + nConsumed; return rc; }else if( *zInput==')' ){ @@ -153228,7 +175675,7 @@ static int getNextNode( } /* If control flows to this point, this must be a regular token, or - ** the end of the input. Read a regular token using the sqlite3_tokenizer + ** the end of the input. Read a regular token using the tdsqlite3_tokenizer ** interface. Before doing so, figure out if there is an explicit ** column specifier for the token. ** @@ -153244,7 +175691,7 @@ static int getNextNode( const char *zStr = pParse->azCol[ii]; int nStr = (int)strlen(zStr); if( nInput>nStr && zInput[nStr]==':' - && sqlite3_strnicmp(zStr, zInput, nStr)==0 + && tdsqlite3_strnicmp(zStr, zInput, nStr)==0 ){ iCol = ii; iColLen = (int)((zInput - z) + nStr + 1); @@ -153277,7 +175724,7 @@ static int getNextNode( */ static int opPrecedence(Fts3Expr *p){ assert( p->eType!=FTSQUERY_PHRASE ); - if( sqlite3_fts3_enable_parentheses ){ + if( tdsqlite3_fts3_enable_parentheses ){ return p->eType; }else if( p->eType==FTSQUERY_NEAR ){ return 1; @@ -153351,13 +175798,13 @@ static int fts3ExprParse( if( p ){ int isPhrase; - if( !sqlite3_fts3_enable_parentheses + if( !tdsqlite3_fts3_enable_parentheses && p->eType==FTSQUERY_PHRASE && pParse->isNot ){ /* Create an implicit NOT operator. */ Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr)); if( !pNot ){ - sqlite3Fts3ExprFree(p); + tdsqlite3Fts3ExprFree(p); rc = SQLITE_NOMEM; goto exprparse_out; } @@ -153380,7 +175827,7 @@ static int fts3ExprParse( ** isRequirePhrase is set, this is a syntax error. */ if( !isPhrase && isRequirePhrase ){ - sqlite3Fts3ExprFree(p); + tdsqlite3Fts3ExprFree(p); rc = SQLITE_ERROR; goto exprparse_out; } @@ -153391,7 +175838,7 @@ static int fts3ExprParse( assert( pRet && pPrev ); pAnd = fts3MallocZero(sizeof(Fts3Expr)); if( !pAnd ){ - sqlite3Fts3ExprFree(p); + tdsqlite3Fts3ExprFree(p); rc = SQLITE_NOMEM; goto exprparse_out; } @@ -153413,7 +175860,7 @@ static int fts3ExprParse( (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE) || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR) )){ - sqlite3Fts3ExprFree(p); + tdsqlite3Fts3ExprFree(p); rc = SQLITE_ERROR; goto exprparse_out; } @@ -153446,7 +175893,7 @@ static int fts3ExprParse( if( rc==SQLITE_DONE ){ rc = SQLITE_OK; - if( !sqlite3_fts3_enable_parentheses && pNotBranch ){ + if( !tdsqlite3_fts3_enable_parentheses && pNotBranch ){ if( !pRet ){ rc = SQLITE_ERROR; }else{ @@ -153464,8 +175911,8 @@ static int fts3ExprParse( exprparse_out: if( rc!=SQLITE_OK ){ - sqlite3Fts3ExprFree(pRet); - sqlite3Fts3ExprFree(pNotBranch); + tdsqlite3Fts3ExprFree(pRet); + tdsqlite3Fts3ExprFree(pNotBranch); pRet = 0; } *ppExpr = pRet; @@ -153515,7 +175962,7 @@ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ if( rc==SQLITE_OK ){ if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){ Fts3Expr **apLeaf; - apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth); + apLeaf = (Fts3Expr **)tdsqlite3_malloc64(sizeof(Fts3Expr *) * nMaxDepth); if( 0==apLeaf ){ rc = SQLITE_NOMEM; }else{ @@ -153565,7 +176012,7 @@ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ } } if( p ){ - sqlite3Fts3ExprFree(p); + tdsqlite3Fts3ExprFree(p); rc = SQLITE_TOOBIG; break; } @@ -153616,19 +176063,19 @@ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ }else{ /* An error occurred. Delete the contents of the apLeaf[] array ** and pFree list. Everything else is cleaned up by the call to - ** sqlite3Fts3ExprFree(pRoot) below. */ + ** tdsqlite3Fts3ExprFree(pRoot) below. */ Fts3Expr *pDel; for(i=0; i<nMaxDepth; i++){ - sqlite3Fts3ExprFree(apLeaf[i]); + tdsqlite3Fts3ExprFree(apLeaf[i]); } while( (pDel=pFree)!=0 ){ pFree = pDel->pParent; - sqlite3_free(pDel); + tdsqlite3_free(pDel); } } assert( pFree==0 ); - sqlite3_free( apLeaf ); + tdsqlite3_free( apLeaf ); } }else if( eType==FTSQUERY_NOT ){ Fts3Expr *pLeft = pRoot->pLeft; @@ -153645,8 +176092,8 @@ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ } if( rc!=SQLITE_OK ){ - sqlite3Fts3ExprFree(pRight); - sqlite3Fts3ExprFree(pLeft); + tdsqlite3Fts3ExprFree(pRight); + tdsqlite3Fts3ExprFree(pLeft); }else{ assert( pLeft && pRight ); pRoot->pLeft = pLeft; @@ -153658,7 +176105,7 @@ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ } if( rc!=SQLITE_OK ){ - sqlite3Fts3ExprFree(pRoot); + tdsqlite3Fts3ExprFree(pRoot); pRoot = 0; } *pp = pRoot; @@ -153666,18 +176113,18 @@ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ } /* -** This function is similar to sqlite3Fts3ExprParse(), with the following +** This function is similar to tdsqlite3Fts3ExprParse(), with the following ** differences: ** ** 1. It does not do expression rebalancing. ** 2. It does not check that the expression does not exceed the ** maximum allowable depth. ** 3. Even if it fails, *ppExpr may still be set to point to an -** expression tree. It should be deleted using sqlite3Fts3ExprFree() +** expression tree. It should be deleted using tdsqlite3Fts3ExprFree() ** in this case. */ static int fts3ExprParseUnbalanced( - sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ + tdsqlite3_tokenizer *pTokenizer, /* Tokenizer module */ int iLangid, /* Language id for tokenizer */ char **azCol, /* Array of column names for fts3 table */ int bFts4, /* True to allow FTS4-only syntax */ @@ -153739,8 +176186,8 @@ static int fts3ExprParseUnbalanced( ** specified as part of the query string), or -1 if tokens may by default ** match any table column. */ -SQLITE_PRIVATE int sqlite3Fts3ExprParse( - sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ +SQLITE_PRIVATE int tdsqlite3Fts3ExprParse( + tdsqlite3_tokenizer *pTokenizer, /* Tokenizer module */ int iLangid, /* Language id for tokenizer */ char **azCol, /* Array of column names for fts3 table */ int bFts4, /* True to allow FTS4-only syntax */ @@ -153748,7 +176195,7 @@ SQLITE_PRIVATE int sqlite3Fts3ExprParse( int iDefaultCol, /* Default column to query */ const char *z, int n, /* Text of MATCH query */ Fts3Expr **ppExpr, /* OUT: Parsed query structure */ - char **pzErr /* OUT: Error message (sqlite3_malloc) */ + char **pzErr /* OUT: Error message (tdsqlite3_malloc) */ ){ int rc = fts3ExprParseUnbalanced( pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr @@ -153764,16 +176211,16 @@ SQLITE_PRIVATE int sqlite3Fts3ExprParse( } if( rc!=SQLITE_OK ){ - sqlite3Fts3ExprFree(*ppExpr); + tdsqlite3Fts3ExprFree(*ppExpr); *ppExpr = 0; if( rc==SQLITE_TOOBIG ){ - sqlite3Fts3ErrMsg(pzErr, + tdsqlite3Fts3ErrMsg(pzErr, "FTS expression tree is too large (maximum depth %d)", SQLITE_FTS3_MAX_EXPR_DEPTH ); rc = SQLITE_ERROR; }else if( rc==SQLITE_ERROR ){ - sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z); + tdsqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z); } } @@ -153785,19 +176232,19 @@ SQLITE_PRIVATE int sqlite3Fts3ExprParse( */ static void fts3FreeExprNode(Fts3Expr *p){ assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 ); - sqlite3Fts3EvalPhraseCleanup(p->pPhrase); - sqlite3_free(p->aMI); - sqlite3_free(p); + tdsqlite3Fts3EvalPhraseCleanup(p->pPhrase); + tdsqlite3_free(p->aMI); + tdsqlite3_free(p); } /* -** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse(). +** Free a parsed fts3 query expression allocated by tdsqlite3Fts3ExprParse(). ** ** This function would be simpler if it recursively called itself. But ** that would mean passing a sufficiently large expression to ExprParse() ** could cause a stack overflow. */ -SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){ +SQLITE_PRIVATE void tdsqlite3Fts3ExprFree(Fts3Expr *pDel){ Fts3Expr *p; assert( pDel==0 || pDel->pParent==0 ); for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){ @@ -153828,55 +176275,27 @@ SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){ /* #include <stdio.h> */ /* -** Function to query the hash-table of tokenizers (see README.tokenizers). -*/ -static int queryTestTokenizer( - sqlite3 *db, - const char *zName, - const sqlite3_tokenizer_module **pp -){ - int rc; - sqlite3_stmt *pStmt; - const char zSql[] = "SELECT fts3_tokenizer(?)"; - - *pp = 0; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( rc!=SQLITE_OK ){ - return rc; - } - - sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ - memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); - } - } - - return sqlite3_finalize(pStmt); -} - -/* ** Return a pointer to a buffer containing a text representation of the ** expression passed as the first argument. The buffer is obtained from -** sqlite3_malloc(). It is the responsibility of the caller to use -** sqlite3_free() to release the memory. If an OOM condition is encountered, +** tdsqlite3_malloc(). It is the responsibility of the caller to use +** tdsqlite3_free() to release the memory. If an OOM condition is encountered, ** NULL is returned. ** ** If the second argument is not NULL, then its contents are prepended to -** the returned expression text and then freed using sqlite3_free(). +** the returned expression text and then freed using tdsqlite3_free(). */ static char *exprToString(Fts3Expr *pExpr, char *zBuf){ if( pExpr==0 ){ - return sqlite3_mprintf(""); + return tdsqlite3_mprintf(""); } switch( pExpr->eType ){ case FTSQUERY_PHRASE: { Fts3Phrase *pPhrase = pExpr->pPhrase; int i; - zBuf = sqlite3_mprintf( + zBuf = tdsqlite3_mprintf( "%zPHRASE %d 0", zBuf, pPhrase->iColumn); for(i=0; zBuf && i<pPhrase->nToken; i++){ - zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, + zBuf = tdsqlite3_mprintf("%z %.*s%s", zBuf, pPhrase->aToken[i].n, pPhrase->aToken[i].z, (pPhrase->aToken[i].isPrefix?"+":"") ); @@ -153885,25 +176304,25 @@ static char *exprToString(Fts3Expr *pExpr, char *zBuf){ } case FTSQUERY_NEAR: - zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear); + zBuf = tdsqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear); break; case FTSQUERY_NOT: - zBuf = sqlite3_mprintf("%zNOT ", zBuf); + zBuf = tdsqlite3_mprintf("%zNOT ", zBuf); break; case FTSQUERY_AND: - zBuf = sqlite3_mprintf("%zAND ", zBuf); + zBuf = tdsqlite3_mprintf("%zAND ", zBuf); break; case FTSQUERY_OR: - zBuf = sqlite3_mprintf("%zOR ", zBuf); + zBuf = tdsqlite3_mprintf("%zOR ", zBuf); break; } - if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf); + if( zBuf ) zBuf = tdsqlite3_mprintf("%z{", zBuf); if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf); - if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf); + if( zBuf ) zBuf = tdsqlite3_mprintf("%z} {", zBuf); if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf); - if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf); + if( zBuf ) zBuf = tdsqlite3_mprintf("%z}", zBuf); return zBuf; } @@ -153922,13 +176341,13 @@ static char *exprToString(Fts3Expr *pExpr, char *zBuf){ ** ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2'); */ -static void fts3ExprTest( - sqlite3_context *context, +static void fts3ExprTestCommon( + int bRebalance, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ - sqlite3_tokenizer_module const *pModule = 0; - sqlite3_tokenizer *pTokenizer = 0; + tdsqlite3_tokenizer *pTokenizer = 0; int rc; char **azCol = 0; const char *zExpr; @@ -153937,52 +176356,48 @@ static void fts3ExprTest( int ii; Fts3Expr *pExpr; char *zBuf = 0; - sqlite3 *db = sqlite3_context_db_handle(context); + Fts3Hash *pHash = (Fts3Hash*)tdsqlite3_user_data(context); + const char *zTokenizer = 0; + char *zErr = 0; if( argc<3 ){ - sqlite3_result_error(context, + tdsqlite3_result_error(context, "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1 ); return; } - rc = queryTestTokenizer(db, - (const char *)sqlite3_value_text(argv[0]), &pModule); - if( rc==SQLITE_NOMEM ){ - sqlite3_result_error_nomem(context); - goto exprtest_out; - }else if( !pModule ){ - sqlite3_result_error(context, "No such tokenizer module", -1); - goto exprtest_out; - } - - rc = pModule->xCreate(0, 0, &pTokenizer); - assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); - if( rc==SQLITE_NOMEM ){ - sqlite3_result_error_nomem(context); - goto exprtest_out; + zTokenizer = (const char*)tdsqlite3_value_text(argv[0]); + rc = tdsqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr); + if( rc!=SQLITE_OK ){ + if( rc==SQLITE_NOMEM ){ + tdsqlite3_result_error_nomem(context); + }else{ + tdsqlite3_result_error(context, zErr, -1); + } + tdsqlite3_free(zErr); + return; } - pTokenizer->pModule = pModule; - zExpr = (const char *)sqlite3_value_text(argv[1]); - nExpr = sqlite3_value_bytes(argv[1]); + zExpr = (const char *)tdsqlite3_value_text(argv[1]); + nExpr = tdsqlite3_value_bytes(argv[1]); nCol = argc-2; - azCol = (char **)sqlite3_malloc(nCol*sizeof(char *)); + azCol = (char **)tdsqlite3_malloc64(nCol*sizeof(char *)); if( !azCol ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); goto exprtest_out; } for(ii=0; ii<nCol; ii++){ - azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]); + azCol[ii] = (char *)tdsqlite3_value_text(argv[ii+2]); } - if( sqlite3_user_data(context) ){ + if( bRebalance ){ char *zDummy = 0; - rc = sqlite3Fts3ExprParse( + rc = tdsqlite3Fts3ExprParse( pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy ); assert( rc==SQLITE_OK || pExpr==0 ); - sqlite3_free(zDummy); + tdsqlite3_free(zDummy); }else{ rc = fts3ExprParseUnbalanced( pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr @@ -153990,35 +176405,50 @@ static void fts3ExprTest( } if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){ - sqlite3Fts3ExprFree(pExpr); - sqlite3_result_error(context, "Error parsing expression", -1); + tdsqlite3Fts3ExprFree(pExpr); + tdsqlite3_result_error(context, "Error parsing expression", -1); }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); }else{ - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); - sqlite3_free(zBuf); + tdsqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); + tdsqlite3_free(zBuf); } - sqlite3Fts3ExprFree(pExpr); + tdsqlite3Fts3ExprFree(pExpr); exprtest_out: - if( pModule && pTokenizer ){ - rc = pModule->xDestroy(pTokenizer); + if( pTokenizer ){ + rc = pTokenizer->pModule->xDestroy(pTokenizer); } - sqlite3_free(azCol); + tdsqlite3_free(azCol); +} + +static void fts3ExprTest( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + fts3ExprTestCommon(0, context, argc, argv); +} +static void fts3ExprTestRebalance( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + fts3ExprTestCommon(1, context, argc, argv); } /* ** Register the query expression parser test function fts3_exprtest() ** with database connection db. */ -SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){ - int rc = sqlite3_create_function( - db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0 +SQLITE_PRIVATE int tdsqlite3Fts3ExprInitTestInterface(tdsqlite3 *db, Fts3Hash *pHash){ + int rc = tdsqlite3_create_function( + db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0 ); if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", - -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0 + rc = tdsqlite3_create_function(db, "fts3_exprtest_rebalance", + -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0 ); } return rc; @@ -154066,15 +176496,15 @@ SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){ /* ** Malloc and Free functions */ -static void *fts3HashMalloc(int n){ - void *p = sqlite3_malloc(n); +static void *fts3HashMalloc(tdsqlite3_int64 n){ + void *p = tdsqlite3_malloc64(n); if( p ){ memset(p, 0, n); } return p; } static void fts3HashFree(void *p){ - sqlite3_free(p); + tdsqlite3_free(p); } /* Turn bulk memory into a hash table object by initializing the @@ -154087,7 +176517,7 @@ static void fts3HashFree(void *p){ ** true if the hash table should make its own private copy of keys and ** false if it should just use the supplied pointer. */ -SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){ +SQLITE_PRIVATE void tdsqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){ assert( pNew!=0 ); assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY ); pNew->keyClass = keyClass; @@ -154102,7 +176532,7 @@ SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copy ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ -SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){ +SQLITE_PRIVATE void tdsqlite3Fts3HashClear(Fts3Hash *pH){ Fts3HashElem *elem; /* For looping over all elements of the table */ assert( pH!=0 ); @@ -154310,7 +176740,7 @@ static void fts3RemoveElementByHash( } } -SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem( +SQLITE_PRIVATE Fts3HashElem *tdsqlite3Fts3HashFindElem( const Fts3Hash *pH, const void *pKey, int nKey @@ -154331,10 +176761,10 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem( ** that matches pKey,nKey. Return the data for this element if it is ** found, or NULL if there is no match. */ -SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){ +SQLITE_PRIVATE void *tdsqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){ Fts3HashElem *pElem; /* The element that matches key (if any) */ - pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey); + pElem = tdsqlite3Fts3HashFindElem(pH, pKey, nKey); return pElem ? pElem->data : 0; } @@ -154353,7 +176783,7 @@ SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, i ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ -SQLITE_PRIVATE void *sqlite3Fts3HashInsert( +SQLITE_PRIVATE void *tdsqlite3Fts3HashInsert( Fts3Hash *pH, /* The hash table to insert into */ const void *pKey, /* The key */ int nKey, /* Number of bytes in the key */ @@ -154450,17 +176880,17 @@ SQLITE_PRIVATE void *sqlite3Fts3HashInsert( /* #include "fts3_tokenizer.h" */ /* -** Class derived from sqlite3_tokenizer +** Class derived from tdsqlite3_tokenizer */ typedef struct porter_tokenizer { - sqlite3_tokenizer base; /* Base class */ + tdsqlite3_tokenizer base; /* Base class */ } porter_tokenizer; /* -** Class derived from sqlite3_tokenizer_cursor +** Class derived from tdsqlite3_tokenizer_cursor */ typedef struct porter_tokenizer_cursor { - sqlite3_tokenizer_cursor base; + tdsqlite3_tokenizer_cursor base; const char *zInput; /* input we are tokenizing */ int nInput; /* size of the input */ int iOffset; /* current position in zInput */ @@ -154475,14 +176905,14 @@ typedef struct porter_tokenizer_cursor { */ static int porterCreate( int argc, const char * const *argv, - sqlite3_tokenizer **ppTokenizer + tdsqlite3_tokenizer **ppTokenizer ){ porter_tokenizer *t; UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); - t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t)); + t = (porter_tokenizer *) tdsqlite3_malloc(sizeof(*t)); if( t==NULL ) return SQLITE_NOMEM; memset(t, 0, sizeof(*t)); *ppTokenizer = &t->base; @@ -154492,8 +176922,8 @@ static int porterCreate( /* ** Destroy a tokenizer */ -static int porterDestroy(sqlite3_tokenizer *pTokenizer){ - sqlite3_free(pTokenizer); +static int porterDestroy(tdsqlite3_tokenizer *pTokenizer){ + tdsqlite3_free(pTokenizer); return SQLITE_OK; } @@ -154504,15 +176934,15 @@ static int porterDestroy(sqlite3_tokenizer *pTokenizer){ ** *ppCursor. */ static int porterOpen( - sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + tdsqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *zInput, int nInput, /* String to be tokenized */ - sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ + tdsqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ ){ porter_tokenizer_cursor *c; UNUSED_PARAMETER(pTokenizer); - c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); + c = (porter_tokenizer_cursor *) tdsqlite3_malloc(sizeof(*c)); if( c==NULL ) return SQLITE_NOMEM; c->zInput = zInput; @@ -154536,10 +176966,10 @@ static int porterOpen( ** Close a tokenization cursor previously opened by a call to ** porterOpen() above. */ -static int porterClose(sqlite3_tokenizer_cursor *pCursor){ +static int porterClose(tdsqlite3_tokenizer_cursor *pCursor){ porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; - sqlite3_free(c->zToken); - sqlite3_free(c); + tdsqlite3_free(c->zToken); + tdsqlite3_free(c); return SQLITE_OK; } /* @@ -155009,7 +177439,7 @@ static const char porterIdChar[] = { ** have been opened by a prior call to porterOpen(). */ static int porterNext( - sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */ + tdsqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */ const char **pzToken, /* OUT: *pzToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ @@ -155038,7 +177468,7 @@ static int porterNext( if( n>c->nAllocated ){ char *pNew; c->nAllocated = n+20; - pNew = sqlite3_realloc(c->zToken, c->nAllocated); + pNew = tdsqlite3_realloc(c->zToken, c->nAllocated); if( !pNew ) return SQLITE_NOMEM; c->zToken = pNew; } @@ -155056,7 +177486,7 @@ static int porterNext( /* ** The set of routines that implement the porter-stemmer tokenizer */ -static const sqlite3_tokenizer_module porterTokenizerModule = { +static const tdsqlite3_tokenizer_module porterTokenizerModule = { 0, porterCreate, porterDestroy, @@ -155070,8 +177500,8 @@ static const sqlite3_tokenizer_module porterTokenizerModule = { ** Allocate a new porter tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ -SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule( - sqlite3_tokenizer_module const**ppModule +SQLITE_PRIVATE void tdsqlite3Fts3PorterTokenizerModule( + tdsqlite3_tokenizer_module const**ppModule ){ *ppModule = &porterTokenizerModule; } @@ -155113,13 +177543,13 @@ SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule( /* ** Return true if the two-argument version of fts3_tokenizer() -** has been activated via a prior call to sqlite3_db_config(db, +** has been activated via a prior call to tdsqlite3_db_config(db, ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0); */ -static int fts3TokenizerEnabled(sqlite3_context *context){ - sqlite3 *db = sqlite3_context_db_handle(context); +static int fts3TokenizerEnabled(tdsqlite3_context *context){ + tdsqlite3 *db = tdsqlite3_context_db_handle(context); int isEnabled = 0; - sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled); + tdsqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled); return isEnabled; } @@ -155131,7 +177561,7 @@ static int fts3TokenizerEnabled(sqlite3_context *context){ ** SELECT <function-name>(<key-name>, <pointer>); ** ** where <function-name> is the name passed as the second argument -** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer'). +** to the tdsqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer'). ** ** If the <pointer> argument is specified, it must be a blob value ** containing a pointer to be stored as the hash data corresponding @@ -155144,9 +177574,9 @@ static int fts3TokenizerEnabled(sqlite3_context *context){ ** to string <key-name> (after the hash-table is updated, if applicable). */ static void fts3TokenizerFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ Fts3Hash *pHash; void *pPtr = 0; @@ -155155,43 +177585,45 @@ static void fts3TokenizerFunc( assert( argc==1 || argc==2 ); - pHash = (Fts3Hash *)sqlite3_user_data(context); + pHash = (Fts3Hash *)tdsqlite3_user_data(context); - zName = sqlite3_value_text(argv[0]); - nName = sqlite3_value_bytes(argv[0])+1; + zName = tdsqlite3_value_text(argv[0]); + nName = tdsqlite3_value_bytes(argv[0])+1; if( argc==2 ){ - if( fts3TokenizerEnabled(context) ){ + if( fts3TokenizerEnabled(context) || tdsqlite3_value_frombind(argv[1]) ){ void *pOld; - int n = sqlite3_value_bytes(argv[1]); + int n = tdsqlite3_value_bytes(argv[1]); if( zName==0 || n!=sizeof(pPtr) ){ - sqlite3_result_error(context, "argument type mismatch", -1); + tdsqlite3_result_error(context, "argument type mismatch", -1); return; } - pPtr = *(void **)sqlite3_value_blob(argv[1]); - pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr); + pPtr = *(void **)tdsqlite3_value_blob(argv[1]); + pOld = tdsqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr); if( pOld==pPtr ){ - sqlite3_result_error(context, "out of memory", -1); + tdsqlite3_result_error(context, "out of memory", -1); } }else{ - sqlite3_result_error(context, "fts3tokenize disabled", -1); + tdsqlite3_result_error(context, "fts3tokenize disabled", -1); return; } }else{ if( zName ){ - pPtr = sqlite3Fts3HashFind(pHash, zName, nName); + pPtr = tdsqlite3Fts3HashFind(pHash, zName, nName); } if( !pPtr ){ - char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); - sqlite3_result_error(context, zErr, -1); - sqlite3_free(zErr); + char *zErr = tdsqlite3_mprintf("unknown tokenizer: %s", zName); + tdsqlite3_result_error(context, zErr, -1); + tdsqlite3_free(zErr); return; } } - sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT); + if( fts3TokenizerEnabled(context) || tdsqlite3_value_frombind(argv[0]) ){ + tdsqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT); + } } -SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){ +SQLITE_PRIVATE int tdsqlite3Fts3IsIdChar(char c){ static const char isFtsIdChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ @@ -155205,7 +177637,7 @@ SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){ return (c&0x80 || isFtsIdChar[(int)(c)]); } -SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){ +SQLITE_PRIVATE const char *tdsqlite3Fts3NextToken(const char *zStr, int *pn){ const char *z1; const char *z2 = 0; @@ -155229,9 +177661,9 @@ SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){ break; default: - if( sqlite3Fts3IsIdChar(*z1) ){ + if( tdsqlite3Fts3IsIdChar(*z1) ){ z2 = &z1[1]; - while( sqlite3Fts3IsIdChar(*z2) ) z2++; + while( tdsqlite3Fts3IsIdChar(*z2) ) z2++; }else{ z1++; } @@ -155242,10 +177674,10 @@ SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){ return z1; } -SQLITE_PRIVATE int sqlite3Fts3InitTokenizer( +SQLITE_PRIVATE int tdsqlite3Fts3InitTokenizer( Fts3Hash *pHash, /* Tokenizer hash table */ const char *zArg, /* Tokenizer name */ - sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */ + tdsqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */ char **pzErr /* OUT: Set to malloced error message */ ){ int rc; @@ -155253,53 +177685,53 @@ SQLITE_PRIVATE int sqlite3Fts3InitTokenizer( int n = 0; char *zCopy; char *zEnd; /* Pointer to nul-term of zCopy */ - sqlite3_tokenizer_module *m; + tdsqlite3_tokenizer_module *m; - zCopy = sqlite3_mprintf("%s", zArg); + zCopy = tdsqlite3_mprintf("%s", zArg); if( !zCopy ) return SQLITE_NOMEM; zEnd = &zCopy[strlen(zCopy)]; - z = (char *)sqlite3Fts3NextToken(zCopy, &n); + z = (char *)tdsqlite3Fts3NextToken(zCopy, &n); if( z==0 ){ assert( n==0 ); z = zCopy; } z[n] = '\0'; - sqlite3Fts3Dequote(z); + tdsqlite3Fts3Dequote(z); - m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1); + m = (tdsqlite3_tokenizer_module *)tdsqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1); if( !m ){ - sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z); + tdsqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z); rc = SQLITE_ERROR; }else{ char const **aArg = 0; int iArg = 0; z = &z[n+1]; - while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){ - int nNew = sizeof(char *)*(iArg+1); - char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew); + while( z<zEnd && (NULL!=(z = (char *)tdsqlite3Fts3NextToken(z, &n))) ){ + tdsqlite3_int64 nNew = sizeof(char *)*(iArg+1); + char const **aNew = (const char **)tdsqlite3_realloc64((void *)aArg, nNew); if( !aNew ){ - sqlite3_free(zCopy); - sqlite3_free((void *)aArg); + tdsqlite3_free(zCopy); + tdsqlite3_free((void *)aArg); return SQLITE_NOMEM; } aArg = aNew; aArg[iArg++] = z; z[n] = '\0'; - sqlite3Fts3Dequote(z); + tdsqlite3Fts3Dequote(z); z = &z[n+1]; } rc = m->xCreate(iArg, aArg, ppTok); assert( rc!=SQLITE_OK || *ppTok ); if( rc!=SQLITE_OK ){ - sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer"); + tdsqlite3Fts3ErrMsg(pzErr, "unknown tokenizer"); }else{ (*ppTok)->pModule = m; } - sqlite3_free((void *)aArg); + tdsqlite3_free((void *)aArg); } - sqlite3_free(zCopy); + tdsqlite3_free(zCopy); return rc; } @@ -155321,7 +177753,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitTokenizer( ** SELECT <function-name>(<key-name>, ..., <input-string>); ** ** where <function-name> is the name passed as the second argument -** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer') +** to the tdsqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer') ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test'). ** ** The return value is a string that may be interpreted as a Tcl @@ -155339,14 +177771,14 @@ SQLITE_PRIVATE int sqlite3Fts3InitTokenizer( ** */ static void testFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ Fts3Hash *pHash; - sqlite3_tokenizer_module *p; - sqlite3_tokenizer *pTokenizer = 0; - sqlite3_tokenizer_cursor *pCsr = 0; + tdsqlite3_tokenizer_module *p; + tdsqlite3_tokenizer *pTokenizer = 0; + tdsqlite3_tokenizer_cursor *pCsr = 0; const char *zErr = 0; @@ -155367,22 +177799,22 @@ static void testFunc( Tcl_Obj *pRet; if( argc<2 ){ - sqlite3_result_error(context, "insufficient arguments", -1); + tdsqlite3_result_error(context, "insufficient arguments", -1); return; } - nName = sqlite3_value_bytes(argv[0]); - zName = (const char *)sqlite3_value_text(argv[0]); - nInput = sqlite3_value_bytes(argv[argc-1]); - zInput = (const char *)sqlite3_value_text(argv[argc-1]); + nName = tdsqlite3_value_bytes(argv[0]); + zName = (const char *)tdsqlite3_value_text(argv[0]); + nInput = tdsqlite3_value_bytes(argv[argc-1]); + zInput = (const char *)tdsqlite3_value_text(argv[argc-1]); - pHash = (Fts3Hash *)sqlite3_user_data(context); - p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); + pHash = (Fts3Hash *)tdsqlite3_user_data(context); + p = (tdsqlite3_tokenizer_module *)tdsqlite3Fts3HashFind(pHash, zName, nName+1); if( !p ){ - char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName); - sqlite3_result_error(context, zErr2, -1); - sqlite3_free(zErr2); + char *zErr2 = tdsqlite3_mprintf("unknown tokenizer: %s", zName); + tdsqlite3_result_error(context, zErr2, -1); + tdsqlite3_free(zErr2); return; } @@ -155390,7 +177822,7 @@ static void testFunc( Tcl_IncrRefCount(pRet); for(i=1; i<argc-1; i++){ - azArg[i-1] = (const char *)sqlite3_value_text(argv[i]); + azArg[i-1] = (const char *)tdsqlite3_value_text(argv[i]); } if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){ @@ -155398,7 +177830,7 @@ static void testFunc( goto finish; } pTokenizer->pModule = p; - if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){ + if( tdsqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){ zErr = "error in xOpen()"; goto finish; } @@ -155422,63 +177854,65 @@ static void testFunc( finish: if( zErr ){ - sqlite3_result_error(context, zErr, -1); + tdsqlite3_result_error(context, zErr, -1); }else{ - sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); + tdsqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); } Tcl_DecrRefCount(pRet); } static int registerTokenizer( - sqlite3 *db, + tdsqlite3 *db, char *zName, - const sqlite3_tokenizer_module *p + const tdsqlite3_tokenizer_module *p ){ int rc; - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; const char zSql[] = "SELECT fts3_tokenizer(?, ?)"; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + rc = tdsqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ return rc; } - sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); - sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); - sqlite3_step(pStmt); + tdsqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + tdsqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); + tdsqlite3_step(pStmt); - return sqlite3_finalize(pStmt); + return tdsqlite3_finalize(pStmt); } static int queryTokenizer( - sqlite3 *db, + tdsqlite3 *db, char *zName, - const sqlite3_tokenizer_module **pp + const tdsqlite3_tokenizer_module **pp ){ int rc; - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; const char zSql[] = "SELECT fts3_tokenizer(?)"; *pp = 0; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + rc = tdsqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ return rc; } - sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){ - memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); + tdsqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + if( tdsqlite3_column_type(pStmt, 0)==SQLITE_BLOB + && tdsqlite3_column_bytes(pStmt, 0)==sizeof(*pp) + ){ + memcpy((void *)pp, tdsqlite3_column_blob(pStmt, 0), sizeof(*pp)); } } - return sqlite3_finalize(pStmt); + return tdsqlite3_finalize(pStmt); } -SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); +SQLITE_PRIVATE void tdsqlite3Fts3SimpleTokenizerModule(tdsqlite3_tokenizer_module const**ppModule); /* ** Implementation of the scalar function fts3_tokenizer_internal_test(). @@ -155499,27 +177933,27 @@ SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module co ** */ static void intTestFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ int rc; - const sqlite3_tokenizer_module *p1; - const sqlite3_tokenizer_module *p2; - sqlite3 *db = (sqlite3 *)sqlite3_user_data(context); + const tdsqlite3_tokenizer_module *p1; + const tdsqlite3_tokenizer_module *p2; + tdsqlite3 *db = (tdsqlite3 *)tdsqlite3_user_data(context); UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); /* Test the query function */ - sqlite3Fts3SimpleTokenizerModule(&p1); + tdsqlite3Fts3SimpleTokenizerModule(&p1); rc = queryTokenizer(db, "simple", &p2); assert( rc==SQLITE_OK ); assert( p1==p2 ); rc = queryTokenizer(db, "nosuchtokenizer", &p2); assert( rc==SQLITE_ERROR ); assert( p2==0 ); - assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") ); + assert( 0==strcmp(tdsqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") ); /* Test the storage function */ if( fts3TokenizerEnabled(context) ){ @@ -155530,7 +177964,7 @@ static void intTestFunc( assert( p2==p1 ); } - sqlite3_result_text(context, "ok", -1, SQLITE_STATIC); + tdsqlite3_result_text(context, "ok", -1, SQLITE_STATIC); } #endif @@ -155541,7 +177975,7 @@ static void intTestFunc( ** been initialized to use string keys, and to take a private copy ** of the key when a value is inserted. i.e. by a call similar to: ** -** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); +** tdsqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); ** ** This function adds a scalar function (see header comment above ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is @@ -155552,44 +177986,44 @@ static void intTestFunc( ** The third argument to this function, zName, is used as the name ** of both the scalar and, if created, the virtual table. */ -SQLITE_PRIVATE int sqlite3Fts3InitHashTable( - sqlite3 *db, +SQLITE_PRIVATE int tdsqlite3Fts3InitHashTable( + tdsqlite3 *db, Fts3Hash *pHash, const char *zName ){ int rc = SQLITE_OK; void *p = (void *)pHash; - const int any = SQLITE_ANY; + const int any = SQLITE_UTF8|SQLITE_DIRECTONLY; #ifdef SQLITE_TEST char *zTest = 0; char *zTest2 = 0; void *pdb = (void *)db; - zTest = sqlite3_mprintf("%s_test", zName); - zTest2 = sqlite3_mprintf("%s_internal_test", zName); + zTest = tdsqlite3_mprintf("%s_test", zName); + zTest2 = tdsqlite3_mprintf("%s_internal_test", zName); if( !zTest || !zTest2 ){ rc = SQLITE_NOMEM; } #endif if( SQLITE_OK==rc ){ - rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0); + rc = tdsqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0); } if( SQLITE_OK==rc ){ - rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0); + rc = tdsqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0); } #ifdef SQLITE_TEST if( SQLITE_OK==rc ){ - rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0); + rc = tdsqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0); } if( SQLITE_OK==rc ){ - rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0); + rc = tdsqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0); } #endif #ifdef SQLITE_TEST - sqlite3_free(zTest); - sqlite3_free(zTest2); + tdsqlite3_free(zTest); + tdsqlite3_free(zTest2); #endif return rc; @@ -155634,12 +178068,12 @@ SQLITE_PRIVATE int sqlite3Fts3InitHashTable( /* #include "fts3_tokenizer.h" */ typedef struct simple_tokenizer { - sqlite3_tokenizer base; + tdsqlite3_tokenizer base; char delim[128]; /* flag ASCII delimiters */ } simple_tokenizer; typedef struct simple_tokenizer_cursor { - sqlite3_tokenizer_cursor base; + tdsqlite3_tokenizer_cursor base; const char *pInput; /* input we are tokenizing */ int nBytes; /* size of the input */ int iOffset; /* current position in pInput */ @@ -155661,11 +178095,11 @@ static int fts3_isalnum(int x){ */ static int simpleCreate( int argc, const char * const *argv, - sqlite3_tokenizer **ppTokenizer + tdsqlite3_tokenizer **ppTokenizer ){ simple_tokenizer *t; - t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t)); + t = (simple_tokenizer *) tdsqlite3_malloc(sizeof(*t)); if( t==NULL ) return SQLITE_NOMEM; memset(t, 0, sizeof(*t)); @@ -155680,7 +178114,7 @@ static int simpleCreate( unsigned char ch = argv[1][i]; /* We explicitly don't support UTF-8 delimiters for now. */ if( ch>=0x80 ){ - sqlite3_free(t); + tdsqlite3_free(t); return SQLITE_ERROR; } t->delim[ch] = 1; @@ -155700,8 +178134,8 @@ static int simpleCreate( /* ** Destroy a tokenizer */ -static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ - sqlite3_free(pTokenizer); +static int simpleDestroy(tdsqlite3_tokenizer *pTokenizer){ + tdsqlite3_free(pTokenizer); return SQLITE_OK; } @@ -155712,15 +178146,15 @@ static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ ** *ppCursor. */ static int simpleOpen( - sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + tdsqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *pInput, int nBytes, /* String to be tokenized */ - sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ + tdsqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ ){ simple_tokenizer_cursor *c; UNUSED_PARAMETER(pTokenizer); - c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); + c = (simple_tokenizer_cursor *) tdsqlite3_malloc(sizeof(*c)); if( c==NULL ) return SQLITE_NOMEM; c->pInput = pInput; @@ -155744,10 +178178,10 @@ static int simpleOpen( ** Close a tokenization cursor previously opened by a call to ** simpleOpen() above. */ -static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ +static int simpleClose(tdsqlite3_tokenizer_cursor *pCursor){ simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; - sqlite3_free(c->pToken); - sqlite3_free(c); + tdsqlite3_free(c->pToken); + tdsqlite3_free(c); return SQLITE_OK; } @@ -155756,7 +178190,7 @@ static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ ** have been opened by a prior call to simpleOpen(). */ static int simpleNext( - sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + tdsqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ const char **ppToken, /* OUT: *ppToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ @@ -155786,7 +178220,7 @@ static int simpleNext( if( n>c->nTokenAllocated ){ char *pNew; c->nTokenAllocated = n+20; - pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated); + pNew = tdsqlite3_realloc(c->pToken, c->nTokenAllocated); if( !pNew ) return SQLITE_NOMEM; c->pToken = pNew; } @@ -155812,7 +178246,7 @@ static int simpleNext( /* ** The set of routines that implement the simple tokenizer */ -static const sqlite3_tokenizer_module simpleTokenizerModule = { +static const tdsqlite3_tokenizer_module simpleTokenizerModule = { 0, simpleCreate, simpleDestroy, @@ -155826,8 +178260,8 @@ static const sqlite3_tokenizer_module simpleTokenizerModule = { ** Allocate a new simple tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ -SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule( - sqlite3_tokenizer_module const**ppModule +SQLITE_PRIVATE void tdsqlite3Fts3SimpleTokenizerModule( + tdsqlite3_tokenizer_module const**ppModule ){ *ppModule = &simpleTokenizerModule; } @@ -155889,18 +178323,18 @@ typedef struct Fts3tokCursor Fts3tokCursor; ** Virtual table structure. */ struct Fts3tokTable { - sqlite3_vtab base; /* Base class used by SQLite core */ - const sqlite3_tokenizer_module *pMod; - sqlite3_tokenizer *pTok; + tdsqlite3_vtab base; /* Base class used by SQLite core */ + const tdsqlite3_tokenizer_module *pMod; + tdsqlite3_tokenizer *pTok; }; /* ** Virtual table cursor structure. */ struct Fts3tokCursor { - sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + tdsqlite3_vtab_cursor base; /* Base class used by SQLite core */ char *zInput; /* Input string */ - sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */ + tdsqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */ int iRowid; /* Current 'rowid' value */ const char *zToken; /* Current 'token' value */ int nToken; /* Size of zToken in bytes */ @@ -155915,15 +178349,15 @@ struct Fts3tokCursor { static int fts3tokQueryTokenizer( Fts3Hash *pHash, const char *zName, - const sqlite3_tokenizer_module **pp, + const tdsqlite3_tokenizer_module **pp, char **pzErr ){ - sqlite3_tokenizer_module *p; + tdsqlite3_tokenizer_module *p; int nName = (int)strlen(zName); - p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); + p = (tdsqlite3_tokenizer_module *)tdsqlite3Fts3HashFind(pHash, zName, nName+1); if( !p ){ - sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName); + tdsqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName); return SQLITE_ERROR; } @@ -155939,7 +178373,7 @@ static int fts3tokQueryTokenizer( ** ** If successful, output parameter *pazDequote is set to point at the ** array of dequoted strings and SQLITE_OK is returned. The caller is -** responsible for eventually calling sqlite3_free() to free the array +** responsible for eventually calling tdsqlite3_free() to free the array ** in this case. Or, if an error occurs, an SQLite error code is returned. ** The final value of *pazDequote is undefined in this case. */ @@ -155960,7 +178394,7 @@ static int fts3tokDequoteArray( nByte += (int)(strlen(argv[i]) + 1); } - *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte); + *pazDequote = azDequote = tdsqlite3_malloc64(sizeof(char *)*argc + nByte); if( azDequote==0 ){ rc = SQLITE_NOMEM; }else{ @@ -155969,7 +178403,7 @@ static int fts3tokDequoteArray( int n = (int)strlen(argv[i]); azDequote[i] = pSpace; memcpy(pSpace, argv[i], n+1); - sqlite3Fts3Dequote(pSpace); + tdsqlite3Fts3Dequote(pSpace); pSpace += (n+1); } } @@ -155994,21 +178428,21 @@ static int fts3tokDequoteArray( ** argv[3]: first argument (tokenizer name) */ static int fts3tokConnectMethod( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ void *pHash, /* Hash table of tokenizers */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ + tdsqlite3_vtab **ppVtab, /* OUT: New tdsqlite3_vtab object */ + char **pzErr /* OUT: tdsqlite3_malloc'd error message */ ){ Fts3tokTable *pTab = 0; - const sqlite3_tokenizer_module *pMod = 0; - sqlite3_tokenizer *pTok = 0; + const tdsqlite3_tokenizer_module *pMod = 0; + tdsqlite3_tokenizer *pTok = 0; int rc; char **azDequote = 0; int nDequote; - rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA); + rc = tdsqlite3_declare_vtab(db, FTS3_TOK_SCHEMA); if( rc!=SQLITE_OK ) return rc; nDequote = argc-3; @@ -156031,7 +178465,7 @@ static int fts3tokConnectMethod( } if( rc==SQLITE_OK ){ - pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable)); + pTab = (Fts3tokTable *)tdsqlite3_malloc(sizeof(Fts3tokTable)); if( pTab==0 ){ rc = SQLITE_NOMEM; } @@ -156048,7 +178482,7 @@ static int fts3tokConnectMethod( } } - sqlite3_free(azDequote); + tdsqlite3_free(azDequote); return rc; } @@ -156057,11 +178491,11 @@ static int fts3tokConnectMethod( ** These tables have no persistent representation of their own, so xDisconnect ** and xDestroy are identical operations. */ -static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){ +static int fts3tokDisconnectMethod(tdsqlite3_vtab *pVtab){ Fts3tokTable *pTab = (Fts3tokTable *)pVtab; pTab->pMod->xDestroy(pTab->pTok); - sqlite3_free(pTab); + tdsqlite3_free(pTab); return SQLITE_OK; } @@ -156069,8 +178503,8 @@ static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){ ** xBestIndex - Analyze a WHERE and ORDER BY clause. */ static int fts3tokBestIndexMethod( - sqlite3_vtab *pVTab, - sqlite3_index_info *pInfo + tdsqlite3_vtab *pVTab, + tdsqlite3_index_info *pInfo ){ int i; UNUSED_PARAMETER(pVTab); @@ -156097,17 +178531,17 @@ static int fts3tokBestIndexMethod( /* ** xOpen - Open a cursor. */ -static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ +static int fts3tokOpenMethod(tdsqlite3_vtab *pVTab, tdsqlite3_vtab_cursor **ppCsr){ Fts3tokCursor *pCsr; UNUSED_PARAMETER(pVTab); - pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor)); + pCsr = (Fts3tokCursor *)tdsqlite3_malloc(sizeof(Fts3tokCursor)); if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(Fts3tokCursor)); - *ppCsr = (sqlite3_vtab_cursor *)pCsr; + *ppCsr = (tdsqlite3_vtab_cursor *)pCsr; return SQLITE_OK; } @@ -156121,7 +178555,7 @@ static void fts3tokResetCursor(Fts3tokCursor *pCsr){ pTab->pMod->xClose(pCsr->pCsr); pCsr->pCsr = 0; } - sqlite3_free(pCsr->zInput); + tdsqlite3_free(pCsr->zInput); pCsr->zInput = 0; pCsr->zToken = 0; pCsr->nToken = 0; @@ -156134,18 +178568,18 @@ static void fts3tokResetCursor(Fts3tokCursor *pCsr){ /* ** xClose - Close a cursor. */ -static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){ +static int fts3tokCloseMethod(tdsqlite3_vtab_cursor *pCursor){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; fts3tokResetCursor(pCsr); - sqlite3_free(pCsr); + tdsqlite3_free(pCsr); return SQLITE_OK; } /* ** xNext - Advance the cursor to the next row, if any. */ -static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){ +static int fts3tokNextMethod(tdsqlite3_vtab_cursor *pCursor){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); int rc; /* Return code */ @@ -156168,11 +178602,11 @@ static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){ ** xFilter - Initialize a cursor to point at the start of its data. */ static int fts3tokFilterMethod( - sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + tdsqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ - sqlite3_value **apVal /* Arguments for the indexing scheme */ + tdsqlite3_value **apVal /* Arguments for the indexing scheme */ ){ int rc = SQLITE_ERROR; Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; @@ -156182,9 +178616,9 @@ static int fts3tokFilterMethod( fts3tokResetCursor(pCsr); if( idxNum==1 ){ - const char *zByte = (const char *)sqlite3_value_text(apVal[0]); - int nByte = sqlite3_value_bytes(apVal[0]); - pCsr->zInput = sqlite3_malloc(nByte+1); + const char *zByte = (const char *)tdsqlite3_value_text(apVal[0]); + int nByte = tdsqlite3_value_bytes(apVal[0]); + pCsr->zInput = tdsqlite3_malloc64(nByte+1); if( pCsr->zInput==0 ){ rc = SQLITE_NOMEM; }else{ @@ -156204,7 +178638,7 @@ static int fts3tokFilterMethod( /* ** xEof - Return true if the cursor is at EOF, or false otherwise. */ -static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){ +static int fts3tokEofMethod(tdsqlite3_vtab_cursor *pCursor){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; return (pCsr->zToken==0); } @@ -156213,8 +178647,8 @@ static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){ ** xColumn - Return a column value. */ static int fts3tokColumnMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + tdsqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + tdsqlite3_context *pCtx, /* Context for tdsqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; @@ -156222,20 +178656,20 @@ static int fts3tokColumnMethod( /* CREATE TABLE x(input, token, start, end, position) */ switch( iCol ){ case 0: - sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT); + tdsqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT); break; case 1: - sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT); + tdsqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT); break; case 2: - sqlite3_result_int(pCtx, pCsr->iStart); + tdsqlite3_result_int(pCtx, pCsr->iStart); break; case 3: - sqlite3_result_int(pCtx, pCsr->iEnd); + tdsqlite3_result_int(pCtx, pCsr->iEnd); break; default: assert( iCol==4 ); - sqlite3_result_int(pCtx, pCsr->iPos); + tdsqlite3_result_int(pCtx, pCsr->iPos); break; } return SQLITE_OK; @@ -156245,20 +178679,20 @@ static int fts3tokColumnMethod( ** xRowid - Return the current rowid for the cursor. */ static int fts3tokRowidMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + tdsqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ sqlite_int64 *pRowid /* OUT: Rowid value */ ){ Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; - *pRowid = (sqlite3_int64)pCsr->iRowid; + *pRowid = (tdsqlite3_int64)pCsr->iRowid; return SQLITE_OK; } /* ** Register the fts3tok module with database connection db. Return SQLITE_OK -** if successful or an error code if sqlite3_create_module() fails. +** if successful or an error code if tdsqlite3_create_module() fails. */ -SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){ - static const sqlite3_module fts3tok_module = { +SQLITE_PRIVATE int tdsqlite3Fts3InitTok(tdsqlite3 *db, Fts3Hash *pHash){ + static const tdsqlite3_module fts3tok_module = { 0, /* iVersion */ fts3tokConnectMethod, /* xCreate */ fts3tokConnectMethod, /* xConnect */ @@ -156281,11 +178715,12 @@ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){ 0, /* xRename */ 0, /* xSavepoint */ 0, /* xRelease */ - 0 /* xRollbackTo */ + 0, /* xRollbackTo */ + 0 /* xShadowName */ }; int rc; /* Return code */ - rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash); + rc = tdsqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash); return rc; } @@ -156318,7 +178753,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){ /* #include <string.h> */ /* #include <assert.h> */ /* #include <stdlib.h> */ - +/* #include <stdio.h> */ #define FTS_MAX_APPENDABLE_HEIGHT 16 @@ -156362,7 +178797,7 @@ int test_fts3_node_chunk_threshold = (4*1024)*4; #endif /* -** The two values that may be meaningfully bound to the :1 parameter in +** The values that may be meaningfully bound to the :1 parameter in ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT. */ #define FTS_STAT_DOCTOTAL 0 @@ -156370,14 +178805,14 @@ int test_fts3_node_chunk_threshold = (4*1024)*4; #define FTS_STAT_AUTOINCRMERGE 2 /* -** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic +** If FTS_LOG_MERGES is defined, call tdsqlite3_log() to report each automatic ** and incremental merge operation that takes place. This is used for ** debugging FTS only, it should not usually be turned on in production ** systems. */ #ifdef FTS3_LOG_MERGES -static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){ - sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel); +static void fts3LogMerge(int nMerge, tdsqlite3_int64 iAbsLevel){ + tdsqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel); } #else #define fts3LogMerge(x, y) @@ -156396,9 +178831,9 @@ struct PendingList { int nData; char *aData; int nSpace; - sqlite3_int64 iLastDocid; - sqlite3_int64 iLastCol; - sqlite3_int64 iLastPos; + tdsqlite3_int64 iLastDocid; + tdsqlite3_int64 iLastCol; + tdsqlite3_int64 iLastPos; }; @@ -156419,9 +178854,9 @@ struct Fts3DeferredToken { ** of type Fts3SegReader* are also used by code in fts3.c to iterate through ** terms when querying the full-text index. See functions: ** -** sqlite3Fts3SegReaderNew() -** sqlite3Fts3SegReaderFree() -** sqlite3Fts3SegReaderIterate() +** tdsqlite3Fts3SegReaderNew() +** tdsqlite3Fts3SegReaderFree() +** tdsqlite3Fts3SegReaderIterate() ** ** Methods used to manipulate Fts3SegReader structures: ** @@ -156434,15 +178869,15 @@ struct Fts3SegReader { u8 bLookup; /* True for a lookup only */ u8 rootOnly; /* True for a root-only reader */ - sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */ - sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */ - sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */ - sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */ + tdsqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */ + tdsqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */ + tdsqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */ + tdsqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */ char *aNode; /* Pointer to node data (or NULL) */ int nNode; /* Size of buffer at aNode (or 0) */ int nPopulate; /* If >0, bytes of buffer aNode[] loaded */ - sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */ + tdsqlite3_blob *pBlob; /* If not NULL, blob handle to read node */ Fts3HashElem **ppNextElem; @@ -156462,7 +178897,7 @@ struct Fts3SegReader { */ char *pOffsetList; int nOffsetList; /* For descending pending seg-readers only */ - sqlite3_int64 iDocid; + tdsqlite3_int64 iDocid; }; #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0) @@ -156479,8 +178914,8 @@ struct Fts3SegReader { */ struct SegmentWriter { SegmentNode *pTree; /* Pointer to interior tree structure */ - sqlite3_int64 iFirst; /* First slot in %_segments written */ - sqlite3_int64 iFree; /* Next free slot in %_segments */ + tdsqlite3_int64 iFirst; /* First slot in %_segments written */ + tdsqlite3_int64 iFree; /* Next free slot in %_segments */ char *zTerm; /* Pointer to previous term buffer */ int nTerm; /* Number of bytes in zTerm */ int nMalloc; /* Size of malloc'd buffer at zMalloc */ @@ -156582,8 +179017,8 @@ struct SegmentNode { static int fts3SqlStmt( Fts3Table *p, /* Virtual table handle */ int eStmt, /* One of the SQL_XXX constants above */ - sqlite3_stmt **pp, /* OUT: Statement handle */ - sqlite3_value **apVal /* Values to bind to statement */ + tdsqlite3_stmt **pp, /* OUT: Statement handle */ + tdsqlite3_value **apVal /* Values to bind to statement */ ){ const char *azSql[] = { /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?", @@ -156630,11 +179065,11 @@ static int fts3SqlStmt( ** returns zero rows. */ /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' " " GROUP BY level HAVING cnt>=?" - " ORDER BY (level %% 1024) ASC LIMIT 1", + " ORDER BY (level %% 1024) ASC, 2 DESC LIMIT 1", /* Estimate the upper limit on the number of leaf nodes in a new segment ** created by merging the oldest :2 segments from absolute level :1. See -** function sqlite3Fts3Incrmerge() for details. */ +** function tdsqlite3Fts3Incrmerge() for details. */ /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) " " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?", @@ -156684,35 +179119,37 @@ static int fts3SqlStmt( }; int rc = SQLITE_OK; - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; assert( SizeofArray(azSql)==SizeofArray(p->aStmt) ); assert( eStmt<SizeofArray(azSql) && eStmt>=0 ); pStmt = p->aStmt[eStmt]; if( !pStmt ){ + int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB; char *zSql; if( eStmt==SQL_CONTENT_INSERT ){ - zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist); + zSql = tdsqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist); }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){ - zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist); + f &= ~SQLITE_PREPARE_NO_VTAB; + zSql = tdsqlite3_mprintf(azSql[eStmt], p->zReadExprlist); }else{ - zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName); + zSql = tdsqlite3_mprintf(azSql[eStmt], p->zDb, p->zName); } if( !zSql ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL); - sqlite3_free(zSql); + rc = tdsqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL); + tdsqlite3_free(zSql); assert( rc==SQLITE_OK || pStmt==0 ); p->aStmt[eStmt] = pStmt; } } if( apVal ){ int i; - int nParam = sqlite3_bind_parameter_count(pStmt); + int nParam = tdsqlite3_bind_parameter_count(pStmt); for(i=0; rc==SQLITE_OK && i<nParam; i++){ - rc = sqlite3_bind_value(pStmt, i+1, apVal[i]); + rc = tdsqlite3_bind_value(pStmt, i+1, apVal[i]); } } *pp = pStmt; @@ -156722,18 +179159,18 @@ static int fts3SqlStmt( static int fts3SelectDocsize( Fts3Table *pTab, /* FTS3 table handle */ - sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */ - sqlite3_stmt **ppStmt /* OUT: Statement handle */ + tdsqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */ + tdsqlite3_stmt **ppStmt /* OUT: Statement handle */ ){ - sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */ + tdsqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */ int rc; /* Return code */ rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pStmt, 1, iDocid); - rc = sqlite3_step(pStmt); - if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){ - rc = sqlite3_reset(pStmt); + tdsqlite3_bind_int64(pStmt, 1, iDocid); + rc = tdsqlite3_step(pStmt); + if( rc!=SQLITE_ROW || tdsqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){ + rc = tdsqlite3_reset(pStmt); if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB; pStmt = 0; }else{ @@ -156745,19 +179182,19 @@ static int fts3SelectDocsize( return rc; } -SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal( +SQLITE_PRIVATE int tdsqlite3Fts3SelectDoctotal( Fts3Table *pTab, /* Fts3 table handle */ - sqlite3_stmt **ppStmt /* OUT: Statement handle */ + tdsqlite3_stmt **ppStmt /* OUT: Statement handle */ ){ - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; int rc; rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); - if( sqlite3_step(pStmt)!=SQLITE_ROW - || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB + tdsqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); + if( tdsqlite3_step(pStmt)!=SQLITE_ROW + || tdsqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){ - rc = sqlite3_reset(pStmt); + rc = tdsqlite3_reset(pStmt); if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB; pStmt = 0; } @@ -156766,10 +179203,10 @@ SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal( return rc; } -SQLITE_PRIVATE int sqlite3Fts3SelectDocsize( +SQLITE_PRIVATE int tdsqlite3Fts3SelectDocsize( Fts3Table *pTab, /* Fts3 table handle */ - sqlite3_int64 iDocid, /* Docid to read size data for */ - sqlite3_stmt **ppStmt /* OUT: Statement handle */ + tdsqlite3_int64 iDocid, /* Docid to read size data for */ + tdsqlite3_stmt **ppStmt /* OUT: Statement handle */ ){ return fts3SelectDocsize(pTab, iDocid, ppStmt); } @@ -156786,15 +179223,15 @@ static void fts3SqlExec( int *pRC, /* Result code */ Fts3Table *p, /* The FTS3 table */ int eStmt, /* Index of statement to evaluate */ - sqlite3_value **apVal /* Parameters to bind */ + tdsqlite3_value **apVal /* Parameters to bind */ ){ - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; int rc; if( *pRC ) return; rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); if( rc==SQLITE_OK ){ - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); + tdsqlite3_step(pStmt); + rc = tdsqlite3_reset(pStmt); } *pRC = rc; } @@ -156818,12 +179255,12 @@ static int fts3Writelock(Fts3Table *p){ int rc = SQLITE_OK; if( p->nPendingData==0 ){ - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_null(pStmt, 1); - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); + tdsqlite3_bind_null(pStmt, 1); + tdsqlite3_step(pStmt); + rc = tdsqlite3_reset(pStmt); } } @@ -156853,18 +179290,18 @@ static int fts3Writelock(Fts3Table *p){ ** absolute levels that corresponds to language-id iLangid and index ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024). */ -static sqlite3_int64 getAbsoluteLevel( +static tdsqlite3_int64 getAbsoluteLevel( Fts3Table *p, /* FTS3 table handle */ int iLangid, /* Language id */ int iIndex, /* Index in p->aIndex[] */ int iLevel /* Level of segments */ ){ - sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */ - assert( iLangid>=0 ); + tdsqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */ + assert_fts3_nc( iLangid>=0 ); assert( p->nIndex>0 ); assert( iIndex>=0 && iIndex<p->nIndex ); - iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL; + iBase = ((tdsqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL; return iBase + iLevel; } @@ -156885,15 +179322,15 @@ static sqlite3_int64 getAbsoluteLevel( ** 3: end_block ** 4: root */ -SQLITE_PRIVATE int sqlite3Fts3AllSegdirs( +SQLITE_PRIVATE int tdsqlite3Fts3AllSegdirs( Fts3Table *p, /* FTS3 table */ int iLangid, /* Language being queried */ int iIndex, /* Index for p->aIndex[] */ int iLevel, /* Level to select (relative level) */ - sqlite3_stmt **ppStmt /* OUT: Compiled statement */ + tdsqlite3_stmt **ppStmt /* OUT: Compiled statement */ ){ int rc; - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 ); assert( iLevel<FTS3_SEGDIR_MAXLEVEL ); @@ -156903,8 +179340,8 @@ SQLITE_PRIVATE int sqlite3Fts3AllSegdirs( /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); - sqlite3_bind_int64(pStmt, 2, + tdsqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); + tdsqlite3_bind_int64(pStmt, 2, getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) ); } @@ -156912,7 +179349,7 @@ SQLITE_PRIVATE int sqlite3Fts3AllSegdirs( /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */ rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel)); + tdsqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel)); } } *ppStmt = pStmt; @@ -156934,13 +179371,13 @@ SQLITE_PRIVATE int sqlite3Fts3AllSegdirs( */ static int fts3PendingListAppendVarint( PendingList **pp, /* IN/OUT: Pointer to PendingList struct */ - sqlite3_int64 i /* Value to append to data */ + tdsqlite3_int64 i /* Value to append to data */ ){ PendingList *p = *pp; /* Allocate or grow the PendingList as required. */ if( !p ){ - p = sqlite3_malloc(sizeof(*p) + 100); + p = tdsqlite3_malloc(sizeof(*p) + 100); if( !p ){ return SQLITE_NOMEM; } @@ -156950,9 +179387,9 @@ static int fts3PendingListAppendVarint( } else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){ int nNew = p->nSpace * 2; - p = sqlite3_realloc(p, sizeof(*p) + nNew); + p = tdsqlite3_realloc(p, sizeof(*p) + nNew); if( !p ){ - sqlite3_free(*pp); + tdsqlite3_free(*pp); *pp = 0; return SQLITE_NOMEM; } @@ -156961,7 +179398,7 @@ static int fts3PendingListAppendVarint( } /* Append the new serialized varint to the end of the list. */ - p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i); + p->nData += tdsqlite3Fts3PutVarint(&p->aData[p->nData], i); p->aData[p->nData] = '\0'; *pp = p; return SQLITE_OK; @@ -156969,7 +179406,7 @@ static int fts3PendingListAppendVarint( /* ** Add a docid/column/position entry to a PendingList structure. Non-zero -** is returned if the structure is sqlite3_realloced as part of adding +** is returned if the structure is tdsqlite3_realloced as part of adding ** the entry. Otherwise, zero. ** ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning. @@ -156978,9 +179415,9 @@ static int fts3PendingListAppendVarint( */ static int fts3PendingListAppend( PendingList **pp, /* IN/OUT: PendingList structure */ - sqlite3_int64 iDocid, /* Docid for entry to add */ - sqlite3_int64 iCol, /* Column for entry to add */ - sqlite3_int64 iPos, /* Position of term for entry to add */ + tdsqlite3_int64 iDocid, /* Docid for entry to add */ + tdsqlite3_int64 iCol, /* Column for entry to add */ + tdsqlite3_int64 iPos, /* Position of term for entry to add */ int *pRc /* OUT: Return code */ ){ PendingList *p = *pp; @@ -156989,7 +179426,7 @@ static int fts3PendingListAppend( assert( !p || p->iLastDocid<=iDocid ); if( !p || p->iLastDocid!=iDocid ){ - sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0); + u64 iDelta = (u64)iDocid - (u64)(p ? p->iLastDocid : 0); if( p ){ assert( p->nData<p->nSpace ); assert( p->aData[p->nData]==0 ); @@ -157032,7 +179469,7 @@ static int fts3PendingListAppend( ** Free a PendingList object allocated by fts3PendingListAppend(). */ static void fts3PendingListDelete(PendingList *pList){ - sqlite3_free(pList); + tdsqlite3_free(pList); } /* @@ -157059,7 +179496,7 @@ static int fts3PendingTermsAddOne( ** happen if there was no previous entry for this token. */ assert( 0==fts3HashFind(pHash, zToken, nToken) ); - sqlite3_free(pList); + tdsqlite3_free(pList); rc = SQLITE_NOMEM; } } @@ -157092,10 +179529,10 @@ static int fts3PendingTermsAdd( char const *zToken; int nToken = 0; - sqlite3_tokenizer *pTokenizer = p->pTokenizer; - sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; - sqlite3_tokenizer_cursor *pCsr; - int (*xNext)(sqlite3_tokenizer_cursor *pCursor, + tdsqlite3_tokenizer *pTokenizer = p->pTokenizer; + tdsqlite3_tokenizer_module const *pModule = pTokenizer->pModule; + tdsqlite3_tokenizer_cursor *pCsr; + int (*xNext)(tdsqlite3_tokenizer_cursor *pCursor, const char**,int*,int*,int*,int*); assert( pTokenizer && pModule ); @@ -157108,7 +179545,7 @@ static int fts3PendingTermsAdd( return SQLITE_OK; } - rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr); + rc = tdsqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr); if( rc!=SQLITE_OK ){ return rc; } @@ -157174,7 +179611,7 @@ static int fts3PendingTermsDocid( || p->iPrevLangid!=iLangid || p->nPendingData>p->nMaxPendingData ){ - int rc = sqlite3Fts3PendingTermsFlush(p); + int rc = tdsqlite3Fts3PendingTermsFlush(p); if( rc!=SQLITE_OK ) return rc; } p->iPrevDocid = iDocid; @@ -157186,7 +179623,7 @@ static int fts3PendingTermsDocid( /* ** Discard the contents of the pending-terms hash tables. */ -SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){ +SQLITE_PRIVATE void tdsqlite3Fts3PendingTermsClear(Fts3Table *p){ int i; for(i=0; i<p->nIndex; i++){ Fts3HashElem *pElem; @@ -157211,19 +179648,19 @@ SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){ static int fts3InsertTerms( Fts3Table *p, int iLangid, - sqlite3_value **apVal, + tdsqlite3_value **apVal, u32 *aSz ){ int i; /* Iterator variable */ for(i=2; i<p->nColumn+2; i++){ int iCol = i-2; if( p->abNotindexed[iCol]==0 ){ - const char *zText = (const char *)sqlite3_value_text(apVal[i]); + const char *zText = (const char *)tdsqlite3_value_text(apVal[i]); int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]); if( rc!=SQLITE_OK ){ return rc; } - aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]); + aSz[p->nColumn] += tdsqlite3_value_bytes(apVal[i]); } } return SQLITE_OK; @@ -157245,21 +179682,21 @@ static int fts3InsertTerms( */ static int fts3InsertData( Fts3Table *p, /* Full-text table */ - sqlite3_value **apVal, /* Array of values to insert */ - sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */ + tdsqlite3_value **apVal, /* Array of values to insert */ + tdsqlite3_int64 *piDocid /* OUT: Docid for row just inserted */ ){ int rc; /* Return code */ - sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */ + tdsqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */ if( p->zContentTbl ){ - sqlite3_value *pRowid = apVal[p->nColumn+3]; - if( sqlite3_value_type(pRowid)==SQLITE_NULL ){ + tdsqlite3_value *pRowid = apVal[p->nColumn+3]; + if( tdsqlite3_value_type(pRowid)==SQLITE_NULL ){ pRowid = apVal[1]; } - if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){ + if( tdsqlite3_value_type(pRowid)!=SQLITE_INTEGER ){ return SQLITE_CONSTRAINT; } - *piDocid = sqlite3_value_int64(pRowid); + *piDocid = tdsqlite3_value_int64(pRowid); return SQLITE_OK; } @@ -157273,9 +179710,9 @@ static int fts3InsertData( */ rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]); if( rc==SQLITE_OK && p->zLanguageid ){ - rc = sqlite3_bind_int( + rc = tdsqlite3_bind_int( pContentInsert, p->nColumn+2, - sqlite3_value_int(apVal[p->nColumn+4]) + tdsqlite3_value_int(apVal[p->nColumn+4]) ); } if( rc!=SQLITE_OK ) return rc; @@ -157290,24 +179727,24 @@ static int fts3InsertData( ** In FTS3, this is an error. It is an error to specify non-NULL values ** for both docid and some other rowid alias. */ - if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){ - if( SQLITE_NULL==sqlite3_value_type(apVal[0]) - && SQLITE_NULL!=sqlite3_value_type(apVal[1]) + if( SQLITE_NULL!=tdsqlite3_value_type(apVal[3+p->nColumn]) ){ + if( SQLITE_NULL==tdsqlite3_value_type(apVal[0]) + && SQLITE_NULL!=tdsqlite3_value_type(apVal[1]) ){ /* A rowid/docid conflict. */ return SQLITE_ERROR; } - rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]); + rc = tdsqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]); if( rc!=SQLITE_OK ) return rc; } /* Execute the statement to insert the record. Set *piDocid to the ** new docid value. */ - sqlite3_step(pContentInsert); - rc = sqlite3_reset(pContentInsert); + tdsqlite3_step(pContentInsert); + rc = tdsqlite3_reset(pContentInsert); - *piDocid = sqlite3_last_insert_rowid(p->db); + *piDocid = tdsqlite3_last_insert_rowid(p->db); return rc; } @@ -157321,7 +179758,7 @@ static int fts3DeleteAll(Fts3Table *p, int bContent){ int rc = SQLITE_OK; /* Return code */ /* Discard the contents of the pending-terms hash table. */ - sqlite3Fts3PendingTermsClear(p); + tdsqlite3Fts3PendingTermsClear(p); /* Delete everything from the shadow tables. Except, leave %_content as ** is if bContent is false. */ @@ -157341,9 +179778,9 @@ static int fts3DeleteAll(Fts3Table *p, int bContent){ /* ** */ -static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){ +static int langidFromSelect(Fts3Table *p, tdsqlite3_stmt *pSelect){ int iLangid = 0; - if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1); + if( p->zLanguageid ) iLangid = tdsqlite3_column_int(pSelect, p->nColumn+1); return iLangid; } @@ -157355,40 +179792,40 @@ static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){ static void fts3DeleteTerms( int *pRC, /* Result code */ Fts3Table *p, /* The FTS table to delete from */ - sqlite3_value *pRowid, /* The docid to be deleted */ + tdsqlite3_value *pRowid, /* The docid to be deleted */ u32 *aSz, /* Sizes of deleted document written here */ int *pbFound /* OUT: Set to true if row really does exist */ ){ int rc; - sqlite3_stmt *pSelect; + tdsqlite3_stmt *pSelect; assert( *pbFound==0 ); if( *pRC ) return; rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid); if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pSelect) ){ + if( SQLITE_ROW==tdsqlite3_step(pSelect) ){ int i; int iLangid = langidFromSelect(p, pSelect); - i64 iDocid = sqlite3_column_int64(pSelect, 0); + i64 iDocid = tdsqlite3_column_int64(pSelect, 0); rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid); for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){ int iCol = i-1; if( p->abNotindexed[iCol]==0 ){ - const char *zText = (const char *)sqlite3_column_text(pSelect, i); + const char *zText = (const char *)tdsqlite3_column_text(pSelect, i); rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]); - aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i); + aSz[p->nColumn] += tdsqlite3_column_bytes(pSelect, i); } } if( rc!=SQLITE_OK ){ - sqlite3_reset(pSelect); + tdsqlite3_reset(pSelect); *pRC = rc; return; } *pbFound = 1; } - rc = sqlite3_reset(pSelect); + rc = tdsqlite3_reset(pSelect); }else{ - sqlite3_reset(pSelect); + tdsqlite3_reset(pSelect); } *pRC = rc; } @@ -157422,7 +179859,7 @@ static int fts3AllocateSegdirIdx( int *piIdx ){ int rc; /* Return Code */ - sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */ + tdsqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */ int iNext = 0; /* Result of query pNextIdx */ assert( iLangid>=0 ); @@ -157431,13 +179868,13 @@ static int fts3AllocateSegdirIdx( /* Set variable iNext to the next available segdir index at level iLevel. */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64( + tdsqlite3_bind_int64( pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) ); - if( SQLITE_ROW==sqlite3_step(pNextIdx) ){ - iNext = sqlite3_column_int(pNextIdx, 0); + if( SQLITE_ROW==tdsqlite3_step(pNextIdx) ){ + iNext = tdsqlite3_column_int(pNextIdx, 0); } - rc = sqlite3_reset(pNextIdx); + rc = tdsqlite3_reset(pNextIdx); } if( rc==SQLITE_OK ){ @@ -157446,7 +179883,7 @@ static int fts3AllocateSegdirIdx( ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise, ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext. */ - if( iNext>=FTS3_MERGE_COUNT ){ + if( iNext>=MergeCount(p) ){ fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel)); rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel); *piIdx = 0; @@ -157465,7 +179902,7 @@ static int fts3AllocateSegdirIdx( ** ** This function reads data from a single row of the %_segments table. The ** specific row is identified by the iBlockid parameter. If paBlob is not -** NULL, then a buffer is allocated using sqlite3_malloc() and populated +** NULL, then a buffer is allocated using tdsqlite3_malloc() and populated ** with the contents of the blob stored in the "block" column of the ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set ** to the size of the blob in bytes before returning. @@ -157475,19 +179912,19 @@ static int fts3AllocateSegdirIdx( ** paBlob is non-NULL, then it is the responsibility of the caller to ** eventually free the returned buffer. ** -** This function may leave an open sqlite3_blob* handle in the +** This function may leave an open tdsqlite3_blob* handle in the ** Fts3Table.pSegments variable. This handle is reused by subsequent calls ** to this function. The handle may be closed by calling the -** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy +** tdsqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy ** performance improvement, but the blob handle should always be closed ** before control is returned to the user (to prevent a lock being held ** on the database file for longer than necessary). Thus, any virtual table ** method (xFilter etc.) that may directly or indirectly call this function -** must call sqlite3Fts3SegmentsClose() before returning. +** must call tdsqlite3Fts3SegmentsClose() before returning. */ -SQLITE_PRIVATE int sqlite3Fts3ReadBlock( +SQLITE_PRIVATE int tdsqlite3Fts3ReadBlock( Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */ + tdsqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */ char **paBlob, /* OUT: Blob data in malloc'd buffer */ int *pnBlob, /* OUT: Size of blob data */ int *pnLoad /* OUT: Bytes actually loaded */ @@ -157498,22 +179935,22 @@ SQLITE_PRIVATE int sqlite3Fts3ReadBlock( assert( pnBlob ); if( p->pSegments ){ - rc = sqlite3_blob_reopen(p->pSegments, iBlockid); + rc = tdsqlite3_blob_reopen(p->pSegments, iBlockid); }else{ if( 0==p->zSegmentsTbl ){ - p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName); + p->zSegmentsTbl = tdsqlite3_mprintf("%s_segments", p->zName); if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM; } - rc = sqlite3_blob_open( + rc = tdsqlite3_blob_open( p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments ); } if( rc==SQLITE_OK ){ - int nByte = sqlite3_blob_bytes(p->pSegments); + int nByte = tdsqlite3_blob_bytes(p->pSegments); *pnBlob = nByte; if( paBlob ){ - char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING); + char *aByte = tdsqlite3_malloc(nByte + FTS3_NODE_PADDING); if( !aByte ){ rc = SQLITE_NOMEM; }else{ @@ -157521,15 +179958,17 @@ SQLITE_PRIVATE int sqlite3Fts3ReadBlock( nByte = FTS3_NODE_CHUNKSIZE; *pnLoad = nByte; } - rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0); + rc = tdsqlite3_blob_read(p->pSegments, aByte, nByte, 0); memset(&aByte[nByte], 0, FTS3_NODE_PADDING); if( rc!=SQLITE_OK ){ - sqlite3_free(aByte); + tdsqlite3_free(aByte); aByte = 0; } } *paBlob = aByte; } + }else if( rc==SQLITE_ERROR ){ + rc = FTS_CORRUPT_VTAB; } return rc; @@ -157537,10 +179976,10 @@ SQLITE_PRIVATE int sqlite3Fts3ReadBlock( /* ** Close the blob handle at p->pSegments, if it is open. See comments above -** the sqlite3Fts3ReadBlock() function for details. +** the tdsqlite3Fts3ReadBlock() function for details. */ -SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){ - sqlite3_blob_close(p->pSegments); +SQLITE_PRIVATE void tdsqlite3Fts3SegmentsClose(Fts3Table *p){ + tdsqlite3_blob_close(p->pSegments); p->pSegments = 0; } @@ -157549,7 +179988,7 @@ static int fts3SegReaderIncrRead(Fts3SegReader *pReader){ int rc; /* Return code */ nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE); - rc = sqlite3_blob_read( + rc = tdsqlite3_blob_read( pReader->pBlob, &pReader->aNode[pReader->nPopulate], nRead, @@ -157560,7 +179999,7 @@ static int fts3SegReaderIncrRead(Fts3SegReader *pReader){ pReader->nPopulate += nRead; memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING); if( pReader->nPopulate==pReader->nNode ){ - sqlite3_blob_close(pReader->pBlob); + tdsqlite3_blob_close(pReader->pBlob); pReader->pBlob = 0; pReader->nPopulate = 0; } @@ -157586,8 +180025,8 @@ static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){ */ static void fts3SegReaderSetEof(Fts3SegReader *pSeg){ if( !fts3SegReaderIsRootOnly(pSeg) ){ - sqlite3_free(pSeg->aNode); - sqlite3_blob_close(pSeg->pBlob); + tdsqlite3_free(pSeg->aNode); + tdsqlite3_blob_close(pSeg->pBlob); pSeg->pBlob = 0; } pSeg->aNode = 0; @@ -157618,7 +180057,7 @@ static int fts3SegReaderNext( if( fts3SegReaderIsPending(pReader) ){ Fts3HashElem *pElem = *(pReader->ppNextElem); - sqlite3_free(pReader->aNode); + tdsqlite3_free(pReader->aNode); pReader->aNode = 0; if( pElem ){ char *aCopy; @@ -157626,7 +180065,7 @@ static int fts3SegReaderNext( int nCopy = pList->nData+1; pReader->zTerm = (char *)fts3HashKey(pElem); pReader->nTerm = fts3HashKeysize(pElem); - aCopy = (char*)sqlite3_malloc(nCopy); + aCopy = (char*)tdsqlite3_malloc(nCopy); if( !aCopy ) return SQLITE_NOMEM; memcpy(aCopy, pList->aData, nCopy); pReader->nNode = pReader->nDoclist = nCopy; @@ -157641,12 +180080,14 @@ static int fts3SegReaderNext( /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf ** blocks have already been traversed. */ - assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock ); +#ifdef CORRUPT_DB + assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB ); +#endif if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){ return SQLITE_OK; } - rc = sqlite3Fts3ReadBlock( + rc = tdsqlite3Fts3ReadBlock( p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, (bIncr ? &pReader->nPopulate : 0) ); @@ -157668,15 +180109,19 @@ static int fts3SegReaderNext( ** safe (no risk of overread) even if the node data is corrupted. */ pNext += fts3GetVarint32(pNext, &nPrefix); pNext += fts3GetVarint32(pNext, &nSuffix); - if( nPrefix<0 || nSuffix<=0 - || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] + if( nSuffix<=0 + || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix + || nPrefix>pReader->nTerm ){ return FTS_CORRUPT_VTAB; } - if( nPrefix+nSuffix>pReader->nTermAlloc ){ - int nNew = (nPrefix+nSuffix)*2; - char *zNew = sqlite3_realloc(pReader->zTerm, nNew); + /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are + ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer + ** overflow - hence the (i64) casts. */ + if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){ + i64 nNew = ((i64)nPrefix+nSuffix)*2; + char *zNew = tdsqlite3_realloc64(pReader->zTerm, nNew); if( !zNew ){ return SQLITE_NOMEM; } @@ -157698,7 +180143,7 @@ static int fts3SegReaderNext( ** b-tree node. And that the final byte of the doclist is 0x00. If either ** of these statements is untrue, then the data structure is corrupt. */ - if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] + if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode) || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1]) ){ return FTS_CORRUPT_VTAB; @@ -157718,14 +180163,14 @@ static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){ u8 bEof = 0; pReader->iDocid = 0; pReader->nOffsetList = 0; - sqlite3Fts3DoclistPrev(0, + tdsqlite3Fts3DoclistPrev(0, pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, &pReader->iDocid, &pReader->nOffsetList, &bEof ); }else{ rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX); if( rc==SQLITE_OK ){ - int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid); + int n = tdsqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid); pReader->pOffsetList = &pReader->aDoclist[n]; } } @@ -157763,7 +180208,7 @@ static int fts3SegReaderNextDocid( *ppOffsetList = pReader->pOffsetList; *pnOffsetList = pReader->nOffsetList - 1; } - sqlite3Fts3DoclistPrev(0, + tdsqlite3Fts3DoclistPrev(0, pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid, &pReader->nOffsetList, &bEof ); @@ -157816,22 +180261,22 @@ static int fts3SegReaderNextDocid( }else{ rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX); if( rc==SQLITE_OK ){ - sqlite3_int64 iDelta; - pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta); + u64 iDelta; + pReader->pOffsetList = p + tdsqlite3Fts3GetVarintU(p, &iDelta); if( pTab->bDescIdx ){ - pReader->iDocid -= iDelta; + pReader->iDocid = (i64)((u64)pReader->iDocid - iDelta); }else{ - pReader->iDocid += iDelta; + pReader->iDocid = (i64)((u64)pReader->iDocid + iDelta); } } } } - return SQLITE_OK; + return rc; } -SQLITE_PRIVATE int sqlite3Fts3MsrOvfl( +SQLITE_PRIVATE int tdsqlite3Fts3MsrOvfl( Fts3Cursor *pCsr, Fts3MultiSegReader *pMsr, int *pnOvfl @@ -157850,10 +180295,10 @@ SQLITE_PRIVATE int sqlite3Fts3MsrOvfl( if( !fts3SegReaderIsPending(pReader) && !fts3SegReaderIsRootOnly(pReader) ){ - sqlite3_int64 jj; + tdsqlite3_int64 jj; for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){ int nBlob; - rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0); + rc = tdsqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0); if( rc!=SQLITE_OK ) break; if( (nBlob+35)>pgsz ){ nOvfl += (nBlob + 34)/pgsz; @@ -157869,28 +180314,28 @@ SQLITE_PRIVATE int sqlite3Fts3MsrOvfl( ** Free all allocations associated with the iterator passed as the ** second argument. */ -SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){ +SQLITE_PRIVATE void tdsqlite3Fts3SegReaderFree(Fts3SegReader *pReader){ if( pReader ){ if( !fts3SegReaderIsPending(pReader) ){ - sqlite3_free(pReader->zTerm); + tdsqlite3_free(pReader->zTerm); } if( !fts3SegReaderIsRootOnly(pReader) ){ - sqlite3_free(pReader->aNode); + tdsqlite3_free(pReader->aNode); } - sqlite3_blob_close(pReader->pBlob); + tdsqlite3_blob_close(pReader->pBlob); } - sqlite3_free(pReader); + tdsqlite3_free(pReader); } /* ** Allocate a new SegReader object. */ -SQLITE_PRIVATE int sqlite3Fts3SegReaderNew( +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderNew( int iAge, /* Segment "age". */ int bLookup, /* True for a lookup only */ - sqlite3_int64 iStartLeaf, /* First leaf to traverse */ - sqlite3_int64 iEndLeaf, /* Final leaf to traverse */ - sqlite3_int64 iEndBlock, /* Final block of segment */ + tdsqlite3_int64 iStartLeaf, /* First leaf to traverse */ + tdsqlite3_int64 iEndLeaf, /* Final leaf to traverse */ + tdsqlite3_int64 iEndBlock, /* Final block of segment */ const char *zRoot, /* Buffer containing root node */ int nRoot, /* Size of buffer containing root node */ Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */ @@ -157898,12 +180343,17 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderNew( Fts3SegReader *pReader; /* Newly allocated SegReader object */ int nExtra = 0; /* Bytes to allocate segment root node */ - assert( iStartLeaf<=iEndLeaf ); + assert( zRoot!=0 || nRoot==0 ); +#ifdef CORRUPT_DB + assert( zRoot!=0 || CORRUPT_DB ); +#endif + if( iStartLeaf==0 ){ + if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB; nExtra = nRoot + FTS3_NODE_PADDING; } - pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra); + pReader = (Fts3SegReader *)tdsqlite3_malloc(sizeof(Fts3SegReader) + nExtra); if( !pReader ){ return SQLITE_NOMEM; } @@ -157919,7 +180369,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderNew( pReader->aNode = (char *)&pReader[1]; pReader->rootOnly = 1; pReader->nNode = nRoot; - memcpy(pReader->aNode, zRoot, nRoot); + if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot); memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING); }else{ pReader->iCurrentBlock = iStartLeaf-1; @@ -157969,7 +180419,7 @@ static int SQLITE_CDECL fts3CompareElemByTerm( ** ** firebird mysql sqlite */ -SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderPending( Fts3Table *p, /* Virtual table handle */ int iIndex, /* Index for p->aIndex */ const char *zTerm, /* Term to search for */ @@ -157995,7 +180445,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( if( nElem==nAlloc ){ Fts3HashElem **aElem2; nAlloc += 16; - aElem2 = (Fts3HashElem **)sqlite3_realloc( + aElem2 = (Fts3HashElem **)tdsqlite3_realloc( aElem, nAlloc*sizeof(Fts3HashElem *) ); if( !aElem2 ){ @@ -158034,8 +180484,9 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( } if( nElem>0 ){ - int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); - pReader = (Fts3SegReader *)sqlite3_malloc(nByte); + tdsqlite3_int64 nByte; + nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); + pReader = (Fts3SegReader *)tdsqlite3_malloc64(nByte); if( !pReader ){ rc = SQLITE_NOMEM; }else{ @@ -158047,7 +180498,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( } if( bPrefix ){ - sqlite3_free(aElem); + tdsqlite3_free(aElem); } *ppReader = pReader; return rc; @@ -158191,17 +180642,18 @@ static void fts3SegReaderSort( */ static int fts3WriteSegment( Fts3Table *p, /* Virtual table handle */ - sqlite3_int64 iBlock, /* Block id for new block */ + tdsqlite3_int64 iBlock, /* Block id for new block */ char *z, /* Pointer to buffer containing block data */ int n /* Size of buffer z in bytes */ ){ - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pStmt, 1, iBlock); - sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC); - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); + tdsqlite3_bind_int64(pStmt, 1, iBlock); + tdsqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC); + tdsqlite3_step(pStmt); + rc = tdsqlite3_reset(pStmt); + tdsqlite3_bind_null(pStmt, 2); } return rc; } @@ -158211,17 +180663,17 @@ static int fts3WriteSegment( ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs, ** set *pnMax to zero and return an SQLite error code. */ -SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){ +SQLITE_PRIVATE int tdsqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){ int rc; int mxLevel = 0; - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0); if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - mxLevel = sqlite3_column_int(pStmt, 0); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + mxLevel = tdsqlite3_column_int(pStmt, 0); } - rc = sqlite3_reset(pStmt); + rc = tdsqlite3_reset(pStmt); } *pnMax = mxLevel; return rc; @@ -158232,32 +180684,33 @@ SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){ */ static int fts3WriteSegdir( Fts3Table *p, /* Virtual table handle */ - sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */ + tdsqlite3_int64 iLevel, /* Value for "level" field (absolute level) */ int iIdx, /* Value for "idx" field */ - sqlite3_int64 iStartBlock, /* Value for "start_block" field */ - sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */ - sqlite3_int64 iEndBlock, /* Value for "end_block" field */ - sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */ + tdsqlite3_int64 iStartBlock, /* Value for "start_block" field */ + tdsqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */ + tdsqlite3_int64 iEndBlock, /* Value for "end_block" field */ + tdsqlite3_int64 nLeafData, /* Bytes of leaf data in segment */ char *zRoot, /* Blob value for "root" field */ int nRoot /* Number of bytes in buffer zRoot */ ){ - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pStmt, 1, iLevel); - sqlite3_bind_int(pStmt, 2, iIdx); - sqlite3_bind_int64(pStmt, 3, iStartBlock); - sqlite3_bind_int64(pStmt, 4, iLeafEndBlock); + tdsqlite3_bind_int64(pStmt, 1, iLevel); + tdsqlite3_bind_int(pStmt, 2, iIdx); + tdsqlite3_bind_int64(pStmt, 3, iStartBlock); + tdsqlite3_bind_int64(pStmt, 4, iLeafEndBlock); if( nLeafData==0 ){ - sqlite3_bind_int64(pStmt, 5, iEndBlock); + tdsqlite3_bind_int64(pStmt, 5, iEndBlock); }else{ - char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData); + char *zEnd = tdsqlite3_mprintf("%lld %lld", iEndBlock, nLeafData); if( !zEnd ) return SQLITE_NOMEM; - sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free); + tdsqlite3_bind_text(pStmt, 5, zEnd, -1, tdsqlite3_free); } - sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC); - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); + tdsqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC); + tdsqlite3_step(pStmt); + rc = tdsqlite3_reset(pStmt); + tdsqlite3_bind_null(pStmt, 6); } return rc; } @@ -158309,7 +180762,12 @@ static int fts3NodeAddTerm( nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm); nSuffix = nTerm-nPrefix; - nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix; + /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of + ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when + ** compared with BINARY collation. This indicates corruption. */ + if( nSuffix<=0 ) return FTS_CORRUPT_VTAB; + + nReq += tdsqlite3Fts3VarintLen(nPrefix)+tdsqlite3Fts3VarintLen(nSuffix)+nSuffix; if( nReq<=p->nNodeSize || !pTree->zTerm ){ if( nReq>p->nNodeSize ){ @@ -158321,7 +180779,7 @@ static int fts3NodeAddTerm( ** this is not expected to be a serious problem. */ assert( pTree->aData==(char *)&pTree[1] ); - pTree->aData = (char *)sqlite3_malloc(nReq); + pTree->aData = (char *)tdsqlite3_malloc(nReq); if( !pTree->aData ){ return SQLITE_NOMEM; } @@ -158329,17 +180787,17 @@ static int fts3NodeAddTerm( if( pTree->zTerm ){ /* There is no prefix-length field for first term in a node */ - nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix); + nData += tdsqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix); } - nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix); + nData += tdsqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix); memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix); pTree->nData = nData + nSuffix; pTree->nEntry++; if( isCopyTerm ){ if( pTree->nMalloc<nTerm ){ - char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2); + char *zNew = tdsqlite3_realloc(pTree->zMalloc, nTerm*2); if( !zNew ){ return SQLITE_NOMEM; } @@ -158365,7 +180823,7 @@ static int fts3NodeAddTerm( ** now. Instead, the term is inserted into the parent of pTree. If pTree ** has no parent, one is created here. */ - pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize); + pNew = (SegmentNode *)tdsqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize); if( !pNew ){ return SQLITE_NOMEM; } @@ -158400,13 +180858,13 @@ static int fts3NodeAddTerm( static int fts3TreeFinishNode( SegmentNode *pTree, int iHeight, - sqlite3_int64 iLeftChild + tdsqlite3_int64 iLeftChild ){ int nStart; assert( iHeight>=1 && iHeight<128 ); - nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild); + nStart = FTS3_VARINT_MAX - tdsqlite3Fts3VarintLen(iLeftChild); pTree->aData[nStart] = (char)iHeight; - sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild); + tdsqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild); return nStart; } @@ -158427,9 +180885,9 @@ static int fts3NodeWrite( Fts3Table *p, /* Virtual table handle */ SegmentNode *pTree, /* SegmentNode handle */ int iHeight, /* Height of this node in tree */ - sqlite3_int64 iLeaf, /* Block id of first leaf node */ - sqlite3_int64 iFree, /* Block id of next free slot in %_segments */ - sqlite3_int64 *piLast, /* OUT: Block id of last entry written */ + tdsqlite3_int64 iLeaf, /* Block id of first leaf node */ + tdsqlite3_int64 iFree, /* Block id of next free slot in %_segments */ + tdsqlite3_int64 *piLast, /* OUT: Block id of last entry written */ char **paRoot, /* OUT: Data for root node */ int *pnRoot /* OUT: Size of root node in bytes */ ){ @@ -158443,8 +180901,8 @@ static int fts3NodeWrite( *paRoot = &pTree->aData[nStart]; }else{ SegmentNode *pIter; - sqlite3_int64 iNextFree = iFree; - sqlite3_int64 iNextLeaf = iLeaf; + tdsqlite3_int64 iNextFree = iFree; + tdsqlite3_int64 iNextLeaf = iLeaf; for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){ int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf); int nWrite = pIter->nData - nStart; @@ -158474,11 +180932,11 @@ static void fts3NodeFree(SegmentNode *pTree){ while( p ){ SegmentNode *pRight = p->pRight; if( p->aData!=(char *)&p[1] ){ - sqlite3_free(p->aData); + tdsqlite3_free(p->aData); } assert( pRight==0 || p->zMalloc==0 ); - sqlite3_free(p->zMalloc); - sqlite3_free(p); + tdsqlite3_free(p->zMalloc); + tdsqlite3_free(p); p = pRight; } } @@ -158509,27 +180967,27 @@ static int fts3SegWriterAdd( if( !pWriter ){ int rc; - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; /* Allocate the SegmentWriter structure */ - pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter)); + pWriter = (SegmentWriter *)tdsqlite3_malloc(sizeof(SegmentWriter)); if( !pWriter ) return SQLITE_NOMEM; memset(pWriter, 0, sizeof(SegmentWriter)); *ppWriter = pWriter; /* Allocate a buffer in which to accumulate data */ - pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize); + pWriter->aData = (char *)tdsqlite3_malloc(p->nNodeSize); if( !pWriter->aData ) return SQLITE_NOMEM; pWriter->nSize = p->nNodeSize; /* Find the next free blockid in the %_segments table */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - pWriter->iFree = sqlite3_column_int64(pStmt, 0); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + pWriter->iFree = tdsqlite3_column_int64(pStmt, 0); pWriter->iFirst = pWriter->iFree; } - rc = sqlite3_reset(pStmt); + rc = tdsqlite3_reset(pStmt); if( rc!=SQLITE_OK ) return rc; } nData = pWriter->nData; @@ -158537,17 +180995,23 @@ static int fts3SegWriterAdd( nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm); nSuffix = nTerm-nPrefix; + /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of + ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when + ** compared with BINARY collation. This indicates corruption. */ + if( nSuffix<=0 ) return FTS_CORRUPT_VTAB; + /* Figure out how many bytes are required by this new entry */ - nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */ - sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */ + nReq = tdsqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */ + tdsqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */ nSuffix + /* Term suffix */ - sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ + tdsqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ nDoclist; /* Doclist data */ if( nData>0 && nData+nReq>p->nNodeSize ){ int rc; /* The current leaf node is full. Write it out to the database. */ + if( pWriter->iFree==LARGEST_INT64 ) return FTS_CORRUPT_VTAB; rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData); if( rc!=SQLITE_OK ) return rc; p->nLeafAdd++; @@ -158574,9 +181038,9 @@ static int fts3SegWriterAdd( nPrefix = 0; nSuffix = nTerm; nReq = 1 + /* varint containing prefix size */ - sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */ + tdsqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */ nTerm + /* Term suffix */ - sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ + tdsqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ nDoclist; /* Doclist data */ } @@ -158587,7 +181051,7 @@ static int fts3SegWriterAdd( ** the buffer to make it large enough. */ if( nReq>pWriter->nSize ){ - char *aNew = sqlite3_realloc(pWriter->aData, nReq); + char *aNew = tdsqlite3_realloc(pWriter->aData, nReq); if( !aNew ) return SQLITE_NOMEM; pWriter->aData = aNew; pWriter->nSize = nReq; @@ -158595,11 +181059,13 @@ static int fts3SegWriterAdd( assert( nData+nReq<=pWriter->nSize ); /* Append the prefix-compressed term and doclist to the buffer. */ - nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix); - nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix); + nData += tdsqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix); + nData += tdsqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix); + assert( nSuffix>0 ); memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); nData += nSuffix; - nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); + nData += tdsqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); + assert( nDoclist>0 ); memcpy(&pWriter->aData[nData], aDoclist, nDoclist); pWriter->nData = nData + nDoclist; @@ -158610,7 +181076,7 @@ static int fts3SegWriterAdd( */ if( isCopyTerm ){ if( nTerm>pWriter->nMalloc ){ - char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2); + char *zNew = tdsqlite3_realloc(pWriter->zMalloc, nTerm*2); if( !zNew ){ return SQLITE_NOMEM; } @@ -158619,6 +181085,7 @@ static int fts3SegWriterAdd( pWriter->zTerm = zNew; } assert( pWriter->zTerm==pWriter->zMalloc ); + assert( nTerm>0 ); memcpy(pWriter->zTerm, zTerm, nTerm); }else{ pWriter->zTerm = (char *)zTerm; @@ -158637,13 +181104,13 @@ static int fts3SegWriterAdd( static int fts3SegWriterFlush( Fts3Table *p, /* Virtual table handle */ SegmentWriter *pWriter, /* SegmentWriter to flush to the db */ - sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */ + tdsqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */ int iIdx /* Value for 'idx' column of %_segdir */ ){ int rc; /* Return code */ if( pWriter->pTree ){ - sqlite3_int64 iLast = 0; /* Largest block id written to database */ - sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */ + tdsqlite3_int64 iLast = 0; /* Largest block id written to database */ + tdsqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */ char *zRoot = NULL; /* Pointer to buffer containing root node */ int nRoot = 0; /* Size of buffer zRoot */ @@ -158672,10 +181139,10 @@ static int fts3SegWriterFlush( */ static void fts3SegWriterFree(SegmentWriter *pWriter){ if( pWriter ){ - sqlite3_free(pWriter->aData); - sqlite3_free(pWriter->zMalloc); + tdsqlite3_free(pWriter->aData); + tdsqlite3_free(pWriter->zMalloc); fts3NodeFree(pWriter->pTree); - sqlite3_free(pWriter); + tdsqlite3_free(pWriter); } } @@ -158689,8 +181156,8 @@ static void fts3SegWriterFree(SegmentWriter *pWriter){ ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an ** error occurs, an SQLite error code is returned. */ -static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){ - sqlite3_stmt *pStmt; +static int fts3IsEmpty(Fts3Table *p, tdsqlite3_value *pRowid, int *pisEmpty){ + tdsqlite3_stmt *pStmt; int rc; if( p->zContentTbl ){ /* If using the content=xxx option, assume the table is never empty */ @@ -158699,10 +181166,10 @@ static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){ }else{ rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid); if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - *pisEmpty = sqlite3_column_int(pStmt, 0); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + *pisEmpty = tdsqlite3_column_int(pStmt, 0); } - rc = sqlite3_reset(pStmt); + rc = tdsqlite3_reset(pStmt); } } return rc; @@ -158720,9 +181187,9 @@ static int fts3SegmentMaxLevel( Fts3Table *p, int iLangid, int iIndex, - sqlite3_int64 *pnMax + tdsqlite3_int64 *pnMax ){ - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; int rc; assert( iIndex>=0 && iIndex<p->nIndex ); @@ -158734,14 +181201,14 @@ static int fts3SegmentMaxLevel( */ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; - sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); - sqlite3_bind_int64(pStmt, 2, + tdsqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); + tdsqlite3_bind_int64(pStmt, 2, getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) ); - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - *pnMax = sqlite3_column_int64(pStmt, 0); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + *pnMax = tdsqlite3_column_int64(pStmt, 0); } - return sqlite3_reset(pStmt); + return tdsqlite3_reset(pStmt); } /* @@ -158760,19 +181227,19 @@ static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){ ** ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR). */ - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); if( rc!=SQLITE_OK ) return rc; - sqlite3_bind_int64(pStmt, 1, iAbsLevel+1); - sqlite3_bind_int64(pStmt, 2, + tdsqlite3_bind_int64(pStmt, 1, iAbsLevel+1); + tdsqlite3_bind_int64(pStmt, 2, ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL ); *pbMax = 0; - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL; + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + *pbMax = tdsqlite3_column_type(pStmt, 0)==SQLITE_NULL; } - return sqlite3_reset(pStmt); + return tdsqlite3_reset(pStmt); } /* @@ -158786,13 +181253,13 @@ static int fts3DeleteSegment( ){ int rc = SQLITE_OK; /* Return code */ if( pSeg->iStartBlock ){ - sqlite3_stmt *pDelete; /* SQL statement to delete rows */ + tdsqlite3_stmt *pDelete; /* SQL statement to delete rows */ rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock); - sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock); - sqlite3_step(pDelete); - rc = sqlite3_reset(pDelete); + tdsqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock); + tdsqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock); + tdsqlite3_step(pDelete); + rc = tdsqlite3_reset(pDelete); } } return rc; @@ -158822,7 +181289,7 @@ static int fts3DeleteSegdir( ){ int rc = SQLITE_OK; /* Return Code */ int i; /* Iterator variable */ - sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */ + tdsqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */ for(i=0; rc==SQLITE_OK && i<nReader; i++){ rc = fts3DeleteSegment(p, apSegment[i]); @@ -158835,23 +181302,23 @@ static int fts3DeleteSegdir( if( iLevel==FTS3_SEGCURSOR_ALL ){ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); - sqlite3_bind_int64(pDelete, 2, + tdsqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); + tdsqlite3_bind_int64(pDelete, 2, getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) ); } }else{ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64( + tdsqlite3_bind_int64( pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) ); } } if( rc==SQLITE_OK ){ - sqlite3_step(pDelete); - rc = sqlite3_reset(pDelete); + tdsqlite3_step(pDelete); + rc = tdsqlite3_reset(pDelete); } return rc; @@ -158893,14 +181360,14 @@ static void fts3ColumnFilter( nList -= (int)(p - pList); pList = p; - if( nList==0 ){ + if( nList<=0 ){ break; } p = &pList[1]; p += fts3GetVarint32(p, &iCurrent); } - if( bZero && &pList[nList]!=pEnd ){ + if( bZero && (pEnd - &pList[nList])>0){ memset(&pList[nList], 0, pEnd - &pList[nList]); } *ppList = pList; @@ -158922,19 +181389,20 @@ static int fts3MsrBufferData( if( nList>pMsr->nBuffer ){ char *pNew; pMsr->nBuffer = nList*2; - pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer); + pNew = (char *)tdsqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer); if( !pNew ) return SQLITE_NOMEM; pMsr->aBuffer = pNew; } + assert( nList>0 ); memcpy(pMsr->aBuffer, pList, nList); return SQLITE_OK; } -SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( +SQLITE_PRIVATE int tdsqlite3Fts3MsrIncrNext( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */ - sqlite3_int64 *piDocid, /* OUT: Docid value */ + tdsqlite3_int64 *piDocid, /* OUT: Docid value */ char **paPoslist, /* OUT: Pointer to position list */ int *pnPoslist /* OUT: Size of position list in bytes */ ){ @@ -158961,7 +181429,7 @@ SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( char *pList; int nList; int j; - sqlite3_int64 iDocid = apSegment[0]->iDocid; + tdsqlite3_int64 iDocid = apSegment[0]->iDocid; rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); j = 1; @@ -159031,7 +181499,7 @@ static int fts3SegReaderStart( return SQLITE_OK; } -SQLITE_PRIVATE int sqlite3Fts3SegReaderStart( +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderStart( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr, /* Cursor object */ Fts3SegFilter *pFilter /* Restrictions on range of iteration */ @@ -159040,7 +181508,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStart( return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm); } -SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( +SQLITE_PRIVATE int tdsqlite3Fts3MsrIncrStart( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr, /* Cursor object */ int iCol, /* Column to match on. */ @@ -159085,17 +181553,17 @@ SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( /* ** This function is called on a MultiSegReader that has been started using -** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also +** tdsqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also ** have been made. Calling this function puts the MultiSegReader in such ** a state that if the next two calls are: ** -** sqlite3Fts3SegReaderStart() -** sqlite3Fts3SegReaderStep() +** tdsqlite3Fts3SegReaderStart() +** tdsqlite3Fts3SegReaderStep() ** ** then the entire doclist for the term is available in ** MultiSegReader.aDoclist/nDoclist. */ -SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){ +SQLITE_PRIVATE int tdsqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){ int i; /* Used to iterate through segment-readers */ assert( pCsr->zTerm==0 ); @@ -159115,7 +181583,7 @@ SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){ } -SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( +SQLITE_PRIVATE int tdsqlite3Fts3SegReaderStep( Fts3Table *p, /* Virtual table handle */ Fts3MultiSegReader *pCsr /* Cursor object */ ){ @@ -159204,7 +181672,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( if( rc==SQLITE_OK ) rc = SQLITE_ROW; }else{ int nDoclist = 0; /* Size of doclist */ - sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */ + tdsqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */ /* The current term of the first nMerge entries in the array ** of Fts3SegReader objects is the same. The doclists must be merged @@ -159219,7 +181687,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( char *pList = 0; int nList = 0; int nByte; - sqlite3_int64 iDocid = apSegment[0]->iDocid; + tdsqlite3_int64 iDocid = apSegment[0]->iDocid; fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); j = 1; while( j<nMerge @@ -159238,20 +181706,20 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( /* Calculate the 'docid' delta value to write into the merged ** doclist. */ - sqlite3_int64 iDelta; + tdsqlite3_int64 iDelta; if( p->bDescIdx && nDoclist>0 ){ - iDelta = iPrev - iDocid; + if( iPrev<=iDocid ) return FTS_CORRUPT_VTAB; + iDelta = (i64)((u64)iPrev - (u64)iDocid); }else{ - iDelta = iDocid - iPrev; + if( nDoclist>0 && iPrev>=iDocid ) return FTS_CORRUPT_VTAB; + iDelta = (i64)((u64)iDocid - (u64)iPrev); } - assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) ); - assert( nDoclist>0 || iDelta==iDocid ); - nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0); + nByte = tdsqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0); if( nDoclist+nByte>pCsr->nBuffer ){ char *aNew; pCsr->nBuffer = (nDoclist+nByte)*2; - aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer); + aNew = tdsqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer); if( !aNew ){ return SQLITE_NOMEM; } @@ -159262,13 +181730,13 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( char *a = &pCsr->aBuffer[nDoclist]; int nWrite; - nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a); + nWrite = tdsqlite3Fts3FirstFilter(iDelta, pList, nList, a); if( nWrite ){ iPrev = iDocid; nDoclist += nWrite; } }else{ - nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta); + nDoclist += tdsqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta); iPrev = iDocid; if( isRequirePos ){ memcpy(&pCsr->aBuffer[nDoclist], pList, nList); @@ -159293,16 +181761,16 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( } -SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish( +SQLITE_PRIVATE void tdsqlite3Fts3SegReaderFinish( Fts3MultiSegReader *pCsr /* Cursor object */ ){ if( pCsr ){ int i; for(i=0; i<pCsr->nSegment; i++){ - sqlite3Fts3SegReaderFree(pCsr->apSegment[i]); + tdsqlite3Fts3SegReaderFree(pCsr->apSegment[i]); } - sqlite3_free(pCsr->apSegment); - sqlite3_free(pCsr->aBuffer); + tdsqlite3_free(pCsr->apSegment); + tdsqlite3_free(pCsr->aBuffer); pCsr->nSegment = 0; pCsr->apSegment = 0; @@ -159321,12 +181789,12 @@ SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish( ** set *piEndBlock to the first value and *pnByte to the second. */ static void fts3ReadEndBlockField( - sqlite3_stmt *pStmt, + tdsqlite3_stmt *pStmt, int iCol, i64 *piEndBlock, i64 *pnByte ){ - const unsigned char *zText = sqlite3_column_text(pStmt, iCol); + const unsigned char *zText = tdsqlite3_column_text(pStmt, iCol); if( zText ){ int i; int iMul = 1; @@ -159355,11 +181823,11 @@ static void fts3ReadEndBlockField( */ static int fts3PromoteSegments( Fts3Table *p, /* FTS table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level just updated */ - sqlite3_int64 nByte /* Size of new segment at iAbsLevel */ + tdsqlite3_int64 iAbsLevel, /* Absolute level just updated */ + tdsqlite3_int64 nByte /* Size of new segment at iAbsLevel */ ){ int rc = SQLITE_OK; - sqlite3_stmt *pRange; + tdsqlite3_stmt *pRange; rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0); @@ -159373,9 +181841,9 @@ static int fts3PromoteSegments( ** at least one such segment, and it is possible to determine that all ** such segments are smaller than nLimit bytes in size, they will be ** promoted to level iAbsLevel. */ - sqlite3_bind_int64(pRange, 1, iAbsLevel+1); - sqlite3_bind_int64(pRange, 2, iLast); - while( SQLITE_ROW==sqlite3_step(pRange) ){ + tdsqlite3_bind_int64(pRange, 1, iAbsLevel+1); + tdsqlite3_bind_int64(pRange, 2, iLast); + while( SQLITE_ROW==tdsqlite3_step(pRange) ){ i64 nSize = 0, dummy; fts3ReadEndBlockField(pRange, 2, &dummy, &nSize); if( nSize<=0 || nSize>nLimit ){ @@ -159389,12 +181857,12 @@ static int fts3PromoteSegments( } bOk = 1; } - rc = sqlite3_reset(pRange); + rc = tdsqlite3_reset(pRange); if( bOk ){ int iIdx = 0; - sqlite3_stmt *pUpdate1 = 0; - sqlite3_stmt *pUpdate2 = 0; + tdsqlite3_stmt *pUpdate1 = 0; + tdsqlite3_stmt *pUpdate2 = 0; if( rc==SQLITE_OK ){ rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0); @@ -159414,28 +181882,28 @@ static int fts3PromoteSegments( ** setting the "idx" fields as appropriate to keep them in the same ** order. The contents of level -1 (which is never used, except ** transiently here), will be moved back to level iAbsLevel below. */ - sqlite3_bind_int64(pRange, 1, iAbsLevel); - while( SQLITE_ROW==sqlite3_step(pRange) ){ - sqlite3_bind_int(pUpdate1, 1, iIdx++); - sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0)); - sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1)); - sqlite3_step(pUpdate1); - rc = sqlite3_reset(pUpdate1); + tdsqlite3_bind_int64(pRange, 1, iAbsLevel); + while( SQLITE_ROW==tdsqlite3_step(pRange) ){ + tdsqlite3_bind_int(pUpdate1, 1, iIdx++); + tdsqlite3_bind_int(pUpdate1, 2, tdsqlite3_column_int(pRange, 0)); + tdsqlite3_bind_int(pUpdate1, 3, tdsqlite3_column_int(pRange, 1)); + tdsqlite3_step(pUpdate1); + rc = tdsqlite3_reset(pUpdate1); if( rc!=SQLITE_OK ){ - sqlite3_reset(pRange); + tdsqlite3_reset(pRange); break; } } } if( rc==SQLITE_OK ){ - rc = sqlite3_reset(pRange); + rc = tdsqlite3_reset(pRange); } /* Move level -1 to level iAbsLevel */ if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pUpdate2, 1, iAbsLevel); - sqlite3_step(pUpdate2); - rc = sqlite3_reset(pUpdate2); + tdsqlite3_bind_int64(pUpdate2, 1, iAbsLevel); + tdsqlite3_step(pUpdate2); + rc = tdsqlite3_reset(pUpdate2); } } } @@ -159463,7 +181931,7 @@ static int fts3SegmentMerge( ){ int rc; /* Return code */ int iIdx = 0; /* Index of new segment */ - sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */ + tdsqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */ SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */ Fts3SegFilter filter; /* Segment term filter condition */ Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */ @@ -159477,7 +181945,7 @@ static int fts3SegmentMerge( assert( iLevel<FTS3_SEGDIR_MAXLEVEL ); assert( iIndex>=0 && iIndex<p->nIndex ); - rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr); + rc = tdsqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr); if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished; if( iLevel!=FTS3_SEGCURSOR_PENDING ){ @@ -159510,22 +181978,24 @@ static int fts3SegmentMerge( if( rc!=SQLITE_OK ) goto finished; assert( csr.nSegment>0 ); - assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) ); - assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) ); + assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) ); + assert_fts3_nc( + iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) + ); memset(&filter, 0, sizeof(Fts3SegFilter)); filter.flags = FTS3_SEGMENT_REQUIRE_POS; filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0); - rc = sqlite3Fts3SegReaderStart(p, &csr, &filter); + rc = tdsqlite3Fts3SegReaderStart(p, &csr, &filter); while( SQLITE_OK==rc ){ - rc = sqlite3Fts3SegReaderStep(p, &csr); + rc = tdsqlite3Fts3SegReaderStep(p, &csr); if( rc!=SQLITE_ROW ) break; rc = fts3SegWriterAdd(p, &pWriter, 1, csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist); } if( rc!=SQLITE_OK ) goto finished; - assert( pWriter || bIgnoreEmpty ); + assert_fts3_nc( pWriter || bIgnoreEmpty ); if( iLevel!=FTS3_SEGCURSOR_PENDING ){ rc = fts3DeleteSegdir( @@ -159544,7 +182014,7 @@ static int fts3SegmentMerge( finished: fts3SegWriterFree(pWriter); - sqlite3Fts3SegReaderFinish(&csr); + tdsqlite3Fts3SegReaderFinish(&csr); return rc; } @@ -159552,7 +182022,7 @@ static int fts3SegmentMerge( /* ** Flush the contents of pendingTerms to level 0 segments. */ -SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){ +SQLITE_PRIVATE int tdsqlite3Fts3PendingTermsFlush(Fts3Table *p){ int rc = SQLITE_OK; int i; @@ -159560,7 +182030,7 @@ SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){ rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING); if( rc==SQLITE_DONE ) rc = SQLITE_OK; } - sqlite3Fts3PendingTermsClear(p); + tdsqlite3Fts3PendingTermsClear(p); /* Determine the auto-incr-merge setting if unknown. If enabled, ** estimate the number of leaf blocks of content to be written @@ -159568,18 +182038,18 @@ SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){ if( rc==SQLITE_OK && p->bHasStat && p->nAutoincrmerge==0xff && p->nLeafAdd>0 ){ - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); - rc = sqlite3_step(pStmt); + tdsqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); + rc = tdsqlite3_step(pStmt); if( rc==SQLITE_ROW ){ - p->nAutoincrmerge = sqlite3_column_int(pStmt, 0); + p->nAutoincrmerge = tdsqlite3_column_int(pStmt, 0); if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8; }else if( rc==SQLITE_DONE ){ p->nAutoincrmerge = 0; } - rc = sqlite3_reset(pStmt); + rc = tdsqlite3_reset(pStmt); } } return rc; @@ -159596,7 +182066,7 @@ static void fts3EncodeIntArray( ){ int i, j; for(i=j=0; i<N; i++){ - j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]); + j += tdsqlite3Fts3PutVarint(&zBuf[j], (tdsqlite3_int64)a[i]); } *pNBuf = j; } @@ -159610,14 +182080,16 @@ static void fts3DecodeIntArray( const char *zBuf, /* The BLOB containing the varints */ int nBuf /* size of the BLOB */ ){ - int i, j; - UNUSED_PARAMETER(nBuf); - for(i=j=0; i<N; i++){ - sqlite3_int64 x; - j += sqlite3Fts3GetVarint(&zBuf[j], &x); - assert(j<=nBuf); - a[i] = (u32)(x & 0xffffffff); + int i = 0; + if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){ + int j; + for(i=j=0; i<N && j<nBuf; i++){ + tdsqlite3_int64 x; + j += tdsqlite3Fts3GetVarint(&zBuf[j], &x); + a[i] = (u32)(x & 0xffffffff); + } } + while( i<N ) a[i++] = 0; } /* @@ -159632,11 +182104,11 @@ static void fts3InsertDocsize( ){ char *pBlob; /* The BLOB encoding of the document size */ int nBlob; /* Number of bytes in the BLOB */ - sqlite3_stmt *pStmt; /* Statement used to insert the encoding */ + tdsqlite3_stmt *pStmt; /* Statement used to insert the encoding */ int rc; /* Result code from subfunctions */ if( *pRC ) return; - pBlob = sqlite3_malloc( 10*p->nColumn ); + pBlob = tdsqlite3_malloc64( 10*(tdsqlite3_int64)p->nColumn ); if( pBlob==0 ){ *pRC = SQLITE_NOMEM; return; @@ -159644,14 +182116,14 @@ static void fts3InsertDocsize( fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob); rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0); if( rc ){ - sqlite3_free(pBlob); + tdsqlite3_free(pBlob); *pRC = rc; return; } - sqlite3_bind_int64(pStmt, 1, p->iPrevDocid); - sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free); - sqlite3_step(pStmt); - *pRC = sqlite3_reset(pStmt); + tdsqlite3_bind_int64(pStmt, 1, p->iPrevDocid); + tdsqlite3_bind_blob(pStmt, 2, pBlob, nBlob, tdsqlite3_free); + tdsqlite3_step(pStmt); + *pRC = tdsqlite3_reset(pStmt); } /* @@ -159679,14 +182151,14 @@ static void fts3UpdateDocTotals( char *pBlob; /* Storage for BLOB written into %_stat */ int nBlob; /* Size of BLOB written into %_stat */ u32 *a; /* Array of integers that becomes the BLOB */ - sqlite3_stmt *pStmt; /* Statement for reading and writing */ + tdsqlite3_stmt *pStmt; /* Statement for reading and writing */ int i; /* Loop counter */ int rc; /* Result code from subfunctions */ const int nStat = p->nColumn+2; if( *pRC ) return; - a = sqlite3_malloc( (sizeof(u32)+10)*nStat ); + a = tdsqlite3_malloc64( (sizeof(u32)+10)*(tdsqlite3_int64)nStat ); if( a==0 ){ *pRC = SQLITE_NOMEM; return; @@ -159694,21 +182166,21 @@ static void fts3UpdateDocTotals( pBlob = (char*)&a[nStat]; rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); if( rc ){ - sqlite3_free(a); + tdsqlite3_free(a); *pRC = rc; return; } - sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); - if( sqlite3_step(pStmt)==SQLITE_ROW ){ + tdsqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); + if( tdsqlite3_step(pStmt)==SQLITE_ROW ){ fts3DecodeIntArray(nStat, a, - sqlite3_column_blob(pStmt, 0), - sqlite3_column_bytes(pStmt, 0)); + tdsqlite3_column_blob(pStmt, 0), + tdsqlite3_column_bytes(pStmt, 0)); }else{ memset(a, 0, sizeof(u32)*(nStat) ); } - rc = sqlite3_reset(pStmt); + rc = tdsqlite3_reset(pStmt); if( rc!=SQLITE_OK ){ - sqlite3_free(a); + tdsqlite3_free(a); *pRC = rc; return; } @@ -159729,15 +182201,16 @@ static void fts3UpdateDocTotals( fts3EncodeIntArray(nStat, a, pBlob, &nBlob); rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); if( rc ){ - sqlite3_free(a); + tdsqlite3_free(a); *pRC = rc; return; } - sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); - sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC); - sqlite3_step(pStmt); - *pRC = sqlite3_reset(pStmt); - sqlite3_free(a); + tdsqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); + tdsqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC); + tdsqlite3_step(pStmt); + *pRC = tdsqlite3_reset(pStmt); + tdsqlite3_bind_null(pStmt, 2); + tdsqlite3_free(a); } /* @@ -159747,16 +182220,19 @@ static void fts3UpdateDocTotals( static int fts3DoOptimize(Fts3Table *p, int bReturnDone){ int bSeenDone = 0; int rc; - sqlite3_stmt *pAllLangid = 0; + tdsqlite3_stmt *pAllLangid = 0; - rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); + rc = tdsqlite3Fts3PendingTermsFlush(p); + if( rc==SQLITE_OK ){ + rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); + } if( rc==SQLITE_OK ){ int rc2; - sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid); - sqlite3_bind_int(pAllLangid, 2, p->nIndex); - while( sqlite3_step(pAllLangid)==SQLITE_ROW ){ + tdsqlite3_bind_int(pAllLangid, 1, p->iPrevLangid); + tdsqlite3_bind_int(pAllLangid, 2, p->nIndex); + while( tdsqlite3_step(pAllLangid)==SQLITE_ROW ){ int i; - int iLangid = sqlite3_column_int(pAllLangid, 0); + int iLangid = tdsqlite3_column_int(pAllLangid, 0); for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){ rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL); if( rc==SQLITE_DONE ){ @@ -159765,12 +182241,11 @@ static int fts3DoOptimize(Fts3Table *p, int bReturnDone){ } } } - rc2 = sqlite3_reset(pAllLangid); + rc2 = tdsqlite3_reset(pAllLangid); if( rc==SQLITE_OK ) rc = rc2; } - sqlite3Fts3SegmentsClose(p); - sqlite3Fts3PendingTermsClear(p); + tdsqlite3Fts3SegmentsClose(p); return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc; } @@ -159793,21 +182268,21 @@ static int fts3DoRebuild(Fts3Table *p){ u32 *aSz = 0; u32 *aSzIns = 0; u32 *aSzDel = 0; - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; int nEntry = 0; /* Compose and prepare an SQL statement to loop through the content table */ - char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); + char *zSql = tdsqlite3_mprintf("SELECT %s" , p->zReadExprlist); if( !zSql ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); + rc = tdsqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + tdsqlite3_free(zSql); } if( rc==SQLITE_OK ){ - int nByte = sizeof(u32) * (p->nColumn+1)*3; - aSz = (u32 *)sqlite3_malloc(nByte); + tdsqlite3_int64 nByte = sizeof(u32) * ((tdsqlite3_int64)p->nColumn+1)*3; + aSz = (u32 *)tdsqlite3_malloc64(nByte); if( aSz==0 ){ rc = SQLITE_NOMEM; }else{ @@ -159817,23 +182292,23 @@ static int fts3DoRebuild(Fts3Table *p){ } } - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ + while( rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pStmt) ){ int iCol; int iLangid = langidFromSelect(p, pStmt); - rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0)); + rc = fts3PendingTermsDocid(p, 0, iLangid, tdsqlite3_column_int64(pStmt, 0)); memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1)); for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){ if( p->abNotindexed[iCol]==0 ){ - const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1); + const char *z = (const char *) tdsqlite3_column_text(pStmt, iCol+1); rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]); - aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1); + aSz[p->nColumn] += tdsqlite3_column_bytes(pStmt, iCol+1); } } if( p->bHasDocsize ){ fts3InsertDocsize(&rc, p, aSz); } if( rc!=SQLITE_OK ){ - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); pStmt = 0; }else{ nEntry++; @@ -159845,10 +182320,10 @@ static int fts3DoRebuild(Fts3Table *p){ if( p->bFts4 ){ fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry); } - sqlite3_free(aSz); + tdsqlite3_free(aSz); if( pStmt ){ - int rc2 = sqlite3_finalize(pStmt); + int rc2 = tdsqlite3_finalize(pStmt); if( rc==SQLITE_OK ){ rc = rc2; } @@ -159867,18 +182342,18 @@ static int fts3DoRebuild(Fts3Table *p){ */ static int fts3IncrmergeCsr( Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level to open */ + tdsqlite3_int64 iAbsLevel, /* Absolute level to open */ int nSeg, /* Number of segments to merge */ Fts3MultiSegReader *pCsr /* Cursor object to populate */ ){ int rc; /* Return Code */ - sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */ - int nByte; /* Bytes allocated at pCsr->apSegment[] */ + tdsqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */ + tdsqlite3_int64 nByte; /* Bytes allocated at pCsr->apSegment[] */ /* Allocate space for the Fts3MultiSegReader.aCsr[] array */ memset(pCsr, 0, sizeof(*pCsr)); nByte = sizeof(Fts3SegReader *) * nSeg; - pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte); + pCsr->apSegment = (Fts3SegReader **)tdsqlite3_malloc64(nByte); if( pCsr->apSegment==0 ){ rc = SQLITE_NOMEM; @@ -159889,20 +182364,20 @@ static int fts3IncrmergeCsr( if( rc==SQLITE_OK ){ int i; int rc2; - sqlite3_bind_int64(pStmt, 1, iAbsLevel); + tdsqlite3_bind_int64(pStmt, 1, iAbsLevel); assert( pCsr->nSegment==0 ); - for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){ - rc = sqlite3Fts3SegReaderNew(i, 0, - sqlite3_column_int64(pStmt, 1), /* segdir.start_block */ - sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */ - sqlite3_column_int64(pStmt, 3), /* segdir.end_block */ - sqlite3_column_blob(pStmt, 4), /* segdir.root */ - sqlite3_column_bytes(pStmt, 4), /* segdir.root */ + for(i=0; rc==SQLITE_OK && tdsqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){ + rc = tdsqlite3Fts3SegReaderNew(i, 0, + tdsqlite3_column_int64(pStmt, 1), /* segdir.start_block */ + tdsqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */ + tdsqlite3_column_int64(pStmt, 3), /* segdir.end_block */ + tdsqlite3_column_blob(pStmt, 4), /* segdir.root */ + tdsqlite3_column_bytes(pStmt, 4), /* segdir.root */ &pCsr->apSegment[i] ); pCsr->nSegment++; } - rc2 = sqlite3_reset(pStmt); + rc2 = tdsqlite3_reset(pStmt); if( rc==SQLITE_OK ) rc = rc2; } @@ -159931,7 +182406,7 @@ struct Blob { ** nodes (blocks). */ struct NodeWriter { - sqlite3_int64 iBlock; /* Current block id */ + tdsqlite3_int64 iBlock; /* Current block id */ Blob key; /* Last key written to the current block */ Blob block; /* Current block image */ }; @@ -159943,11 +182418,11 @@ struct NodeWriter { struct IncrmergeWriter { int nLeafEst; /* Space allocated for leaf blocks */ int nWork; /* Number of leaf pages flushed */ - sqlite3_int64 iAbsLevel; /* Absolute level of input segments */ + tdsqlite3_int64 iAbsLevel; /* Absolute level of input segments */ int iIdx; /* Index of *output* segment in iAbsLevel+1 */ - sqlite3_int64 iStart; /* Block number of first allocated block */ - sqlite3_int64 iEnd; /* Block number of last allocated block */ - sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */ + tdsqlite3_int64 iStart; /* Block number of first allocated block */ + tdsqlite3_int64 iEnd; /* Block number of last allocated block */ + tdsqlite3_int64 nLeafData; /* Bytes of leaf page data so far */ u8 bNoLeafData; /* If true, store 0 for segment size */ NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT]; }; @@ -159966,7 +182441,7 @@ struct NodeReader { int iOff; /* Current offset within aNode[] */ /* Output variables. Containing the current node entry. */ - sqlite3_int64 iChild; /* Pointer to child node */ + tdsqlite3_int64 iChild; /* Pointer to child node */ Blob term; /* Current term */ const char *aDoclist; /* Pointer to doclist */ int nDoclist; /* Size of doclist in bytes */ @@ -159984,7 +182459,7 @@ struct NodeReader { static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){ if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){ int nAlloc = nMin; - char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc); + char *a = (char *)tdsqlite3_realloc(pBlob->a, nAlloc); if( a ){ pBlob->nAlloc = nAlloc; pBlob->a = a; @@ -160021,6 +182496,9 @@ static int nodeReaderNext(NodeReader *p){ } p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix); + if( nPrefix>p->term.n || nSuffix>p->nNode-p->iOff || nSuffix==0 ){ + return FTS_CORRUPT_VTAB; + } blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc); if( rc==SQLITE_OK ){ memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix); @@ -160028,14 +182506,16 @@ static int nodeReaderNext(NodeReader *p){ p->iOff += nSuffix; if( p->iChild==0 ){ p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist); + if( (p->nNode-p->iOff)<p->nDoclist ){ + return FTS_CORRUPT_VTAB; + } p->aDoclist = &p->aNode[p->iOff]; p->iOff += p->nDoclist; } } } - assert( p->iOff<=p->nNode ); - + assert_fts3_nc( p->iOff<=p->nNode ); return rc; } @@ -160043,7 +182523,7 @@ static int nodeReaderNext(NodeReader *p){ ** Release all dynamic resources held by node-reader object *p. */ static void nodeReaderRelease(NodeReader *p){ - sqlite3_free(p->term.a); + tdsqlite3_free(p->term.a); } /* @@ -160059,14 +182539,14 @@ static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){ p->nNode = nNode; /* Figure out if this is a leaf or an internal node. */ - if( p->aNode[0] ){ + if( aNode && aNode[0] ){ /* An internal node. */ - p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild); + p->iOff = 1 + tdsqlite3Fts3GetVarint(&p->aNode[1], &p->iChild); }else{ p->iOff = 1; } - return nodeReaderNext(p); + return aNode ? nodeReaderNext(p) : SQLITE_OK; } /* @@ -160085,12 +182565,12 @@ static int fts3IncrmergePush( const char *zTerm, /* Term to write to internal node */ int nTerm /* Bytes at zTerm */ ){ - sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock; + tdsqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock; int iLayer; assert( nTerm>0 ); for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){ - sqlite3_int64 iNextPtr = 0; + tdsqlite3_int64 iNextPtr = 0; NodeWriter *pNode = &pWriter->aNodeWriter[iLayer]; int rc = SQLITE_OK; int nPrefix; @@ -160103,8 +182583,9 @@ static int fts3IncrmergePush( ** be added to. */ nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm); nSuffix = nTerm - nPrefix; - nSpace = sqlite3Fts3VarintLen(nPrefix); - nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; + if(nSuffix<=0 ) return FTS_CORRUPT_VTAB; + nSpace = tdsqlite3Fts3VarintLen(nPrefix); + nSpace += tdsqlite3Fts3VarintLen(nSuffix) + nSuffix; if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ /* If the current node of layer iLayer contains zero keys, or if adding @@ -160116,7 +182597,7 @@ static int fts3IncrmergePush( blobGrowBuffer(pBlk, p->nNodeSize, &rc); if( rc==SQLITE_OK ){ pBlk->a[0] = (char)iLayer; - pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr); + pBlk->n = 1 + tdsqlite3Fts3PutVarint(&pBlk->a[1], iPtr); } } blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc); @@ -160124,9 +182605,9 @@ static int fts3IncrmergePush( if( rc==SQLITE_OK ){ if( pNode->key.n ){ - pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix); + pBlk->n += tdsqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix); } - pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix); + pBlk->n += tdsqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix); memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix); pBlk->n += nSuffix; @@ -160141,7 +182622,7 @@ static int fts3IncrmergePush( assert( pNode->block.nAlloc>=p->nNodeSize ); pNode->block.a[0] = (char)iLayer; - pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1); + pNode->block.n = 1 + tdsqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1); iNextPtr = pNode->iBlock; pNode->iBlock++; @@ -160196,25 +182677,26 @@ static int fts3AppendToNode( /* Node must have already been started. There must be a doclist for a ** leaf node, and there must not be a doclist for an internal node. */ assert( pNode->n>0 ); - assert( (pNode->a[0]=='\0')==(aDoclist!=0) ); + assert_fts3_nc( (pNode->a[0]=='\0')==(aDoclist!=0) ); blobGrowBuffer(pPrev, nTerm, &rc); if( rc!=SQLITE_OK ) return rc; nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm); nSuffix = nTerm - nPrefix; + if( nSuffix<=0 ) return FTS_CORRUPT_VTAB; memcpy(pPrev->a, zTerm, nTerm); pPrev->n = nTerm; if( bFirst==0 ){ - pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix); + pNode->n += tdsqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix); } - pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix); + pNode->n += tdsqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix); memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix); pNode->n += nSuffix; if( aDoclist ){ - pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist); + pNode->n += tdsqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist); memcpy(&pNode->a[pNode->n], aDoclist, nDoclist); pNode->n += nDoclist; } @@ -160249,9 +182731,9 @@ static int fts3IncrmergeAppend( nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm); nSuffix = nTerm - nPrefix; - nSpace = sqlite3Fts3VarintLen(nPrefix); - nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; - nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; + nSpace = tdsqlite3Fts3VarintLen(nPrefix); + nSpace += tdsqlite3Fts3VarintLen(nSuffix) + nSuffix; + nSpace += tdsqlite3Fts3VarintLen(nDoclist) + nDoclist; /* If the current block is not empty, and if adding this term/doclist ** to the current block would make it larger than Fts3Table.nNodeSize @@ -160283,8 +182765,8 @@ static int fts3IncrmergeAppend( nSuffix = nTerm; nSpace = 1; - nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; - nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; + nSpace += tdsqlite3Fts3VarintLen(nSuffix) + nSuffix; + nSpace += tdsqlite3Fts3VarintLen(nDoclist) + nDoclist; } pWriter->nLeafData += nSpace; @@ -160334,8 +182816,8 @@ static void fts3IncrmergeRelease( if( pNode->block.n>0 ) break; assert( *pRc || pNode->block.nAlloc==0 ); assert( *pRc || pNode->key.nAlloc==0 ); - sqlite3_free(pNode->block.a); - sqlite3_free(pNode->key.a); + tdsqlite3_free(pNode->block.a); + tdsqlite3_free(pNode->key.a); } /* Empty output segment. This is a no-op. */ @@ -160361,7 +182843,7 @@ static void fts3IncrmergeRelease( blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc); if( rc==SQLITE_OK ){ pBlock->a[0] = 0x01; - pBlock->n = 1 + sqlite3Fts3PutVarint( + pBlock->n = 1 + tdsqlite3Fts3PutVarint( &pBlock->a[1], pWriter->aNodeWriter[0].iBlock ); } @@ -160375,8 +182857,8 @@ static void fts3IncrmergeRelease( if( pNode->block.n>0 && rc==SQLITE_OK ){ rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); } - sqlite3_free(pNode->block.a); - sqlite3_free(pNode->key.a); + tdsqlite3_free(pNode->block.a); + tdsqlite3_free(pNode->key.a); } /* Write the %_segdir record. */ @@ -160391,8 +182873,8 @@ static void fts3IncrmergeRelease( pRoot->block.a, pRoot->block.n /* root */ ); } - sqlite3_free(pRoot->block.a); - sqlite3_free(pRoot->key.a); + tdsqlite3_free(pRoot->block.a); + tdsqlite3_free(pRoot->key.a); *pRc = rc; } @@ -160412,7 +182894,7 @@ static int fts3TermCmp( int nCmp = MIN(nLhs, nRhs); int res; - res = memcmp(zLhs, zRhs, nCmp); + res = (nCmp ? memcmp(zLhs, zRhs, nCmp) : 0); if( res==0 ) res = nLhs - nRhs; return res; @@ -160431,16 +182913,16 @@ static int fts3TermCmp( ** is, then a NULL entry has been inserted into the %_segments table ** with blockid %_segdir.end_block. */ -static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){ +static int fts3IsAppendable(Fts3Table *p, tdsqlite3_int64 iEnd, int *pbRes){ int bRes = 0; /* Result to set *pbRes to */ - sqlite3_stmt *pCheck = 0; /* Statement to query database with */ + tdsqlite3_stmt *pCheck = 0; /* Statement to query database with */ int rc; /* Return code */ rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pCheck, 1, iEnd); - if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1; - rc = sqlite3_reset(pCheck); + tdsqlite3_bind_int64(pCheck, 1, iEnd); + if( SQLITE_ROW==tdsqlite3_step(pCheck) ) bRes = 1; + rc = tdsqlite3_reset(pCheck); } *pbRes = bRes; @@ -160464,40 +182946,44 @@ static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){ */ static int fts3IncrmergeLoad( Fts3Table *p, /* Fts3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ + tdsqlite3_int64 iAbsLevel, /* Absolute level of input segments */ int iIdx, /* Index of candidate output segment */ const char *zKey, /* First key to write */ int nKey, /* Number of bytes in nKey */ IncrmergeWriter *pWriter /* Populate this object */ ){ int rc; /* Return code */ - sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */ + tdsqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0); if( rc==SQLITE_OK ){ - sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */ - sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */ - sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */ + tdsqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */ + tdsqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */ + tdsqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */ const char *aRoot = 0; /* Pointer to %_segdir.root buffer */ int nRoot = 0; /* Size of aRoot[] in bytes */ - int rc2; /* Return code from sqlite3_reset() */ + int rc2; /* Return code from tdsqlite3_reset() */ int bAppendable = 0; /* Set to true if segment is appendable */ /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */ - sqlite3_bind_int64(pSelect, 1, iAbsLevel+1); - sqlite3_bind_int(pSelect, 2, iIdx); - if( sqlite3_step(pSelect)==SQLITE_ROW ){ - iStart = sqlite3_column_int64(pSelect, 1); - iLeafEnd = sqlite3_column_int64(pSelect, 2); + tdsqlite3_bind_int64(pSelect, 1, iAbsLevel+1); + tdsqlite3_bind_int(pSelect, 2, iIdx); + if( tdsqlite3_step(pSelect)==SQLITE_ROW ){ + iStart = tdsqlite3_column_int64(pSelect, 1); + iLeafEnd = tdsqlite3_column_int64(pSelect, 2); fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData); if( pWriter->nLeafData<0 ){ pWriter->nLeafData = pWriter->nLeafData * -1; } pWriter->bNoLeafData = (pWriter->nLeafData==0); - nRoot = sqlite3_column_bytes(pSelect, 4); - aRoot = sqlite3_column_blob(pSelect, 4); + nRoot = tdsqlite3_column_bytes(pSelect, 4); + aRoot = tdsqlite3_column_blob(pSelect, 4); + if( aRoot==0 ){ + tdsqlite3_reset(pSelect); + return nRoot ? SQLITE_NOMEM : FTS_CORRUPT_VTAB; + } }else{ - return sqlite3_reset(pSelect); + return tdsqlite3_reset(pSelect); } /* Check for the zero-length marker in the %_segments table */ @@ -160508,7 +182994,7 @@ static int fts3IncrmergeLoad( char *aLeaf = 0; int nLeaf = 0; - rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0); + rc = tdsqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0); if( rc==SQLITE_OK ){ NodeReader reader; for(rc = nodeReaderInit(&reader, aLeaf, nLeaf); @@ -160522,7 +183008,7 @@ static int fts3IncrmergeLoad( } nodeReaderRelease(&reader); } - sqlite3_free(aLeaf); + tdsqlite3_free(aLeaf); } if( rc==SQLITE_OK && bAppendable ){ @@ -160531,6 +183017,10 @@ static int fts3IncrmergeLoad( int i; int nHeight = (int)aRoot[0]; NodeWriter *pNode; + if( nHeight<1 || nHeight>FTS_MAX_APPENDABLE_HEIGHT ){ + tdsqlite3_reset(pSelect); + return FTS_CORRUPT_VTAB; + } pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT; pWriter->iStart = iStart; @@ -160544,41 +183034,49 @@ static int fts3IncrmergeLoad( pNode = &pWriter->aNodeWriter[nHeight]; pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight; - blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc); + blobGrowBuffer(&pNode->block, + MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc + ); if( rc==SQLITE_OK ){ memcpy(pNode->block.a, aRoot, nRoot); pNode->block.n = nRoot; + memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING); } for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){ NodeReader reader; pNode = &pWriter->aNodeWriter[i]; - rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n); - while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader); - blobGrowBuffer(&pNode->key, reader.term.n, &rc); - if( rc==SQLITE_OK ){ - memcpy(pNode->key.a, reader.term.a, reader.term.n); - pNode->key.n = reader.term.n; - if( i>0 ){ - char *aBlock = 0; - int nBlock = 0; - pNode = &pWriter->aNodeWriter[i-1]; - pNode->iBlock = reader.iChild; - rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0); - blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc); - if( rc==SQLITE_OK ){ - memcpy(pNode->block.a, aBlock, nBlock); - pNode->block.n = nBlock; + if( pNode->block.a){ + rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n); + while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader); + blobGrowBuffer(&pNode->key, reader.term.n, &rc); + if( rc==SQLITE_OK ){ + memcpy(pNode->key.a, reader.term.a, reader.term.n); + pNode->key.n = reader.term.n; + if( i>0 ){ + char *aBlock = 0; + int nBlock = 0; + pNode = &pWriter->aNodeWriter[i-1]; + pNode->iBlock = reader.iChild; + rc = tdsqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0); + blobGrowBuffer(&pNode->block, + MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc + ); + if( rc==SQLITE_OK ){ + memcpy(pNode->block.a, aBlock, nBlock); + pNode->block.n = nBlock; + memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING); + } + tdsqlite3_free(aBlock); } - sqlite3_free(aBlock); } } nodeReaderRelease(&reader); } } - rc2 = sqlite3_reset(pSelect); + rc2 = tdsqlite3_reset(pSelect); if( rc==SQLITE_OK ) rc = rc2; } @@ -160596,18 +183094,18 @@ static int fts3IncrmergeLoad( */ static int fts3IncrmergeOutputIdx( Fts3Table *p, /* FTS Table handle */ - sqlite3_int64 iAbsLevel, /* Absolute index of input segments */ + tdsqlite3_int64 iAbsLevel, /* Absolute index of input segments */ int *piIdx /* OUT: Next free index at iAbsLevel+1 */ ){ int rc; - sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */ + tdsqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1); - sqlite3_step(pOutputIdx); - *piIdx = sqlite3_column_int(pOutputIdx, 0); - rc = sqlite3_reset(pOutputIdx); + tdsqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1); + tdsqlite3_step(pOutputIdx); + *piIdx = tdsqlite3_column_int(pOutputIdx, 0); + rc = tdsqlite3_reset(pOutputIdx); } return rc; @@ -160641,7 +183139,7 @@ static int fts3IncrmergeOutputIdx( */ static int fts3IncrmergeWriter( Fts3Table *p, /* Fts3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ + tdsqlite3_int64 iAbsLevel, /* Absolute level of input segments */ int iIdx, /* Index of new output segment */ Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */ IncrmergeWriter *pWriter /* Populate this object */ @@ -160649,30 +183147,30 @@ static int fts3IncrmergeWriter( int rc; /* Return Code */ int i; /* Iterator variable */ int nLeafEst = 0; /* Blocks allocated for leaf nodes */ - sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */ - sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */ + tdsqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */ + tdsqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */ /* Calculate nLeafEst. */ rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pLeafEst, 1, iAbsLevel); - sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment); - if( SQLITE_ROW==sqlite3_step(pLeafEst) ){ - nLeafEst = sqlite3_column_int(pLeafEst, 0); + tdsqlite3_bind_int64(pLeafEst, 1, iAbsLevel); + tdsqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment); + if( SQLITE_ROW==tdsqlite3_step(pLeafEst) ){ + nLeafEst = tdsqlite3_column_int(pLeafEst, 0); } - rc = sqlite3_reset(pLeafEst); + rc = tdsqlite3_reset(pLeafEst); } if( rc!=SQLITE_OK ) return rc; /* Calculate the first block to use in the output segment */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0); if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){ - pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0); + if( SQLITE_ROW==tdsqlite3_step(pFirstBlock) ){ + pWriter->iStart = tdsqlite3_column_int64(pFirstBlock, 0); pWriter->iEnd = pWriter->iStart - 1; pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT; } - rc = sqlite3_reset(pFirstBlock); + rc = tdsqlite3_reset(pFirstBlock); } if( rc!=SQLITE_OK ) return rc; @@ -160706,18 +183204,18 @@ static int fts3IncrmergeWriter( */ static int fts3RemoveSegdirEntry( Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level to delete from */ + tdsqlite3_int64 iAbsLevel, /* Absolute level to delete from */ int iIdx /* Index of %_segdir entry to delete */ ){ int rc; /* Return code */ - sqlite3_stmt *pDelete = 0; /* DELETE statement */ + tdsqlite3_stmt *pDelete = 0; /* DELETE statement */ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDelete, 1, iAbsLevel); - sqlite3_bind_int(pDelete, 2, iIdx); - sqlite3_step(pDelete); - rc = sqlite3_reset(pDelete); + tdsqlite3_bind_int64(pDelete, 1, iAbsLevel); + tdsqlite3_bind_int(pDelete, 2, iIdx); + tdsqlite3_step(pDelete); + rc = tdsqlite3_reset(pDelete); } return rc; @@ -160730,34 +183228,34 @@ static int fts3RemoveSegdirEntry( */ static int fts3RepackSegdirLevel( Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iAbsLevel /* Absolute level to repack */ + tdsqlite3_int64 iAbsLevel /* Absolute level to repack */ ){ int rc; /* Return code */ int *aIdx = 0; /* Array of remaining idx values */ int nIdx = 0; /* Valid entries in aIdx[] */ int nAlloc = 0; /* Allocated size of aIdx[] */ int i; /* Iterator variable */ - sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */ - sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */ + tdsqlite3_stmt *pSelect = 0; /* Select statement to read idx values */ + tdsqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */ rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0); if( rc==SQLITE_OK ){ int rc2; - sqlite3_bind_int64(pSelect, 1, iAbsLevel); - while( SQLITE_ROW==sqlite3_step(pSelect) ){ + tdsqlite3_bind_int64(pSelect, 1, iAbsLevel); + while( SQLITE_ROW==tdsqlite3_step(pSelect) ){ if( nIdx>=nAlloc ){ int *aNew; nAlloc += 16; - aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int)); + aNew = tdsqlite3_realloc(aIdx, nAlloc*sizeof(int)); if( !aNew ){ rc = SQLITE_NOMEM; break; } aIdx = aNew; } - aIdx[nIdx++] = sqlite3_column_int(pSelect, 0); + aIdx[nIdx++] = tdsqlite3_column_int(pSelect, 0); } - rc2 = sqlite3_reset(pSelect); + rc2 = tdsqlite3_reset(pSelect); if( rc==SQLITE_OK ) rc = rc2; } @@ -160765,30 +183263,30 @@ static int fts3RepackSegdirLevel( rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0); } if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pUpdate, 2, iAbsLevel); + tdsqlite3_bind_int64(pUpdate, 2, iAbsLevel); } assert( p->bIgnoreSavepoint==0 ); p->bIgnoreSavepoint = 1; for(i=0; rc==SQLITE_OK && i<nIdx; i++){ if( aIdx[i]!=i ){ - sqlite3_bind_int(pUpdate, 3, aIdx[i]); - sqlite3_bind_int(pUpdate, 1, i); - sqlite3_step(pUpdate); - rc = sqlite3_reset(pUpdate); + tdsqlite3_bind_int(pUpdate, 3, aIdx[i]); + tdsqlite3_bind_int(pUpdate, 1, i); + tdsqlite3_step(pUpdate); + rc = tdsqlite3_reset(pUpdate); } } p->bIgnoreSavepoint = 0; - sqlite3_free(aIdx); + tdsqlite3_free(aIdx); return rc; } -static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){ +static void fts3StartNode(Blob *pNode, int iHeight, tdsqlite3_int64 iChild){ pNode->a[0] = (char)iHeight; if( iChild ){ - assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) ); - pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild); + assert( pNode->nAlloc>=1+tdsqlite3Fts3VarintLen(iChild) ); + pNode->n = 1 + tdsqlite3Fts3PutVarint(&pNode->a[1], iChild); }else{ assert( pNode->nAlloc>=1 ); pNode->n = 1; @@ -160809,12 +183307,15 @@ static int fts3TruncateNode( Blob *pNew, /* OUT: Write new node image here */ const char *zTerm, /* Omit all terms smaller than this */ int nTerm, /* Size of zTerm in bytes */ - sqlite3_int64 *piBlock /* OUT: Block number in next layer down */ + tdsqlite3_int64 *piBlock /* OUT: Block number in next layer down */ ){ NodeReader reader; /* Reader object */ Blob prev = {0, 0, 0}; /* Previous term written to new node */ int rc = SQLITE_OK; /* Return code */ - int bLeaf = aNode[0]=='\0'; /* True for a leaf node */ + int bLeaf; /* True for a leaf node */ + + if( nNode<1 ) return FTS_CORRUPT_VTAB; + bLeaf = aNode[0]=='\0'; /* Allocate required output space */ blobGrowBuffer(pNew, nNode, &rc); @@ -160845,7 +183346,7 @@ static int fts3TruncateNode( assert( pNew->n<=pNew->nAlloc ); nodeReaderRelease(&reader); - sqlite3_free(prev.a); + tdsqlite3_free(prev.a); return rc; } @@ -160860,7 +183361,7 @@ static int fts3TruncateNode( */ static int fts3TruncateSegment( Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */ + tdsqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */ int iIdx, /* Index within level of segment to modify */ const char *zTerm, /* Remove terms smaller than this */ int nTerm /* Number of bytes in buffer zTerm */ @@ -160868,23 +183369,23 @@ static int fts3TruncateSegment( int rc = SQLITE_OK; /* Return code */ Blob root = {0,0,0}; /* New root page image */ Blob block = {0,0,0}; /* Buffer used for any other block */ - sqlite3_int64 iBlock = 0; /* Block id */ - sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */ - sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */ - sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */ + tdsqlite3_int64 iBlock = 0; /* Block id */ + tdsqlite3_int64 iNewStart = 0; /* New value for iStartBlock */ + tdsqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */ + tdsqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */ rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0); if( rc==SQLITE_OK ){ - int rc2; /* sqlite3_reset() return code */ - sqlite3_bind_int64(pFetch, 1, iAbsLevel); - sqlite3_bind_int(pFetch, 2, iIdx); - if( SQLITE_ROW==sqlite3_step(pFetch) ){ - const char *aRoot = sqlite3_column_blob(pFetch, 4); - int nRoot = sqlite3_column_bytes(pFetch, 4); - iOldStart = sqlite3_column_int64(pFetch, 1); + int rc2; /* tdsqlite3_reset() return code */ + tdsqlite3_bind_int64(pFetch, 1, iAbsLevel); + tdsqlite3_bind_int(pFetch, 2, iIdx); + if( SQLITE_ROW==tdsqlite3_step(pFetch) ){ + const char *aRoot = tdsqlite3_column_blob(pFetch, 4); + int nRoot = tdsqlite3_column_bytes(pFetch, 4); + iOldStart = tdsqlite3_column_int64(pFetch, 1); rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock); } - rc2 = sqlite3_reset(pFetch); + rc2 = tdsqlite3_reset(pFetch); if( rc==SQLITE_OK ) rc = rc2; } @@ -160893,43 +183394,44 @@ static int fts3TruncateSegment( int nBlock = 0; iNewStart = iBlock; - rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0); + rc = tdsqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0); if( rc==SQLITE_OK ){ rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock); } if( rc==SQLITE_OK ){ rc = fts3WriteSegment(p, iNewStart, block.a, block.n); } - sqlite3_free(aBlock); + tdsqlite3_free(aBlock); } /* Variable iNewStart now contains the first valid leaf node. */ if( rc==SQLITE_OK && iNewStart ){ - sqlite3_stmt *pDel = 0; + tdsqlite3_stmt *pDel = 0; rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDel, 1, iOldStart); - sqlite3_bind_int64(pDel, 2, iNewStart-1); - sqlite3_step(pDel); - rc = sqlite3_reset(pDel); + tdsqlite3_bind_int64(pDel, 1, iOldStart); + tdsqlite3_bind_int64(pDel, 2, iNewStart-1); + tdsqlite3_step(pDel); + rc = tdsqlite3_reset(pDel); } } if( rc==SQLITE_OK ){ - sqlite3_stmt *pChomp = 0; + tdsqlite3_stmt *pChomp = 0; rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pChomp, 1, iNewStart); - sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC); - sqlite3_bind_int64(pChomp, 3, iAbsLevel); - sqlite3_bind_int(pChomp, 4, iIdx); - sqlite3_step(pChomp); - rc = sqlite3_reset(pChomp); + tdsqlite3_bind_int64(pChomp, 1, iNewStart); + tdsqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC); + tdsqlite3_bind_int64(pChomp, 3, iAbsLevel); + tdsqlite3_bind_int(pChomp, 4, iIdx); + tdsqlite3_step(pChomp); + rc = tdsqlite3_reset(pChomp); + tdsqlite3_bind_null(pChomp, 2); } } - sqlite3_free(root.a); - sqlite3_free(block.a); + tdsqlite3_free(root.a); + tdsqlite3_free(block.a); return rc; } @@ -160945,7 +183447,7 @@ static int fts3TruncateSegment( */ static int fts3IncrmergeChomp( Fts3Table *p, /* FTS table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level containing segments */ + tdsqlite3_int64 iAbsLevel, /* Absolute level containing segments */ Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */ int *pnRem /* Number of segments not deleted */ ){ @@ -160995,15 +183497,16 @@ static int fts3IncrmergeChomp( ** Store an incr-merge hint in the database. */ static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){ - sqlite3_stmt *pReplace = 0; + tdsqlite3_stmt *pReplace = 0; int rc; /* Return code */ rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT); - sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC); - sqlite3_step(pReplace); - rc = sqlite3_reset(pReplace); + tdsqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT); + tdsqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC); + tdsqlite3_step(pReplace); + rc = tdsqlite3_reset(pReplace); + tdsqlite3_bind_null(pReplace, 2); } return rc; @@ -161018,17 +183521,17 @@ static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){ ** SQLite error code. */ static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){ - sqlite3_stmt *pSelect = 0; + tdsqlite3_stmt *pSelect = 0; int rc; pHint->n = 0; rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0); if( rc==SQLITE_OK ){ int rc2; - sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT); - if( SQLITE_ROW==sqlite3_step(pSelect) ){ - const char *aHint = sqlite3_column_blob(pSelect, 0); - int nHint = sqlite3_column_bytes(pSelect, 0); + tdsqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT); + if( SQLITE_ROW==tdsqlite3_step(pSelect) ){ + const char *aHint = tdsqlite3_column_blob(pSelect, 0); + int nHint = tdsqlite3_column_bytes(pSelect, 0); if( aHint ){ blobGrowBuffer(pHint, nHint, &rc); if( rc==SQLITE_OK ){ @@ -161037,7 +183540,7 @@ static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){ } } } - rc2 = sqlite3_reset(pSelect); + rc2 = tdsqlite3_reset(pSelect); if( rc==SQLITE_OK ) rc = rc2; } @@ -161061,8 +183564,8 @@ static void fts3IncrmergeHintPush( ){ blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc); if( *pRc==SQLITE_OK ){ - pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel); - pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput); + pHint->n += tdsqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel); + pHint->n += tdsqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput); } } @@ -161078,13 +183581,17 @@ static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){ const int nHint = pHint->n; int i; - i = pHint->n-2; + i = pHint->n-1; + if( (pHint->a[i] & 0x80) ) return FTS_CORRUPT_VTAB; while( i>0 && (pHint->a[i-1] & 0x80) ) i--; + if( i==0 ) return FTS_CORRUPT_VTAB; + i--; while( i>0 && (pHint->a[i-1] & 0x80) ) i--; pHint->n = i; - i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel); + i += tdsqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel); i += fts3GetVarint32(&pHint->a[i], pnInput); + assert( i<=nHint ); if( i!=nHint ) return FTS_CORRUPT_VTAB; return SQLITE_OK; @@ -161100,20 +183607,20 @@ static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){ ** at least nMin segments. Multiple merges might occur in an attempt to ** write the quota of nMerge leaf blocks. */ -SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ +SQLITE_PRIVATE int tdsqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ int rc; /* Return code */ int nRem = nMerge; /* Number of leaf pages yet to be written */ Fts3MultiSegReader *pCsr; /* Cursor used to read input data */ Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */ IncrmergeWriter *pWriter; /* Writer object */ int nSeg = 0; /* Number of input segments */ - sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */ + tdsqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */ Blob hint = {0, 0, 0}; /* Hint read from %_stat table */ int bDirtyHint = 0; /* True if blob 'hint' has been modified */ /* Allocate space for the cursor, filter and writer objects */ const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter); - pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc); + pWriter = (IncrmergeWriter *)tdsqlite3_malloc(nAlloc); if( !pWriter ) return SQLITE_NOMEM; pFilter = (Fts3SegFilter *)&pWriter[1]; pCsr = (Fts3MultiSegReader *)&pFilter[1]; @@ -161121,7 +183628,7 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ rc = fts3IncrmergeHintLoad(p, &hint); while( rc==SQLITE_OK && nRem>0 ){ const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex; - sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */ + tdsqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */ int bUseHint = 0; /* True if attempting to append */ int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */ @@ -161132,15 +183639,15 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ ** set nSeg to -1. */ rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0); - sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin)); - if( sqlite3_step(pFindLevel)==SQLITE_ROW ){ - iAbsLevel = sqlite3_column_int64(pFindLevel, 0); - nSeg = sqlite3_column_int(pFindLevel, 1); + tdsqlite3_bind_int(pFindLevel, 1, MAX(2, nMin)); + if( tdsqlite3_step(pFindLevel)==SQLITE_ROW ){ + iAbsLevel = tdsqlite3_column_int64(pFindLevel, 0); + nSeg = tdsqlite3_column_int(pFindLevel, 1); assert( nSeg>=2 ); }else{ nSeg = -1; } - rc = sqlite3_reset(pFindLevel); + rc = tdsqlite3_reset(pFindLevel); /* If the hint read from the %_stat table is not empty, check if the ** last entry in it specifies a relative level smaller than or equal @@ -161149,13 +183656,19 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ */ if( rc==SQLITE_OK && hint.n ){ int nHint = hint.n; - sqlite3_int64 iHintAbsLevel = 0; /* Hint level */ + tdsqlite3_int64 iHintAbsLevel = 0; /* Hint level */ int nHintSeg = 0; /* Hint number of segments */ rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg); if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){ + /* Based on the scan in the block above, it is known that there + ** are no levels with a relative level smaller than that of + ** iAbsLevel with more than nSeg segments, or if nSeg is -1, + ** no levels with more than nMin segments. Use this to limit the + ** value of nHintSeg to avoid a large memory allocation in case the + ** merge-hint is corrupt*/ iAbsLevel = iHintAbsLevel; - nSeg = nHintSeg; + nSeg = MIN(MAX(nMin,nSeg), nHintSeg); bUseHint = 1; bDirtyHint = 1; }else{ @@ -161168,7 +183681,7 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ /* If nSeg is less that zero, then there is no level with at least ** nMin segments and no hint in the %_stat table. No work to do. ** Exit early in this case. */ - if( nSeg<0 ) break; + if( nSeg<=0 ) break; /* Open a cursor to iterate through the contents of the oldest nSeg ** indexes of absolute level iAbsLevel. If this cursor is opened using @@ -161195,9 +183708,16 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr); } if( SQLITE_OK==rc && pCsr->nSegment==nSeg - && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter)) - && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr)) + && SQLITE_OK==(rc = tdsqlite3Fts3SegReaderStart(p, pCsr, pFilter)) ){ + int bEmpty = 0; + rc = tdsqlite3Fts3SegReaderStep(p, pCsr); + if( rc==SQLITE_OK ){ + bEmpty = 1; + }else if( rc!=SQLITE_ROW ){ + tdsqlite3Fts3SegReaderFinish(pCsr); + break; + } if( bUseHint && iIdx>0 ){ const char *zKey = pCsr->zTerm; int nKey = pCsr->nTerm; @@ -161208,11 +183728,13 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ if( rc==SQLITE_OK && pWriter->nLeafEst ){ fts3LogMerge(nSeg, iAbsLevel); - do { - rc = fts3IncrmergeAppend(p, pWriter, pCsr); - if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr); - if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK; - }while( rc==SQLITE_ROW ); + if( bEmpty==0 ){ + do { + rc = fts3IncrmergeAppend(p, pWriter, pCsr); + if( rc==SQLITE_OK ) rc = tdsqlite3Fts3SegReaderStep(p, pCsr); + if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK; + }while( rc==SQLITE_ROW ); + } /* Update or delete the input segments */ if( rc==SQLITE_OK ){ @@ -161234,7 +183756,7 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ } } - sqlite3Fts3SegReaderFinish(pCsr); + tdsqlite3Fts3SegReaderFinish(pCsr); } /* Write the hint values into the %_stat table for the next incr-merger */ @@ -161242,8 +183764,8 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ rc = fts3IncrmergeHintStore(p, &hint); } - sqlite3_free(pWriter); - sqlite3_free(hint.a); + tdsqlite3_free(pWriter); + tdsqlite3_free(hint.a); return rc; } @@ -161251,11 +183773,14 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ ** Convert the text beginning at *pz into an integer and return ** its value. Advance *pz to point to the first character past ** the integer. +** +** This function used for parameters to merge= and incrmerge= +** commands. */ static int fts3Getint(const char **pz){ const char *z = *pz; int i = 0; - while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0'; + while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0'; *pz = z; return i; } @@ -161274,7 +183799,7 @@ static int fts3DoIncrmerge( const char *zParam /* Nul-terminated string containing "A,B" */ ){ int rc; - int nMin = (FTS3_MERGE_COUNT / 2); + int nMin = (MergeCount(p) / 2); int nMerge = 0; const char *z = zParam; @@ -161294,12 +183819,12 @@ static int fts3DoIncrmerge( rc = SQLITE_OK; if( !p->bHasStat ){ assert( p->bFts4==0 ); - sqlite3Fts3CreateStatTable(&rc, p); + tdsqlite3Fts3CreateStatTable(&rc, p); } if( rc==SQLITE_OK ){ - rc = sqlite3Fts3Incrmerge(p, nMerge, nMin); + rc = tdsqlite3Fts3Incrmerge(p, nMerge, nMin); } - sqlite3Fts3SegmentsClose(p); + tdsqlite3Fts3SegmentsClose(p); } return rc; } @@ -161317,22 +183842,22 @@ static int fts3DoAutoincrmerge( const char *zParam /* Nul-terminated string containing boolean */ ){ int rc = SQLITE_OK; - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; p->nAutoincrmerge = fts3Getint(&zParam); - if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){ + if( p->nAutoincrmerge==1 || p->nAutoincrmerge>MergeCount(p) ){ p->nAutoincrmerge = 8; } if( !p->bHasStat ){ assert( p->bFts4==0 ); - sqlite3Fts3CreateStatTable(&rc, p); + tdsqlite3Fts3CreateStatTable(&rc, p); if( rc ) return rc; } rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); if( rc ) return rc; - sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); - sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge); - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); + tdsqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); + tdsqlite3_bind_int(pStmt, 2, p->nAutoincrmerge); + tdsqlite3_step(pStmt); + rc = tdsqlite3_reset(pStmt); return rc; } @@ -161388,35 +183913,39 @@ static u64 fts3ChecksumIndex( filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; filter.flags |= FTS3_SEGMENT_SCAN; - rc = sqlite3Fts3SegReaderCursor( + rc = tdsqlite3Fts3SegReaderCursor( p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr ); if( rc==SQLITE_OK ){ - rc = sqlite3Fts3SegReaderStart(p, &csr, &filter); + rc = tdsqlite3Fts3SegReaderStart(p, &csr, &filter); } if( rc==SQLITE_OK ){ - while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){ + while( SQLITE_ROW==(rc = tdsqlite3Fts3SegReaderStep(p, &csr)) ){ char *pCsr = csr.aDoclist; char *pEnd = &pCsr[csr.nDoclist]; i64 iDocid = 0; i64 iCol = 0; - i64 iPos = 0; + u64 iPos = 0; - pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid); + pCsr += tdsqlite3Fts3GetVarint(pCsr, &iDocid); while( pCsr<pEnd ){ - i64 iVal = 0; - pCsr += sqlite3Fts3GetVarint(pCsr, &iVal); + u64 iVal = 0; + pCsr += tdsqlite3Fts3GetVarintU(pCsr, &iVal); if( pCsr<pEnd ){ if( iVal==0 || iVal==1 ){ iCol = 0; iPos = 0; if( iVal ){ - pCsr += sqlite3Fts3GetVarint(pCsr, &iCol); + pCsr += tdsqlite3Fts3GetVarint(pCsr, &iCol); }else{ - pCsr += sqlite3Fts3GetVarint(pCsr, &iVal); - iDocid += iVal; + pCsr += tdsqlite3Fts3GetVarintU(pCsr, &iVal); + if( p->bDescIdx ){ + iDocid = (i64)((u64)iDocid - iVal); + }else{ + iDocid = (i64)((u64)iDocid + iVal); + } } }else{ iPos += (iVal - 2); @@ -161429,7 +183958,7 @@ static u64 fts3ChecksumIndex( } } } - sqlite3Fts3SegReaderFinish(&csr); + tdsqlite3Fts3SegReaderFinish(&csr); *pRc = rc; return cksum; @@ -161448,51 +183977,50 @@ static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){ int rc = SQLITE_OK; /* Return code */ u64 cksum1 = 0; /* Checksum based on FTS index contents */ u64 cksum2 = 0; /* Checksum based on %_content contents */ - sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */ + tdsqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */ /* This block calculates the checksum according to the FTS index. */ rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); if( rc==SQLITE_OK ){ int rc2; - sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid); - sqlite3_bind_int(pAllLangid, 2, p->nIndex); - while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){ - int iLangid = sqlite3_column_int(pAllLangid, 0); + tdsqlite3_bind_int(pAllLangid, 1, p->iPrevLangid); + tdsqlite3_bind_int(pAllLangid, 2, p->nIndex); + while( rc==SQLITE_OK && tdsqlite3_step(pAllLangid)==SQLITE_ROW ){ + int iLangid = tdsqlite3_column_int(pAllLangid, 0); int i; for(i=0; i<p->nIndex; i++){ cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc); } } - rc2 = sqlite3_reset(pAllLangid); + rc2 = tdsqlite3_reset(pAllLangid); if( rc==SQLITE_OK ) rc = rc2; } /* This block calculates the checksum according to the %_content table */ if( rc==SQLITE_OK ){ - sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule; - sqlite3_stmt *pStmt = 0; + tdsqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule; + tdsqlite3_stmt *pStmt = 0; char *zSql; - zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); + zSql = tdsqlite3_mprintf("SELECT %s" , p->zReadExprlist); if( !zSql ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); + rc = tdsqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + tdsqlite3_free(zSql); } - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - i64 iDocid = sqlite3_column_int64(pStmt, 0); + while( rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pStmt) ){ + i64 iDocid = tdsqlite3_column_int64(pStmt, 0); int iLang = langidFromSelect(p, pStmt); int iCol; for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){ if( p->abNotindexed[iCol]==0 ){ - const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1); - int nText = sqlite3_column_bytes(pStmt, iCol+1); - sqlite3_tokenizer_cursor *pT = 0; + const char *zText = (const char *)tdsqlite3_column_text(pStmt, iCol+1); + tdsqlite3_tokenizer_cursor *pT = 0; - rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT); + rc = tdsqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, -1, &pT); while( rc==SQLITE_OK ){ char const *zToken; /* Buffer containing token */ int nToken = 0; /* Number of bytes in token */ @@ -161520,7 +184048,7 @@ static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){ } } - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); } *pbOk = (cksum1==cksum2); @@ -161576,47 +184104,53 @@ static int fts3DoIntegrityCheck( ** Argument pVal contains the result of <expr>. Currently the only ** meaningful value to insert is the text 'optimize'. */ -static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){ - int rc; /* Return Code */ - const char *zVal = (const char *)sqlite3_value_text(pVal); - int nVal = sqlite3_value_bytes(pVal); +static int fts3SpecialInsert(Fts3Table *p, tdsqlite3_value *pVal){ + int rc = SQLITE_ERROR; /* Return Code */ + const char *zVal = (const char *)tdsqlite3_value_text(pVal); + int nVal = tdsqlite3_value_bytes(pVal); if( !zVal ){ return SQLITE_NOMEM; - }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){ + }else if( nVal==8 && 0==tdsqlite3_strnicmp(zVal, "optimize", 8) ){ rc = fts3DoOptimize(p, 0); - }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){ + }else if( nVal==7 && 0==tdsqlite3_strnicmp(zVal, "rebuild", 7) ){ rc = fts3DoRebuild(p); - }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){ + }else if( nVal==15 && 0==tdsqlite3_strnicmp(zVal, "integrity-check", 15) ){ rc = fts3DoIntegrityCheck(p); - }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){ + }else if( nVal>6 && 0==tdsqlite3_strnicmp(zVal, "merge=", 6) ){ rc = fts3DoIncrmerge(p, &zVal[6]); - }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){ + }else if( nVal>10 && 0==tdsqlite3_strnicmp(zVal, "automerge=", 10) ){ rc = fts3DoAutoincrmerge(p, &zVal[10]); -#ifdef SQLITE_TEST - }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){ - p->nNodeSize = atoi(&zVal[9]); - rc = SQLITE_OK; - }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ - p->nMaxPendingData = atoi(&zVal[11]); - rc = SQLITE_OK; - }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){ - p->bNoIncrDoclist = atoi(&zVal[21]); - rc = SQLITE_OK; -#endif +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) }else{ - rc = SQLITE_ERROR; + int v; + if( nVal>9 && 0==tdsqlite3_strnicmp(zVal, "nodesize=", 9) ){ + v = atoi(&zVal[9]); + if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v; + rc = SQLITE_OK; + }else if( nVal>11 && 0==tdsqlite3_strnicmp(zVal, "maxpending=", 9) ){ + v = atoi(&zVal[11]); + if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v; + rc = SQLITE_OK; + }else if( nVal>21 && 0==tdsqlite3_strnicmp(zVal,"test-no-incr-doclist=",21) ){ + p->bNoIncrDoclist = atoi(&zVal[21]); + rc = SQLITE_OK; + }else if( nVal>11 && 0==tdsqlite3_strnicmp(zVal,"mergecount=",11) ){ + v = atoi(&zVal[11]); + if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v; + rc = SQLITE_OK; + } +#endif } - return rc; } #ifndef SQLITE_DISABLE_FTS4_DEFERRED /* ** Delete all cached deferred doclists. Deferred doclists are cached -** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function. +** (allocated) by the tdsqlite3Fts3CacheDeferredDoclists() function. */ -SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){ +SQLITE_PRIVATE void tdsqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){ Fts3DeferredToken *pDef; for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){ fts3PendingListDelete(pDef->pList); @@ -161626,15 +184160,15 @@ SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){ /* ** Free all entries in the pCsr->pDeffered list. Entries are added to -** this list using sqlite3Fts3DeferToken(). +** this list using tdsqlite3Fts3DeferToken(). */ -SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){ +SQLITE_PRIVATE void tdsqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){ Fts3DeferredToken *pDef; Fts3DeferredToken *pNext; for(pDef=pCsr->pDeferred; pDef; pDef=pNext){ pNext = pDef->pNext; fts3PendingListDelete(pDef->pList); - sqlite3_free(pDef); + tdsqlite3_free(pDef); } pCsr->pDeferred = 0; } @@ -161647,26 +184181,26 @@ SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){ ** included, except that it only contains entries for a single row of the ** table, not for all rows. */ -SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){ +SQLITE_PRIVATE int tdsqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){ int rc = SQLITE_OK; /* Return code */ if( pCsr->pDeferred ){ int i; /* Used to iterate through table columns */ - sqlite3_int64 iDocid; /* Docid of the row pCsr points to */ + tdsqlite3_int64 iDocid; /* Docid of the row pCsr points to */ Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */ Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; - sqlite3_tokenizer *pT = p->pTokenizer; - sqlite3_tokenizer_module const *pModule = pT->pModule; + tdsqlite3_tokenizer *pT = p->pTokenizer; + tdsqlite3_tokenizer_module const *pModule = pT->pModule; assert( pCsr->isRequireSeek==0 ); - iDocid = sqlite3_column_int64(pCsr->pStmt, 0); + iDocid = tdsqlite3_column_int64(pCsr->pStmt, 0); for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){ if( p->abNotindexed[i]==0 ){ - const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1); - sqlite3_tokenizer_cursor *pTC = 0; + const char *zText = (const char *)tdsqlite3_column_text(pCsr->pStmt, i+1); + tdsqlite3_tokenizer_cursor *pTC = 0; - rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC); + rc = tdsqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC); while( rc==SQLITE_OK ){ char const *zToken; /* Buffer containing token */ int nToken = 0; /* Number of bytes in token */ @@ -161700,14 +184234,14 @@ SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){ return rc; } -SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList( +SQLITE_PRIVATE int tdsqlite3Fts3DeferredTokenList( Fts3DeferredToken *p, char **ppData, int *pnData ){ char *pRet; int nSkip; - sqlite3_int64 dummy; + tdsqlite3_int64 dummy; *ppData = 0; *pnData = 0; @@ -161716,10 +184250,10 @@ SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList( return SQLITE_OK; } - pRet = (char *)sqlite3_malloc(p->pList->nData); + pRet = (char *)tdsqlite3_malloc(p->pList->nData); if( !pRet ) return SQLITE_NOMEM; - nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy); + nSkip = tdsqlite3Fts3GetVarint(p->pList->aData, &dummy); *pnData = p->pList->nData - nSkip; *ppData = pRet; @@ -161730,13 +184264,13 @@ SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList( /* ** Add an entry for token pToken to the pCsr->pDeferred list. */ -SQLITE_PRIVATE int sqlite3Fts3DeferToken( +SQLITE_PRIVATE int tdsqlite3Fts3DeferToken( Fts3Cursor *pCsr, /* Fts3 table cursor */ Fts3PhraseToken *pToken, /* Token to defer */ int iCol /* Column that token must appear in (or -1) */ ){ Fts3DeferredToken *pDeferred; - pDeferred = sqlite3_malloc(sizeof(*pDeferred)); + pDeferred = tdsqlite3_malloc(sizeof(*pDeferred)); if( !pDeferred ){ return SQLITE_NOMEM; } @@ -161760,7 +184294,7 @@ SQLITE_PRIVATE int sqlite3Fts3DeferToken( */ static int fts3DeleteByRowid( Fts3Table *p, - sqlite3_value *pRowid, + tdsqlite3_value *pRowid, int *pnChng, /* IN/OUT: Decrement if row is deleted */ u32 *aSzDel ){ @@ -161807,15 +184341,14 @@ static int fts3DeleteByRowid( ** ** */ -SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( - sqlite3_vtab *pVtab, /* FTS3 vtab object */ +SQLITE_PRIVATE int tdsqlite3Fts3UpdateMethod( + tdsqlite3_vtab *pVtab, /* FTS3 vtab object */ int nArg, /* Size of argument array */ - sqlite3_value **apVal, /* Array of arguments */ + tdsqlite3_value **apVal, /* Array of arguments */ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ ){ Fts3Table *p = (Fts3Table *)pVtab; int rc = SQLITE_OK; /* Return Code */ - int isRemove = 0; /* True for an UPDATE or DELETE */ u32 *aSzIns = 0; /* Sizes of inserted documents */ u32 *aSzDel = 0; /* Sizes of deleted documents */ int nChng = 0; /* Net change in number of documents */ @@ -161836,20 +184369,20 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( ** INSERT INTO xyz(xyz) VALUES('command'); */ if( nArg>1 - && sqlite3_value_type(apVal[0])==SQLITE_NULL - && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL + && tdsqlite3_value_type(apVal[0])==SQLITE_NULL + && tdsqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){ rc = fts3SpecialInsert(p, apVal[p->nColumn+2]); goto update_out; } - if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){ + if( nArg>1 && tdsqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){ rc = SQLITE_CONSTRAINT; goto update_out; } /* Allocate space to hold the change in document sizes */ - aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 ); + aSzDel = tdsqlite3_malloc64(sizeof(aSzDel[0])*((tdsqlite3_int64)p->nColumn+1)*2); if( aSzDel==0 ){ rc = SQLITE_NOMEM; goto update_out; @@ -161871,14 +184404,14 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( */ if( nArg>1 && p->zContentTbl==0 ){ /* Find the value object that holds the new rowid value. */ - sqlite3_value *pNewRowid = apVal[3+p->nColumn]; - if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){ + tdsqlite3_value *pNewRowid = apVal[3+p->nColumn]; + if( tdsqlite3_value_type(pNewRowid)==SQLITE_NULL ){ pNewRowid = apVal[1]; } - if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( - sqlite3_value_type(apVal[0])==SQLITE_NULL - || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid) + if( tdsqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( + tdsqlite3_value_type(apVal[0])==SQLITE_NULL + || tdsqlite3_value_int64(apVal[0])!=tdsqlite3_value_int64(pNewRowid) )){ /* The new rowid is not NULL (in this case the rowid will be ** automatically assigned and there is no chance of a conflict), and @@ -161897,7 +184430,7 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( ** invoked, it will delete zero rows (since no row will have ** docid=$pNewRowid if $pNewRowid is not an integer value). */ - if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){ + if( tdsqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){ rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel); }else{ rc = fts3InsertData(p, apVal, pRowid); @@ -161910,22 +184443,21 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( } /* If this is a DELETE or UPDATE operation, remove the old record. */ - if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ - assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER ); + if( tdsqlite3_value_type(apVal[0])!=SQLITE_NULL ){ + assert( tdsqlite3_value_type(apVal[0])==SQLITE_INTEGER ); rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel); - isRemove = 1; } /* If this is an INSERT or UPDATE operation, insert the new record. */ if( nArg>1 && rc==SQLITE_OK ){ - int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]); + int iLangid = tdsqlite3_value_int(apVal[2 + p->nColumn + 2]); if( bInsertDone==0 ){ rc = fts3InsertData(p, apVal, pRowid); if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){ rc = FTS_CORRUPT_VTAB; } } - if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){ + if( rc==SQLITE_OK ){ rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid); } if( rc==SQLITE_OK ){ @@ -161943,8 +184475,8 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( } update_out: - sqlite3_free(aSzDel); - sqlite3Fts3SegmentsClose(p); + tdsqlite3_free(aSzDel); + tdsqlite3Fts3SegmentsClose(p); return rc; } @@ -161953,20 +184485,20 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( ** merge all segments in the database (including the new segment, if ** there was any data to flush) into a single segment. */ -SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){ +SQLITE_PRIVATE int tdsqlite3Fts3Optimize(Fts3Table *p){ int rc; - rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0); + rc = tdsqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0); if( rc==SQLITE_OK ){ rc = fts3DoOptimize(p, 1); if( rc==SQLITE_OK || rc==SQLITE_DONE ){ - int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); + int rc2 = tdsqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); if( rc2!=SQLITE_OK ) rc = rc2; }else{ - sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0); - sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); + tdsqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0); + tdsqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); } } - sqlite3Fts3SegmentsClose(p); + tdsqlite3Fts3SegmentsClose(p); return rc; } @@ -162065,7 +184597,7 @@ struct MatchInfo { Fts3Cursor *pCursor; /* FTS3 Cursor */ int nCol; /* Number of columns in table */ int nPhrase; /* Number of matchable phrases in query */ - sqlite3_int64 nDoc; /* Number of docs in database */ + tdsqlite3_int64 nDoc; /* Number of docs in database */ char flag; u32 *aMatchinfo; /* Pre-allocated buffer */ }; @@ -162104,17 +184636,19 @@ struct StrBuffer { /* ** Allocate a two-slot MatchinfoBuffer object. */ -static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){ +static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){ MatchinfoBuffer *pRet; - int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer); - int nStr = (int)strlen(zMatchinfo); + tdsqlite3_int64 nByte = sizeof(u32) * (2*(tdsqlite3_int64)nElem + 1) + + sizeof(MatchinfoBuffer); + tdsqlite3_int64 nStr = strlen(zMatchinfo); - pRet = sqlite3_malloc(nByte + nStr+1); + pRet = tdsqlite3_malloc64(nByte + nStr+1); if( pRet ){ memset(pRet, 0, nByte); pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet; - pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1); - pRet->nElem = nElem; + pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + + sizeof(u32)*((int)nElem+1); + pRet->nElem = (int)nElem; pRet->zMatchinfo = ((char*)pRet) + nByte; memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1); pRet->aRef[0] = 1; @@ -162136,7 +184670,7 @@ static void fts3MIBufferFree(void *p){ } if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){ - sqlite3_free(pBuf); + tdsqlite3_free(pBuf); } } @@ -162154,9 +184688,9 @@ static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){ aOut = &p->aMatchinfo[p->nElem+2]; xRet = fts3MIBufferFree; }else{ - aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32)); + aOut = (u32*)tdsqlite3_malloc64(p->nElem * sizeof(u32)); if( aOut ){ - xRet = sqlite3_free; + xRet = tdsqlite3_free; if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32)); } } @@ -162173,12 +184707,12 @@ static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){ /* ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew() */ -SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){ +SQLITE_PRIVATE void tdsqlite3Fts3MIBufferFree(MatchinfoBuffer *p){ if( p ){ assert( p->aRef[0]==1 ); p->aRef[0] = 0; if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){ - sqlite3_free(p); + tdsqlite3_free(p); } } } @@ -162405,11 +184939,12 @@ static void fts3SnippetDetails( char *pCsr = pPhrase->pTail; int iCsr = pPhrase->iTail; - while( iCsr<(iStart+pIter->nSnippet) ){ + while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){ int j; - u64 mPhrase = (u64)1 << i; + u64 mPhrase = (u64)1 << (i%64); u64 mPos = (u64)1 << (iCsr - iStart); - assert( iCsr>=iStart ); + assert( iCsr>=iStart && (iCsr - iStart)<=64 ); + assert( i>=0 ); if( (mCover|mCovered)&mPhrase ){ iScore++; }else{ @@ -162445,17 +184980,20 @@ static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){ int rc; pPhrase->nToken = pExpr->pPhrase->nToken; - rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr); + rc = tdsqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr); assert( rc==SQLITE_OK || pCsr==0 ); if( pCsr ){ int iFirst = 0; pPhrase->pList = pCsr; fts3GetDeltaPosition(&pCsr, &iFirst); - assert( iFirst>=0 ); - pPhrase->pHead = pCsr; - pPhrase->pTail = pCsr; - pPhrase->iHead = iFirst; - pPhrase->iTail = iFirst; + if( iFirst<0 ){ + rc = FTS_CORRUPT_VTAB; + }else{ + pPhrase->pHead = pCsr; + pPhrase->pTail = pCsr; + pPhrase->iHead = iFirst; + pPhrase->iTail = iFirst; + } }else{ assert( rc!=SQLITE_OK || ( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 @@ -162492,7 +185030,7 @@ static int fts3BestSnippet( int rc; /* Return Code */ int nList; /* Number of phrases in expression */ SnippetIter sIter; /* Iterates through snippet candidates */ - int nByte; /* Number of bytes of space to allocate */ + tdsqlite3_int64 nByte; /* Number of bytes of space to allocate */ int iBestScore = -1; /* Best snippet score found so far */ int i; /* Loop counter */ @@ -162510,7 +185048,7 @@ static int fts3BestSnippet( ** the required space using malloc(). */ nByte = sizeof(SnippetPhrase) * nList; - sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte); + sIter.aPhrase = (SnippetPhrase *)tdsqlite3_malloc64(nByte); if( !sIter.aPhrase ){ return SQLITE_NOMEM; } @@ -162530,7 +185068,7 @@ static int fts3BestSnippet( /* Set the *pmSeen output variable. */ for(i=0; i<nList; i++){ if( sIter.aPhrase[i].pHead ){ - *pmSeen |= (u64)1 << i; + *pmSeen |= (u64)1 << (i%64); } } @@ -162555,7 +185093,7 @@ static int fts3BestSnippet( *piScore = iBestScore; } - sqlite3_free(sIter.aPhrase); + tdsqlite3_free(sIter.aPhrase); return rc; } @@ -162580,8 +185118,8 @@ static int fts3StringAppend( ** appended data. */ if( pStr->n+nAppend+1>=pStr->nAlloc ){ - int nAlloc = pStr->nAlloc+nAppend+100; - char *zNew = sqlite3_realloc(pStr->z, nAlloc); + tdsqlite3_int64 nAlloc = pStr->nAlloc+(tdsqlite3_int64)nAppend+100; + char *zNew = tdsqlite3_realloc64(pStr->z, nAlloc); if( !zNew ){ return SQLITE_NOMEM; } @@ -162636,6 +185174,7 @@ static int fts3SnippetShift( for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++); for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++); + assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 ); nDesired = (nLeft-nRight)/2; /* Ideally, the start of the snippet should be pushed forward in the @@ -162649,14 +185188,14 @@ static int fts3SnippetShift( int nShift; /* Number of tokens to shift snippet by */ int iCurrent = 0; /* Token counter */ int rc; /* Return Code */ - sqlite3_tokenizer_module *pMod; - sqlite3_tokenizer_cursor *pC; - pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; + tdsqlite3_tokenizer_module *pMod; + tdsqlite3_tokenizer_cursor *pC; + pMod = (tdsqlite3_tokenizer_module *)pTab->pTokenizer->pModule; /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired) ** or more tokens in zDoc/nDoc. */ - rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC); + rc = tdsqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC); if( rc!=SQLITE_OK ){ return rc; } @@ -162703,21 +185242,21 @@ static int fts3SnippetText( int iPos = pFragment->iPos; /* First token of snippet */ u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */ int iCol = pFragment->iCol+1; /* Query column to extract text from */ - sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */ - sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */ + tdsqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */ + tdsqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */ - zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol); + zDoc = (const char *)tdsqlite3_column_text(pCsr->pStmt, iCol); if( zDoc==0 ){ - if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){ + if( tdsqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){ return SQLITE_NOMEM; } return SQLITE_OK; } - nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol); + nDoc = tdsqlite3_column_bytes(pCsr->pStmt, iCol); /* Open a token cursor on the document. */ - pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; - rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC); + pMod = (tdsqlite3_tokenizer_module *)pTab->pTokenizer->pModule; + rc = tdsqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC); if( rc!=SQLITE_OK ){ return rc; } @@ -162828,7 +185367,7 @@ static int fts3ColumnlistCount(char **ppCollist){ /* ** This function gathers 'y' or 'b' data for a single phrase. */ -static void fts3ExprLHits( +static int fts3ExprLHits( Fts3Expr *pExpr, /* Phrase expression node */ MatchInfo *p /* Matchinfo context */ ){ @@ -162858,25 +185397,29 @@ static void fts3ExprLHits( if( *pIter!=0x01 ) break; pIter++; pIter += fts3GetVarint32(pIter, &iCol); + if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB; } + return SQLITE_OK; } /* ** Gather the results for matchinfo directives 'y' and 'b'. */ -static void fts3ExprLHitGather( +static int fts3ExprLHitGather( Fts3Expr *pExpr, MatchInfo *p ){ + int rc = SQLITE_OK; assert( (pExpr->pLeft==0)==(pExpr->pRight==0) ); if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){ if( pExpr->pLeft ){ - fts3ExprLHitGather(pExpr->pLeft, p); - fts3ExprLHitGather(pExpr->pRight, p); + rc = fts3ExprLHitGather(pExpr->pLeft, p); + if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p); }else{ - fts3ExprLHits(pExpr, p); + rc = fts3ExprLHits(pExpr, p); } } + return rc; } /* @@ -162912,7 +185455,7 @@ static int fts3ExprGlobalHitsCb( void *pCtx /* Pointer to MatchInfo structure */ ){ MatchInfo *p = (MatchInfo *)pCtx; - return sqlite3Fts3EvalPhraseStats( + return tdsqlite3Fts3EvalPhraseStats( p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol] ); } @@ -162934,7 +185477,7 @@ static int fts3ExprLocalHitsCb( for(i=0; i<p->nCol && rc==SQLITE_OK; i++){ char *pCsr; - rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr); + rc = tdsqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr); if( pCsr ){ p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr); }else{ @@ -162962,12 +185505,12 @@ static int fts3MatchinfoCheck( ){ return SQLITE_OK; } - sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg); + tdsqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg); return SQLITE_ERROR; } -static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ - int nVal; /* Number of integers output by cArg */ +static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ + size_t nVal; /* Number of integers output by cArg */ switch( cArg ){ case FTS3_MATCHINFO_NDOC: @@ -163001,27 +185544,39 @@ static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ static int fts3MatchinfoSelectDoctotal( Fts3Table *pTab, - sqlite3_stmt **ppStmt, - sqlite3_int64 *pnDoc, - const char **paLen + tdsqlite3_stmt **ppStmt, + tdsqlite3_int64 *pnDoc, + const char **paLen, + const char **ppEnd ){ - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; const char *a; - sqlite3_int64 nDoc; + const char *pEnd; + tdsqlite3_int64 nDoc; + int n; + if( !*ppStmt ){ - int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt); + int rc = tdsqlite3Fts3SelectDoctotal(pTab, ppStmt); if( rc!=SQLITE_OK ) return rc; } pStmt = *ppStmt; - assert( sqlite3_data_count(pStmt)==1 ); + assert( tdsqlite3_data_count(pStmt)==1 ); - a = sqlite3_column_blob(pStmt, 0); - a += sqlite3Fts3GetVarint(a, &nDoc); - if( nDoc==0 ) return FTS_CORRUPT_VTAB; - *pnDoc = (u32)nDoc; + n = tdsqlite3_column_bytes(pStmt, 0); + a = tdsqlite3_column_blob(pStmt, 0); + if( a==0 ){ + return FTS_CORRUPT_VTAB; + } + pEnd = a + n; + a += tdsqlite3Fts3GetVarintBounded(a, pEnd, &nDoc); + if( nDoc<=0 || a>pEnd ){ + return FTS_CORRUPT_VTAB; + } + *pnDoc = nDoc; if( paLen ) *paLen = a; + if( ppEnd ) *ppEnd = pEnd; return SQLITE_OK; } @@ -163062,10 +185617,10 @@ static int fts3MatchinfoLcsCb( */ static int fts3LcsIteratorAdvance(LcsIterator *pIter){ char *pRead = pIter->pRead; - sqlite3_int64 iRead; + tdsqlite3_int64 iRead; int rc = 0; - pRead += sqlite3Fts3GetVarint(pRead, &iRead); + pRead += tdsqlite3Fts3GetVarint(pRead, &iRead); if( iRead==0 || iRead==1 ){ pRead = 0; rc = 1; @@ -163093,11 +185648,12 @@ static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){ int i; int iCol; int nToken = 0; + int rc = SQLITE_OK; /* Allocate and populate the array of LcsIterator objects. The array ** contains one element for each matchable phrase in the query. **/ - aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase); + aIter = tdsqlite3_malloc64(sizeof(LcsIterator) * pCsr->nPhrase); if( !aIter ) return SQLITE_NOMEM; memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase); (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter); @@ -163113,13 +185669,16 @@ static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){ int nLive = 0; /* Number of iterators in aIter not at EOF */ for(i=0; i<pInfo->nPhrase; i++){ - int rc; LcsIterator *pIt = &aIter[i]; - rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead); - if( rc!=SQLITE_OK ) return rc; + rc = tdsqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead); + if( rc!=SQLITE_OK ) goto matchinfo_lcs_out; if( pIt->pRead ){ pIt->iPos = pIt->iPosOffset; - fts3LcsIteratorAdvance(&aIter[i]); + fts3LcsIteratorAdvance(pIt); + if( pIt->pRead==0 ){ + rc = FTS_CORRUPT_VTAB; + goto matchinfo_lcs_out; + } nLive++; } } @@ -163151,8 +185710,9 @@ static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){ pInfo->aMatchinfo[iCol] = nLcs; } - sqlite3_free(aIter); - return SQLITE_OK; + matchinfo_lcs_out: + tdsqlite3_free(aIter); + return rc; } /* @@ -163181,7 +185741,7 @@ static int fts3MatchinfoValues( int rc = SQLITE_OK; int i; Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - sqlite3_stmt *pSelect = 0; + tdsqlite3_stmt *pSelect = 0; for(i=0; rc==SQLITE_OK && zArg[i]; i++){ pInfo->flag = zArg[i]; @@ -163196,24 +185756,29 @@ static int fts3MatchinfoValues( case FTS3_MATCHINFO_NDOC: if( bGlobal ){ - sqlite3_int64 nDoc = 0; - rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0); + tdsqlite3_int64 nDoc = 0; + rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0, 0); pInfo->aMatchinfo[0] = (u32)nDoc; } break; case FTS3_MATCHINFO_AVGLENGTH: if( bGlobal ){ - sqlite3_int64 nDoc; /* Number of rows in table */ + tdsqlite3_int64 nDoc; /* Number of rows in table */ const char *a; /* Aggregate column length array */ + const char *pEnd; /* First byte past end of length array */ - rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a); + rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a, &pEnd); if( rc==SQLITE_OK ){ int iCol; for(iCol=0; iCol<pInfo->nCol; iCol++){ u32 iVal; - sqlite3_int64 nToken; - a += sqlite3Fts3GetVarint(a, &nToken); + tdsqlite3_int64 nToken; + a += tdsqlite3Fts3GetVarint(a, &nToken); + if( a>pEnd ){ + rc = SQLITE_CORRUPT_VTAB; + break; + } iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc); pInfo->aMatchinfo[iCol] = iVal; } @@ -163222,18 +185787,23 @@ static int fts3MatchinfoValues( break; case FTS3_MATCHINFO_LENGTH: { - sqlite3_stmt *pSelectDocsize = 0; - rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize); + tdsqlite3_stmt *pSelectDocsize = 0; + rc = tdsqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize); if( rc==SQLITE_OK ){ int iCol; - const char *a = sqlite3_column_blob(pSelectDocsize, 0); + const char *a = tdsqlite3_column_blob(pSelectDocsize, 0); + const char *pEnd = a + tdsqlite3_column_bytes(pSelectDocsize, 0); for(iCol=0; iCol<pInfo->nCol; iCol++){ - sqlite3_int64 nToken; - a += sqlite3Fts3GetVarint(a, &nToken); + tdsqlite3_int64 nToken; + a += tdsqlite3Fts3GetVarintBounded(a, pEnd, &nToken); + if( a>pEnd ){ + rc = SQLITE_CORRUPT_VTAB; + break; + } pInfo->aMatchinfo[iCol] = (u32)nToken; } } - sqlite3_reset(pSelectDocsize); + tdsqlite3_reset(pSelectDocsize); break; } @@ -163246,9 +185816,9 @@ static int fts3MatchinfoValues( case FTS3_MATCHINFO_LHITS_BM: case FTS3_MATCHINFO_LHITS: { - int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32); + size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32); memset(pInfo->aMatchinfo, 0, nZero); - fts3ExprLHitGather(pCsr->pExpr, pInfo); + rc = fts3ExprLHitGather(pCsr->pExpr, pInfo); break; } @@ -163260,11 +185830,11 @@ static int fts3MatchinfoValues( if( rc!=SQLITE_OK ) break; if( bGlobal ){ if( pCsr->pDeferred ){ - rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0); + rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc,0,0); if( rc!=SQLITE_OK ) break; } rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo); - sqlite3Fts3EvalTestDeferred(pCsr, &rc); + tdsqlite3Fts3EvalTestDeferred(pCsr, &rc); if( rc!=SQLITE_OK ) break; } (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo); @@ -163275,7 +185845,7 @@ static int fts3MatchinfoValues( pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]); } - sqlite3_reset(pSelect); + tdsqlite3_reset(pSelect); return rc; } @@ -163285,7 +185855,7 @@ static int fts3MatchinfoValues( ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32). */ static void fts3GetMatchinfo( - sqlite3_context *pCtx, /* Return results here */ + tdsqlite3_context *pCtx, /* Return results here */ Fts3Cursor *pCsr, /* FTS3 Cursor object */ const char *zArg /* Second argument to matchinfo() function */ ){ @@ -163305,7 +185875,7 @@ static void fts3GetMatchinfo( ** cache does not match the format string for this request, discard ** the cached data. */ if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){ - sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); + tdsqlite3Fts3MIBufferFree(pCsr->pMIBuffer); pCsr->pMIBuffer = 0; } @@ -163315,7 +185885,7 @@ static void fts3GetMatchinfo( ** initialize those elements that are constant for every row. */ if( pCsr->pMIBuffer==0 ){ - int nMatchinfo = 0; /* Number of u32 elements in match-info */ + size_t nMatchinfo = 0; /* Number of u32 elements in match-info */ int i; /* Used to iterate through zArg */ /* Determine the number of phrases in the query */ @@ -163326,8 +185896,8 @@ static void fts3GetMatchinfo( for(i=0; zArg[i]; i++){ char *zErr = 0; if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){ - sqlite3_result_error(pCtx, zErr, -1); - sqlite3_free(zErr); + tdsqlite3_result_error(pCtx, zErr, -1); + tdsqlite3_free(zErr); return; } nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]); @@ -163358,19 +185928,19 @@ static void fts3GetMatchinfo( } if( rc!=SQLITE_OK ){ - sqlite3_result_error_code(pCtx, rc); + tdsqlite3_result_error_code(pCtx, rc); if( xDestroyOut ) xDestroyOut(aOut); }else{ int n = pCsr->pMIBuffer->nElem * sizeof(u32); - sqlite3_result_blob(pCtx, aOut, n, xDestroyOut); + tdsqlite3_result_blob(pCtx, aOut, n, xDestroyOut); } } /* ** Implementation of snippet() function. */ -SQLITE_PRIVATE void sqlite3Fts3Snippet( - sqlite3_context *pCtx, /* SQLite function call context */ +SQLITE_PRIVATE void tdsqlite3Fts3Snippet( + tdsqlite3_context *pCtx, /* SQLite function call context */ Fts3Cursor *pCsr, /* Cursor object */ const char *zStart, /* Snippet start text - "<b>" */ const char *zEnd, /* Snippet end text - "</b>" */ @@ -163396,10 +185966,14 @@ SQLITE_PRIVATE void sqlite3Fts3Snippet( int nFToken = -1; /* Number of tokens in each fragment */ if( !pCsr->pExpr ){ - sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); + tdsqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); return; } + /* Limit the snippet length to 64 tokens. */ + if( nToken<-64 ) nToken = -64; + if( nToken>+64 ) nToken = +64; + for(nSnippet=1; 1; nSnippet++){ int iSnip; /* Loop counter 0..nSnippet-1 */ @@ -163458,12 +186032,12 @@ SQLITE_PRIVATE void sqlite3Fts3Snippet( } snippet_out: - sqlite3Fts3SegmentsClose(pTab); + tdsqlite3Fts3SegmentsClose(pTab); if( rc!=SQLITE_OK ){ - sqlite3_result_error_code(pCtx, rc); - sqlite3_free(res.z); + tdsqlite3_result_error_code(pCtx, rc); + tdsqlite3_free(res.z); }else{ - sqlite3_result_text(pCtx, res.z, -1, sqlite3_free); + tdsqlite3_result_text(pCtx, res.z, -1, tdsqlite3_free); } } @@ -163481,12 +186055,12 @@ struct TermOffsetCtx { Fts3Cursor *pCsr; int iCol; /* Column of table to populate aTerm for */ int iTerm; - sqlite3_int64 iDocid; + tdsqlite3_int64 iDocid; TermOffset *aTerm; }; /* -** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets(). +** This function is an fts3ExprIterate() callback used by tdsqlite3Fts3Offsets(). */ static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){ TermOffsetCtx *p = (TermOffsetCtx *)ctx; @@ -163497,11 +186071,11 @@ static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){ int rc; UNUSED_PARAMETER(iPhrase); - rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList); + rc = tdsqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList); nTerm = pExpr->pPhrase->nToken; if( pList ){ fts3GetDeltaPosition(&pList, &iPos); - assert( iPos>=0 ); + assert_fts3_nc( iPos>=0 ); } for(iTerm=0; iTerm<nTerm; iTerm++){ @@ -163517,12 +186091,12 @@ static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){ /* ** Implementation of offsets() function. */ -SQLITE_PRIVATE void sqlite3Fts3Offsets( - sqlite3_context *pCtx, /* SQLite function call context */ +SQLITE_PRIVATE void tdsqlite3Fts3Offsets( + tdsqlite3_context *pCtx, /* SQLite function call context */ Fts3Cursor *pCsr /* Cursor object */ ){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule; + tdsqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule; int rc; /* Return Code */ int nToken; /* Number of tokens in query */ int iCol; /* Column currently being processed */ @@ -163530,7 +186104,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */ if( !pCsr->pExpr ){ - sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); + tdsqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); return; } @@ -163542,7 +186116,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( if( rc!=SQLITE_OK ) goto offsets_out; /* Allocate the array of TermOffset iterators. */ - sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken); + sCtx.aTerm = (TermOffset *)tdsqlite3_malloc64(sizeof(TermOffset)*nToken); if( 0==sCtx.aTerm ){ rc = SQLITE_NOMEM; goto offsets_out; @@ -163554,7 +186128,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( ** string-buffer res for each column. */ for(iCol=0; iCol<pTab->nColumn; iCol++){ - sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */ + tdsqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */ const char *ZDUMMY; /* Dummy argument used with xNext() */ int NDUMMY = 0; /* Dummy argument used with xNext() */ int iStart = 0; @@ -163577,10 +186151,10 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM ** to the caller. */ - zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1); - nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1); + zDoc = (const char *)tdsqlite3_column_text(pCsr->pStmt, iCol+1); + nDoc = tdsqlite3_column_bytes(pCsr->pStmt, iCol+1); if( zDoc==0 ){ - if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){ + if( tdsqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){ continue; } rc = SQLITE_NOMEM; @@ -163588,7 +186162,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( } /* Initialize a tokenizer iterator to iterate through column iCol. */ - rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, + rc = tdsqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc, nDoc, &pC ); if( rc!=SQLITE_OK ) goto offsets_out; @@ -163611,7 +186185,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( /* All offsets for this column have been gathered. */ rc = SQLITE_DONE; }else{ - assert( iCurrent<=iMinPos ); + assert_fts3_nc( iCurrent<=iMinPos ); if( 0==(0xFE&*pTerm->pList) ){ pTerm->pList = 0; }else{ @@ -163622,7 +186196,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( } if( rc==SQLITE_OK ){ char aBuffer[64]; - sqlite3_snprintf(sizeof(aBuffer), aBuffer, + tdsqlite3_snprintf(sizeof(aBuffer), aBuffer, "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart ); rc = fts3StringAppend(&res, aBuffer, -1); @@ -163640,14 +186214,14 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( } offsets_out: - sqlite3_free(sCtx.aTerm); + tdsqlite3_free(sCtx.aTerm); assert( rc!=SQLITE_DONE ); - sqlite3Fts3SegmentsClose(pTab); + tdsqlite3Fts3SegmentsClose(pTab); if( rc!=SQLITE_OK ){ - sqlite3_result_error_code(pCtx, rc); - sqlite3_free(res.z); + tdsqlite3_result_error_code(pCtx, rc); + tdsqlite3_free(res.z); }else{ - sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free); + tdsqlite3_result_text(pCtx, res.z, res.n-1, tdsqlite3_free); } return; } @@ -163655,8 +186229,8 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( /* ** Implementation of matchinfo() function. */ -SQLITE_PRIVATE void sqlite3Fts3Matchinfo( - sqlite3_context *pContext, /* Function call context */ +SQLITE_PRIVATE void tdsqlite3Fts3Matchinfo( + tdsqlite3_context *pContext, /* Function call context */ Fts3Cursor *pCsr, /* FTS3 table cursor */ const char *zArg /* Second arg to matchinfo() function */ ){ @@ -163670,12 +186244,12 @@ SQLITE_PRIVATE void sqlite3Fts3Matchinfo( } if( !pCsr->pExpr ){ - sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC); + tdsqlite3_result_blob(pContext, "", 0, SQLITE_STATIC); return; }else{ /* Retrieve matchinfo() data. */ fts3GetMatchinfo(pContext, pCsr, zFormat); - sqlite3Fts3SegmentsClose(pTab); + tdsqlite3Fts3SegmentsClose(pTab); } } @@ -163712,12 +186286,12 @@ SQLITE_PRIVATE void sqlite3Fts3Matchinfo( /* ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied -** from the sqlite3 source file utf.c. If this file is compiled as part +** from the tdsqlite3 source file utf.c. If this file is compiled as part ** of the amalgamation, they are not required. */ #ifndef SQLITE_AMALGAMATION -static const unsigned char sqlite3Utf8Trans1[] = { +static const unsigned char tdsqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, @@ -163731,7 +186305,7 @@ static const unsigned char sqlite3Utf8Trans1[] = { #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ - c = sqlite3Utf8Trans1[c-0xc0]; \ + c = tdsqlite3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ @@ -163766,14 +186340,14 @@ typedef struct unicode_tokenizer unicode_tokenizer; typedef struct unicode_cursor unicode_cursor; struct unicode_tokenizer { - sqlite3_tokenizer base; - int bRemoveDiacritic; + tdsqlite3_tokenizer base; + int eRemoveDiacritic; int nException; int *aiException; }; struct unicode_cursor { - sqlite3_tokenizer_cursor base; + tdsqlite3_tokenizer_cursor base; const unsigned char *aInput; /* Input text being tokenized */ int nInput; /* Size of aInput[] in bytes */ int iOff; /* Current offset within aInput[] */ @@ -163786,11 +186360,11 @@ struct unicode_cursor { /* ** Destroy a tokenizer allocated by unicodeCreate(). */ -static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){ +static int unicodeDestroy(tdsqlite3_tokenizer *pTokenizer){ if( pTokenizer ){ unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer; - sqlite3_free(p->aiException); - sqlite3_free(p); + tdsqlite3_free(p->aiException); + tdsqlite3_free(p); } return SQLITE_OK; } @@ -163802,13 +186376,13 @@ static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){ ** token characters (if bAlnum==1). ** ** For each codepoint in the zIn/nIn string, this function checks if the -** sqlite3FtsUnicodeIsalnum() function already returns the desired result. +** tdsqlite3FtsUnicodeIsalnum() function already returns the desired result. ** If so, no action is taken. Otherwise, the codepoint is added to the ** unicode_tokenizer.aiException[] array. For the purposes of tokenization, -** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all +** the return value of tdsqlite3FtsUnicodeIsalnum() is inverted for all ** codepoints in the aiException[] array. ** -** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic() +** If a standalone diacritic mark (one that tdsqlite3FtsUnicodeIsdiacritic() ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored. ** It is not possible to change the behavior of the tokenizer with respect ** to these codepoints. @@ -163821,16 +186395,16 @@ static int unicodeAddExceptions( ){ const unsigned char *z = (const unsigned char *)zIn; const unsigned char *zTerm = &z[nIn]; - int iCode; + unsigned int iCode; int nEntry = 0; assert( bAlnum==0 || bAlnum==1 ); while( z<zTerm ){ READ_UTF8(z, zTerm, iCode); - assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); - if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum - && sqlite3FtsUnicodeIsdiacritic(iCode)==0 + assert( (tdsqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 ); + if( tdsqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum + && tdsqlite3FtsUnicodeIsdiacritic((int)iCode)==0 ){ nEntry++; } @@ -163840,20 +186414,20 @@ static int unicodeAddExceptions( int *aNew; /* New aiException[] array */ int nNew; /* Number of valid entries in array aNew[] */ - aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int)); + aNew = tdsqlite3_realloc64(p->aiException,(p->nException+nEntry)*sizeof(int)); if( aNew==0 ) return SQLITE_NOMEM; nNew = p->nException; z = (const unsigned char *)zIn; while( z<zTerm ){ READ_UTF8(z, zTerm, iCode); - if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum - && sqlite3FtsUnicodeIsdiacritic(iCode)==0 + if( tdsqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum + && tdsqlite3FtsUnicodeIsdiacritic((int)iCode)==0 ){ int i, j; - for(i=0; i<nNew && aNew[i]<iCode; i++); + for(i=0; i<nNew && aNew[i]<(int)iCode; i++); for(j=nNew; j>i; j--) aNew[j] = aNew[j-1]; - aNew[i] = iCode; + aNew[i] = (int)iCode; nNew++; } } @@ -163893,8 +186467,8 @@ static int unicodeIsException(unicode_tokenizer *p, int iCode){ ** considered a token character (not a separator). */ static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){ - assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); - return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode); + assert( (tdsqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); + return tdsqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode); } /* @@ -163903,26 +186477,29 @@ static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){ static int unicodeCreate( int nArg, /* Size of array argv[] */ const char * const *azArg, /* Tokenizer creation arguments */ - sqlite3_tokenizer **pp /* OUT: New tokenizer handle */ + tdsqlite3_tokenizer **pp /* OUT: New tokenizer handle */ ){ unicode_tokenizer *pNew; /* New tokenizer object */ int i; int rc = SQLITE_OK; - pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer)); + pNew = (unicode_tokenizer *) tdsqlite3_malloc(sizeof(unicode_tokenizer)); if( pNew==NULL ) return SQLITE_NOMEM; memset(pNew, 0, sizeof(unicode_tokenizer)); - pNew->bRemoveDiacritic = 1; + pNew->eRemoveDiacritic = 1; for(i=0; rc==SQLITE_OK && i<nArg; i++){ const char *z = azArg[i]; int n = (int)strlen(z); if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){ - pNew->bRemoveDiacritic = 1; + pNew->eRemoveDiacritic = 1; } else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){ - pNew->bRemoveDiacritic = 0; + pNew->eRemoveDiacritic = 0; + } + else if( n==19 && memcmp("remove_diacritics=2", z, 19)==0 ){ + pNew->eRemoveDiacritic = 2; } else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){ rc = unicodeAddExceptions(pNew, 1, &z[11], n-11); @@ -163937,10 +186514,10 @@ static int unicodeCreate( } if( rc!=SQLITE_OK ){ - unicodeDestroy((sqlite3_tokenizer *)pNew); + unicodeDestroy((tdsqlite3_tokenizer *)pNew); pNew = 0; } - *pp = (sqlite3_tokenizer *)pNew; + *pp = (tdsqlite3_tokenizer *)pNew; return rc; } @@ -163951,14 +186528,14 @@ static int unicodeCreate( ** *ppCursor. */ static int unicodeOpen( - sqlite3_tokenizer *p, /* The tokenizer */ + tdsqlite3_tokenizer *p, /* The tokenizer */ const char *aInput, /* Input string */ int nInput, /* Size of string aInput in bytes */ - sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */ + tdsqlite3_tokenizer_cursor **pp /* OUT: New cursor object */ ){ unicode_cursor *pCsr; - pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor)); + pCsr = (unicode_cursor *)tdsqlite3_malloc(sizeof(unicode_cursor)); if( pCsr==0 ){ return SQLITE_NOMEM; } @@ -163982,10 +186559,10 @@ static int unicodeOpen( ** Close a tokenization cursor previously opened by a call to ** simpleOpen() above. */ -static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){ +static int unicodeClose(tdsqlite3_tokenizer_cursor *pCursor){ unicode_cursor *pCsr = (unicode_cursor *) pCursor; - sqlite3_free(pCsr->zToken); - sqlite3_free(pCsr); + tdsqlite3_free(pCsr->zToken); + tdsqlite3_free(pCsr); return SQLITE_OK; } @@ -163994,7 +186571,7 @@ static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){ ** have been opened by a prior call to simpleOpen(). */ static int unicodeNext( - sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */ + tdsqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */ const char **paToken, /* OUT: Token text */ int *pnToken, /* OUT: Number of bytes at *paToken */ int *piStart, /* OUT: Starting offset of token */ @@ -164003,7 +186580,7 @@ static int unicodeNext( ){ unicode_cursor *pCsr = (unicode_cursor *)pC; unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer); - int iCode = 0; + unsigned int iCode = 0; char *zOut; const unsigned char *z = &pCsr->aInput[pCsr->iOff]; const unsigned char *zStart = z; @@ -164015,7 +186592,7 @@ static int unicodeNext( ** the input. */ while( z<zTerm ){ READ_UTF8(z, zTerm, iCode); - if( unicodeIsAlnum(p, iCode) ) break; + if( unicodeIsAlnum(p, (int)iCode) ) break; zStart = z; } if( zStart>=zTerm ) return SQLITE_DONE; @@ -164026,7 +186603,7 @@ static int unicodeNext( /* Grow the output buffer if required. */ if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){ - char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64); + char *zNew = tdsqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64); if( !zNew ) return SQLITE_NOMEM; zOut = &zNew[zOut - pCsr->zToken]; pCsr->zToken = zNew; @@ -164035,7 +186612,7 @@ static int unicodeNext( /* Write the folded case of the last character read to the output */ zEnd = z; - iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic); + iOut = tdsqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic); if( iOut ){ WRITE_UTF8(zOut, iOut); } @@ -164043,8 +186620,8 @@ static int unicodeNext( /* If the cursor is not at EOF, read the next character */ if( z>=zTerm ) break; READ_UTF8(z, zTerm, iCode); - }while( unicodeIsAlnum(p, iCode) - || sqlite3FtsUnicodeIsdiacritic(iCode) + }while( unicodeIsAlnum(p, (int)iCode) + || tdsqlite3FtsUnicodeIsdiacritic((int)iCode) ); /* Set the output variables and return. */ @@ -164058,11 +186635,11 @@ static int unicodeNext( } /* -** Set *ppModule to a pointer to the sqlite3_tokenizer_module +** Set *ppModule to a pointer to the tdsqlite3_tokenizer_module ** structure for the unicode tokenizer. */ -SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){ - static const sqlite3_tokenizer_module module = { +SQLITE_PRIVATE void tdsqlite3Fts3UnicodeTokenizer(tdsqlite3_tokenizer_module const **ppModule){ + static const tdsqlite3_tokenizer_module module = { 0, unicodeCreate, unicodeDestroy, @@ -164080,7 +186657,7 @@ SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const * /************** End of fts3_unicode.c ****************************************/ /************** Begin file fts3_unicode2.c ***********************************/ /* -** 2012 May 25 +** 2012-05-25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: @@ -164108,7 +186685,7 @@ SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const * ** The results are undefined if the value passed to this function ** is less than zero. */ -SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){ +SQLITE_PRIVATE int tdsqlite3FtsUnicodeIsalnum(int c){ /* Each unsigned integer in the following array corresponds to a contiguous ** range of unicode codepoints that are not either letters or numbers (i.e. ** codepoints for which this function should return 0). @@ -164208,9 +186785,9 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){ 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001, }; - if( c<128 ){ - return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 ); - }else if( c<(1<<22) ){ + if( (unsigned int)c<128 ){ + return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 ); + }else if( (unsigned int)c<(1<<22) ){ unsigned int key = (((unsigned int)c)<<10) | 0x000003FF; int iRes = 0; int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; @@ -164240,32 +186817,48 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){ ** E"). The resuls of passing a codepoint that corresponds to an ** uppercase letter are undefined. */ -static int remove_diacritic(int c){ +static int remove_diacritic(int c, int bComplex){ unsigned short aDia[] = { 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995, 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286, 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732, 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336, - 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928, - 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234, - 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504, - 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529, - 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, - 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, - 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, - 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, - 62924, 63050, 63082, 63274, 63390, + 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896, + 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106, + 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344, + 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198, + 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468, + 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704, + 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914, + 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218, + 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554, + 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766, + 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118, + 63182, 63242, 63274, 63310, 63368, 63390, }; - char aChar[] = { - '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c', - 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r', - 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o', - 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r', - 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0', - '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h', - 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't', - 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a', - 'e', 'i', 'o', 'u', 'y', +#define HIBIT ((unsigned char)0x80) + unsigned char aChar[] = { + '\0', 'a', 'c', 'e', 'i', 'n', + 'o', 'u', 'y', 'y', 'a', 'c', + 'd', 'e', 'e', 'g', 'h', 'i', + 'j', 'k', 'l', 'n', 'o', 'r', + 's', 't', 'u', 'u', 'w', 'y', + 'z', 'o', 'u', 'a', 'i', 'o', + 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o', + 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a', + 'e', 'i', 'o', 'r', 'u', 's', + 't', 'h', 'a', 'e', 'o'|HIBIT, 'o', + 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', 'a', 'b', + 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT, + 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT, + 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n', + 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's', + 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w', + 'w', 'x', 'y', 'z', 'h', 't', + 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT, + 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT, + 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y', }; unsigned int key = (((unsigned int)c)<<3) | 0x00000007; @@ -164282,7 +186875,8 @@ static int remove_diacritic(int c){ } } assert( key>=aDia[iRes] ); - return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]); + if( bComplex==0 && (aChar[iRes] & 0x80) ) return c; + return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F); } @@ -164290,13 +186884,13 @@ static int remove_diacritic(int c){ ** Return true if the argument interpreted as a unicode codepoint ** is a diacritical modifier character. */ -SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){ +SQLITE_PRIVATE int tdsqlite3FtsUnicodeIsdiacritic(int c){ unsigned int mask0 = 0x08029FDF; unsigned int mask1 = 0x000361F8; if( c<768 || c>817 ) return 0; return (c < 768+32) ? - (mask0 & (1 << (c-768))) : - (mask1 & (1 << (c-768-32))); + (mask0 & ((unsigned int)1 << (c-768))) : + (mask1 & ((unsigned int)1 << (c-768-32))); } @@ -164309,7 +186903,7 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){ ** The results are undefined if the value passed to this function ** is less than zero. */ -SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ +SQLITE_PRIVATE int tdsqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){ /* Each entry in the following array defines a rule for folding a range ** of codepoints to lower case. The rule applies to a range of nRange ** codepoints starting at codepoint iCode. @@ -164403,16 +186997,17 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ int ret = c; - assert( c>=0 ); assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 ); if( c<128 ){ if( c>='A' && c<='Z' ) ret = c + ('a' - 'A'); }else if( c<65536 ){ + const struct TableEntry *p; int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; int iLo = 0; int iRes = -1; + assert( c>aEntry[0].iCode ); while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; int cmp = (c - aEntry[iTest].iCode); @@ -164423,17 +187018,17 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ iHi = iTest-1; } } - assert( iRes<0 || c>=aEntry[iRes].iCode ); - if( iRes>=0 ){ - const struct TableEntry *p = &aEntry[iRes]; - if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){ - ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF; - assert( ret>0 ); - } + assert( iRes>=0 && c>=aEntry[iRes].iCode ); + p = &aEntry[iRes]; + if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){ + ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF; + assert( ret>0 ); } - if( bRemoveDiacritic ) ret = remove_diacritic(ret); + if( eRemoveDiacritic ){ + ret = remove_diacritic(ret, eRemoveDiacritic==2); + } } else if( c>=66560 && c<66600 ){ @@ -164446,6 +187041,2634 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */ /************** End of fts3_unicode2.c ***************************************/ +/************** Begin file json1.c *******************************************/ +/* +** 2015-08-12 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This SQLite extension implements JSON functions. The interface is +** modeled after MySQL JSON functions: +** +** https://dev.mysql.com/doc/refman/5.7/en/json.html +** +** For the time being, all JSON is stored as pure text. (We might add +** a JSONB type in the future which stores a binary encoding of JSON in +** a BLOB, but there is no support for JSONB in the current implementation. +** This implementation parses JSON text at 250 MB/s, so it is hard to see +** how JSONB might improve on that.) +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) +#if !defined(SQLITEINT_H) +/* #include "tdsqlite3ext.h" */ +#endif +SQLITE_EXTENSION_INIT1 +/* #include <assert.h> */ +/* #include <string.h> */ +/* #include <stdlib.h> */ +/* #include <stdarg.h> */ + +/* Mark a function parameter as unused, to suppress nuisance compiler +** warnings. */ +#ifndef UNUSED_PARAM +# define UNUSED_PARAM(X) (void)(X) +#endif + +#ifndef LARGEST_INT64 +# define LARGEST_INT64 (0xffffffff|(((tdsqlite3_int64)0x7fffffff)<<32)) +# define SMALLEST_INT64 (((tdsqlite3_int64)-1) - LARGEST_INT64) +#endif + +/* +** Versions of isspace(), isalnum() and isdigit() to which it is safe +** to pass signed char values. +*/ +#ifdef tdsqlite3Isdigit + /* Use the SQLite core versions if this routine is part of the + ** SQLite amalgamation */ +# define safe_isdigit(x) tdsqlite3Isdigit(x) +# define safe_isalnum(x) tdsqlite3Isalnum(x) +# define safe_isxdigit(x) tdsqlite3Isxdigit(x) +#else + /* Use the standard library for separate compilation */ +#include <ctype.h> /* amalgamator: keep */ +# define safe_isdigit(x) isdigit((unsigned char)(x)) +# define safe_isalnum(x) isalnum((unsigned char)(x)) +# define safe_isxdigit(x) isxdigit((unsigned char)(x)) +#endif + +/* +** Growing our own isspace() routine this way is twice as fast as +** the library isspace() function, resulting in a 7% overall performance +** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os). +*/ +static const char jsonIsSpace[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +}; +#define safe_isspace(x) (jsonIsSpace[(unsigned char)x]) + +#ifndef SQLITE_AMALGAMATION + /* Unsigned integer types. These are already defined in the sqliteInt.h, + ** but the definitions need to be repeated for separate compilation. */ + typedef tdsqlite3_uint64 u64; + typedef unsigned int u32; + typedef unsigned short int u16; + typedef unsigned char u8; +#endif + +/* Objects */ +typedef struct JsonString JsonString; +typedef struct JsonNode JsonNode; +typedef struct JsonParse JsonParse; + +/* An instance of this object represents a JSON string +** under construction. Really, this is a generic string accumulator +** that can be and is used to create strings other than JSON. +*/ +struct JsonString { + tdsqlite3_context *pCtx; /* Function context - put error messages here */ + char *zBuf; /* Append JSON content here */ + u64 nAlloc; /* Bytes of storage available in zBuf[] */ + u64 nUsed; /* Bytes of zBuf[] currently used */ + u8 bStatic; /* True if zBuf is static space */ + u8 bErr; /* True if an error has been encountered */ + char zSpace[100]; /* Initial static space */ +}; + +/* JSON type values +*/ +#define JSON_NULL 0 +#define JSON_TRUE 1 +#define JSON_FALSE 2 +#define JSON_INT 3 +#define JSON_REAL 4 +#define JSON_STRING 5 +#define JSON_ARRAY 6 +#define JSON_OBJECT 7 + +/* The "subtype" set for JSON values */ +#define JSON_SUBTYPE 74 /* Ascii for "J" */ + +/* +** Names of the various JSON types: +*/ +static const char * const jsonType[] = { + "null", "true", "false", "integer", "real", "text", "array", "object" +}; + +/* Bit values for the JsonNode.jnFlag field +*/ +#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */ +#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */ +#define JNODE_REMOVE 0x04 /* Do not output */ +#define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */ +#define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */ +#define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */ +#define JNODE_LABEL 0x40 /* Is a label of an object */ + + +/* A single node of parsed JSON +*/ +struct JsonNode { + u8 eType; /* One of the JSON_ type values */ + u8 jnFlags; /* JNODE flags */ + u32 n; /* Bytes of content, or number of sub-nodes */ + union { + const char *zJContent; /* Content for INT, REAL, and STRING */ + u32 iAppend; /* More terms for ARRAY and OBJECT */ + u32 iKey; /* Key for ARRAY objects in json_tree() */ + u32 iReplace; /* Replacement content for JNODE_REPLACE */ + JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */ + } u; +}; + +/* A completely parsed JSON string +*/ +struct JsonParse { + u32 nNode; /* Number of slots of aNode[] used */ + u32 nAlloc; /* Number of slots of aNode[] allocated */ + JsonNode *aNode; /* Array of nodes containing the parse */ + const char *zJson; /* Original JSON string */ + u32 *aUp; /* Index of parent of each node */ + u8 oom; /* Set to true if out of memory */ + u8 nErr; /* Number of errors seen */ + u16 iDepth; /* Nesting depth */ + int nJson; /* Length of the zJson string in bytes */ + u32 iHold; /* Replace cache line with the lowest iHold value */ +}; + +/* +** Maximum nesting depth of JSON for this implementation. +** +** This limit is needed to avoid a stack overflow in the recursive +** descent parser. A depth of 2000 is far deeper than any sane JSON +** should go. +*/ +#define JSON_MAX_DEPTH 2000 + +/************************************************************************** +** Utility routines for dealing with JsonString objects +**************************************************************************/ + +/* Set the JsonString object to an empty string +*/ +static void jsonZero(JsonString *p){ + p->zBuf = p->zSpace; + p->nAlloc = sizeof(p->zSpace); + p->nUsed = 0; + p->bStatic = 1; +} + +/* Initialize the JsonString object +*/ +static void jsonInit(JsonString *p, tdsqlite3_context *pCtx){ + p->pCtx = pCtx; + p->bErr = 0; + jsonZero(p); +} + + +/* Free all allocated memory and reset the JsonString object back to its +** initial state. +*/ +static void jsonReset(JsonString *p){ + if( !p->bStatic ) tdsqlite3_free(p->zBuf); + jsonZero(p); +} + + +/* Report an out-of-memory (OOM) condition +*/ +static void jsonOom(JsonString *p){ + p->bErr = 1; + tdsqlite3_result_error_nomem(p->pCtx); + jsonReset(p); +} + +/* Enlarge pJson->zBuf so that it can hold at least N more bytes. +** Return zero on success. Return non-zero on an OOM error +*/ +static int jsonGrow(JsonString *p, u32 N){ + u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10; + char *zNew; + if( p->bStatic ){ + if( p->bErr ) return 1; + zNew = tdsqlite3_malloc64(nTotal); + if( zNew==0 ){ + jsonOom(p); + return SQLITE_NOMEM; + } + memcpy(zNew, p->zBuf, (size_t)p->nUsed); + p->zBuf = zNew; + p->bStatic = 0; + }else{ + zNew = tdsqlite3_realloc64(p->zBuf, nTotal); + if( zNew==0 ){ + jsonOom(p); + return SQLITE_NOMEM; + } + p->zBuf = zNew; + } + p->nAlloc = nTotal; + return SQLITE_OK; +} + +/* Append N bytes from zIn onto the end of the JsonString string. +*/ +static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){ + if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return; + memcpy(p->zBuf+p->nUsed, zIn, N); + p->nUsed += N; +} + +/* Append formatted text (not to exceed N bytes) to the JsonString. +*/ +static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){ + va_list ap; + if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return; + va_start(ap, zFormat); + tdsqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap); + va_end(ap); + p->nUsed += (int)strlen(p->zBuf+p->nUsed); +} + +/* Append a single character +*/ +static void jsonAppendChar(JsonString *p, char c){ + if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return; + p->zBuf[p->nUsed++] = c; +} + +/* Append a comma separator to the output buffer, if the previous +** character is not '[' or '{'. +*/ +static void jsonAppendSeparator(JsonString *p){ + char c; + if( p->nUsed==0 ) return; + c = p->zBuf[p->nUsed-1]; + if( c!='[' && c!='{' ) jsonAppendChar(p, ','); +} + +/* Append the N-byte string in zIn to the end of the JsonString string +** under construction. Enclose the string in "..." and escape +** any double-quotes or backslash characters contained within the +** string. +*/ +static void jsonAppendString(JsonString *p, const char *zIn, u32 N){ + u32 i; + if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return; + p->zBuf[p->nUsed++] = '"'; + for(i=0; i<N; i++){ + unsigned char c = ((unsigned const char*)zIn)[i]; + if( c=='"' || c=='\\' ){ + json_simple_escape: + if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return; + p->zBuf[p->nUsed++] = '\\'; + }else if( c<=0x1f ){ + static const char aSpecial[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + assert( sizeof(aSpecial)==32 ); + assert( aSpecial['\b']=='b' ); + assert( aSpecial['\f']=='f' ); + assert( aSpecial['\n']=='n' ); + assert( aSpecial['\r']=='r' ); + assert( aSpecial['\t']=='t' ); + if( aSpecial[c] ){ + c = aSpecial[c]; + goto json_simple_escape; + } + if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return; + p->zBuf[p->nUsed++] = '\\'; + p->zBuf[p->nUsed++] = 'u'; + p->zBuf[p->nUsed++] = '0'; + p->zBuf[p->nUsed++] = '0'; + p->zBuf[p->nUsed++] = '0' + (c>>4); + c = "0123456789abcdef"[c&0xf]; + } + p->zBuf[p->nUsed++] = c; + } + p->zBuf[p->nUsed++] = '"'; + assert( p->nUsed<p->nAlloc ); +} + +/* +** Append a function parameter value to the JSON string under +** construction. +*/ +static void jsonAppendValue( + JsonString *p, /* Append to this JSON string */ + tdsqlite3_value *pValue /* Value to append */ +){ + switch( tdsqlite3_value_type(pValue) ){ + case SQLITE_NULL: { + jsonAppendRaw(p, "null", 4); + break; + } + case SQLITE_INTEGER: + case SQLITE_FLOAT: { + const char *z = (const char*)tdsqlite3_value_text(pValue); + u32 n = (u32)tdsqlite3_value_bytes(pValue); + jsonAppendRaw(p, z, n); + break; + } + case SQLITE_TEXT: { + const char *z = (const char*)tdsqlite3_value_text(pValue); + u32 n = (u32)tdsqlite3_value_bytes(pValue); + if( tdsqlite3_value_subtype(pValue)==JSON_SUBTYPE ){ + jsonAppendRaw(p, z, n); + }else{ + jsonAppendString(p, z, n); + } + break; + } + default: { + if( p->bErr==0 ){ + tdsqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1); + p->bErr = 2; + jsonReset(p); + } + break; + } + } +} + + +/* Make the JSON in p the result of the SQL function. +*/ +static void jsonResult(JsonString *p){ + if( p->bErr==0 ){ + tdsqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, + p->bStatic ? SQLITE_TRANSIENT : tdsqlite3_free, + SQLITE_UTF8); + jsonZero(p); + } + assert( p->bStatic ); +} + +/************************************************************************** +** Utility routines for dealing with JsonNode and JsonParse objects +**************************************************************************/ + +/* +** Return the number of consecutive JsonNode slots need to represent +** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and +** OBJECT types, the number might be larger. +** +** Appended elements are not counted. The value returned is the number +** by which the JsonNode counter should increment in order to go to the +** next peer value. +*/ +static u32 jsonNodeSize(JsonNode *pNode){ + return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1; +} + +/* +** Reclaim all memory allocated by a JsonParse object. But do not +** delete the JsonParse object itself. +*/ +static void jsonParseReset(JsonParse *pParse){ + tdsqlite3_free(pParse->aNode); + pParse->aNode = 0; + pParse->nNode = 0; + pParse->nAlloc = 0; + tdsqlite3_free(pParse->aUp); + pParse->aUp = 0; +} + +/* +** Free a JsonParse object that was obtained from tdsqlite3_malloc(). +*/ +static void jsonParseFree(JsonParse *pParse){ + jsonParseReset(pParse); + tdsqlite3_free(pParse); +} + +/* +** Convert the JsonNode pNode into a pure JSON string and +** append to pOut. Subsubstructure is also included. Return +** the number of JsonNode objects that are encoded. +*/ +static void jsonRenderNode( + JsonNode *pNode, /* The node to render */ + JsonString *pOut, /* Write JSON here */ + tdsqlite3_value **aReplace /* Replacement values */ +){ + if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){ + if( pNode->jnFlags & JNODE_REPLACE ){ + jsonAppendValue(pOut, aReplace[pNode->u.iReplace]); + return; + } + pNode = pNode->u.pPatch; + } + switch( pNode->eType ){ + default: { + assert( pNode->eType==JSON_NULL ); + jsonAppendRaw(pOut, "null", 4); + break; + } + case JSON_TRUE: { + jsonAppendRaw(pOut, "true", 4); + break; + } + case JSON_FALSE: { + jsonAppendRaw(pOut, "false", 5); + break; + } + case JSON_STRING: { + if( pNode->jnFlags & JNODE_RAW ){ + jsonAppendString(pOut, pNode->u.zJContent, pNode->n); + break; + } + /* Fall through into the next case */ + } + case JSON_REAL: + case JSON_INT: { + jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n); + break; + } + case JSON_ARRAY: { + u32 j = 1; + jsonAppendChar(pOut, '['); + for(;;){ + while( j<=pNode->n ){ + if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){ + jsonAppendSeparator(pOut); + jsonRenderNode(&pNode[j], pOut, aReplace); + } + j += jsonNodeSize(&pNode[j]); + } + if( (pNode->jnFlags & JNODE_APPEND)==0 ) break; + pNode = &pNode[pNode->u.iAppend]; + j = 1; + } + jsonAppendChar(pOut, ']'); + break; + } + case JSON_OBJECT: { + u32 j = 1; + jsonAppendChar(pOut, '{'); + for(;;){ + while( j<=pNode->n ){ + if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){ + jsonAppendSeparator(pOut); + jsonRenderNode(&pNode[j], pOut, aReplace); + jsonAppendChar(pOut, ':'); + jsonRenderNode(&pNode[j+1], pOut, aReplace); + } + j += 1 + jsonNodeSize(&pNode[j+1]); + } + if( (pNode->jnFlags & JNODE_APPEND)==0 ) break; + pNode = &pNode[pNode->u.iAppend]; + j = 1; + } + jsonAppendChar(pOut, '}'); + break; + } + } +} + +/* +** Return a JsonNode and all its descendents as a JSON string. +*/ +static void jsonReturnJson( + JsonNode *pNode, /* Node to return */ + tdsqlite3_context *pCtx, /* Return value for this function */ + tdsqlite3_value **aReplace /* Array of replacement values */ +){ + JsonString s; + jsonInit(&s, pCtx); + jsonRenderNode(pNode, &s, aReplace); + jsonResult(&s); + tdsqlite3_result_subtype(pCtx, JSON_SUBTYPE); +} + +/* +** Translate a single byte of Hex into an integer. +** This routine only works if h really is a valid hexadecimal +** character: 0..9a..fA..F +*/ +static u8 jsonHexToInt(int h){ + assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); +#ifdef SQLITE_EBCDIC + h += 9*(1&~(h>>4)); +#else + h += 9*(1&(h>>6)); +#endif + return (u8)(h & 0xf); +} + +/* +** Convert a 4-byte hex string into an integer +*/ +static u32 jsonHexToInt4(const char *z){ + u32 v; + assert( safe_isxdigit(z[0]) ); + assert( safe_isxdigit(z[1]) ); + assert( safe_isxdigit(z[2]) ); + assert( safe_isxdigit(z[3]) ); + v = (jsonHexToInt(z[0])<<12) + + (jsonHexToInt(z[1])<<8) + + (jsonHexToInt(z[2])<<4) + + jsonHexToInt(z[3]); + return v; +} + +/* +** Make the JsonNode the return value of the function. +*/ +static void jsonReturn( + JsonNode *pNode, /* Node to return */ + tdsqlite3_context *pCtx, /* Return value for this function */ + tdsqlite3_value **aReplace /* Array of replacement values */ +){ + switch( pNode->eType ){ + default: { + assert( pNode->eType==JSON_NULL ); + tdsqlite3_result_null(pCtx); + break; + } + case JSON_TRUE: { + tdsqlite3_result_int(pCtx, 1); + break; + } + case JSON_FALSE: { + tdsqlite3_result_int(pCtx, 0); + break; + } + case JSON_INT: { + tdsqlite3_int64 i = 0; + const char *z = pNode->u.zJContent; + if( z[0]=='-' ){ z++; } + while( z[0]>='0' && z[0]<='9' ){ + unsigned v = *(z++) - '0'; + if( i>=LARGEST_INT64/10 ){ + if( i>LARGEST_INT64/10 ) goto int_as_real; + if( z[0]>='0' && z[0]<='9' ) goto int_as_real; + if( v==9 ) goto int_as_real; + if( v==8 ){ + if( pNode->u.zJContent[0]=='-' ){ + tdsqlite3_result_int64(pCtx, SMALLEST_INT64); + goto int_done; + }else{ + goto int_as_real; + } + } + } + i = i*10 + v; + } + if( pNode->u.zJContent[0]=='-' ){ i = -i; } + tdsqlite3_result_int64(pCtx, i); + int_done: + break; + int_as_real: /* fall through to real */; + } + case JSON_REAL: { + double r; +#ifdef SQLITE_AMALGAMATION + const char *z = pNode->u.zJContent; + tdsqlite3AtoF(z, &r, tdsqlite3Strlen30(z), SQLITE_UTF8); +#else + r = strtod(pNode->u.zJContent, 0); +#endif + tdsqlite3_result_double(pCtx, r); + break; + } + case JSON_STRING: { +#if 0 /* Never happens because JNODE_RAW is only set by json_set(), + ** json_insert() and json_replace() and those routines do not + ** call jsonReturn() */ + if( pNode->jnFlags & JNODE_RAW ){ + tdsqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n, + SQLITE_TRANSIENT); + }else +#endif + assert( (pNode->jnFlags & JNODE_RAW)==0 ); + if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){ + /* JSON formatted without any backslash-escapes */ + tdsqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2, + SQLITE_TRANSIENT); + }else{ + /* Translate JSON formatted string into raw text */ + u32 i; + u32 n = pNode->n; + const char *z = pNode->u.zJContent; + char *zOut; + u32 j; + zOut = tdsqlite3_malloc( n+1 ); + if( zOut==0 ){ + tdsqlite3_result_error_nomem(pCtx); + break; + } + for(i=1, j=0; i<n-1; i++){ + char c = z[i]; + if( c!='\\' ){ + zOut[j++] = c; + }else{ + c = z[++i]; + if( c=='u' ){ + u32 v = jsonHexToInt4(z+i+1); + i += 4; + if( v==0 ) break; + if( v<=0x7f ){ + zOut[j++] = (char)v; + }else if( v<=0x7ff ){ + zOut[j++] = (char)(0xc0 | (v>>6)); + zOut[j++] = 0x80 | (v&0x3f); + }else{ + u32 vlo; + if( (v&0xfc00)==0xd800 + && i<n-6 + && z[i+1]=='\\' + && z[i+2]=='u' + && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00 + ){ + /* We have a surrogate pair */ + v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000; + i += 6; + zOut[j++] = 0xf0 | (v>>18); + zOut[j++] = 0x80 | ((v>>12)&0x3f); + zOut[j++] = 0x80 | ((v>>6)&0x3f); + zOut[j++] = 0x80 | (v&0x3f); + }else{ + zOut[j++] = 0xe0 | (v>>12); + zOut[j++] = 0x80 | ((v>>6)&0x3f); + zOut[j++] = 0x80 | (v&0x3f); + } + } + }else{ + if( c=='b' ){ + c = '\b'; + }else if( c=='f' ){ + c = '\f'; + }else if( c=='n' ){ + c = '\n'; + }else if( c=='r' ){ + c = '\r'; + }else if( c=='t' ){ + c = '\t'; + } + zOut[j++] = c; + } + } + } + zOut[j] = 0; + tdsqlite3_result_text(pCtx, zOut, j, tdsqlite3_free); + } + break; + } + case JSON_ARRAY: + case JSON_OBJECT: { + jsonReturnJson(pNode, pCtx, aReplace); + break; + } + } +} + +/* Forward reference */ +static int jsonParseAddNode(JsonParse*,u32,u32,const char*); + +/* +** A macro to hint to the compiler that a function should not be +** inlined. +*/ +#if defined(__GNUC__) +# define JSON_NOINLINE __attribute__((noinline)) +#elif defined(_MSC_VER) && _MSC_VER>=1310 +# define JSON_NOINLINE __declspec(noinline) +#else +# define JSON_NOINLINE +#endif + + +static JSON_NOINLINE int jsonParseAddNodeExpand( + JsonParse *pParse, /* Append the node to this object */ + u32 eType, /* Node type */ + u32 n, /* Content size or sub-node count */ + const char *zContent /* Content */ +){ + u32 nNew; + JsonNode *pNew; + assert( pParse->nNode>=pParse->nAlloc ); + if( pParse->oom ) return -1; + nNew = pParse->nAlloc*2 + 10; + pNew = tdsqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew); + if( pNew==0 ){ + pParse->oom = 1; + return -1; + } + pParse->nAlloc = nNew; + pParse->aNode = pNew; + assert( pParse->nNode<pParse->nAlloc ); + return jsonParseAddNode(pParse, eType, n, zContent); +} + +/* +** Create a new JsonNode instance based on the arguments and append that +** instance to the JsonParse. Return the index in pParse->aNode[] of the +** new node, or -1 if a memory allocation fails. +*/ +static int jsonParseAddNode( + JsonParse *pParse, /* Append the node to this object */ + u32 eType, /* Node type */ + u32 n, /* Content size or sub-node count */ + const char *zContent /* Content */ +){ + JsonNode *p; + if( pParse->nNode>=pParse->nAlloc ){ + return jsonParseAddNodeExpand(pParse, eType, n, zContent); + } + p = &pParse->aNode[pParse->nNode]; + p->eType = (u8)eType; + p->jnFlags = 0; + p->n = n; + p->u.zJContent = zContent; + return pParse->nNode++; +} + +/* +** Return true if z[] begins with 4 (or more) hexadecimal digits +*/ +static int jsonIs4Hex(const char *z){ + int i; + for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0; + return 1; +} + +/* +** Parse a single JSON value which begins at pParse->zJson[i]. Return the +** index of the first character past the end of the value parsed. +** +** Return negative for a syntax error. Special cases: return -2 if the +** first non-whitespace character is '}' and return -3 if the first +** non-whitespace character is ']'. +*/ +static int jsonParseValue(JsonParse *pParse, u32 i){ + char c; + u32 j; + int iThis; + int x; + JsonNode *pNode; + const char *z = pParse->zJson; + while( safe_isspace(z[i]) ){ i++; } + if( (c = z[i])=='{' ){ + /* Parse object */ + iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0); + if( iThis<0 ) return -1; + for(j=i+1;;j++){ + while( safe_isspace(z[j]) ){ j++; } + if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1; + x = jsonParseValue(pParse, j); + if( x<0 ){ + pParse->iDepth--; + if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1; + return -1; + } + if( pParse->oom ) return -1; + pNode = &pParse->aNode[pParse->nNode-1]; + if( pNode->eType!=JSON_STRING ) return -1; + pNode->jnFlags |= JNODE_LABEL; + j = x; + while( safe_isspace(z[j]) ){ j++; } + if( z[j]!=':' ) return -1; + j++; + x = jsonParseValue(pParse, j); + pParse->iDepth--; + if( x<0 ) return -1; + j = x; + while( safe_isspace(z[j]) ){ j++; } + c = z[j]; + if( c==',' ) continue; + if( c!='}' ) return -1; + break; + } + pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1; + return j+1; + }else if( c=='[' ){ + /* Parse array */ + iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0); + if( iThis<0 ) return -1; + for(j=i+1;;j++){ + while( safe_isspace(z[j]) ){ j++; } + if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1; + x = jsonParseValue(pParse, j); + pParse->iDepth--; + if( x<0 ){ + if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1; + return -1; + } + j = x; + while( safe_isspace(z[j]) ){ j++; } + c = z[j]; + if( c==',' ) continue; + if( c!=']' ) return -1; + break; + } + pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1; + return j+1; + }else if( c=='"' ){ + /* Parse string */ + u8 jnFlags = 0; + j = i+1; + for(;;){ + c = z[j]; + if( (c & ~0x1f)==0 ){ + /* Control characters are not allowed in strings */ + return -1; + } + if( c=='\\' ){ + c = z[++j]; + if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f' + || c=='n' || c=='r' || c=='t' + || (c=='u' && jsonIs4Hex(z+j+1)) ){ + jnFlags = JNODE_ESCAPE; + }else{ + return -1; + } + }else if( c=='"' ){ + break; + } + j++; + } + jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]); + if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags; + return j+1; + }else if( c=='n' + && strncmp(z+i,"null",4)==0 + && !safe_isalnum(z[i+4]) ){ + jsonParseAddNode(pParse, JSON_NULL, 0, 0); + return i+4; + }else if( c=='t' + && strncmp(z+i,"true",4)==0 + && !safe_isalnum(z[i+4]) ){ + jsonParseAddNode(pParse, JSON_TRUE, 0, 0); + return i+4; + }else if( c=='f' + && strncmp(z+i,"false",5)==0 + && !safe_isalnum(z[i+5]) ){ + jsonParseAddNode(pParse, JSON_FALSE, 0, 0); + return i+5; + }else if( c=='-' || (c>='0' && c<='9') ){ + /* Parse number */ + u8 seenDP = 0; + u8 seenE = 0; + assert( '-' < '0' ); + if( c<='0' ){ + j = c=='-' ? i+1 : i; + if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1; + } + j = i+1; + for(;; j++){ + c = z[j]; + if( c>='0' && c<='9' ) continue; + if( c=='.' ){ + if( z[j-1]=='-' ) return -1; + if( seenDP ) return -1; + seenDP = 1; + continue; + } + if( c=='e' || c=='E' ){ + if( z[j-1]<'0' ) return -1; + if( seenE ) return -1; + seenDP = seenE = 1; + c = z[j+1]; + if( c=='+' || c=='-' ){ + j++; + c = z[j+1]; + } + if( c<'0' || c>'9' ) return -1; + continue; + } + break; + } + if( z[j-1]<'0' ) return -1; + jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT, + j - i, &z[i]); + return j; + }else if( c=='}' ){ + return -2; /* End of {...} */ + }else if( c==']' ){ + return -3; /* End of [...] */ + }else if( c==0 ){ + return 0; /* End of file */ + }else{ + return -1; /* Syntax error */ + } +} + +/* +** Parse a complete JSON string. Return 0 on success or non-zero if there +** are any errors. If an error occurs, free all memory associated with +** pParse. +** +** pParse is uninitialized when this routine is called. +*/ +static int jsonParse( + JsonParse *pParse, /* Initialize and fill this JsonParse object */ + tdsqlite3_context *pCtx, /* Report errors here */ + const char *zJson /* Input JSON text to be parsed */ +){ + int i; + memset(pParse, 0, sizeof(*pParse)); + if( zJson==0 ) return 1; + pParse->zJson = zJson; + i = jsonParseValue(pParse, 0); + if( pParse->oom ) i = -1; + if( i>0 ){ + assert( pParse->iDepth==0 ); + while( safe_isspace(zJson[i]) ) i++; + if( zJson[i] ) i = -1; + } + if( i<=0 ){ + if( pCtx!=0 ){ + if( pParse->oom ){ + tdsqlite3_result_error_nomem(pCtx); + }else{ + tdsqlite3_result_error(pCtx, "malformed JSON", -1); + } + } + jsonParseReset(pParse); + return 1; + } + return 0; +} + +/* Mark node i of pParse as being a child of iParent. Call recursively +** to fill in all the descendants of node i. +*/ +static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){ + JsonNode *pNode = &pParse->aNode[i]; + u32 j; + pParse->aUp[i] = iParent; + switch( pNode->eType ){ + case JSON_ARRAY: { + for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){ + jsonParseFillInParentage(pParse, i+j, i); + } + break; + } + case JSON_OBJECT: { + for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){ + pParse->aUp[i+j] = i; + jsonParseFillInParentage(pParse, i+j+1, i); + } + break; + } + default: { + break; + } + } +} + +/* +** Compute the parentage of all nodes in a completed parse. +*/ +static int jsonParseFindParents(JsonParse *pParse){ + u32 *aUp; + assert( pParse->aUp==0 ); + aUp = pParse->aUp = tdsqlite3_malloc64( sizeof(u32)*pParse->nNode ); + if( aUp==0 ){ + pParse->oom = 1; + return SQLITE_NOMEM; + } + jsonParseFillInParentage(pParse, 0, 0); + return SQLITE_OK; +} + +/* +** Magic number used for the JSON parse cache in tdsqlite3_get_auxdata() +*/ +#define JSON_CACHE_ID (-429938) /* First cache entry */ +#define JSON_CACHE_SZ 4 /* Max number of cache entries */ + +/* +** Obtain a complete parse of the JSON found in the first argument +** of the argv array. Use the tdsqlite3_get_auxdata() cache for this +** parse if it is available. If the cache is not available or if it +** is no longer valid, parse the JSON again and return the new parse, +** and also register the new parse so that it will be available for +** future tdsqlite3_get_auxdata() calls. +*/ +static JsonParse *jsonParseCached( + tdsqlite3_context *pCtx, + tdsqlite3_value **argv, + tdsqlite3_context *pErrCtx +){ + const char *zJson = (const char*)tdsqlite3_value_text(argv[0]); + int nJson = tdsqlite3_value_bytes(argv[0]); + JsonParse *p; + JsonParse *pMatch = 0; + int iKey; + int iMinKey = 0; + u32 iMinHold = 0xffffffff; + u32 iMaxHold = 0; + if( zJson==0 ) return 0; + for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){ + p = (JsonParse*)tdsqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey); + if( p==0 ){ + iMinKey = iKey; + break; + } + if( pMatch==0 + && p->nJson==nJson + && memcmp(p->zJson,zJson,nJson)==0 + ){ + p->nErr = 0; + pMatch = p; + }else if( p->iHold<iMinHold ){ + iMinHold = p->iHold; + iMinKey = iKey; + } + if( p->iHold>iMaxHold ){ + iMaxHold = p->iHold; + } + } + if( pMatch ){ + pMatch->nErr = 0; + pMatch->iHold = iMaxHold+1; + return pMatch; + } + p = tdsqlite3_malloc64( sizeof(*p) + nJson + 1 ); + if( p==0 ){ + tdsqlite3_result_error_nomem(pCtx); + return 0; + } + memset(p, 0, sizeof(*p)); + p->zJson = (char*)&p[1]; + memcpy((char*)p->zJson, zJson, nJson+1); + if( jsonParse(p, pErrCtx, p->zJson) ){ + tdsqlite3_free(p); + return 0; + } + p->nJson = nJson; + p->iHold = iMaxHold+1; + tdsqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p, + (void(*)(void*))jsonParseFree); + return (JsonParse*)tdsqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey); +} + +/* +** Compare the OBJECT label at pNode against zKey,nKey. Return true on +** a match. +*/ +static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){ + if( pNode->jnFlags & JNODE_RAW ){ + if( pNode->n!=nKey ) return 0; + return strncmp(pNode->u.zJContent, zKey, nKey)==0; + }else{ + if( pNode->n!=nKey+2 ) return 0; + return strncmp(pNode->u.zJContent+1, zKey, nKey)==0; + } +} + +/* forward declaration */ +static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**); + +/* +** Search along zPath to find the node specified. Return a pointer +** to that node, or NULL if zPath is malformed or if there is no such +** node. +** +** If pApnd!=0, then try to append new nodes to complete zPath if it is +** possible to do so and if no existing node corresponds to zPath. If +** new nodes are appended *pApnd is set to 1. +*/ +static JsonNode *jsonLookupStep( + JsonParse *pParse, /* The JSON to search */ + u32 iRoot, /* Begin the search at this node */ + const char *zPath, /* The path to search */ + int *pApnd, /* Append nodes to complete path if not NULL */ + const char **pzErr /* Make *pzErr point to any syntax error in zPath */ +){ + u32 i, j, nKey; + const char *zKey; + JsonNode *pRoot = &pParse->aNode[iRoot]; + if( zPath[0]==0 ) return pRoot; + if( pRoot->jnFlags & JNODE_REPLACE ) return 0; + if( zPath[0]=='.' ){ + if( pRoot->eType!=JSON_OBJECT ) return 0; + zPath++; + if( zPath[0]=='"' ){ + zKey = zPath + 1; + for(i=1; zPath[i] && zPath[i]!='"'; i++){} + nKey = i-1; + if( zPath[i] ){ + i++; + }else{ + *pzErr = zPath; + return 0; + } + }else{ + zKey = zPath; + for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){} + nKey = i; + } + if( nKey==0 ){ + *pzErr = zPath; + return 0; + } + j = 1; + for(;;){ + while( j<=pRoot->n ){ + if( jsonLabelCompare(pRoot+j, zKey, nKey) ){ + return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr); + } + j++; + j += jsonNodeSize(&pRoot[j]); + } + if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break; + iRoot += pRoot->u.iAppend; + pRoot = &pParse->aNode[iRoot]; + j = 1; + } + if( pApnd ){ + u32 iStart, iLabel; + JsonNode *pNode; + iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0); + iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey); + zPath += i; + pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr); + if( pParse->oom ) return 0; + if( pNode ){ + pRoot = &pParse->aNode[iRoot]; + pRoot->u.iAppend = iStart - iRoot; + pRoot->jnFlags |= JNODE_APPEND; + pParse->aNode[iLabel].jnFlags |= JNODE_RAW; + } + return pNode; + } + }else if( zPath[0]=='[' ){ + i = 0; + j = 1; + while( safe_isdigit(zPath[j]) ){ + i = i*10 + zPath[j] - '0'; + j++; + } + if( j<2 || zPath[j]!=']' ){ + if( zPath[1]=='#' ){ + JsonNode *pBase = pRoot; + int iBase = iRoot; + if( pRoot->eType!=JSON_ARRAY ) return 0; + for(;;){ + while( j<=pBase->n ){ + if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++; + j += jsonNodeSize(&pBase[j]); + } + if( (pBase->jnFlags & JNODE_APPEND)==0 ) break; + iBase += pBase->u.iAppend; + pBase = &pParse->aNode[iBase]; + j = 1; + } + j = 2; + if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){ + unsigned int x = 0; + j = 3; + do{ + x = x*10 + zPath[j] - '0'; + j++; + }while( safe_isdigit(zPath[j]) ); + if( x>i ) return 0; + i -= x; + } + if( zPath[j]!=']' ){ + *pzErr = zPath; + return 0; + } + }else{ + *pzErr = zPath; + return 0; + } + } + if( pRoot->eType!=JSON_ARRAY ) return 0; + zPath += j + 1; + j = 1; + for(;;){ + while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){ + if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--; + j += jsonNodeSize(&pRoot[j]); + } + if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break; + iRoot += pRoot->u.iAppend; + pRoot = &pParse->aNode[iRoot]; + j = 1; + } + if( j<=pRoot->n ){ + return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr); + } + if( i==0 && pApnd ){ + u32 iStart; + JsonNode *pNode; + iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0); + pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr); + if( pParse->oom ) return 0; + if( pNode ){ + pRoot = &pParse->aNode[iRoot]; + pRoot->u.iAppend = iStart - iRoot; + pRoot->jnFlags |= JNODE_APPEND; + } + return pNode; + } + }else{ + *pzErr = zPath; + } + return 0; +} + +/* +** Append content to pParse that will complete zPath. Return a pointer +** to the inserted node, or return NULL if the append fails. +*/ +static JsonNode *jsonLookupAppend( + JsonParse *pParse, /* Append content to the JSON parse */ + const char *zPath, /* Description of content to append */ + int *pApnd, /* Set this flag to 1 */ + const char **pzErr /* Make this point to any syntax error */ +){ + *pApnd = 1; + if( zPath[0]==0 ){ + jsonParseAddNode(pParse, JSON_NULL, 0, 0); + return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1]; + } + if( zPath[0]=='.' ){ + jsonParseAddNode(pParse, JSON_OBJECT, 0, 0); + }else if( strncmp(zPath,"[0]",3)==0 ){ + jsonParseAddNode(pParse, JSON_ARRAY, 0, 0); + }else{ + return 0; + } + if( pParse->oom ) return 0; + return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr); +} + +/* +** Return the text of a syntax error message on a JSON path. Space is +** obtained from tdsqlite3_malloc(). +*/ +static char *jsonPathSyntaxError(const char *zErr){ + return tdsqlite3_mprintf("JSON path error near '%q'", zErr); +} + +/* +** Do a node lookup using zPath. Return a pointer to the node on success. +** Return NULL if not found or if there is an error. +** +** On an error, write an error message into pCtx and increment the +** pParse->nErr counter. +** +** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if +** nodes are appended. +*/ +static JsonNode *jsonLookup( + JsonParse *pParse, /* The JSON to search */ + const char *zPath, /* The path to search */ + int *pApnd, /* Append nodes to complete path if not NULL */ + tdsqlite3_context *pCtx /* Report errors here, if not NULL */ +){ + const char *zErr = 0; + JsonNode *pNode = 0; + char *zMsg; + + if( zPath==0 ) return 0; + if( zPath[0]!='$' ){ + zErr = zPath; + goto lookup_err; + } + zPath++; + pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr); + if( zErr==0 ) return pNode; + +lookup_err: + pParse->nErr++; + assert( zErr!=0 && pCtx!=0 ); + zMsg = jsonPathSyntaxError(zErr); + if( zMsg ){ + tdsqlite3_result_error(pCtx, zMsg, -1); + tdsqlite3_free(zMsg); + }else{ + tdsqlite3_result_error_nomem(pCtx); + } + return 0; +} + + +/* +** Report the wrong number of arguments for json_insert(), json_replace() +** or json_set(). +*/ +static void jsonWrongNumArgs( + tdsqlite3_context *pCtx, + const char *zFuncName +){ + char *zMsg = tdsqlite3_mprintf("json_%s() needs an odd number of arguments", + zFuncName); + tdsqlite3_result_error(pCtx, zMsg, -1); + tdsqlite3_free(zMsg); +} + +/* +** Mark all NULL entries in the Object passed in as JNODE_REMOVE. +*/ +static void jsonRemoveAllNulls(JsonNode *pNode){ + int i, n; + assert( pNode->eType==JSON_OBJECT ); + n = pNode->n; + for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){ + switch( pNode[i].eType ){ + case JSON_NULL: + pNode[i].jnFlags |= JNODE_REMOVE; + break; + case JSON_OBJECT: + jsonRemoveAllNulls(&pNode[i]); + break; + } + } +} + + +/**************************************************************************** +** SQL functions used for testing and debugging +****************************************************************************/ + +#ifdef SQLITE_DEBUG +/* +** The json_parse(JSON) function returns a string which describes +** a parse of the JSON provided. Or it returns NULL if JSON is not +** well-formed. +*/ +static void jsonParseFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonString s; /* Output string - not real JSON */ + JsonParse x; /* The parse */ + u32 i; + + assert( argc==1 ); + if( jsonParse(&x, ctx, (const char*)tdsqlite3_value_text(argv[0])) ) return; + jsonParseFindParents(&x); + jsonInit(&s, ctx); + for(i=0; i<x.nNode; i++){ + const char *zType; + if( x.aNode[i].jnFlags & JNODE_LABEL ){ + assert( x.aNode[i].eType==JSON_STRING ); + zType = "label"; + }else{ + zType = jsonType[x.aNode[i].eType]; + } + jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d", + i, zType, x.aNode[i].n, x.aUp[i]); + if( x.aNode[i].u.zJContent!=0 ){ + jsonAppendRaw(&s, " ", 1); + jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n); + } + jsonAppendRaw(&s, "\n", 1); + } + jsonParseReset(&x); + jsonResult(&s); +} + +/* +** The json_test1(JSON) function return true (1) if the input is JSON +** text generated by another json function. It returns (0) if the input +** is not known to be JSON. +*/ +static void jsonTest1Func( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + UNUSED_PARAM(argc); + tdsqlite3_result_int(ctx, tdsqlite3_value_subtype(argv[0])==JSON_SUBTYPE); +} +#endif /* SQLITE_DEBUG */ + +/**************************************************************************** +** Scalar SQL function implementations +****************************************************************************/ + +/* +** Implementation of the json_QUOTE(VALUE) function. Return a JSON value +** corresponding to the SQL value input. Mostly this means putting +** double-quotes around strings and returning the unquoted string "null" +** when given a NULL input. +*/ +static void jsonQuoteFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonString jx; + UNUSED_PARAM(argc); + + jsonInit(&jx, ctx); + jsonAppendValue(&jx, argv[0]); + jsonResult(&jx); + tdsqlite3_result_subtype(ctx, JSON_SUBTYPE); +} + +/* +** Implementation of the json_array(VALUE,...) function. Return a JSON +** array that contains all values given in arguments. Or if any argument +** is a BLOB, throw an error. +*/ +static void jsonArrayFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + int i; + JsonString jx; + + jsonInit(&jx, ctx); + jsonAppendChar(&jx, '['); + for(i=0; i<argc; i++){ + jsonAppendSeparator(&jx); + jsonAppendValue(&jx, argv[i]); + } + jsonAppendChar(&jx, ']'); + jsonResult(&jx); + tdsqlite3_result_subtype(ctx, JSON_SUBTYPE); +} + + +/* +** json_array_length(JSON) +** json_array_length(JSON, PATH) +** +** Return the number of elements in the top-level JSON array. +** Return 0 if the input is not a well-formed JSON array. +*/ +static void jsonArrayLengthFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonParse *p; /* The parse */ + tdsqlite3_int64 n = 0; + u32 i; + JsonNode *pNode; + + p = jsonParseCached(ctx, argv, ctx); + if( p==0 ) return; + assert( p->nNode ); + if( argc==2 ){ + const char *zPath = (const char*)tdsqlite3_value_text(argv[1]); + pNode = jsonLookup(p, zPath, 0, ctx); + }else{ + pNode = p->aNode; + } + if( pNode==0 ){ + return; + } + if( pNode->eType==JSON_ARRAY ){ + assert( (pNode->jnFlags & JNODE_APPEND)==0 ); + for(i=1; i<=pNode->n; n++){ + i += jsonNodeSize(&pNode[i]); + } + } + tdsqlite3_result_int64(ctx, n); +} + +/* +** json_extract(JSON, PATH, ...) +** +** Return the element described by PATH. Return NULL if there is no +** PATH element. If there are multiple PATHs, then return a JSON array +** with the result from each path. Throw an error if the JSON or any PATH +** is malformed. +*/ +static void jsonExtractFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonParse *p; /* The parse */ + JsonNode *pNode; + const char *zPath; + JsonString jx; + int i; + + if( argc<2 ) return; + p = jsonParseCached(ctx, argv, ctx); + if( p==0 ) return; + jsonInit(&jx, ctx); + jsonAppendChar(&jx, '['); + for(i=1; i<argc; i++){ + zPath = (const char*)tdsqlite3_value_text(argv[i]); + pNode = jsonLookup(p, zPath, 0, ctx); + if( p->nErr ) break; + if( argc>2 ){ + jsonAppendSeparator(&jx); + if( pNode ){ + jsonRenderNode(pNode, &jx, 0); + }else{ + jsonAppendRaw(&jx, "null", 4); + } + }else if( pNode ){ + jsonReturn(pNode, ctx, 0); + } + } + if( argc>2 && i==argc ){ + jsonAppendChar(&jx, ']'); + jsonResult(&jx); + tdsqlite3_result_subtype(ctx, JSON_SUBTYPE); + } + jsonReset(&jx); +} + +/* This is the RFC 7396 MergePatch algorithm. +*/ +static JsonNode *jsonMergePatch( + JsonParse *pParse, /* The JSON parser that contains the TARGET */ + u32 iTarget, /* Node of the TARGET in pParse */ + JsonNode *pPatch /* The PATCH */ +){ + u32 i, j; + u32 iRoot; + JsonNode *pTarget; + if( pPatch->eType!=JSON_OBJECT ){ + return pPatch; + } + assert( iTarget>=0 && iTarget<pParse->nNode ); + pTarget = &pParse->aNode[iTarget]; + assert( (pPatch->jnFlags & JNODE_APPEND)==0 ); + if( pTarget->eType!=JSON_OBJECT ){ + jsonRemoveAllNulls(pPatch); + return pPatch; + } + iRoot = iTarget; + for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){ + u32 nKey; + const char *zKey; + assert( pPatch[i].eType==JSON_STRING ); + assert( pPatch[i].jnFlags & JNODE_LABEL ); + nKey = pPatch[i].n; + zKey = pPatch[i].u.zJContent; + assert( (pPatch[i].jnFlags & JNODE_RAW)==0 ); + for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){ + assert( pTarget[j].eType==JSON_STRING ); + assert( pTarget[j].jnFlags & JNODE_LABEL ); + assert( (pPatch[i].jnFlags & JNODE_RAW)==0 ); + if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){ + if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break; + if( pPatch[i+1].eType==JSON_NULL ){ + pTarget[j+1].jnFlags |= JNODE_REMOVE; + }else{ + JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]); + if( pNew==0 ) return 0; + pTarget = &pParse->aNode[iTarget]; + if( pNew!=&pTarget[j+1] ){ + pTarget[j+1].u.pPatch = pNew; + pTarget[j+1].jnFlags |= JNODE_PATCH; + } + } + break; + } + } + if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){ + int iStart, iPatch; + iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0); + jsonParseAddNode(pParse, JSON_STRING, nKey, zKey); + iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0); + if( pParse->oom ) return 0; + jsonRemoveAllNulls(pPatch); + pTarget = &pParse->aNode[iTarget]; + pParse->aNode[iRoot].jnFlags |= JNODE_APPEND; + pParse->aNode[iRoot].u.iAppend = iStart - iRoot; + iRoot = iStart; + pParse->aNode[iPatch].jnFlags |= JNODE_PATCH; + pParse->aNode[iPatch].u.pPatch = &pPatch[i+1]; + } + } + return pTarget; +} + +/* +** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON +** object that is the result of running the RFC 7396 MergePatch() algorithm +** on the two arguments. +*/ +static void jsonPatchFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonParse x; /* The JSON that is being patched */ + JsonParse y; /* The patch */ + JsonNode *pResult; /* The result of the merge */ + + UNUSED_PARAM(argc); + if( jsonParse(&x, ctx, (const char*)tdsqlite3_value_text(argv[0])) ) return; + if( jsonParse(&y, ctx, (const char*)tdsqlite3_value_text(argv[1])) ){ + jsonParseReset(&x); + return; + } + pResult = jsonMergePatch(&x, 0, y.aNode); + assert( pResult!=0 || x.oom ); + if( pResult ){ + jsonReturnJson(pResult, ctx, 0); + }else{ + tdsqlite3_result_error_nomem(ctx); + } + jsonParseReset(&x); + jsonParseReset(&y); +} + + +/* +** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON +** object that contains all name/value given in arguments. Or if any name +** is not a string or if any value is a BLOB, throw an error. +*/ +static void jsonObjectFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + int i; + JsonString jx; + const char *z; + u32 n; + + if( argc&1 ){ + tdsqlite3_result_error(ctx, "json_object() requires an even number " + "of arguments", -1); + return; + } + jsonInit(&jx, ctx); + jsonAppendChar(&jx, '{'); + for(i=0; i<argc; i+=2){ + if( tdsqlite3_value_type(argv[i])!=SQLITE_TEXT ){ + tdsqlite3_result_error(ctx, "json_object() labels must be TEXT", -1); + jsonReset(&jx); + return; + } + jsonAppendSeparator(&jx); + z = (const char*)tdsqlite3_value_text(argv[i]); + n = (u32)tdsqlite3_value_bytes(argv[i]); + jsonAppendString(&jx, z, n); + jsonAppendChar(&jx, ':'); + jsonAppendValue(&jx, argv[i+1]); + } + jsonAppendChar(&jx, '}'); + jsonResult(&jx); + tdsqlite3_result_subtype(ctx, JSON_SUBTYPE); +} + + +/* +** json_remove(JSON, PATH, ...) +** +** Remove the named elements from JSON and return the result. malformed +** JSON or PATH arguments result in an error. +*/ +static void jsonRemoveFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonParse x; /* The parse */ + JsonNode *pNode; + const char *zPath; + u32 i; + + if( argc<1 ) return; + if( jsonParse(&x, ctx, (const char*)tdsqlite3_value_text(argv[0])) ) return; + assert( x.nNode ); + for(i=1; i<(u32)argc; i++){ + zPath = (const char*)tdsqlite3_value_text(argv[i]); + if( zPath==0 ) goto remove_done; + pNode = jsonLookup(&x, zPath, 0, ctx); + if( x.nErr ) goto remove_done; + if( pNode ) pNode->jnFlags |= JNODE_REMOVE; + } + if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){ + jsonReturnJson(x.aNode, ctx, 0); + } +remove_done: + jsonParseReset(&x); +} + +/* +** json_replace(JSON, PATH, VALUE, ...) +** +** Replace the value at PATH with VALUE. If PATH does not already exist, +** this routine is a no-op. If JSON or PATH is malformed, throw an error. +*/ +static void jsonReplaceFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonParse x; /* The parse */ + JsonNode *pNode; + const char *zPath; + u32 i; + + if( argc<1 ) return; + if( (argc&1)==0 ) { + jsonWrongNumArgs(ctx, "replace"); + return; + } + if( jsonParse(&x, ctx, (const char*)tdsqlite3_value_text(argv[0])) ) return; + assert( x.nNode ); + for(i=1; i<(u32)argc; i+=2){ + zPath = (const char*)tdsqlite3_value_text(argv[i]); + pNode = jsonLookup(&x, zPath, 0, ctx); + if( x.nErr ) goto replace_err; + if( pNode ){ + pNode->jnFlags |= (u8)JNODE_REPLACE; + pNode->u.iReplace = i + 1; + } + } + if( x.aNode[0].jnFlags & JNODE_REPLACE ){ + tdsqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]); + }else{ + jsonReturnJson(x.aNode, ctx, argv); + } +replace_err: + jsonParseReset(&x); +} + +/* +** json_set(JSON, PATH, VALUE, ...) +** +** Set the value at PATH to VALUE. Create the PATH if it does not already +** exist. Overwrite existing values that do exist. +** If JSON or PATH is malformed, throw an error. +** +** json_insert(JSON, PATH, VALUE, ...) +** +** Create PATH and initialize it to VALUE. If PATH already exists, this +** routine is a no-op. If JSON or PATH is malformed, throw an error. +*/ +static void jsonSetFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonParse x; /* The parse */ + JsonNode *pNode; + const char *zPath; + u32 i; + int bApnd; + int bIsSet = *(int*)tdsqlite3_user_data(ctx); + + if( argc<1 ) return; + if( (argc&1)==0 ) { + jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert"); + return; + } + if( jsonParse(&x, ctx, (const char*)tdsqlite3_value_text(argv[0])) ) return; + assert( x.nNode ); + for(i=1; i<(u32)argc; i+=2){ + zPath = (const char*)tdsqlite3_value_text(argv[i]); + bApnd = 0; + pNode = jsonLookup(&x, zPath, &bApnd, ctx); + if( x.oom ){ + tdsqlite3_result_error_nomem(ctx); + goto jsonSetDone; + }else if( x.nErr ){ + goto jsonSetDone; + }else if( pNode && (bApnd || bIsSet) ){ + pNode->jnFlags |= (u8)JNODE_REPLACE; + pNode->u.iReplace = i + 1; + } + } + if( x.aNode[0].jnFlags & JNODE_REPLACE ){ + tdsqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]); + }else{ + jsonReturnJson(x.aNode, ctx, argv); + } +jsonSetDone: + jsonParseReset(&x); +} + +/* +** json_type(JSON) +** json_type(JSON, PATH) +** +** Return the top-level "type" of a JSON string. Throw an error if +** either the JSON or PATH inputs are not well-formed. +*/ +static void jsonTypeFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonParse *p; /* The parse */ + const char *zPath; + JsonNode *pNode; + + p = jsonParseCached(ctx, argv, ctx); + if( p==0 ) return; + if( argc==2 ){ + zPath = (const char*)tdsqlite3_value_text(argv[1]); + pNode = jsonLookup(p, zPath, 0, ctx); + }else{ + pNode = p->aNode; + } + if( pNode ){ + tdsqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC); + } +} + +/* +** json_valid(JSON) +** +** Return 1 if JSON is a well-formed JSON string according to RFC-7159. +** Return 0 otherwise. +*/ +static void jsonValidFunc( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonParse *p; /* The parse */ + UNUSED_PARAM(argc); + p = jsonParseCached(ctx, argv, 0); + tdsqlite3_result_int(ctx, p!=0); +} + + +/**************************************************************************** +** Aggregate SQL function implementations +****************************************************************************/ +/* +** json_group_array(VALUE) +** +** Return a JSON array composed of all values in the aggregate. +*/ +static void jsonArrayStep( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonString *pStr; + UNUSED_PARAM(argc); + pStr = (JsonString*)tdsqlite3_aggregate_context(ctx, sizeof(*pStr)); + if( pStr ){ + if( pStr->zBuf==0 ){ + jsonInit(pStr, ctx); + jsonAppendChar(pStr, '['); + }else if( pStr->nUsed>1 ){ + jsonAppendChar(pStr, ','); + pStr->pCtx = ctx; + } + jsonAppendValue(pStr, argv[0]); + } +} +static void jsonArrayCompute(tdsqlite3_context *ctx, int isFinal){ + JsonString *pStr; + pStr = (JsonString*)tdsqlite3_aggregate_context(ctx, 0); + if( pStr ){ + pStr->pCtx = ctx; + jsonAppendChar(pStr, ']'); + if( pStr->bErr ){ + if( pStr->bErr==1 ) tdsqlite3_result_error_nomem(ctx); + assert( pStr->bStatic ); + }else if( isFinal ){ + tdsqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, + pStr->bStatic ? SQLITE_TRANSIENT : tdsqlite3_free); + pStr->bStatic = 1; + }else{ + tdsqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT); + pStr->nUsed--; + } + }else{ + tdsqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC); + } + tdsqlite3_result_subtype(ctx, JSON_SUBTYPE); +} +static void jsonArrayValue(tdsqlite3_context *ctx){ + jsonArrayCompute(ctx, 0); +} +static void jsonArrayFinal(tdsqlite3_context *ctx){ + jsonArrayCompute(ctx, 1); +} + +#ifndef SQLITE_OMIT_WINDOWFUNC +/* +** This method works for both json_group_array() and json_group_object(). +** It works by removing the first element of the group by searching forward +** to the first comma (",") that is not within a string and deleting all +** text through that comma. +*/ +static void jsonGroupInverse( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + unsigned int i; + int inStr = 0; + int nNest = 0; + char *z; + char c; + JsonString *pStr; + UNUSED_PARAM(argc); + UNUSED_PARAM(argv); + pStr = (JsonString*)tdsqlite3_aggregate_context(ctx, 0); +#ifdef NEVER + /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will + ** always have been called to initalize it */ + if( NEVER(!pStr) ) return; +#endif + z = pStr->zBuf; + for(i=1; (c = z[i])!=',' || inStr || nNest; i++){ + if( i>=pStr->nUsed ){ + pStr->nUsed = 1; + return; + } + if( c=='"' ){ + inStr = !inStr; + }else if( c=='\\' ){ + i++; + }else if( !inStr ){ + if( c=='{' || c=='[' ) nNest++; + if( c=='}' || c==']' ) nNest--; + } + } + pStr->nUsed -= i; + memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1); +} +#else +# define jsonGroupInverse 0 +#endif + + +/* +** json_group_obj(NAME,VALUE) +** +** Return a JSON object composed of all names and values in the aggregate. +*/ +static void jsonObjectStep( + tdsqlite3_context *ctx, + int argc, + tdsqlite3_value **argv +){ + JsonString *pStr; + const char *z; + u32 n; + UNUSED_PARAM(argc); + pStr = (JsonString*)tdsqlite3_aggregate_context(ctx, sizeof(*pStr)); + if( pStr ){ + if( pStr->zBuf==0 ){ + jsonInit(pStr, ctx); + jsonAppendChar(pStr, '{'); + }else if( pStr->nUsed>1 ){ + jsonAppendChar(pStr, ','); + pStr->pCtx = ctx; + } + z = (const char*)tdsqlite3_value_text(argv[0]); + n = (u32)tdsqlite3_value_bytes(argv[0]); + jsonAppendString(pStr, z, n); + jsonAppendChar(pStr, ':'); + jsonAppendValue(pStr, argv[1]); + } +} +static void jsonObjectCompute(tdsqlite3_context *ctx, int isFinal){ + JsonString *pStr; + pStr = (JsonString*)tdsqlite3_aggregate_context(ctx, 0); + if( pStr ){ + jsonAppendChar(pStr, '}'); + if( pStr->bErr ){ + if( pStr->bErr==1 ) tdsqlite3_result_error_nomem(ctx); + assert( pStr->bStatic ); + }else if( isFinal ){ + tdsqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, + pStr->bStatic ? SQLITE_TRANSIENT : tdsqlite3_free); + pStr->bStatic = 1; + }else{ + tdsqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT); + pStr->nUsed--; + } + }else{ + tdsqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC); + } + tdsqlite3_result_subtype(ctx, JSON_SUBTYPE); +} +static void jsonObjectValue(tdsqlite3_context *ctx){ + jsonObjectCompute(ctx, 0); +} +static void jsonObjectFinal(tdsqlite3_context *ctx){ + jsonObjectCompute(ctx, 1); +} + + + +#ifndef SQLITE_OMIT_VIRTUALTABLE +/**************************************************************************** +** The json_each virtual table +****************************************************************************/ +typedef struct JsonEachCursor JsonEachCursor; +struct JsonEachCursor { + tdsqlite3_vtab_cursor base; /* Base class - must be first */ + u32 iRowid; /* The rowid */ + u32 iBegin; /* The first node of the scan */ + u32 i; /* Index in sParse.aNode[] of current row */ + u32 iEnd; /* EOF when i equals or exceeds this value */ + u8 eType; /* Type of top-level element */ + u8 bRecursive; /* True for json_tree(). False for json_each() */ + char *zJson; /* Input JSON */ + char *zRoot; /* Path by which to filter zJson */ + JsonParse sParse; /* Parse of the input JSON */ +}; + +/* Constructor for the json_each virtual table */ +static int jsonEachConnect( + tdsqlite3 *db, + void *pAux, + int argc, const char *const*argv, + tdsqlite3_vtab **ppVtab, + char **pzErr +){ + tdsqlite3_vtab *pNew; + int rc; + +/* Column numbers */ +#define JEACH_KEY 0 +#define JEACH_VALUE 1 +#define JEACH_TYPE 2 +#define JEACH_ATOM 3 +#define JEACH_ID 4 +#define JEACH_PARENT 5 +#define JEACH_FULLKEY 6 +#define JEACH_PATH 7 +/* The xBestIndex method assumes that the JSON and ROOT columns are +** the last two columns in the table. Should this ever changes, be +** sure to update the xBestIndex method. */ +#define JEACH_JSON 8 +#define JEACH_ROOT 9 + + UNUSED_PARAM(pzErr); + UNUSED_PARAM(argv); + UNUSED_PARAM(argc); + UNUSED_PARAM(pAux); + rc = tdsqlite3_declare_vtab(db, + "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path," + "json HIDDEN,root HIDDEN)"); + if( rc==SQLITE_OK ){ + pNew = *ppVtab = tdsqlite3_malloc( sizeof(*pNew) ); + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + tdsqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); + } + return rc; +} + +/* destructor for json_each virtual table */ +static int jsonEachDisconnect(tdsqlite3_vtab *pVtab){ + tdsqlite3_free(pVtab); + return SQLITE_OK; +} + +/* constructor for a JsonEachCursor object for json_each(). */ +static int jsonEachOpenEach(tdsqlite3_vtab *p, tdsqlite3_vtab_cursor **ppCursor){ + JsonEachCursor *pCur; + + UNUSED_PARAM(p); + pCur = tdsqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* constructor for a JsonEachCursor object for json_tree(). */ +static int jsonEachOpenTree(tdsqlite3_vtab *p, tdsqlite3_vtab_cursor **ppCursor){ + int rc = jsonEachOpenEach(p, ppCursor); + if( rc==SQLITE_OK ){ + JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor; + pCur->bRecursive = 1; + } + return rc; +} + +/* Reset a JsonEachCursor back to its original state. Free any memory +** held. */ +static void jsonEachCursorReset(JsonEachCursor *p){ + tdsqlite3_free(p->zJson); + tdsqlite3_free(p->zRoot); + jsonParseReset(&p->sParse); + p->iRowid = 0; + p->i = 0; + p->iEnd = 0; + p->eType = 0; + p->zJson = 0; + p->zRoot = 0; +} + +/* Destructor for a jsonEachCursor object */ +static int jsonEachClose(tdsqlite3_vtab_cursor *cur){ + JsonEachCursor *p = (JsonEachCursor*)cur; + jsonEachCursorReset(p); + tdsqlite3_free(cur); + return SQLITE_OK; +} + +/* Return TRUE if the jsonEachCursor object has been advanced off the end +** of the JSON object */ +static int jsonEachEof(tdsqlite3_vtab_cursor *cur){ + JsonEachCursor *p = (JsonEachCursor*)cur; + return p->i >= p->iEnd; +} + +/* Advance the cursor to the next element for json_tree() */ +static int jsonEachNext(tdsqlite3_vtab_cursor *cur){ + JsonEachCursor *p = (JsonEachCursor*)cur; + if( p->bRecursive ){ + if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++; + p->i++; + p->iRowid++; + if( p->i<p->iEnd ){ + u32 iUp = p->sParse.aUp[p->i]; + JsonNode *pUp = &p->sParse.aNode[iUp]; + p->eType = pUp->eType; + if( pUp->eType==JSON_ARRAY ){ + if( iUp==p->i-1 ){ + pUp->u.iKey = 0; + }else{ + pUp->u.iKey++; + } + } + } + }else{ + switch( p->eType ){ + case JSON_ARRAY: { + p->i += jsonNodeSize(&p->sParse.aNode[p->i]); + p->iRowid++; + break; + } + case JSON_OBJECT: { + p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]); + p->iRowid++; + break; + } + default: { + p->i = p->iEnd; + break; + } + } + } + return SQLITE_OK; +} + +/* Append the name of the path for element i to pStr +*/ +static void jsonEachComputePath( + JsonEachCursor *p, /* The cursor */ + JsonString *pStr, /* Write the path here */ + u32 i /* Path to this element */ +){ + JsonNode *pNode, *pUp; + u32 iUp; + if( i==0 ){ + jsonAppendChar(pStr, '$'); + return; + } + iUp = p->sParse.aUp[i]; + jsonEachComputePath(p, pStr, iUp); + pNode = &p->sParse.aNode[i]; + pUp = &p->sParse.aNode[iUp]; + if( pUp->eType==JSON_ARRAY ){ + jsonPrintf(30, pStr, "[%d]", pUp->u.iKey); + }else{ + assert( pUp->eType==JSON_OBJECT ); + if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--; + assert( pNode->eType==JSON_STRING ); + assert( pNode->jnFlags & JNODE_LABEL ); + jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1); + } +} + +/* Return the value of a column */ +static int jsonEachColumn( + tdsqlite3_vtab_cursor *cur, /* The cursor */ + tdsqlite3_context *ctx, /* First argument to tdsqlite3_result_...() */ + int i /* Which column to return */ +){ + JsonEachCursor *p = (JsonEachCursor*)cur; + JsonNode *pThis = &p->sParse.aNode[p->i]; + switch( i ){ + case JEACH_KEY: { + if( p->i==0 ) break; + if( p->eType==JSON_OBJECT ){ + jsonReturn(pThis, ctx, 0); + }else if( p->eType==JSON_ARRAY ){ + u32 iKey; + if( p->bRecursive ){ + if( p->iRowid==0 ) break; + iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey; + }else{ + iKey = p->iRowid; + } + tdsqlite3_result_int64(ctx, (tdsqlite3_int64)iKey); + } + break; + } + case JEACH_VALUE: { + if( pThis->jnFlags & JNODE_LABEL ) pThis++; + jsonReturn(pThis, ctx, 0); + break; + } + case JEACH_TYPE: { + if( pThis->jnFlags & JNODE_LABEL ) pThis++; + tdsqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC); + break; + } + case JEACH_ATOM: { + if( pThis->jnFlags & JNODE_LABEL ) pThis++; + if( pThis->eType>=JSON_ARRAY ) break; + jsonReturn(pThis, ctx, 0); + break; + } + case JEACH_ID: { + tdsqlite3_result_int64(ctx, + (tdsqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0)); + break; + } + case JEACH_PARENT: { + if( p->i>p->iBegin && p->bRecursive ){ + tdsqlite3_result_int64(ctx, (tdsqlite3_int64)p->sParse.aUp[p->i]); + } + break; + } + case JEACH_FULLKEY: { + JsonString x; + jsonInit(&x, ctx); + if( p->bRecursive ){ + jsonEachComputePath(p, &x, p->i); + }else{ + if( p->zRoot ){ + jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot)); + }else{ + jsonAppendChar(&x, '$'); + } + if( p->eType==JSON_ARRAY ){ + jsonPrintf(30, &x, "[%d]", p->iRowid); + }else if( p->eType==JSON_OBJECT ){ + jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1); + } + } + jsonResult(&x); + break; + } + case JEACH_PATH: { + if( p->bRecursive ){ + JsonString x; + jsonInit(&x, ctx); + jsonEachComputePath(p, &x, p->sParse.aUp[p->i]); + jsonResult(&x); + break; + } + /* For json_each() path and root are the same so fall through + ** into the root case */ + } + default: { + const char *zRoot = p->zRoot; + if( zRoot==0 ) zRoot = "$"; + tdsqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC); + break; + } + case JEACH_JSON: { + assert( i==JEACH_JSON ); + tdsqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC); + break; + } + } + return SQLITE_OK; +} + +/* Return the current rowid value */ +static int jsonEachRowid(tdsqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + JsonEachCursor *p = (JsonEachCursor*)cur; + *pRowid = p->iRowid; + return SQLITE_OK; +} + +/* The query strategy is to look for an equality constraint on the json +** column. Without such a constraint, the table cannot operate. idxNum is +** 1 if the constraint is found, 3 if the constraint and zRoot are found, +** and 0 otherwise. +*/ +static int jsonEachBestIndex( + tdsqlite3_vtab *tab, + tdsqlite3_index_info *pIdxInfo +){ + int i; /* Loop counter or computed array index */ + int aIdx[2]; /* Index of constraints for JSON and ROOT */ + int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */ + int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */ + const struct tdsqlite3_index_constraint *pConstraint; + + /* This implementation assumes that JSON and ROOT are the last two + ** columns in the table */ + assert( JEACH_ROOT == JEACH_JSON+1 ); + UNUSED_PARAM(tab); + aIdx[0] = aIdx[1] = -1; + pConstraint = pIdxInfo->aConstraint; + for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ + int iCol; + int iMask; + if( pConstraint->iColumn < JEACH_JSON ) continue; + iCol = pConstraint->iColumn - JEACH_JSON; + assert( iCol==0 || iCol==1 ); + iMask = 1 << iCol; + if( pConstraint->usable==0 ){ + unusableMask |= iMask; + }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + aIdx[iCol] = i; + idxMask |= iMask; + } + } + if( (unusableMask & ~idxMask)!=0 ){ + /* If there are any unusable constraints on JSON or ROOT, then reject + ** this entire plan */ + return SQLITE_CONSTRAINT; + } + if( aIdx[0]<0 ){ + /* No JSON input. Leave estimatedCost at the huge value that it was + ** initialized to to discourage the query planner from selecting this + ** plan. */ + pIdxInfo->idxNum = 0; + }else{ + pIdxInfo->estimatedCost = 1.0; + i = aIdx[0]; + pIdxInfo->aConstraintUsage[i].argvIndex = 1; + pIdxInfo->aConstraintUsage[i].omit = 1; + if( aIdx[1]<0 ){ + pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */ + }else{ + i = aIdx[1]; + pIdxInfo->aConstraintUsage[i].argvIndex = 2; + pIdxInfo->aConstraintUsage[i].omit = 1; + pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */ + } + } + return SQLITE_OK; +} + +/* Start a search on a new JSON string */ +static int jsonEachFilter( + tdsqlite3_vtab_cursor *cur, + int idxNum, const char *idxStr, + int argc, tdsqlite3_value **argv +){ + JsonEachCursor *p = (JsonEachCursor*)cur; + const char *z; + const char *zRoot = 0; + tdsqlite3_int64 n; + + UNUSED_PARAM(idxStr); + UNUSED_PARAM(argc); + jsonEachCursorReset(p); + if( idxNum==0 ) return SQLITE_OK; + z = (const char*)tdsqlite3_value_text(argv[0]); + if( z==0 ) return SQLITE_OK; + n = tdsqlite3_value_bytes(argv[0]); + p->zJson = tdsqlite3_malloc64( n+1 ); + if( p->zJson==0 ) return SQLITE_NOMEM; + memcpy(p->zJson, z, (size_t)n+1); + if( jsonParse(&p->sParse, 0, p->zJson) ){ + int rc = SQLITE_NOMEM; + if( p->sParse.oom==0 ){ + tdsqlite3_free(cur->pVtab->zErrMsg); + cur->pVtab->zErrMsg = tdsqlite3_mprintf("malformed JSON"); + if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR; + } + jsonEachCursorReset(p); + return rc; + }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){ + jsonEachCursorReset(p); + return SQLITE_NOMEM; + }else{ + JsonNode *pNode = 0; + if( idxNum==3 ){ + const char *zErr = 0; + zRoot = (const char*)tdsqlite3_value_text(argv[1]); + if( zRoot==0 ) return SQLITE_OK; + n = tdsqlite3_value_bytes(argv[1]); + p->zRoot = tdsqlite3_malloc64( n+1 ); + if( p->zRoot==0 ) return SQLITE_NOMEM; + memcpy(p->zRoot, zRoot, (size_t)n+1); + if( zRoot[0]!='$' ){ + zErr = zRoot; + }else{ + pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr); + } + if( zErr ){ + tdsqlite3_free(cur->pVtab->zErrMsg); + cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr); + jsonEachCursorReset(p); + return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; + }else if( pNode==0 ){ + return SQLITE_OK; + } + }else{ + pNode = p->sParse.aNode; + } + p->iBegin = p->i = (int)(pNode - p->sParse.aNode); + p->eType = pNode->eType; + if( p->eType>=JSON_ARRAY ){ + pNode->u.iKey = 0; + p->iEnd = p->i + pNode->n + 1; + if( p->bRecursive ){ + p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType; + if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){ + p->i--; + } + }else{ + p->i++; + } + }else{ + p->iEnd = p->i+1; + } + } + return SQLITE_OK; +} + +/* The methods of the json_each virtual table */ +static tdsqlite3_module jsonEachModule = { + 0, /* iVersion */ + 0, /* xCreate */ + jsonEachConnect, /* xConnect */ + jsonEachBestIndex, /* xBestIndex */ + jsonEachDisconnect, /* xDisconnect */ + 0, /* xDestroy */ + jsonEachOpenEach, /* xOpen - open a cursor */ + jsonEachClose, /* xClose - close a cursor */ + jsonEachFilter, /* xFilter - configure scan constraints */ + jsonEachNext, /* xNext - advance a cursor */ + jsonEachEof, /* xEof - check for end of scan */ + jsonEachColumn, /* xColumn - read data */ + jsonEachRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0 /* xShadowName */ +}; + +/* The methods of the json_tree virtual table. */ +static tdsqlite3_module jsonTreeModule = { + 0, /* iVersion */ + 0, /* xCreate */ + jsonEachConnect, /* xConnect */ + jsonEachBestIndex, /* xBestIndex */ + jsonEachDisconnect, /* xDisconnect */ + 0, /* xDestroy */ + jsonEachOpenTree, /* xOpen - open a cursor */ + jsonEachClose, /* xClose - close a cursor */ + jsonEachFilter, /* xFilter - configure scan constraints */ + jsonEachNext, /* xNext - advance a cursor */ + jsonEachEof, /* xEof - check for end of scan */ + jsonEachColumn, /* xColumn - read data */ + jsonEachRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0 /* xShadowName */ +}; +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +/**************************************************************************** +** The following routines are the only publically visible identifiers in this +** file. Call the following routines in order to register the various SQL +** functions and the virtual table implemented by this file. +****************************************************************************/ + +SQLITE_PRIVATE int tdsqlite3Json1Init(tdsqlite3 *db){ + int rc = SQLITE_OK; + unsigned int i; + static const struct { + const char *zName; + int nArg; + int flag; + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**); + } aFunc[] = { + { "json", 1, 0, jsonRemoveFunc }, + { "json_array", -1, 0, jsonArrayFunc }, + { "json_array_length", 1, 0, jsonArrayLengthFunc }, + { "json_array_length", 2, 0, jsonArrayLengthFunc }, + { "json_extract", -1, 0, jsonExtractFunc }, + { "json_insert", -1, 0, jsonSetFunc }, + { "json_object", -1, 0, jsonObjectFunc }, + { "json_patch", 2, 0, jsonPatchFunc }, + { "json_quote", 1, 0, jsonQuoteFunc }, + { "json_remove", -1, 0, jsonRemoveFunc }, + { "json_replace", -1, 0, jsonReplaceFunc }, + { "json_set", -1, 1, jsonSetFunc }, + { "json_type", 1, 0, jsonTypeFunc }, + { "json_type", 2, 0, jsonTypeFunc }, + { "json_valid", 1, 0, jsonValidFunc }, + +#if SQLITE_DEBUG + /* DEBUG and TESTING functions */ + { "json_parse", 1, 0, jsonParseFunc }, + { "json_test1", 1, 0, jsonTest1Func }, +#endif + }; + static const struct { + const char *zName; + int nArg; + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**); + void (*xFinal)(tdsqlite3_context*); + void (*xValue)(tdsqlite3_context*); + } aAgg[] = { + { "json_group_array", 1, + jsonArrayStep, jsonArrayFinal, jsonArrayValue }, + { "json_group_object", 2, + jsonObjectStep, jsonObjectFinal, jsonObjectValue }, + }; +#ifndef SQLITE_OMIT_VIRTUALTABLE + static const struct { + const char *zName; + tdsqlite3_module *pModule; + } aMod[] = { + { "json_each", &jsonEachModule }, + { "json_tree", &jsonTreeModule }, + }; +#endif + static const int enc = + SQLITE_UTF8 | + SQLITE_DETERMINISTIC | + SQLITE_INNOCUOUS; + for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){ + rc = tdsqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, enc, + (void*)&aFunc[i].flag, + aFunc[i].xFunc, 0, 0); + } +#ifndef SQLITE_OMIT_WINDOWFUNC + for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){ + rc = tdsqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg, + SQLITE_SUBTYPE | enc, 0, + aAgg[i].xStep, aAgg[i].xFinal, + aAgg[i].xValue, jsonGroupInverse, 0); + } +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){ + rc = tdsqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0); + } +#endif + return rc; +} + + +#ifndef SQLITE_CORE +#ifdef _WIN32 +__declspec(dllexport) +#endif +SQLITE_API int tdsqlite3_json_init( + tdsqlite3 *db, + char **pzErrMsg, + const tdsqlite3_api_routines *pApi +){ + SQLITE_EXTENSION_INIT2(pApi); + (void)pzErrMsg; /* Unused parameter */ + return tdsqlite3Json1Init(db); +} +#endif +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */ + +/************** End of json1.c ***********************************************/ /************** Begin file rtree.c *******************************************/ /* ** 2001 September 15 @@ -164473,14 +189696,15 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ ** ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB) ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER) -** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER) +** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...) ** ** The data for each node of the r-tree structure is stored in the %_node ** table. For each node that is not the root node of the r-tree, there is ** an entry in the %_parent table associating the node with its parent. ** And for each row of data in the table, there is an entry in the %_rowid ** table that maps from the entries rowid to the id of the node that it -** is stored on. +** is stored on. If the r-tree contains auxiliary columns, those are stored +** on the end of the %_rowid table. ** ** The root node of an r-tree always exists, even if the r-tree table is ** empty. The nodeno of the root node is always 1. All other nodes in the @@ -164501,27 +189725,36 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){ ** child page. */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE) +#if !defined(SQLITE_CORE) \ + || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE)) #ifndef SQLITE_CORE -/* #include "sqlite3ext.h" */ +/* #include "tdsqlite3ext.h" */ SQLITE_EXTENSION_INIT1 #else /* #include "sqlite3.h" */ #endif - -/* #include <string.h> */ -/* #include <assert.h> */ -/* #include <stdio.h> */ +SQLITE_PRIVATE int tdsqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */ #ifndef SQLITE_AMALGAMATION -#include "sqlite3rtree.h" -typedef sqlite3_int64 i64; +#include "tdsqlite3rtree.h" +typedef tdsqlite3_int64 i64; +typedef tdsqlite3_uint64 u64; typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif +#if defined(NDEBUG) && defined(SQLITE_DEBUG) +# undef NDEBUG +#endif #endif +/* #include <string.h> */ +/* #include <stdio.h> */ +/* #include <assert.h> */ + /* The following macro is used to suppress compiler warnings. */ #ifndef UNUSED_PARAMETER @@ -164541,6 +189774,9 @@ typedef struct RtreeSearchPoint RtreeSearchPoint; /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */ #define RTREE_MAX_DIMENSIONS 5 +/* Maximum number of auxiliary columns */ +#define RTREE_MAX_AUX_COLUMN 100 + /* Size of hash table Rtree.aHash. This hash table is not expected to ** ever contain very many entries, so a fixed number of buckets is ** used. @@ -164561,17 +189797,27 @@ typedef struct RtreeSearchPoint RtreeSearchPoint; ** An rtree virtual-table object. */ struct Rtree { - sqlite3_vtab base; /* Base class. Must be first */ - sqlite3 *db; /* Host database connection */ + tdsqlite3_vtab base; /* Base class. Must be first */ + tdsqlite3 *db; /* Host database connection */ int iNodeSize; /* Size in bytes of each node in the node table */ u8 nDim; /* Number of dimensions */ + u8 nDim2; /* Twice the number of dimensions */ u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */ u8 nBytesPerCell; /* Bytes consumed per cell */ + u8 inWrTrans; /* True if inside write transaction */ + u8 nAux; /* # of auxiliary columns in %_rowid */ + u8 nAuxNotNull; /* Number of initial not-null aux columns */ +#ifdef SQLITE_DEBUG + u8 bCorrupt; /* Shadow table corruption detected */ +#endif int iDepth; /* Current depth of the r-tree structure */ char *zDb; /* Name of database containing r-tree table */ char *zName; /* Name of r-tree table */ - int nBusy; /* Current number of users of this structure */ + u32 nBusy; /* Current number of users of this structure */ i64 nRowEst; /* Estimated number of rows in this table */ + u32 nCursor; /* Number of open cursors */ + u32 nNodeRef; /* Number RtreeNodes with positive nRef */ + char *zReadAuxSql; /* SQL for statement to read aux data */ /* List of nodes removed during a CondenseTree operation. List is ** linked together via the pointer normally used for hash chains - @@ -164581,20 +189827,25 @@ struct Rtree { RtreeNode *pDeleted; int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */ + /* Blob I/O on xxx_node */ + tdsqlite3_blob *pNodeBlob; + /* Statements to read/write/delete a record from xxx_node */ - sqlite3_stmt *pReadNode; - sqlite3_stmt *pWriteNode; - sqlite3_stmt *pDeleteNode; + tdsqlite3_stmt *pWriteNode; + tdsqlite3_stmt *pDeleteNode; /* Statements to read/write/delete a record from xxx_rowid */ - sqlite3_stmt *pReadRowid; - sqlite3_stmt *pWriteRowid; - sqlite3_stmt *pDeleteRowid; + tdsqlite3_stmt *pReadRowid; + tdsqlite3_stmt *pWriteRowid; + tdsqlite3_stmt *pDeleteRowid; /* Statements to read/write/delete a record from xxx_parent */ - sqlite3_stmt *pReadParent; - sqlite3_stmt *pWriteParent; - sqlite3_stmt *pDeleteParent; + tdsqlite3_stmt *pReadParent; + tdsqlite3_stmt *pWriteParent; + tdsqlite3_stmt *pDeleteParent; + + /* Statement for writing to the "aux:" fields, if there are any */ + tdsqlite3_stmt *pWriteAux; RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ }; @@ -164609,7 +189860,7 @@ struct Rtree { ** will be done. */ #ifdef SQLITE_RTREE_INT_ONLY - typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */ + typedef tdsqlite3_int64 RtreeDValue; /* High accuracy coordinate */ typedef int RtreeValue; /* Low accuracy coordinate */ # define RTREE_ZERO 0 #else @@ -164619,6 +189870,15 @@ struct Rtree { #endif /* +** Set the Rtree.bCorrupt flag +*/ +#ifdef SQLITE_DEBUG +# define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1) +#else +# define RTREE_IS_CORRUPT(X) +#endif + +/* ** When doing a search of an r-tree, instances of the following structure ** record intermediate results from the tree walk. ** @@ -164629,7 +189889,7 @@ struct Rtree { */ struct RtreeSearchPoint { RtreeDValue rScore; /* The score for this node. Smallest goes first. */ - sqlite3_int64 id; /* Node ID */ + tdsqlite3_int64 id; /* Node ID */ u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */ u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */ u8 iCell; /* Cell index within the node */ @@ -164652,7 +189912,7 @@ struct RtreeSearchPoint { ** The smallest possible node-size is (512-64)==448 bytes. And the largest ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates). ** Therefore all non-root nodes must contain at least 3 entries. Since -** 2^40 is greater than 2^64, an r-tree structure always has a depth of +** 3^40 is greater than 2^64, an r-tree structure always has a depth of ** 40 or less. */ #define RTREE_MAX_DEPTH 40 @@ -164669,9 +189929,10 @@ struct RtreeSearchPoint { ** An rtree cursor object. */ struct RtreeCursor { - sqlite3_vtab_cursor base; /* Base class. Must be first */ + tdsqlite3_vtab_cursor base; /* Base class. Must be first */ u8 atEOF; /* True if at end of search */ u8 bPoint; /* True if sPoint is valid */ + u8 bAuxValid; /* True if pReadAux is valid */ int iStrategy; /* Copy of idxNum search parameter */ int nConstraint; /* Number of entries in aConstraint */ RtreeConstraint *aConstraint; /* Search constraints. */ @@ -164679,6 +189940,7 @@ struct RtreeCursor { int nPoint; /* Number of slots used in aPoint[] */ int mxLevel; /* iLevel value for root of the tree */ RtreeSearchPoint *aPoint; /* Priority queue for search points */ + tdsqlite3_stmt *pReadAux; /* Statement to read aux-data */ RtreeSearchPoint sPoint; /* Cached next search point */ RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */ u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */ @@ -164721,10 +189983,10 @@ struct RtreeConstraint { int op; /* Constraining operation */ union { RtreeDValue rValue; /* Constraint value. */ - int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*); - int (*xQueryFunc)(sqlite3_rtree_query_info*); + int (*xGeom)(tdsqlite3_rtree_geometry*,int,RtreeDValue*,int*); + int (*xQueryFunc)(tdsqlite3_rtree_query_info*); } u; - sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */ + tdsqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */ }; /* Possible values for RtreeConstraint.op */ @@ -164733,9 +189995,15 @@ struct RtreeConstraint { #define RTREE_LT 0x43 /* C */ #define RTREE_GE 0x44 /* D */ #define RTREE_GT 0x45 /* E */ -#define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */ -#define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */ +#define RTREE_MATCH 0x46 /* F: Old-style tdsqlite3_rtree_geometry_callback() */ +#define RTREE_QUERY 0x47 /* G: New-style tdsqlite3_rtree_query_callback() */ +/* Special operators available only on cursors. Needs to be consecutive +** with the normal values above, but must be less than RTREE_MATCH. These +** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or +** x<'xyz' (RTREE_TRUE) */ +#define RTREE_TRUE 0x3f /* ? */ +#define RTREE_FALSE 0x40 /* @ */ /* ** An rtree structure node. @@ -164762,45 +190030,37 @@ struct RtreeCell { /* -** This object becomes the sqlite3_user_data() for the SQL functions -** that are created by sqlite3_rtree_geometry_callback() and -** sqlite3_rtree_query_callback() and which appear on the right of MATCH +** This object becomes the tdsqlite3_user_data() for the SQL functions +** that are created by tdsqlite3_rtree_geometry_callback() and +** tdsqlite3_rtree_query_callback() and which appear on the right of MATCH ** operators in order to constrain a search. ** ** xGeom and xQueryFunc are the callback functions. Exactly one of ** xGeom and xQueryFunc fields is non-NULL, depending on whether the -** SQL function was created using sqlite3_rtree_geometry_callback() or -** sqlite3_rtree_query_callback(). +** SQL function was created using tdsqlite3_rtree_geometry_callback() or +** tdsqlite3_rtree_query_callback(). ** ** This object is deleted automatically by the destructor mechanism in -** sqlite3_create_function_v2(). +** tdsqlite3_create_function_v2(). */ struct RtreeGeomCallback { - int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*); - int (*xQueryFunc)(sqlite3_rtree_query_info*); + int (*xGeom)(tdsqlite3_rtree_geometry*, int, RtreeDValue*, int*); + int (*xQueryFunc)(tdsqlite3_rtree_query_info*); void (*xDestructor)(void*); void *pContext; }; - -/* -** Value for the first field of every RtreeMatchArg object. The MATCH -** operator tests that the first field of a blob operand matches this -** value to avoid operating on invalid blobs (which could cause a segfault). -*/ -#define RTREE_GEOMETRY_MAGIC 0x891245AB - /* ** An instance of this structure (in the form of a BLOB) is returned by -** the SQL functions that sqlite3_rtree_geometry_callback() and -** sqlite3_rtree_query_callback() create, and is read as the right-hand +** the SQL functions that tdsqlite3_rtree_geometry_callback() and +** tdsqlite3_rtree_query_callback() create, and is read as the right-hand ** operand to the MATCH operator of an R-Tree. */ struct RtreeMatchArg { - u32 magic; /* Always RTREE_GEOMETRY_MAGIC */ + u32 iSize; /* Size of this object */ RtreeGeomCallback cb; /* Info about the callback functions */ int nParam; /* Number of parameters to the SQL function */ - sqlite3_value **apSqlParam; /* Original SQL parameter values */ + tdsqlite3_value **apSqlParam; /* Original SQL parameter values */ RtreeDValue aParam[1]; /* Values for parameters to the SQL function */ }; @@ -164811,6 +190071,58 @@ struct RtreeMatchArg { # define MIN(x,y) ((x) > (y) ? (y) : (x)) #endif +/* What version of GCC is being used. 0 means GCC is not being used . +** Note that the GCC_VERSION macro will also be set correctly when using +** clang, since clang works hard to be gcc compatible. So the gcc +** optimizations will also work when compiling with clang. +*/ +#ifndef GCC_VERSION +#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) +# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) +#else +# define GCC_VERSION 0 +#endif +#endif + +/* The testcase() macro should already be defined in the amalgamation. If +** it is not, make it a no-op. +*/ +#ifndef SQLITE_AMALGAMATION +# define testcase(X) +#endif + +/* +** Macros to determine whether the machine is big or little endian, +** and whether or not that determination is run-time or compile-time. +** +** For best performance, an attempt is made to guess at the byte-order +** using C-preprocessor macros. If that is unsuccessful, or if +** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined +** at run-time. +*/ +#ifndef SQLITE_BYTEORDER +#if defined(i386) || defined(__i386__) || defined(_M_IX86) || \ + defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ + defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ + defined(__arm__) +# define SQLITE_BYTEORDER 1234 +#elif defined(sparc) || defined(__ppc__) +# define SQLITE_BYTEORDER 4321 +#else +# define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */ +#endif +#endif + + +/* What version of MSVC is being used. 0 means MSVC is not being used */ +#ifndef MSVC_VERSION +#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) +# define MSVC_VERSION _MSC_VER +#else +# define MSVC_VERSION 0 +#endif +#endif + /* ** Functions to deserialize a 16 bit integer, 32 bit real number and ** 64 bit integer. The deserialized value is returned. @@ -164819,24 +190131,47 @@ static int readInt16(u8 *p){ return (p[0]<<8) + p[1]; } static void readCoord(u8 *p, RtreeCoord *pCoord){ + assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */ +#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 + pCoord->u = _byteswap_ulong(*(u32*)p); +#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 + pCoord->u = __builtin_bswap32(*(u32*)p); +#elif SQLITE_BYTEORDER==4321 + pCoord->u = *(u32*)p; +#else pCoord->u = ( (((u32)p[0]) << 24) + (((u32)p[1]) << 16) + (((u32)p[2]) << 8) + (((u32)p[3]) << 0) ); +#endif } static i64 readInt64(u8 *p){ - return ( - (((i64)p[0]) << 56) + - (((i64)p[1]) << 48) + - (((i64)p[2]) << 40) + - (((i64)p[3]) << 32) + - (((i64)p[4]) << 24) + - (((i64)p[5]) << 16) + - (((i64)p[6]) << 8) + - (((i64)p[7]) << 0) +#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 + u64 x; + memcpy(&x, p, 8); + return (i64)_byteswap_uint64(x); +#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 + u64 x; + memcpy(&x, p, 8); + return (i64)__builtin_bswap64(x); +#elif SQLITE_BYTEORDER==4321 + i64 x; + memcpy(&x, p, 8); + return x; +#else + return (i64)( + (((u64)p[0]) << 56) + + (((u64)p[1]) << 48) + + (((u64)p[2]) << 40) + + (((u64)p[3]) << 32) + + (((u64)p[4]) << 24) + + (((u64)p[5]) << 16) + + (((u64)p[6]) << 8) + + (((u64)p[7]) << 0) ); +#endif } /* @@ -164844,23 +190179,43 @@ static i64 readInt64(u8 *p){ ** 64 bit integer. The value returned is the number of bytes written ** to the argument buffer (always 2, 4 and 8 respectively). */ -static int writeInt16(u8 *p, int i){ +static void writeInt16(u8 *p, int i){ p[0] = (i>> 8)&0xFF; p[1] = (i>> 0)&0xFF; - return 2; } static int writeCoord(u8 *p, RtreeCoord *pCoord){ u32 i; + assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */ assert( sizeof(RtreeCoord)==4 ); assert( sizeof(u32)==4 ); +#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 + i = __builtin_bswap32(pCoord->u); + memcpy(p, &i, 4); +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 + i = _byteswap_ulong(pCoord->u); + memcpy(p, &i, 4); +#elif SQLITE_BYTEORDER==4321 + i = pCoord->u; + memcpy(p, &i, 4); +#else i = pCoord->u; p[0] = (i>>24)&0xFF; p[1] = (i>>16)&0xFF; p[2] = (i>> 8)&0xFF; p[3] = (i>> 0)&0xFF; +#endif return 4; } static int writeInt64(u8 *p, i64 i){ +#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 + i = (i64)__builtin_bswap64((u64)i); + memcpy(p, &i, 8); +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 + i = (i64)_byteswap_uint64((u64)i); + memcpy(p, &i, 8); +#elif SQLITE_BYTEORDER==4321 + memcpy(p, &i, 8); +#else p[0] = (i>>56)&0xFF; p[1] = (i>>48)&0xFF; p[2] = (i>>40)&0xFF; @@ -164869,6 +190224,7 @@ static int writeInt64(u8 *p, i64 i){ p[5] = (i>>16)&0xFF; p[6] = (i>> 8)&0xFF; p[7] = (i>> 0)&0xFF; +#endif return 8; } @@ -164877,6 +190233,7 @@ static int writeInt64(u8 *p, i64 i){ */ static void nodeReference(RtreeNode *p){ if( p ){ + assert( p->nRef>0 ); p->nRef++; } } @@ -164893,8 +190250,8 @@ static void nodeZero(Rtree *pRtree, RtreeNode *p){ ** Given a node number iNode, return the corresponding key to use ** in the Rtree.aHash table. */ -static int nodeHash(i64 iNode){ - return iNode % HASHSIZE; +static unsigned int nodeHash(i64 iNode){ + return ((unsigned)iNode) % HASHSIZE; } /* @@ -164939,11 +190296,12 @@ static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){ */ static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){ RtreeNode *pNode; - pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); + pNode = (RtreeNode *)tdsqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize); if( pNode ){ memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize); pNode->zData = (u8 *)&pNode[1]; pNode->nRef = 1; + pRtree->nNodeRef++; pNode->pParent = pParent; pNode->isDirty = 1; nodeReference(pParent); @@ -164952,6 +190310,29 @@ static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){ } /* +** Clear the Rtree.pNodeBlob object +*/ +static void nodeBlobReset(Rtree *pRtree){ + if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){ + tdsqlite3_blob *pBlob = pRtree->pNodeBlob; + pRtree->pNodeBlob = 0; + tdsqlite3_blob_close(pBlob); + } +} + +/* +** Check to see if pNode is the same as pParent or any of the parents +** of pParent. +*/ +static int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){ + do{ + if( pNode==pParent ) return 1; + pParent = pParent->pParent; + }while( pParent ); + return 0; +} + +/* ** Obtain a reference to an r-tree node. */ static int nodeAcquire( @@ -164960,46 +190341,71 @@ static int nodeAcquire( RtreeNode *pParent, /* Either the parent node or NULL */ RtreeNode **ppNode /* OUT: Acquired node */ ){ - int rc; - int rc2 = SQLITE_OK; - RtreeNode *pNode; + int rc = SQLITE_OK; + RtreeNode *pNode = 0; /* Check if the requested node is already in the hash table. If so, ** increase its reference count and return it. */ - if( (pNode = nodeHashLookup(pRtree, iNode)) ){ - assert( !pParent || !pNode->pParent || pNode->pParent==pParent ); + if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){ if( pParent && !pNode->pParent ){ - nodeReference(pParent); + if( nodeInParentChain(pNode, pParent) ){ + RTREE_IS_CORRUPT(pRtree); + return SQLITE_CORRUPT_VTAB; + } + pParent->nRef++; pNode->pParent = pParent; + }else if( pParent && pNode->pParent && pParent!=pNode->pParent ){ + RTREE_IS_CORRUPT(pRtree); + return SQLITE_CORRUPT_VTAB; } pNode->nRef++; *ppNode = pNode; return SQLITE_OK; } - sqlite3_bind_int64(pRtree->pReadNode, 1, iNode); - rc = sqlite3_step(pRtree->pReadNode); - if( rc==SQLITE_ROW ){ - const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0); - if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){ - pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize); - if( !pNode ){ - rc2 = SQLITE_NOMEM; - }else{ - pNode->pParent = pParent; - pNode->zData = (u8 *)&pNode[1]; - pNode->nRef = 1; - pNode->iNode = iNode; - pNode->isDirty = 0; - pNode->pNext = 0; - memcpy(pNode->zData, zBlob, pRtree->iNodeSize); - nodeReference(pParent); - } + if( pRtree->pNodeBlob ){ + tdsqlite3_blob *pBlob = pRtree->pNodeBlob; + pRtree->pNodeBlob = 0; + rc = tdsqlite3_blob_reopen(pBlob, iNode); + pRtree->pNodeBlob = pBlob; + if( rc ){ + nodeBlobReset(pRtree); + if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM; + } + } + if( pRtree->pNodeBlob==0 ){ + char *zTab = tdsqlite3_mprintf("%s_node", pRtree->zName); + if( zTab==0 ) return SQLITE_NOMEM; + rc = tdsqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0, + &pRtree->pNodeBlob); + tdsqlite3_free(zTab); + } + if( rc ){ + nodeBlobReset(pRtree); + *ppNode = 0; + /* If unable to open an tdsqlite3_blob on the desired row, that can only + ** be because the shadow tables hold erroneous data. */ + if( rc==SQLITE_ERROR ){ + rc = SQLITE_CORRUPT_VTAB; + RTREE_IS_CORRUPT(pRtree); + } + }else if( pRtree->iNodeSize==tdsqlite3_blob_bytes(pRtree->pNodeBlob) ){ + pNode = (RtreeNode *)tdsqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize); + if( !pNode ){ + rc = SQLITE_NOMEM; + }else{ + pNode->pParent = pParent; + pNode->zData = (u8 *)&pNode[1]; + pNode->nRef = 1; + pRtree->nNodeRef++; + pNode->iNode = iNode; + pNode->isDirty = 0; + pNode->pNext = 0; + rc = tdsqlite3_blob_read(pRtree->pNodeBlob, pNode->zData, + pRtree->iNodeSize, 0); } } - rc = sqlite3_reset(pRtree->pReadNode); - if( rc==SQLITE_OK ) rc = rc2; /* If the root node was just loaded, set pRtree->iDepth to the height ** of the r-tree structure. A height of zero means all data is stored on @@ -165011,6 +190417,7 @@ static int nodeAcquire( pRtree->iDepth = readInt16(pNode->zData); if( pRtree->iDepth>RTREE_MAX_DEPTH ){ rc = SQLITE_CORRUPT_VTAB; + RTREE_IS_CORRUPT(pRtree); } } @@ -165021,18 +190428,24 @@ static int nodeAcquire( if( pNode && rc==SQLITE_OK ){ if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){ rc = SQLITE_CORRUPT_VTAB; + RTREE_IS_CORRUPT(pRtree); } } if( rc==SQLITE_OK ){ if( pNode!=0 ){ + nodeReference(pParent); nodeHashInsert(pRtree, pNode); }else{ rc = SQLITE_CORRUPT_VTAB; + RTREE_IS_CORRUPT(pRtree); } *ppNode = pNode; }else{ - sqlite3_free(pNode); + if( pNode ){ + pRtree->nNodeRef--; + tdsqlite3_free(pNode); + } *ppNode = 0; } @@ -165051,7 +190464,7 @@ static void nodeOverwriteCell( int ii; u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; p += writeInt64(p, pCell->iRowid); - for(ii=0; ii<(pRtree->nDim*2); ii++){ + for(ii=0; ii<pRtree->nDim2; ii++){ p += writeCoord(p, &pCell->aCoord[ii]); } pNode->isDirty = 1; @@ -165102,18 +190515,19 @@ static int nodeInsertCell( static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){ int rc = SQLITE_OK; if( pNode->isDirty ){ - sqlite3_stmt *p = pRtree->pWriteNode; + tdsqlite3_stmt *p = pRtree->pWriteNode; if( pNode->iNode ){ - sqlite3_bind_int64(p, 1, pNode->iNode); + tdsqlite3_bind_int64(p, 1, pNode->iNode); }else{ - sqlite3_bind_null(p, 1); + tdsqlite3_bind_null(p, 1); } - sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); - sqlite3_step(p); + tdsqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); + tdsqlite3_step(p); pNode->isDirty = 0; - rc = sqlite3_reset(p); + rc = tdsqlite3_reset(p); + tdsqlite3_bind_null(p, 2); if( pNode->iNode==0 && rc==SQLITE_OK ){ - pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); + pNode->iNode = tdsqlite3_last_insert_rowid(pRtree->db); nodeHashInsert(pRtree, pNode); } } @@ -165128,8 +190542,10 @@ static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){ int rc = SQLITE_OK; if( pNode ){ assert( pNode->nRef>0 ); + assert( pRtree->nNodeRef>0 ); pNode->nRef--; if( pNode->nRef==0 ){ + pRtree->nNodeRef--; if( pNode->iNode==1 ){ pRtree->iDepth = -1; } @@ -165140,7 +190556,7 @@ static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){ rc = nodeWrite(pRtree, pNode); } nodeHashDelete(pRtree, pNode); - sqlite3_free(pNode); + tdsqlite3_free(pNode); } } return rc; @@ -165185,13 +190601,16 @@ static void nodeGetCell( ){ u8 *pData; RtreeCoord *pCoord; - int ii; + int ii = 0; pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell); pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell); pCoord = pCell->aCoord; - for(ii=0; ii<pRtree->nDim*2; ii++){ - readCoord(&pData[ii*4], &pCoord[ii]); - } + do{ + readCoord(pData, &pCoord[ii]); + readCoord(pData+4, &pCoord[ii+1]); + pData += 8; + ii += 2; + }while( ii<pRtree->nDim2 ); } @@ -165199,17 +190618,17 @@ static void nodeGetCell( ** the virtual table module xCreate() and xConnect() methods. */ static int rtreeInit( - sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int + tdsqlite3 *, void *, int, const char *const*, tdsqlite3_vtab **, char **, int ); /* ** Rtree virtual table module xCreate method. */ static int rtreeCreate( - sqlite3 *db, + tdsqlite3 *db, void *pAux, int argc, const char *const*argv, - sqlite3_vtab **ppVtab, + tdsqlite3_vtab **ppVtab, char **pzErr ){ return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1); @@ -165219,10 +190638,10 @@ static int rtreeCreate( ** Rtree virtual table module xConnect method. */ static int rtreeConnect( - sqlite3 *db, + tdsqlite3 *db, void *pAux, int argc, const char *const*argv, - sqlite3_vtab **ppVtab, + tdsqlite3_vtab **ppVtab, char **pzErr ){ return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0); @@ -165242,23 +190661,28 @@ static void rtreeReference(Rtree *pRtree){ static void rtreeRelease(Rtree *pRtree){ pRtree->nBusy--; if( pRtree->nBusy==0 ){ - sqlite3_finalize(pRtree->pReadNode); - sqlite3_finalize(pRtree->pWriteNode); - sqlite3_finalize(pRtree->pDeleteNode); - sqlite3_finalize(pRtree->pReadRowid); - sqlite3_finalize(pRtree->pWriteRowid); - sqlite3_finalize(pRtree->pDeleteRowid); - sqlite3_finalize(pRtree->pReadParent); - sqlite3_finalize(pRtree->pWriteParent); - sqlite3_finalize(pRtree->pDeleteParent); - sqlite3_free(pRtree); + pRtree->inWrTrans = 0; + assert( pRtree->nCursor==0 ); + nodeBlobReset(pRtree); + assert( pRtree->nNodeRef==0 || pRtree->bCorrupt ); + tdsqlite3_finalize(pRtree->pWriteNode); + tdsqlite3_finalize(pRtree->pDeleteNode); + tdsqlite3_finalize(pRtree->pReadRowid); + tdsqlite3_finalize(pRtree->pWriteRowid); + tdsqlite3_finalize(pRtree->pDeleteRowid); + tdsqlite3_finalize(pRtree->pReadParent); + tdsqlite3_finalize(pRtree->pWriteParent); + tdsqlite3_finalize(pRtree->pDeleteParent); + tdsqlite3_finalize(pRtree->pWriteAux); + tdsqlite3_free(pRtree->zReadAuxSql); + tdsqlite3_free(pRtree); } } /* ** Rtree virtual table module xDisconnect method. */ -static int rtreeDisconnect(sqlite3_vtab *pVtab){ +static int rtreeDisconnect(tdsqlite3_vtab *pVtab){ rtreeRelease((Rtree *)pVtab); return SQLITE_OK; } @@ -165266,10 +190690,10 @@ static int rtreeDisconnect(sqlite3_vtab *pVtab){ /* ** Rtree virtual table module xDestroy method. */ -static int rtreeDestroy(sqlite3_vtab *pVtab){ +static int rtreeDestroy(tdsqlite3_vtab *pVtab){ Rtree *pRtree = (Rtree *)pVtab; int rc; - char *zCreate = sqlite3_mprintf( + char *zCreate = tdsqlite3_mprintf( "DROP TABLE '%q'.'%q_node';" "DROP TABLE '%q'.'%q_rowid';" "DROP TABLE '%q'.'%q_parent';", @@ -165280,8 +190704,9 @@ static int rtreeDestroy(sqlite3_vtab *pVtab){ if( !zCreate ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0); - sqlite3_free(zCreate); + nodeBlobReset(pRtree); + rc = tdsqlite3_exec(pRtree->db, zCreate, 0, 0, 0); + tdsqlite3_free(zCreate); } if( rc==SQLITE_OK ){ rtreeRelease(pRtree); @@ -165293,51 +190718,64 @@ static int rtreeDestroy(sqlite3_vtab *pVtab){ /* ** Rtree virtual table module xOpen method. */ -static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ +static int rtreeOpen(tdsqlite3_vtab *pVTab, tdsqlite3_vtab_cursor **ppCursor){ int rc = SQLITE_NOMEM; + Rtree *pRtree = (Rtree *)pVTab; RtreeCursor *pCsr; - pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor)); + pCsr = (RtreeCursor *)tdsqlite3_malloc64(sizeof(RtreeCursor)); if( pCsr ){ memset(pCsr, 0, sizeof(RtreeCursor)); pCsr->base.pVtab = pVTab; rc = SQLITE_OK; + pRtree->nCursor++; } - *ppCursor = (sqlite3_vtab_cursor *)pCsr; + *ppCursor = (tdsqlite3_vtab_cursor *)pCsr; return rc; } /* -** Free the RtreeCursor.aConstraint[] array and its contents. +** Reset a cursor back to its initial state. */ -static void freeCursorConstraints(RtreeCursor *pCsr){ +static void resetCursor(RtreeCursor *pCsr){ + Rtree *pRtree = (Rtree *)(pCsr->base.pVtab); + int ii; + tdsqlite3_stmt *pStmt; if( pCsr->aConstraint ){ int i; /* Used to iterate through constraint array */ for(i=0; i<pCsr->nConstraint; i++){ - sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo; + tdsqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo; if( pInfo ){ if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser); - sqlite3_free(pInfo); + tdsqlite3_free(pInfo); } } - sqlite3_free(pCsr->aConstraint); + tdsqlite3_free(pCsr->aConstraint); pCsr->aConstraint = 0; } + for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]); + tdsqlite3_free(pCsr->aPoint); + pStmt = pCsr->pReadAux; + memset(pCsr, 0, sizeof(RtreeCursor)); + pCsr->base.pVtab = (tdsqlite3_vtab*)pRtree; + pCsr->pReadAux = pStmt; + } /* ** Rtree virtual table module xClose method. */ -static int rtreeClose(sqlite3_vtab_cursor *cur){ +static int rtreeClose(tdsqlite3_vtab_cursor *cur){ Rtree *pRtree = (Rtree *)(cur->pVtab); - int ii; RtreeCursor *pCsr = (RtreeCursor *)cur; - freeCursorConstraints(pCsr); - sqlite3_free(pCsr->aPoint); - for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]); - sqlite3_free(pCsr); + assert( pRtree->nCursor>0 ); + resetCursor(pCsr); + tdsqlite3_finalize(pCsr->pReadAux); + tdsqlite3_free(pCsr); + pRtree->nCursor--; + nodeBlobReset(pRtree); return SQLITE_OK; } @@ -165347,7 +190785,7 @@ static int rtreeClose(sqlite3_vtab_cursor *cur){ ** Return non-zero if the cursor does not currently point to a valid ** record (i.e if the scan has finished), or zero otherwise. */ -static int rtreeEof(sqlite3_vtab_cursor *cur){ +static int rtreeEof(tdsqlite3_vtab_cursor *cur){ RtreeCursor *pCsr = (RtreeCursor *)cur; return pCsr->atEOF; } @@ -165360,34 +190798,41 @@ static int rtreeEof(sqlite3_vtab_cursor *cur){ ** false. a[] is the four bytes of the on-disk record to be decoded. ** Store the results in "r". ** -** There are three versions of this macro, one each for little-endian and -** big-endian processors and a third generic implementation. The endian- -** specific implementations are much faster and are preferred if the -** processor endianness is known at compile-time. The SQLITE_BYTEORDER -** macro is part of sqliteInt.h and hence the endian-specific -** implementation will only be used if this module is compiled as part -** of the amalgamation. +** There are five versions of this macro. The last one is generic. The +** other four are various architectures-specific optimizations. */ -#if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234 +#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 +#define RTREE_DECODE_COORD(eInt, a, r) { \ + RtreeCoord c; /* Coordinate decoded */ \ + c.u = _byteswap_ulong(*(u32*)a); \ + r = eInt ? (tdsqlite3_rtree_dbl)c.i : (tdsqlite3_rtree_dbl)c.f; \ +} +#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 +#define RTREE_DECODE_COORD(eInt, a, r) { \ + RtreeCoord c; /* Coordinate decoded */ \ + c.u = __builtin_bswap32(*(u32*)a); \ + r = eInt ? (tdsqlite3_rtree_dbl)c.i : (tdsqlite3_rtree_dbl)c.f; \ +} +#elif SQLITE_BYTEORDER==1234 #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ memcpy(&c.u,a,4); \ c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \ ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \ - r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ + r = eInt ? (tdsqlite3_rtree_dbl)c.i : (tdsqlite3_rtree_dbl)c.f; \ } -#elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321 +#elif SQLITE_BYTEORDER==4321 #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ memcpy(&c.u,a,4); \ - r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ + r = eInt ? (tdsqlite3_rtree_dbl)c.i : (tdsqlite3_rtree_dbl)c.f; \ } #else #define RTREE_DECODE_COORD(eInt, a, r) { \ RtreeCoord c; /* Coordinate decoded */ \ c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \ +((u32)a[2]<<8) + a[3]; \ - r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ + r = eInt ? (tdsqlite3_rtree_dbl)c.i : (tdsqlite3_rtree_dbl)c.f; \ } #endif @@ -165400,14 +190845,14 @@ static int rtreeCallbackConstraint( int eInt, /* True if RTree holding integer coordinates */ u8 *pCellData, /* Raw cell content */ RtreeSearchPoint *pSearch, /* Container of this cell */ - sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */ + tdsqlite3_rtree_dbl *prScore, /* OUT: score for the cell */ int *peWithin /* OUT: visibility of the cell */ ){ - int i; /* Loop counter */ - sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */ + tdsqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */ int nCoord = pInfo->nCoord; /* No. of coordinates */ int rc; /* Callback return code */ - sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */ + RtreeCoord c; /* Translator union */ + tdsqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */ assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY ); assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 ); @@ -165416,13 +190861,41 @@ static int rtreeCallbackConstraint( pInfo->iRowid = readInt64(pCellData); } pCellData += 8; - for(i=0; i<nCoord; i++, pCellData += 4){ - RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]); +#ifndef SQLITE_RTREE_INT_ONLY + if( eInt==0 ){ + switch( nCoord ){ + case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f; + readCoord(pCellData+32, &c); aCoord[8] = c.f; + case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f; + readCoord(pCellData+24, &c); aCoord[6] = c.f; + case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f; + readCoord(pCellData+16, &c); aCoord[4] = c.f; + case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f; + readCoord(pCellData+8, &c); aCoord[2] = c.f; + default: readCoord(pCellData+4, &c); aCoord[1] = c.f; + readCoord(pCellData, &c); aCoord[0] = c.f; + } + }else +#endif + { + switch( nCoord ){ + case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i; + readCoord(pCellData+32, &c); aCoord[8] = c.i; + case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i; + readCoord(pCellData+24, &c); aCoord[6] = c.i; + case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i; + readCoord(pCellData+16, &c); aCoord[4] = c.i; + case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i; + readCoord(pCellData+8, &c); aCoord[2] = c.i; + default: readCoord(pCellData+4, &c); aCoord[1] = c.i; + readCoord(pCellData, &c); aCoord[0] = c.i; + } } if( pConstraint->op==RTREE_MATCH ){ - rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo, - nCoord, aCoord, &i); - if( i==0 ) *peWithin = NOT_WITHIN; + int eWithin = 0; + rc = pConstraint->u.xGeom((tdsqlite3_rtree_geometry*)pInfo, + nCoord, aCoord, &eWithin); + if( eWithin==0 ) *peWithin = NOT_WITHIN; *prScore = RTREE_ZERO; }else{ pInfo->aCoord = aCoord; @@ -165449,7 +190922,7 @@ static void rtreeNonleafConstraint( u8 *pCellData, /* Raw cell content as appears on disk */ int *peWithin /* Adjust downward, as appropriate */ ){ - sqlite3_rtree_dbl val; /* Coordinate value convert to a double */ + tdsqlite3_rtree_dbl val; /* Coordinate value convert to a double */ /* p->iCoord might point to either a lower or upper bound coordinate ** in a coordinate pair. But make pCellData point to the lower bound. @@ -165457,8 +190930,12 @@ static void rtreeNonleafConstraint( pCellData += 8 + 4*(p->iCoord&0xfe); assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE - || p->op==RTREE_GT || p->op==RTREE_EQ ); + || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE + || p->op==RTREE_FALSE ); + assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */ switch( p->op ){ + case RTREE_TRUE: return; /* Always satisfied */ + case RTREE_FALSE: break; /* Never satisfied */ case RTREE_LE: case RTREE_LT: case RTREE_EQ: @@ -165496,15 +190973,19 @@ static void rtreeLeafConstraint( RtreeDValue xN; /* Coordinate value converted to a double */ assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE - || p->op==RTREE_GT || p->op==RTREE_EQ ); + || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE + || p->op==RTREE_FALSE ); pCellData += 8 + p->iCoord*4; + assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */ RTREE_DECODE_COORD(eInt, pCellData, xN); switch( p->op ){ - case RTREE_LE: if( xN <= p->u.rValue ) return; break; - case RTREE_LT: if( xN < p->u.rValue ) return; break; - case RTREE_GE: if( xN >= p->u.rValue ) return; break; - case RTREE_GT: if( xN > p->u.rValue ) return; break; - default: if( xN == p->u.rValue ) return; break; + case RTREE_TRUE: return; /* Always satisfied */ + case RTREE_FALSE: break; /* Never satisfied */ + case RTREE_LE: if( xN <= p->u.rValue ) return; break; + case RTREE_LT: if( xN < p->u.rValue ) return; break; + case RTREE_GE: if( xN >= p->u.rValue ) return; break; + case RTREE_GT: if( xN > p->u.rValue ) return; break; + default: if( xN == p->u.rValue ) return; break; } *peWithin = NOT_WITHIN; } @@ -165528,6 +191009,7 @@ static int nodeRowidIndex( return SQLITE_OK; } } + RTREE_IS_CORRUPT(pRtree); return SQLITE_CORRUPT_VTAB; } @@ -165566,7 +191048,7 @@ static int rtreeSearchPointCompare( } /* -** Interchange to search points in a cursor. +** Interchange two search points in a cursor. */ static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){ RtreeSearchPoint t = p->aPoint[i]; @@ -165597,7 +191079,7 @@ static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){ ** Get the RtreeNode for the search point with the lowest score. */ static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){ - sqlite3_int64 id; + tdsqlite3_int64 id; int ii = 1 - pCur->bPoint; assert( ii==0 || ii==1 ); assert( pCur->bPoint || pCur->nPoint ); @@ -165621,7 +191103,7 @@ static RtreeSearchPoint *rtreeEnqueue( RtreeSearchPoint *pNew; if( pCur->nPoint>=pCur->nPointAlloc ){ int nNew = pCur->nPointAlloc*2 + 8; - pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0])); + pNew = tdsqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0])); if( pNew==0 ) return 0; pCur->aPoint = pNew; pCur->nPointAlloc = nNew; @@ -165667,7 +191149,7 @@ static RtreeSearchPoint *rtreeSearchPointNew( if( ii<RTREE_CACHE_SZ ){ assert( pCur->aNode[ii]==0 ); pCur->aNode[ii] = pCur->aNode[0]; - }else{ + }else{ nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]); } pCur->aNode[0] = 0; @@ -165776,13 +191258,14 @@ static int rtreeStepToLeaf(RtreeCursor *pCur){ eInt = pRtree->eCoordType==RTREE_COORD_INT32; while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){ + u8 *pCellData; pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc); if( rc ) return rc; nCell = NCELL(pNode); assert( nCell<200 ); + pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell); while( p->iCell<nCell ){ - sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1; - u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell); + tdsqlite3_rtree_dbl rScore = (tdsqlite3_rtree_dbl)-1; eWithin = FULLY_WITHIN; for(ii=0; ii<nConstraint; ii++){ RtreeConstraint *pConstraint = pCur->aConstraint + ii; @@ -165795,13 +191278,23 @@ static int rtreeStepToLeaf(RtreeCursor *pCur){ }else{ rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin); } - if( eWithin==NOT_WITHIN ) break; + if( eWithin==NOT_WITHIN ){ + p->iCell++; + pCellData += pRtree->nBytesPerCell; + break; + } } - p->iCell++; if( eWithin==NOT_WITHIN ) continue; + p->iCell++; x.iLevel = p->iLevel - 1; if( x.iLevel ){ x.id = readInt64(pCellData); + for(ii=0; ii<pCur->nPoint; ii++){ + if( pCur->aPoint[ii].id==x.id ){ + RTREE_IS_CORRUPT(pRtree); + return SQLITE_CORRUPT_VTAB; + } + } x.iCell = 0; }else{ x.id = p->id; @@ -165814,7 +191307,7 @@ static int rtreeStepToLeaf(RtreeCursor *pCur){ if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO; p = rtreeSearchPointNew(pCur, rScore, x.iLevel); if( p==0 ) return SQLITE_NOMEM; - p->eWithin = eWithin; + p->eWithin = (u8)eWithin; p->id = x.id; p->iCell = x.iCell; RTREE_QUEUE_TRACE(pCur, "PUSH-S:"); @@ -165832,12 +191325,16 @@ static int rtreeStepToLeaf(RtreeCursor *pCur){ /* ** Rtree virtual table module xNext method. */ -static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ +static int rtreeNext(tdsqlite3_vtab_cursor *pVtabCursor){ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; int rc = SQLITE_OK; /* Move to the next entry that matches the configured constraints. */ RTREE_QUEUE_TRACE(pCsr, "POP-Nx:"); + if( pCsr->bAuxValid ){ + pCsr->bAuxValid = 0; + tdsqlite3_reset(pCsr->pReadAux); + } rtreeSearchPointPop(pCsr); rc = rtreeStepToLeaf(pCsr); return rc; @@ -165846,7 +191343,7 @@ static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ /* ** Rtree virtual table module xRowid method. */ -static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ +static int rtreeRowid(tdsqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); int rc = SQLITE_OK; @@ -165860,7 +191357,7 @@ static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ /* ** Rtree virtual table module xColumn method. */ -static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ +static int rtreeColumn(tdsqlite3_vtab_cursor *cur, tdsqlite3_context *ctx, int i){ Rtree *pRtree = (Rtree *)cur->pVtab; RtreeCursor *pCsr = (RtreeCursor *)cur; RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); @@ -165871,20 +191368,39 @@ static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ if( rc ) return rc; if( p==0 ) return SQLITE_OK; if( i==0 ){ - sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell)); - }else{ - if( rc ) return rc; + tdsqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell)); + }else if( i<=pRtree->nDim2 ){ nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c); #ifndef SQLITE_RTREE_INT_ONLY if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - sqlite3_result_double(ctx, c.f); + tdsqlite3_result_double(ctx, c.f); }else #endif { assert( pRtree->eCoordType==RTREE_COORD_INT32 ); - sqlite3_result_int(ctx, c.i); + tdsqlite3_result_int(ctx, c.i); } - } + }else{ + if( !pCsr->bAuxValid ){ + if( pCsr->pReadAux==0 ){ + rc = tdsqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0, + &pCsr->pReadAux, 0); + if( rc ) return rc; + } + tdsqlite3_bind_int64(pCsr->pReadAux, 1, + nodeGetRowid(pRtree, pNode, p->iCell)); + rc = tdsqlite3_step(pCsr->pReadAux); + if( rc==SQLITE_ROW ){ + pCsr->bAuxValid = 1; + }else{ + tdsqlite3_reset(pCsr->pReadAux); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + return rc; + } + } + tdsqlite3_result_value(ctx, + tdsqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1)); + } return SQLITE_OK; } @@ -165899,18 +191415,18 @@ static int findLeafNode( Rtree *pRtree, /* RTree to search */ i64 iRowid, /* The rowid searching for */ RtreeNode **ppLeaf, /* Write the node here */ - sqlite3_int64 *piNode /* Write the node-id here */ + tdsqlite3_int64 *piNode /* Write the node-id here */ ){ int rc; *ppLeaf = 0; - sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); - if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ - i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0); + tdsqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); + if( tdsqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ + i64 iNode = tdsqlite3_column_int64(pRtree->pReadRowid, 0); if( piNode ) *piNode = iNode; rc = nodeAcquire(pRtree, iNode, 0, ppLeaf); - sqlite3_reset(pRtree->pReadRowid); + tdsqlite3_reset(pRtree->pReadRowid); }else{ - rc = sqlite3_reset(pRtree->pReadRowid); + rc = tdsqlite3_reset(pRtree->pReadRowid); } return rc; } @@ -165921,34 +191437,18 @@ static int findLeafNode( ** first argument to this function is the right-hand operand to the MATCH ** operator. */ -static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){ - RtreeMatchArg *pBlob; /* BLOB returned by geometry function */ - sqlite3_rtree_query_info *pInfo; /* Callback information */ - int nBlob; /* Size of the geometry function blob */ - int nExpected; /* Expected size of the BLOB */ - - /* Check that value is actually a blob. */ - if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR; - - /* Check that the blob is roughly the right size. */ - nBlob = sqlite3_value_bytes(pValue); - if( nBlob<(int)sizeof(RtreeMatchArg) ){ - return SQLITE_ERROR; - } +static int deserializeGeometry(tdsqlite3_value *pValue, RtreeConstraint *pCons){ + RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */ + tdsqlite3_rtree_query_info *pInfo; /* Callback information */ - pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob ); + pSrc = tdsqlite3_value_pointer(pValue, "RtreeMatchArg"); + if( pSrc==0 ) return SQLITE_ERROR; + pInfo = (tdsqlite3_rtree_query_info*) + tdsqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize ); if( !pInfo ) return SQLITE_NOMEM; memset(pInfo, 0, sizeof(*pInfo)); pBlob = (RtreeMatchArg*)&pInfo[1]; - - memcpy(pBlob, sqlite3_value_blob(pValue), nBlob); - nExpected = (int)(sizeof(RtreeMatchArg) + - pBlob->nParam*sizeof(sqlite3_value*) + - (pBlob->nParam-1)*sizeof(RtreeDValue)); - if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){ - sqlite3_free(pInfo); - return SQLITE_ERROR; - } + memcpy(pBlob, pSrc, pSrc->iSize); pInfo->pContext = pBlob->cb.pContext; pInfo->nParam = pBlob->nParam; pInfo->aParam = pBlob->aParam; @@ -165968,9 +191468,9 @@ static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){ ** Rtree virtual table module xFilter method. */ static int rtreeFilter( - sqlite3_vtab_cursor *pVtabCursor, + tdsqlite3_vtab_cursor *pVtabCursor, int idxNum, const char *idxStr, - int argc, sqlite3_value **argv + int argc, tdsqlite3_value **argv ){ Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; @@ -165982,19 +191482,24 @@ static int rtreeFilter( rtreeReference(pRtree); /* Reset the cursor to the same state as rtreeOpen() leaves it in. */ - freeCursorConstraints(pCsr); - sqlite3_free(pCsr->aPoint); - memset(pCsr, 0, sizeof(RtreeCursor)); - pCsr->base.pVtab = (sqlite3_vtab*)pRtree; + resetCursor(pCsr); pCsr->iStrategy = idxNum; if( idxNum==1 ){ /* Special case - lookup by rowid. */ RtreeNode *pLeaf; /* Leaf on which the required cell resides */ RtreeSearchPoint *p; /* Search point for the leaf */ - i64 iRowid = sqlite3_value_int64(argv[0]); + i64 iRowid = tdsqlite3_value_int64(argv[0]); i64 iNode = 0; - rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode); + int eType = tdsqlite3_value_numeric_type(argv[0]); + if( eType==SQLITE_INTEGER + || (eType==SQLITE_FLOAT && tdsqlite3_value_double(argv[0])==iRowid) + ){ + rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode); + }else{ + rc = SQLITE_OK; + pLeaf = 0; + } if( rc==SQLITE_OK && pLeaf!=0 ){ p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0); assert( p!=0 ); /* Always returns pCsr->sPoint */ @@ -166002,7 +191507,7 @@ static int rtreeFilter( p->id = iNode; p->eWithin = PARTLY_WITHIN; rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell); - p->iCell = iCell; + p->iCell = (u8)iCell; RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:"); }else{ pCsr->atEOF = 1; @@ -166013,7 +191518,7 @@ static int rtreeFilter( */ rc = nodeAcquire(pRtree, 1, 0, &pRoot); if( rc==SQLITE_OK && argc>0 ){ - pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc); + pCsr->aConstraint = tdsqlite3_malloc64(sizeof(RtreeConstraint)*argc); pCsr->nConstraint = argc; if( !pCsr->aConstraint ){ rc = SQLITE_NOMEM; @@ -166024,33 +191529,43 @@ static int rtreeFilter( || (idxStr && (int)strlen(idxStr)==argc*2) ); for(ii=0; ii<argc; ii++){ RtreeConstraint *p = &pCsr->aConstraint[ii]; + int eType = tdsqlite3_value_numeric_type(argv[ii]); p->op = idxStr[ii*2]; p->iCoord = idxStr[ii*2+1]-'0'; if( p->op>=RTREE_MATCH ){ /* A MATCH operator. The right-hand-side must be a blob that ** can be cast into an RtreeMatchArg object. One created using - ** an sqlite3_rtree_geometry_callback() SQL user function. + ** an tdsqlite3_rtree_geometry_callback() SQL user function. */ rc = deserializeGeometry(argv[ii], p); if( rc!=SQLITE_OK ){ break; } - p->pInfo->nCoord = pRtree->nDim*2; + p->pInfo->nCoord = pRtree->nDim2; p->pInfo->anQueue = pCsr->anQueue; p->pInfo->mxLevel = pRtree->iDepth + 1; - }else{ + }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ #ifdef SQLITE_RTREE_INT_ONLY - p->u.rValue = sqlite3_value_int64(argv[ii]); + p->u.rValue = tdsqlite3_value_int64(argv[ii]); #else - p->u.rValue = sqlite3_value_double(argv[ii]); + p->u.rValue = tdsqlite3_value_double(argv[ii]); #endif + }else{ + p->u.rValue = RTREE_ZERO; + if( eType==SQLITE_NULL ){ + p->op = RTREE_FALSE; + }else if( p->op==RTREE_LT || p->op==RTREE_LE ){ + p->op = RTREE_TRUE; + }else{ + p->op = RTREE_FALSE; + } } } } } if( rc==SQLITE_OK ){ RtreeSearchPoint *pNew; - pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1); + pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1)); if( pNew==0 ) return SQLITE_NOMEM; pNew->id = 1; pNew->iCell = 0; @@ -166069,19 +191584,6 @@ static int rtreeFilter( } /* -** Set the pIdxInfo->estimatedRows variable to nRow. Unless this -** extension is currently being used by a version of SQLite too old to -** support estimatedRows. In that case this function is a no-op. -*/ -static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ -#if SQLITE_VERSION_NUMBER>=3008002 - if( sqlite3_libversion_number()>=3008002 ){ - pIdxInfo->estimatedRows = nRow; - } -#endif -} - -/* ** Rtree virtual table module xBestIndex method. There are three ** table scan strategies to choose from (in order from most to ** least desirable): @@ -166095,7 +191597,7 @@ static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ ** If strategy 1 is used, then idxStr is not meaningful. If strategy ** 2 is used, idxStr is formatted to contain 2 bytes for each ** constraint used. The first two bytes of idxStr correspond to -** the constraint in sqlite3_index_info.aConstraintUsage[] with +** the constraint in tdsqlite3_index_info.aConstraintUsage[] with ** (argvIndex==1) etc. ** ** The first of each pair of bytes in idxStr identifies the constraint @@ -166115,7 +191617,7 @@ static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ ** to which the constraint applies. The leftmost coordinate column ** is 'a', the second from the left 'b' etc. */ -static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ +static int rtreeBestIndex(tdsqlite3_vtab *tab, tdsqlite3_index_info *pIdxInfo){ Rtree *pRtree = (Rtree*)tab; int rc = SQLITE_OK; int ii; @@ -166138,7 +191640,7 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ assert( pIdxInfo->idxStr==0 ); for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){ - struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; + struct tdsqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; if( bMatch==0 && p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ @@ -166160,39 +191662,43 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ ** a single row. */ pIdxInfo->estimatedCost = 30.0; - setEstimatedRows(pIdxInfo, 1); + pIdxInfo->estimatedRows = 1; + pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE; return SQLITE_OK; } - if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){ + if( p->usable + && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2) + || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) + ){ u8 op; switch( p->op ){ - case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; - case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; - case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; - case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; - case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; - default: - assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH ); - op = RTREE_MATCH; - break; + case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; + case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; + case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; + case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; + case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; + case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break; + default: op = 0; break; + } + if( op ){ + zIdxStr[iIdx++] = op; + zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0'); + pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2); + pIdxInfo->aConstraintUsage[ii].omit = 1; } - zIdxStr[iIdx++] = op; - zIdxStr[iIdx++] = p->iColumn - 1 + '0'; - pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2); - pIdxInfo->aConstraintUsage[ii].omit = 1; } } pIdxInfo->idxNum = 2; pIdxInfo->needToFreeIdxStr = 1; - if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ + if( iIdx>0 && 0==(pIdxInfo->idxStr = tdsqlite3_mprintf("%s", zIdxStr)) ){ return SQLITE_NOMEM; } nRow = pRtree->nRowEst >> (iIdx/2); pIdxInfo->estimatedCost = (double)6.0 * (double)nRow; - setEstimatedRows(pIdxInfo, nRow); + pIdxInfo->estimatedRows = nRow; return rc; } @@ -166202,9 +191708,26 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ */ static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){ RtreeDValue area = (RtreeDValue)1; - int ii; - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ - area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]))); + assert( pRtree->nDim>=1 && pRtree->nDim<=5 ); +#ifndef SQLITE_RTREE_INT_ONLY + if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ + switch( pRtree->nDim ){ + case 5: area = p->aCoord[9].f - p->aCoord[8].f; + case 4: area *= p->aCoord[7].f - p->aCoord[6].f; + case 3: area *= p->aCoord[5].f - p->aCoord[4].f; + case 2: area *= p->aCoord[3].f - p->aCoord[2].f; + default: area *= p->aCoord[1].f - p->aCoord[0].f; + } + }else +#endif + { + switch( pRtree->nDim ){ + case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i; + case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i; + case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i; + case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i; + default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i; + } } return area; } @@ -166214,11 +191737,12 @@ static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){ ** of the objects size in each dimension. */ static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){ - RtreeDValue margin = (RtreeDValue)0; - int ii; - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + RtreeDValue margin = 0; + int ii = pRtree->nDim2 - 2; + do{ margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); - } + ii -= 2; + }while( ii>=0 ); return margin; } @@ -166226,17 +191750,19 @@ static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){ ** Store the union of cells p1 and p2 in p1. */ static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ - int ii; + int ii = 0; if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + do{ p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f); p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f); - } + ii += 2; + }while( ii<pRtree->nDim2 ); }else{ - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + do{ p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i); p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i); - } + ii += 2; + }while( ii<pRtree->nDim2 ); } } @@ -166247,7 +191773,7 @@ static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ int ii; int isInt = (pRtree->eCoordType==RTREE_COORD_INT32); - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ + for(ii=0; ii<pRtree->nDim2; ii+=2){ RtreeCoord *a1 = &p1->aCoord[ii]; RtreeCoord *a2 = &p2->aCoord[ii]; if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) @@ -166282,7 +191808,7 @@ static RtreeDValue cellOverlap( for(ii=0; ii<nCell; ii++){ int jj; RtreeDValue o = (RtreeDValue)1; - for(jj=0; jj<(pRtree->nDim*2); jj+=2){ + for(jj=0; jj<pRtree->nDim2; jj+=2){ RtreeDValue x1, x2; x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj])); x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1])); @@ -166311,12 +191837,12 @@ static int ChooseLeaf( ){ int rc; int ii; - RtreeNode *pNode; + RtreeNode *pNode = 0; rc = nodeAcquire(pRtree, 1, 0, &pNode); for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){ int iCell; - sqlite3_int64 iBest = 0; + tdsqlite3_int64 iBest = 0; RtreeDValue fMinGrowth = RTREE_ZERO; RtreeDValue fMinArea = RTREE_ZERO; @@ -166348,7 +191874,7 @@ static int ChooseLeaf( } } - sqlite3_free(aCell); + tdsqlite3_free(aCell); rc = nodeAcquire(pRtree, iBest, pNode, &pChild); nodeRelease(pRtree, pNode); pNode = pChild; @@ -166369,12 +191895,14 @@ static int AdjustTree( RtreeCell *pCell /* This cell was just inserted */ ){ RtreeNode *p = pNode; + int cnt = 0; while( p->pParent ){ RtreeNode *pParent = p->pParent; RtreeCell cell; int iCell; - if( nodeParentIndex(pRtree, p, &iCell) ){ + if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell) ){ + RTREE_IS_CORRUPT(pRtree); return SQLITE_CORRUPT_VTAB; } @@ -166392,21 +191920,21 @@ static int AdjustTree( /* ** Write mapping (iRowid->iNode) to the <rtree>_rowid table. */ -static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){ - sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); - sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); - sqlite3_step(pRtree->pWriteRowid); - return sqlite3_reset(pRtree->pWriteRowid); +static int rowidWrite(Rtree *pRtree, tdsqlite3_int64 iRowid, tdsqlite3_int64 iNode){ + tdsqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); + tdsqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); + tdsqlite3_step(pRtree->pWriteRowid); + return tdsqlite3_reset(pRtree->pWriteRowid); } /* ** Write mapping (iNode->iPar) to the <rtree>_parent table. */ -static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){ - sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); - sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); - sqlite3_step(pRtree->pWriteParent); - return sqlite3_reset(pRtree->pWriteParent); +static int parentWrite(Rtree *pRtree, tdsqlite3_int64 iNode, tdsqlite3_int64 iPar){ + tdsqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); + tdsqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); + tdsqlite3_step(pRtree->pWriteParent); + return tdsqlite3_reset(pRtree->pWriteParent); } static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int); @@ -166571,9 +192099,9 @@ static int splitNodeStartree( int iBestSplit = 0; RtreeDValue fBestMargin = RTREE_ZERO; - int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int)); + tdsqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int)); - aaSorted = (int **)sqlite3_malloc(nByte); + aaSorted = (int **)tdsqlite3_malloc64(nByte); if( !aaSorted ){ return SQLITE_NOMEM; } @@ -166647,7 +192175,7 @@ static int splitNodeStartree( cellUnion(pRtree, pBbox, pCell); } - sqlite3_free(aaSorted); + tdsqlite3_free(aaSorted); return SQLITE_OK; } @@ -166658,7 +192186,7 @@ static int updateMapping( RtreeNode *pNode, int iHeight ){ - int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64); + int (*xSetMapping)(Rtree *, tdsqlite3_int64, tdsqlite3_int64); xSetMapping = ((iHeight==0)?rowidWrite:parentWrite); if( iHeight>0 ){ RtreeNode *pChild = nodeHashLookup(pRtree, iRowid); @@ -166694,7 +192222,7 @@ static int SplitNode( /* Allocate an array and populate it with a copy of pCell and ** all cells from node pLeft. Then zero the original node. */ - aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); + aCell = tdsqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); if( !aCell ){ rc = SQLITE_NOMEM; goto splitnode_out; @@ -166717,7 +192245,7 @@ static int SplitNode( }else{ pLeft = pNode; pRight = nodeNew(pRtree, pLeft->pParent); - nodeReference(pLeft); + pLeft->nRef++; } if( !pLeft || !pRight ){ @@ -166803,7 +192331,7 @@ static int SplitNode( splitnode_out: nodeRelease(pRtree, pRight); nodeRelease(pRtree, pLeft); - sqlite3_free(aCell); + tdsqlite3_free(aCell); return rc; } @@ -166822,9 +192350,9 @@ static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ int rc = SQLITE_OK; RtreeNode *pChild = pLeaf; while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){ - int rc2 = SQLITE_OK; /* sqlite3_reset() return code */ - sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode); - rc = sqlite3_step(pRtree->pReadParent); + int rc2 = SQLITE_OK; /* tdsqlite3_reset() return code */ + tdsqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode); + rc = tdsqlite3_step(pRtree->pReadParent); if( rc==SQLITE_ROW ){ RtreeNode *pTest; /* Used to test for reference loops */ i64 iNode; /* Node number of parent node */ @@ -166834,15 +192362,18 @@ static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ ** want to do this as it leads to a memory leak when trying to delete ** the referenced counted node structures. */ - iNode = sqlite3_column_int64(pRtree->pReadParent, 0); + iNode = tdsqlite3_column_int64(pRtree->pReadParent, 0); for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent); if( !pTest ){ rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent); } } - rc = sqlite3_reset(pRtree->pReadParent); + rc = tdsqlite3_reset(pRtree->pReadParent); if( rc==SQLITE_OK ) rc = rc2; - if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB; + if( rc==SQLITE_OK && !pChild->pParent ){ + RTREE_IS_CORRUPT(pRtree); + rc = SQLITE_CORRUPT_VTAB; + } pChild = pChild->pParent; } return rc; @@ -166874,16 +192405,16 @@ static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){ } /* Remove the xxx_node entry. */ - sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); - sqlite3_step(pRtree->pDeleteNode); - if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){ + tdsqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); + tdsqlite3_step(pRtree->pDeleteNode); + if( SQLITE_OK!=(rc = tdsqlite3_reset(pRtree->pDeleteNode)) ){ return rc; } /* Remove the xxx_parent entry. */ - sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); - sqlite3_step(pRtree->pDeleteParent); - if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){ + tdsqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); + tdsqlite3_step(pRtree->pDeleteParent); + if( SQLITE_OK!=(rc = tdsqlite3_reset(pRtree->pDeleteParent)) ){ return rc; } @@ -166982,7 +192513,7 @@ static int Reinsert( /* Allocate the buffers used by this operation. The allocation is ** relinquished before this function returns. */ - aCell = (RtreeCell *)sqlite3_malloc(n * ( + aCell = (RtreeCell *)tdsqlite3_malloc64(n * ( sizeof(RtreeCell) + /* aCell array */ sizeof(int) + /* aOrder array */ sizeof(int) + /* aSpare array */ @@ -167054,7 +192585,7 @@ static int Reinsert( } } - sqlite3_free(aCell); + tdsqlite3_free(aCell); return rc; } @@ -167126,24 +192657,24 @@ static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){ /* ** Select a currently unused rowid for a new r-tree record. */ -static int newRowid(Rtree *pRtree, i64 *piRowid){ +static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){ int rc; - sqlite3_bind_null(pRtree->pWriteRowid, 1); - sqlite3_bind_null(pRtree->pWriteRowid, 2); - sqlite3_step(pRtree->pWriteRowid); - rc = sqlite3_reset(pRtree->pWriteRowid); - *piRowid = sqlite3_last_insert_rowid(pRtree->db); + tdsqlite3_bind_null(pRtree->pWriteRowid, 1); + tdsqlite3_bind_null(pRtree->pWriteRowid, 2); + tdsqlite3_step(pRtree->pWriteRowid); + rc = tdsqlite3_reset(pRtree->pWriteRowid); + *piRowid = tdsqlite3_last_insert_rowid(pRtree->db); return rc; } /* ** Remove the entry with rowid=iDelete from the r-tree structure. */ -static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ +static int rtreeDeleteRowid(Rtree *pRtree, tdsqlite3_int64 iDelete){ int rc; /* Return code */ RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */ int iCell; /* Index of iDelete cell in pLeaf */ - RtreeNode *pRoot; /* Root node of rtree structure */ + RtreeNode *pRoot = 0; /* Root node of rtree structure */ /* Obtain a reference to the root node to initialize Rtree.iDepth */ @@ -167156,8 +192687,12 @@ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ rc = findLeafNode(pRtree, iDelete, &pLeaf, 0); } +#ifdef CORRUPT_DB + assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB ); +#endif + /* Delete the cell in question from the leaf node. */ - if( rc==SQLITE_OK ){ + if( rc==SQLITE_OK && pLeaf ){ int rc2; rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell); if( rc==SQLITE_OK ){ @@ -167171,9 +192706,9 @@ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ /* Delete the corresponding entry in the <rtree>_rowid table. */ if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); - sqlite3_step(pRtree->pDeleteRowid); - rc = sqlite3_reset(pRtree->pDeleteRowid); + tdsqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); + tdsqlite3_step(pRtree->pDeleteRowid); + rc = tdsqlite3_reset(pRtree->pDeleteRowid); } /* Check if the root node now has exactly one child. If so, remove @@ -167186,7 +192721,7 @@ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ */ if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){ int rc2; - RtreeNode *pChild; + RtreeNode *pChild = 0; i64 iChild = nodeGetRowid(pRtree, pRoot, 0); rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); if( rc==SQLITE_OK ){ @@ -167207,7 +192742,8 @@ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ rc = reinsertNodeContent(pRtree, pLeaf); } pRtree->pDeleted = pLeaf->pNext; - sqlite3_free(pLeaf); + pRtree->nNodeRef--; + tdsqlite3_free(pLeaf); } /* Release the reference to the root node. */ @@ -167228,19 +192764,19 @@ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ #if !defined(SQLITE_RTREE_INT_ONLY) /* -** Convert an sqlite3_value into an RtreeValue (presumably a float) +** Convert an tdsqlite3_value into an RtreeValue (presumably a float) ** while taking care to round toward negative or positive, respectively. */ -static RtreeValue rtreeValueDown(sqlite3_value *v){ - double d = sqlite3_value_double(v); +static RtreeValue rtreeValueDown(tdsqlite3_value *v){ + double d = tdsqlite3_value_double(v); float f = (float)d; if( f>d ){ f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS)); } return f; } -static RtreeValue rtreeValueUp(sqlite3_value *v){ - double d = sqlite3_value_double(v); +static RtreeValue rtreeValueUp(tdsqlite3_value *v){ + double d = tdsqlite3_value_double(v); float f = (float)d; if( f<d ){ f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY)); @@ -167263,35 +192799,35 @@ static RtreeValue rtreeValueUp(sqlite3_value *v){ ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT. */ static int rtreeConstraintError(Rtree *pRtree, int iCol){ - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; char *zSql; int rc; assert( iCol==0 || iCol%2 ); - zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName); + zSql = tdsqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName); if( zSql ){ - rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0); + rc = tdsqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0); }else{ rc = SQLITE_NOMEM; } - sqlite3_free(zSql); + tdsqlite3_free(zSql); if( rc==SQLITE_OK ){ if( iCol==0 ){ - const char *zCol = sqlite3_column_name(pStmt, 0); - pRtree->base.zErrMsg = sqlite3_mprintf( + const char *zCol = tdsqlite3_column_name(pStmt, 0); + pRtree->base.zErrMsg = tdsqlite3_mprintf( "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol ); }else{ - const char *zCol1 = sqlite3_column_name(pStmt, iCol); - const char *zCol2 = sqlite3_column_name(pStmt, iCol+1); - pRtree->base.zErrMsg = sqlite3_mprintf( + const char *zCol1 = tdsqlite3_column_name(pStmt, iCol); + const char *zCol2 = tdsqlite3_column_name(pStmt, iCol+1); + pRtree->base.zErrMsg = tdsqlite3_mprintf( "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2 ); } } - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc); } @@ -167301,9 +192837,9 @@ static int rtreeConstraintError(Rtree *pRtree, int iCol){ ** The xUpdate method for rtree module virtual tables. */ static int rtreeUpdate( - sqlite3_vtab *pVtab, + tdsqlite3_vtab *pVtab, int nData, - sqlite3_value **azData, + tdsqlite3_value **aData, sqlite_int64 *pRowid ){ Rtree *pRtree = (Rtree *)pVtab; @@ -167311,6 +192847,12 @@ static int rtreeUpdate( RtreeCell cell; /* New cell to insert if nData>1 */ int bHaveRowid = 0; /* Set to 1 after new rowid is determined */ + if( pRtree->nNodeRef ){ + /* Unable to write to the btree while another cursor is reading from it, + ** since the write might do a rebalance which would disrupt the read + ** cursor. */ + return SQLITE_LOCKED_VTAB; + } rtreeReference(pRtree); assert(nData>=1); @@ -167329,8 +192871,10 @@ static int rtreeUpdate( */ if( nData>1 ){ int ii; + int nn = nData - 4; - /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. + if( nn > pRtree->nDim2 ) nn = pRtree->nDim2; + /* Populate the cell.aCoord[] array. The first coordinate is aData[3]. ** ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared ** with "column" that are interpreted as table constraints. @@ -167338,13 +192882,12 @@ static int rtreeUpdate( ** This problem was discovered after years of use, so we silently ignore ** these kinds of misdeclared tables to avoid breaking any legacy. */ - assert( nData<=(pRtree->nDim*2 + 3) ); #ifndef SQLITE_RTREE_INT_ONLY if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - for(ii=0; ii<nData-4; ii+=2){ - cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]); - cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]); + for(ii=0; ii<nn; ii+=2){ + cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]); + cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]); if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){ rc = rtreeConstraintError(pRtree, ii+1); goto constraint; @@ -167353,9 +192896,9 @@ static int rtreeUpdate( }else #endif { - for(ii=0; ii<nData-4; ii+=2){ - cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]); - cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]); + for(ii=0; ii<nn; ii+=2){ + cell.aCoord[ii].i = tdsqlite3_value_int(aData[ii+3]); + cell.aCoord[ii+1].i = tdsqlite3_value_int(aData[ii+4]); if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){ rc = rtreeConstraintError(pRtree, ii+1); goto constraint; @@ -167365,17 +192908,17 @@ static int rtreeUpdate( /* If a rowid value was supplied, check if it is already present in ** the table. If so, the constraint has failed. */ - if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){ - cell.iRowid = sqlite3_value_int64(azData[2]); - if( sqlite3_value_type(azData[0])==SQLITE_NULL - || sqlite3_value_int64(azData[0])!=cell.iRowid + if( tdsqlite3_value_type(aData[2])!=SQLITE_NULL ){ + cell.iRowid = tdsqlite3_value_int64(aData[2]); + if( tdsqlite3_value_type(aData[0])==SQLITE_NULL + || tdsqlite3_value_int64(aData[0])!=cell.iRowid ){ int steprc; - sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); - steprc = sqlite3_step(pRtree->pReadRowid); - rc = sqlite3_reset(pRtree->pReadRowid); + tdsqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); + steprc = tdsqlite3_step(pRtree->pReadRowid); + rc = tdsqlite3_reset(pRtree->pReadRowid); if( SQLITE_ROW==steprc ){ - if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ + if( tdsqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ rc = rtreeDeleteRowid(pRtree, cell.iRowid); }else{ rc = rtreeConstraintError(pRtree, 0); @@ -167387,16 +192930,16 @@ static int rtreeUpdate( } } - /* If azData[0] is not an SQL NULL value, it is the rowid of a + /* If aData[0] is not an SQL NULL value, it is the rowid of a ** record to delete from the r-tree table. The following block does ** just that. */ - if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){ - rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0])); + if( tdsqlite3_value_type(aData[0])!=SQLITE_NULL ){ + rc = rtreeDeleteRowid(pRtree, tdsqlite3_value_int64(aData[0])); } - /* If the azData[] array contains more than one element, elements - ** (azData[2]..azData[argc-1]) contain a new record to insert into + /* If the aData[] array contains more than one element, elements + ** (aData[2]..aData[argc-1]) contain a new record to insert into ** the r-tree structure. */ if( rc==SQLITE_OK && nData>1 ){ @@ -167405,7 +192948,7 @@ static int rtreeUpdate( /* Figure out the rowid of the new row. */ if( bHaveRowid==0 ){ - rc = newRowid(pRtree, &cell.iRowid); + rc = rtreeNewRowid(pRtree, &cell.iRowid); } *pRowid = cell.iRowid; @@ -167421,6 +192964,16 @@ static int rtreeUpdate( rc = rc2; } } + if( rc==SQLITE_OK && pRtree->nAux ){ + tdsqlite3_stmt *pUp = pRtree->pWriteAux; + int jj; + tdsqlite3_bind_int64(pUp, 1, *pRowid); + for(jj=0; jj<pRtree->nAux; jj++){ + tdsqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]); + } + tdsqlite3_step(pUp); + rc = tdsqlite3_reset(pUp); + } } constraint: @@ -167429,12 +192982,33 @@ constraint: } /* +** Called when a transaction starts. +*/ +static int rtreeBeginTransaction(tdsqlite3_vtab *pVtab){ + Rtree *pRtree = (Rtree *)pVtab; + assert( pRtree->inWrTrans==0 ); + pRtree->inWrTrans++; + return SQLITE_OK; +} + +/* +** Called when a transaction completes (either by COMMIT or ROLLBACK). +** The tdsqlite3_blob object should be released at this point. +*/ +static int rtreeEndTransaction(tdsqlite3_vtab *pVtab){ + Rtree *pRtree = (Rtree *)pVtab; + pRtree->inWrTrans = 0; + nodeBlobReset(pRtree); + return SQLITE_OK; +} + +/* ** The xRename method for rtree module virtual tables. */ -static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ +static int rtreeRename(tdsqlite3_vtab *pVtab, const char *zNewName){ Rtree *pRtree = (Rtree *)pVtab; int rc = SQLITE_NOMEM; - char *zSql = sqlite3_mprintf( + char *zSql = tdsqlite3_mprintf( "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";" "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";" "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";" @@ -167443,39 +193017,64 @@ static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ , pRtree->zDb, pRtree->zName, zNewName ); if( zSql ){ - rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0); - sqlite3_free(zSql); + nodeBlobReset(pRtree); + rc = tdsqlite3_exec(pRtree->db, zSql, 0, 0, 0); + tdsqlite3_free(zSql); } return rc; } /* +** The xSavepoint method. +** +** This module does not need to do anything to support savepoints. However, +** it uses this hook to close any open blob handle. This is done because a +** DROP TABLE command - which fortunately always opens a savepoint - cannot +** succeed if there are any open blob handles. i.e. if the blob handle were +** not closed here, the following would fail: +** +** BEGIN; +** INSERT INTO rtree... +** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED +** COMMIT; +*/ +static int rtreeSavepoint(tdsqlite3_vtab *pVtab, int iSavepoint){ + Rtree *pRtree = (Rtree *)pVtab; + u8 iwt = pRtree->inWrTrans; + UNUSED_PARAMETER(iSavepoint); + pRtree->inWrTrans = 0; + nodeBlobReset(pRtree); + pRtree->inWrTrans = iwt; + return SQLITE_OK; +} + +/* ** This function populates the pRtree->nRowEst variable with an estimate ** of the number of rows in the virtual table. If possible, this is based ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST. */ -static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){ +static int rtreeQueryStat1(tdsqlite3 *db, Rtree *pRtree){ const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'"; char *zSql; - sqlite3_stmt *p; + tdsqlite3_stmt *p; int rc; i64 nRow = 0; - rc = sqlite3_table_column_metadata( + rc = tdsqlite3_table_column_metadata( db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0 ); if( rc!=SQLITE_OK ){ pRtree->nRowEst = RTREE_DEFAULT_ROWEST; return rc==SQLITE_ERROR ? SQLITE_OK : rc; } - zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName); + zSql = tdsqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0); + rc = tdsqlite3_prepare_v2(db, zSql, -1, &p, 0); if( rc==SQLITE_OK ){ - if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0); - rc = sqlite3_finalize(p); + if( tdsqlite3_step(p)==SQLITE_ROW ) nRow = tdsqlite3_column_int64(p, 0); + rc = tdsqlite3_finalize(p); }else if( rc!=SQLITE_NOMEM ){ rc = SQLITE_OK; } @@ -167487,14 +193086,30 @@ static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){ pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST); } } - sqlite3_free(zSql); + tdsqlite3_free(zSql); } return rc; } -static sqlite3_module rtreeModule = { - 0, /* iVersion */ + +/* +** Return true if zName is the extension on one of the shadow tables used +** by this module. +*/ +static int rtreeShadowName(const char *zName){ + static const char *azName[] = { + "node", "parent", "rowid" + }; + unsigned int i; + for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){ + if( tdsqlite3_stricmp(zName, azName[i])==0 ) return 1; + } + return 0; +} + +static tdsqlite3_module rtreeModule = { + 3, /* iVersion */ rtreeCreate, /* xCreate - create a table */ rtreeConnect, /* xConnect - connect to an existing table */ rtreeBestIndex, /* xBestIndex - Determine search strategy */ @@ -167508,86 +193123,136 @@ static sqlite3_module rtreeModule = { rtreeColumn, /* xColumn - read data */ rtreeRowid, /* xRowid - read data */ rtreeUpdate, /* xUpdate - write data */ - 0, /* xBegin - begin transaction */ - 0, /* xSync - sync transaction */ - 0, /* xCommit - commit transaction */ - 0, /* xRollback - rollback transaction */ + rtreeBeginTransaction, /* xBegin - begin transaction */ + rtreeEndTransaction, /* xSync - sync transaction */ + rtreeEndTransaction, /* xCommit - commit transaction */ + rtreeEndTransaction, /* xRollback - rollback transaction */ 0, /* xFindFunction - function overloading */ rtreeRename, /* xRename - rename the table */ - 0, /* xSavepoint */ + rtreeSavepoint, /* xSavepoint */ 0, /* xRelease */ - 0 /* xRollbackTo */ + 0, /* xRollbackTo */ + rtreeShadowName /* xShadowName */ }; static int rtreeSqlInit( Rtree *pRtree, - sqlite3 *db, + tdsqlite3 *db, const char *zDb, const char *zPrefix, int isCreate ){ int rc = SQLITE_OK; - #define N_STATEMENT 9 + #define N_STATEMENT 8 static const char *azSql[N_STATEMENT] = { - /* Read and write the xxx_node table */ - "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1", - "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)", - "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1", + /* Write the xxx_node table */ + "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)", + "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1", /* Read and write the xxx_rowid table */ - "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1", - "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)", - "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1", + "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1", + "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)", + "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1", /* Read and write the xxx_parent table */ - "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1", - "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)", - "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1" + "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1", + "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)", + "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1" }; - sqlite3_stmt **appStmt[N_STATEMENT]; + tdsqlite3_stmt **appStmt[N_STATEMENT]; int i; + const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB; pRtree->db = db; if( isCreate ){ - char *zCreate = sqlite3_mprintf( -"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);" -"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);" -"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY," - " parentnode INTEGER);" -"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))", - zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize - ); + char *zCreate; + tdsqlite3_str *p = tdsqlite3_str_new(db); + int ii; + tdsqlite3_str_appendf(p, + "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno", + zDb, zPrefix); + for(ii=0; ii<pRtree->nAux; ii++){ + tdsqlite3_str_appendf(p,",a%d",ii); + } + tdsqlite3_str_appendf(p, + ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);", + zDb, zPrefix); + tdsqlite3_str_appendf(p, + "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);", + zDb, zPrefix); + tdsqlite3_str_appendf(p, + "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))", + zDb, zPrefix, pRtree->iNodeSize); + zCreate = tdsqlite3_str_finish(p); if( !zCreate ){ return SQLITE_NOMEM; } - rc = sqlite3_exec(db, zCreate, 0, 0, 0); - sqlite3_free(zCreate); + rc = tdsqlite3_exec(db, zCreate, 0, 0, 0); + tdsqlite3_free(zCreate); if( rc!=SQLITE_OK ){ return rc; } } - appStmt[0] = &pRtree->pReadNode; - appStmt[1] = &pRtree->pWriteNode; - appStmt[2] = &pRtree->pDeleteNode; - appStmt[3] = &pRtree->pReadRowid; - appStmt[4] = &pRtree->pWriteRowid; - appStmt[5] = &pRtree->pDeleteRowid; - appStmt[6] = &pRtree->pReadParent; - appStmt[7] = &pRtree->pWriteParent; - appStmt[8] = &pRtree->pDeleteParent; + appStmt[0] = &pRtree->pWriteNode; + appStmt[1] = &pRtree->pDeleteNode; + appStmt[2] = &pRtree->pReadRowid; + appStmt[3] = &pRtree->pWriteRowid; + appStmt[4] = &pRtree->pDeleteRowid; + appStmt[5] = &pRtree->pReadParent; + appStmt[6] = &pRtree->pWriteParent; + appStmt[7] = &pRtree->pDeleteParent; rc = rtreeQueryStat1(db, pRtree); for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){ - char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix); + char *zSql; + const char *zFormat; + if( i!=3 || pRtree->nAux==0 ){ + zFormat = azSql[i]; + }else { + /* An UPSERT is very slightly slower than REPLACE, but it is needed + ** if there are auxiliary columns */ + zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)" + "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno"; + } + zSql = tdsqlite3_mprintf(zFormat, zDb, zPrefix); if( zSql ){ - rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); + rc = tdsqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0); }else{ rc = SQLITE_NOMEM; } - sqlite3_free(zSql); + tdsqlite3_free(zSql); + } + if( pRtree->nAux ){ + pRtree->zReadAuxSql = tdsqlite3_mprintf( + "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1", + zDb, zPrefix); + if( pRtree->zReadAuxSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + tdsqlite3_str *p = tdsqlite3_str_new(db); + int ii; + char *zSql; + tdsqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix); + for(ii=0; ii<pRtree->nAux; ii++){ + if( ii ) tdsqlite3_str_append(p, ",", 1); + if( ii<pRtree->nAuxNotNull ){ + tdsqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii); + }else{ + tdsqlite3_str_appendf(p,"a%d=?%d",ii,ii+2); + } + } + tdsqlite3_str_appendf(p, " WHERE rowid=?1"); + zSql = tdsqlite3_str_finish(p); + if( zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = tdsqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0); + tdsqlite3_free(zSql); + } + } } return rc; @@ -167600,16 +193265,16 @@ static int rtreeSqlInit( ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error ** code is returned and the value of *piVal after returning is not defined. */ -static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){ +static int getIntFromStmt(tdsqlite3 *db, const char *zSql, int *piVal){ int rc = SQLITE_NOMEM; if( zSql ){ - sqlite3_stmt *pStmt = 0; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); + tdsqlite3_stmt *pStmt = 0; + rc = tdsqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - *piVal = sqlite3_column_int(pStmt, 0); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + *piVal = tdsqlite3_column_int(pStmt, 0); } - rc = sqlite3_finalize(pStmt); + rc = tdsqlite3_finalize(pStmt); } } return rc; @@ -167631,7 +193296,7 @@ static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){ ** would fit in a single node, use a smaller node-size. */ static int getNodeSize( - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ Rtree *pRtree, /* Rtree handle */ int isCreate, /* True for xCreate, false for xConnect */ char **pzErr /* OUT: Error message, if any */ @@ -167640,7 +193305,7 @@ static int getNodeSize( char *zSql; if( isCreate ){ int iPageSize = 0; - zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb); + zSql = tdsqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb); rc = getIntFromStmt(db, zSql, &iPageSize); if( rc==SQLITE_OK ){ pRtree->iNodeSize = iPageSize-64; @@ -167648,23 +193313,36 @@ static int getNodeSize( pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS; } }else{ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + *pzErr = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); } }else{ - zSql = sqlite3_mprintf( + zSql = tdsqlite3_mprintf( "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1", pRtree->zDb, pRtree->zName ); rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize); if( rc!=SQLITE_OK ){ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + *pzErr = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); + }else if( pRtree->iNodeSize<(512-64) ){ + rc = SQLITE_CORRUPT_VTAB; + RTREE_IS_CORRUPT(pRtree); + *pzErr = tdsqlite3_mprintf("undersize RTree blobs in \"%q_node\"", + pRtree->zName); } } - sqlite3_free(zSql); + tdsqlite3_free(zSql); return rc; } +/* +** Return the length of a token +*/ +static int rtreeTokenLength(const char *z){ + int dummy = 0; + return tdsqlite3GetToken((const unsigned char*)z,&dummy); +} + /* ** This function is the implementation of both the xConnect and xCreate ** methods of the r-tree virtual table. @@ -167675,10 +193353,10 @@ static int getNodeSize( ** argv[...] -> column names... */ static int rtreeInit( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ void *pAux, /* One of the RTREE_COORD_* constants */ int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ - sqlite3_vtab **ppVtab, /* OUT: New virtual table */ + tdsqlite3_vtab **ppVtab, /* OUT: New virtual table */ char **pzErr, /* OUT: Error message, if any */ int isCreate /* True for xCreate, false for xConnect */ ){ @@ -167687,26 +193365,31 @@ static int rtreeInit( int nDb; /* Length of string argv[1] */ int nName; /* Length of string argv[2] */ int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32); + tdsqlite3_str *pSql; + char *zSql; + int ii = 4; + int iErr; const char *aErrMsg[] = { 0, /* 0 */ "Wrong number of columns for an rtree table", /* 1 */ "Too few columns for an rtree table", /* 2 */ - "Too many columns for an rtree table" /* 3 */ + "Too many columns for an rtree table", /* 3 */ + "Auxiliary rtree columns must be last" /* 4 */ }; - int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2; - if( aErrMsg[iErr] ){ - *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); + assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */ + if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){ + *pzErr = tdsqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]); return SQLITE_ERROR; } - sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); + tdsqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); - /* Allocate the sqlite3_vtab structure */ + /* Allocate the tdsqlite3_vtab structure */ nDb = (int)strlen(argv[1]); nName = (int)strlen(argv[2]); - pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2); + pRtree = (Rtree *)tdsqlite3_malloc64(sizeof(Rtree)+nDb+nName+2); if( !pRtree ){ return SQLITE_NOMEM; } @@ -167715,52 +193398,75 @@ static int rtreeInit( pRtree->base.pModule = &rtreeModule; pRtree->zDb = (char *)&pRtree[1]; pRtree->zName = &pRtree->zDb[nDb+1]; - pRtree->nDim = (argc-4)/2; - pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2; - pRtree->eCoordType = eCoordType; + pRtree->eCoordType = (u8)eCoordType; memcpy(pRtree->zDb, argv[1], nDb); memcpy(pRtree->zName, argv[2], nName); - /* Figure out the node size to use. */ - rc = getNodeSize(db, pRtree, isCreate, pzErr); /* Create/Connect to the underlying relational database schema. If - ** that is successful, call sqlite3_declare_vtab() to configure + ** that is successful, call tdsqlite3_declare_vtab() to configure ** the r-tree table schema. */ - if( rc==SQLITE_OK ){ - if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + pSql = tdsqlite3_str_new(db); + tdsqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT", + rtreeTokenLength(argv[3]), argv[3]); + for(ii=4; ii<argc; ii++){ + const char *zArg = argv[ii]; + if( zArg[0]=='+' ){ + pRtree->nAux++; + tdsqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1); + }else if( pRtree->nAux>0 ){ + break; }else{ - char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]); - char *zTmp; - int ii; - for(ii=4; zSql && ii<argc; ii++){ - zTmp = zSql; - zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]); - sqlite3_free(zTmp); - } - if( zSql ){ - zTmp = zSql; - zSql = sqlite3_mprintf("%s);", zTmp); - sqlite3_free(zTmp); - } - if( !zSql ){ - rc = SQLITE_NOMEM; - }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - } - sqlite3_free(zSql); + pRtree->nDim2++; + tdsqlite3_str_appendf(pSql, ",%.*s NUM", rtreeTokenLength(zArg), zArg); } } - - if( rc==SQLITE_OK ){ - *ppVtab = (sqlite3_vtab *)pRtree; + tdsqlite3_str_appendf(pSql, ");"); + zSql = tdsqlite3_str_finish(pSql); + if( !zSql ){ + rc = SQLITE_NOMEM; + }else if( ii<argc ){ + *pzErr = tdsqlite3_mprintf("%s", aErrMsg[4]); + rc = SQLITE_ERROR; + }else if( SQLITE_OK!=(rc = tdsqlite3_declare_vtab(db, zSql)) ){ + *pzErr = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); + } + tdsqlite3_free(zSql); + if( rc ) goto rtreeInit_fail; + pRtree->nDim = pRtree->nDim2/2; + if( pRtree->nDim<1 ){ + iErr = 2; + }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){ + iErr = 3; + }else if( pRtree->nDim2 % 2 ){ + iErr = 1; }else{ - assert( *ppVtab==0 ); - assert( pRtree->nBusy==1 ); - rtreeRelease(pRtree); + iErr = 0; } + if( iErr ){ + *pzErr = tdsqlite3_mprintf("%s", aErrMsg[iErr]); + goto rtreeInit_fail; + } + pRtree->nBytesPerCell = 8 + pRtree->nDim2*4; + + /* Figure out the node size to use. */ + rc = getNodeSize(db, pRtree, isCreate, pzErr); + if( rc ) goto rtreeInit_fail; + rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate); + if( rc ){ + *pzErr = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); + goto rtreeInit_fail; + } + + *ppVtab = (tdsqlite3_vtab *)pRtree; + return SQLITE_OK; + +rtreeInit_fail: + if( rc==SQLITE_OK ) rc = SQLITE_ERROR; + assert( *ppVtab==0 ); + assert( pRtree->nBusy==1 ); + rtreeRelease(pRtree); return rc; } @@ -167781,49 +193487,46 @@ static int rtreeInit( ** list, containing the 8-byte rowid/pageno followed by the ** <num-dimension>*2 coordinates. */ -static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ - char *zText = 0; +static void rtreenode(tdsqlite3_context *ctx, int nArg, tdsqlite3_value **apArg){ RtreeNode node; Rtree tree; int ii; + int nData; + int errCode; + tdsqlite3_str *pOut; UNUSED_PARAMETER(nArg); memset(&node, 0, sizeof(RtreeNode)); memset(&tree, 0, sizeof(Rtree)); - tree.nDim = sqlite3_value_int(apArg[0]); + tree.nDim = (u8)tdsqlite3_value_int(apArg[0]); + if( tree.nDim<1 || tree.nDim>5 ) return; + tree.nDim2 = tree.nDim*2; tree.nBytesPerCell = 8 + 8 * tree.nDim; - node.zData = (u8 *)sqlite3_value_blob(apArg[1]); + node.zData = (u8 *)tdsqlite3_value_blob(apArg[1]); + nData = tdsqlite3_value_bytes(apArg[1]); + if( nData<4 ) return; + if( nData<NCELL(&node)*tree.nBytesPerCell ) return; + pOut = tdsqlite3_str_new(0); for(ii=0; ii<NCELL(&node); ii++){ - char zCell[512]; - int nCell = 0; RtreeCell cell; int jj; nodeGetCell(&tree, &node, ii, &cell); - sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid); - nCell = (int)strlen(zCell); - for(jj=0; jj<tree.nDim*2; jj++){ + if( ii>0 ) tdsqlite3_str_append(pOut, " ", 1); + tdsqlite3_str_appendf(pOut, "{%lld", cell.iRowid); + for(jj=0; jj<tree.nDim2; jj++){ #ifndef SQLITE_RTREE_INT_ONLY - sqlite3_snprintf(512-nCell,&zCell[nCell], " %g", - (double)cell.aCoord[jj].f); + tdsqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f); #else - sqlite3_snprintf(512-nCell,&zCell[nCell], " %d", - cell.aCoord[jj].i); + tdsqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i); #endif - nCell = (int)strlen(zCell); - } - - if( zText ){ - char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell); - sqlite3_free(zText); - zText = zTextNew; - }else{ - zText = sqlite3_mprintf("{%s}", zCell); } + tdsqlite3_str_append(pOut, "}", 1); } - - sqlite3_result_text(ctx, zText, -1, sqlite3_free); + errCode = tdsqlite3_str_errcode(pOut); + tdsqlite3_result_text(ctx, tdsqlite3_str_finish(pOut), -1, tdsqlite3_free); + tdsqlite3_result_error_code(ctx, errCode); } /* This routine implements an SQL function that returns the "depth" parameter @@ -167835,30 +193538,2316 @@ static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ ** node always has nodeno=1, so the example above is the primary use for this ** routine. This routine is intended for testing and analysis only. */ -static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ +static void rtreedepth(tdsqlite3_context *ctx, int nArg, tdsqlite3_value **apArg){ UNUSED_PARAMETER(nArg); - if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB - || sqlite3_value_bytes(apArg[0])<2 + if( tdsqlite3_value_type(apArg[0])!=SQLITE_BLOB + || tdsqlite3_value_bytes(apArg[0])<2 + ){ + tdsqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); + }else{ + u8 *zBlob = (u8 *)tdsqlite3_value_blob(apArg[0]); + tdsqlite3_result_int(ctx, readInt16(zBlob)); + } +} + +/* +** Context object passed between the various routines that make up the +** implementation of integrity-check function rtreecheck(). +*/ +typedef struct RtreeCheck RtreeCheck; +struct RtreeCheck { + tdsqlite3 *db; /* Database handle */ + const char *zDb; /* Database containing rtree table */ + const char *zTab; /* Name of rtree table */ + int bInt; /* True for rtree_i32 table */ + int nDim; /* Number of dimensions for this rtree tbl */ + tdsqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */ + tdsqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */ + int nLeaf; /* Number of leaf cells in table */ + int nNonLeaf; /* Number of non-leaf cells in table */ + int rc; /* Return code */ + char *zReport; /* Message to report */ + int nErr; /* Number of lines in zReport */ +}; + +#define RTREE_CHECK_MAX_ERROR 100 + +/* +** Reset SQL statement pStmt. If the tdsqlite3_reset() call returns an error, +** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code. +*/ +static void rtreeCheckReset(RtreeCheck *pCheck, tdsqlite3_stmt *pStmt){ + int rc = tdsqlite3_reset(pStmt); + if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc; +} + +/* +** The second and subsequent arguments to this function are a format string +** and printf style arguments. This function formats the string and attempts +** to compile it as an SQL statement. +** +** If successful, a pointer to the new SQL statement is returned. Otherwise, +** NULL is returned and an error code left in RtreeCheck.rc. +*/ +static tdsqlite3_stmt *rtreeCheckPrepare( + RtreeCheck *pCheck, /* RtreeCheck object */ + const char *zFmt, ... /* Format string and trailing args */ +){ + va_list ap; + char *z; + tdsqlite3_stmt *pRet = 0; + + va_start(ap, zFmt); + z = tdsqlite3_vmprintf(zFmt, ap); + + if( pCheck->rc==SQLITE_OK ){ + if( z==0 ){ + pCheck->rc = SQLITE_NOMEM; + }else{ + pCheck->rc = tdsqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0); + } + } + + tdsqlite3_free(z); + va_end(ap); + return pRet; +} + +/* +** The second and subsequent arguments to this function are a printf() +** style format string and arguments. This function formats the string and +** appends it to the report being accumuated in pCheck. +*/ +static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){ + va_list ap; + va_start(ap, zFmt); + if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){ + char *z = tdsqlite3_vmprintf(zFmt, ap); + if( z==0 ){ + pCheck->rc = SQLITE_NOMEM; + }else{ + pCheck->zReport = tdsqlite3_mprintf("%z%s%z", + pCheck->zReport, (pCheck->zReport ? "\n" : ""), z + ); + if( pCheck->zReport==0 ){ + pCheck->rc = SQLITE_NOMEM; + } + } + pCheck->nErr++; + } + va_end(ap); +} + +/* +** This function is a no-op if there is already an error code stored +** in the RtreeCheck object indicated by the first argument. NULL is +** returned in this case. +** +** Otherwise, the contents of rtree table node iNode are loaded from +** the database and copied into a buffer obtained from tdsqlite3_malloc(). +** If no error occurs, a pointer to the buffer is returned and (*pnNode) +** is set to the size of the buffer in bytes. +** +** Or, if an error does occur, NULL is returned and an error code left +** in the RtreeCheck object. The final value of *pnNode is undefined in +** this case. +*/ +static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){ + u8 *pRet = 0; /* Return value */ + + if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){ + pCheck->pGetNode = rtreeCheckPrepare(pCheck, + "SELECT data FROM %Q.'%q_node' WHERE nodeno=?", + pCheck->zDb, pCheck->zTab + ); + } + + if( pCheck->rc==SQLITE_OK ){ + tdsqlite3_bind_int64(pCheck->pGetNode, 1, iNode); + if( tdsqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){ + int nNode = tdsqlite3_column_bytes(pCheck->pGetNode, 0); + const u8 *pNode = (const u8*)tdsqlite3_column_blob(pCheck->pGetNode, 0); + pRet = tdsqlite3_malloc64(nNode); + if( pRet==0 ){ + pCheck->rc = SQLITE_NOMEM; + }else{ + memcpy(pRet, pNode, nNode); + *pnNode = nNode; + } + } + rtreeCheckReset(pCheck, pCheck->pGetNode); + if( pCheck->rc==SQLITE_OK && pRet==0 ){ + rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode); + } + } + + return pRet; +} + +/* +** This function is used to check that the %_parent (if bLeaf==0) or %_rowid +** (if bLeaf==1) table contains a specified entry. The schemas of the +** two tables are: +** +** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER) +** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...) +** +** In both cases, this function checks that there exists an entry with +** IPK value iKey and the second column set to iVal. +** +*/ +static void rtreeCheckMapping( + RtreeCheck *pCheck, /* RtreeCheck object */ + int bLeaf, /* True for a leaf cell, false for interior */ + i64 iKey, /* Key for mapping */ + i64 iVal /* Expected value for mapping */ +){ + int rc; + tdsqlite3_stmt *pStmt; + const char *azSql[2] = { + "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1", + "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1" + }; + + assert( bLeaf==0 || bLeaf==1 ); + if( pCheck->aCheckMapping[bLeaf]==0 ){ + pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck, + azSql[bLeaf], pCheck->zDb, pCheck->zTab + ); + } + if( pCheck->rc!=SQLITE_OK ) return; + + pStmt = pCheck->aCheckMapping[bLeaf]; + tdsqlite3_bind_int64(pStmt, 1, iKey); + rc = tdsqlite3_step(pStmt); + if( rc==SQLITE_DONE ){ + rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table", + iKey, iVal, (bLeaf ? "%_rowid" : "%_parent") + ); + }else if( rc==SQLITE_ROW ){ + i64 ii = tdsqlite3_column_int64(pStmt, 0); + if( ii!=iVal ){ + rtreeCheckAppendMsg(pCheck, + "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)", + iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal + ); + } + } + rtreeCheckReset(pCheck, pStmt); +} + +/* +** Argument pCell points to an array of coordinates stored on an rtree page. +** This function checks that the coordinates are internally consistent (no +** x1>x2 conditions) and adds an error message to the RtreeCheck object +** if they are not. +** +** Additionally, if pParent is not NULL, then it is assumed to point to +** the array of coordinates on the parent page that bound the page +** containing pCell. In this case it is also verified that the two +** sets of coordinates are mutually consistent and an error message added +** to the RtreeCheck object if they are not. +*/ +static void rtreeCheckCellCoord( + RtreeCheck *pCheck, + i64 iNode, /* Node id to use in error messages */ + int iCell, /* Cell number to use in error messages */ + u8 *pCell, /* Pointer to cell coordinates */ + u8 *pParent /* Pointer to parent coordinates */ +){ + RtreeCoord c1, c2; + RtreeCoord p1, p2; + int i; + + for(i=0; i<pCheck->nDim; i++){ + readCoord(&pCell[4*2*i], &c1); + readCoord(&pCell[4*(2*i + 1)], &c2); + + /* printf("%e, %e\n", c1.u.f, c2.u.f); */ + if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){ + rtreeCheckAppendMsg(pCheck, + "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode + ); + } + + if( pParent ){ + readCoord(&pParent[4*2*i], &p1); + readCoord(&pParent[4*(2*i + 1)], &p2); + + if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f) + || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f) + ){ + rtreeCheckAppendMsg(pCheck, + "Dimension %d of cell %d on node %lld is corrupt relative to parent" + , i, iCell, iNode + ); + } + } + } +} + +/* +** Run rtreecheck() checks on node iNode, which is at depth iDepth within +** the r-tree structure. Argument aParent points to the array of coordinates +** that bound node iNode on the parent node. +** +** If any problems are discovered, an error message is appended to the +** report accumulated in the RtreeCheck object. +*/ +static void rtreeCheckNode( + RtreeCheck *pCheck, + int iDepth, /* Depth of iNode (0==leaf) */ + u8 *aParent, /* Buffer containing parent coords */ + i64 iNode /* Node to check */ +){ + u8 *aNode = 0; + int nNode = 0; + + assert( iNode==1 || aParent!=0 ); + assert( pCheck->nDim>0 ); + + aNode = rtreeCheckGetNode(pCheck, iNode, &nNode); + if( aNode ){ + if( nNode<4 ){ + rtreeCheckAppendMsg(pCheck, + "Node %lld is too small (%d bytes)", iNode, nNode + ); + }else{ + int nCell; /* Number of cells on page */ + int i; /* Used to iterate through cells */ + if( aParent==0 ){ + iDepth = readInt16(aNode); + if( iDepth>RTREE_MAX_DEPTH ){ + rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth); + tdsqlite3_free(aNode); + return; + } + } + nCell = readInt16(&aNode[2]); + if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){ + rtreeCheckAppendMsg(pCheck, + "Node %lld is too small for cell count of %d (%d bytes)", + iNode, nCell, nNode + ); + }else{ + for(i=0; i<nCell; i++){ + u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)]; + i64 iVal = readInt64(pCell); + rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent); + + if( iDepth>0 ){ + rtreeCheckMapping(pCheck, 0, iVal, iNode); + rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal); + pCheck->nNonLeaf++; + }else{ + rtreeCheckMapping(pCheck, 1, iVal, iNode); + pCheck->nLeaf++; + } + } + } + } + tdsqlite3_free(aNode); + } +} + +/* +** The second argument to this function must be either "_rowid" or +** "_parent". This function checks that the number of entries in the +** %_rowid or %_parent table is exactly nExpect. If not, it adds +** an error message to the report in the RtreeCheck object indicated +** by the first argument. +*/ +static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){ + if( pCheck->rc==SQLITE_OK ){ + tdsqlite3_stmt *pCount; + pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'", + pCheck->zDb, pCheck->zTab, zTbl + ); + if( pCount ){ + if( tdsqlite3_step(pCount)==SQLITE_ROW ){ + i64 nActual = tdsqlite3_column_int64(pCount, 0); + if( nActual!=nExpect ){ + rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table" + " - expected %lld, actual %lld" , zTbl, nExpect, nActual + ); + } + } + pCheck->rc = tdsqlite3_finalize(pCount); + } + } +} + +/* +** This function does the bulk of the work for the rtree integrity-check. +** It is called by rtreecheck(), which is the SQL function implementation. +*/ +static int rtreeCheckTable( + tdsqlite3 *db, /* Database handle to access db through */ + const char *zDb, /* Name of db ("main", "temp" etc.) */ + const char *zTab, /* Name of rtree table to check */ + char **pzReport /* OUT: tdsqlite3_malloc'd report text */ +){ + RtreeCheck check; /* Common context for various routines */ + tdsqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */ + int bEnd = 0; /* True if transaction should be closed */ + int nAux = 0; /* Number of extra columns. */ + + /* Initialize the context object */ + memset(&check, 0, sizeof(check)); + check.db = db; + check.zDb = zDb; + check.zTab = zTab; + + /* If there is not already an open transaction, open one now. This is + ** to ensure that the queries run as part of this integrity-check operate + ** on a consistent snapshot. */ + if( tdsqlite3_get_autocommit(db) ){ + check.rc = tdsqlite3_exec(db, "BEGIN", 0, 0, 0); + bEnd = 1; + } + + /* Find the number of auxiliary columns */ + if( check.rc==SQLITE_OK ){ + pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab); + if( pStmt ){ + nAux = tdsqlite3_column_count(pStmt) - 2; + tdsqlite3_finalize(pStmt); + } + check.rc = SQLITE_OK; + } + + /* Find number of dimensions in the rtree table. */ + pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab); + if( pStmt ){ + int rc; + check.nDim = (tdsqlite3_column_count(pStmt) - 1 - nAux) / 2; + if( check.nDim<1 ){ + rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree"); + }else if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + check.bInt = (tdsqlite3_column_type(pStmt, 1)==SQLITE_INTEGER); + } + rc = tdsqlite3_finalize(pStmt); + if( rc!=SQLITE_CORRUPT ) check.rc = rc; + } + + /* Do the actual integrity-check */ + if( check.nDim>=1 ){ + if( check.rc==SQLITE_OK ){ + rtreeCheckNode(&check, 0, 0, 1); + } + rtreeCheckCount(&check, "_rowid", check.nLeaf); + rtreeCheckCount(&check, "_parent", check.nNonLeaf); + } + + /* Finalize SQL statements used by the integrity-check */ + tdsqlite3_finalize(check.pGetNode); + tdsqlite3_finalize(check.aCheckMapping[0]); + tdsqlite3_finalize(check.aCheckMapping[1]); + + /* If one was opened, close the transaction */ + if( bEnd ){ + int rc = tdsqlite3_exec(db, "END", 0, 0, 0); + if( check.rc==SQLITE_OK ) check.rc = rc; + } + *pzReport = check.zReport; + return check.rc; +} + +/* +** Usage: +** +** rtreecheck(<rtree-table>); +** rtreecheck(<database>, <rtree-table>); +** +** Invoking this SQL function runs an integrity-check on the named rtree +** table. The integrity-check verifies the following: +** +** 1. For each cell in the r-tree structure (%_node table), that: +** +** a) for each dimension, (coord1 <= coord2). +** +** b) unless the cell is on the root node, that the cell is bounded +** by the parent cell on the parent node. +** +** c) for leaf nodes, that there is an entry in the %_rowid +** table corresponding to the cell's rowid value that +** points to the correct node. +** +** d) for cells on non-leaf nodes, that there is an entry in the +** %_parent table mapping from the cell's child node to the +** node that it resides on. +** +** 2. That there are the same number of entries in the %_rowid table +** as there are leaf cells in the r-tree structure, and that there +** is a leaf cell that corresponds to each entry in the %_rowid table. +** +** 3. That there are the same number of entries in the %_parent table +** as there are non-leaf cells in the r-tree structure, and that +** there is a non-leaf cell that corresponds to each entry in the +** %_parent table. +*/ +static void rtreecheck( + tdsqlite3_context *ctx, + int nArg, + tdsqlite3_value **apArg +){ + if( nArg!=1 && nArg!=2 ){ + tdsqlite3_result_error(ctx, + "wrong number of arguments to function rtreecheck()", -1 + ); + }else{ + int rc; + char *zReport = 0; + const char *zDb = (const char*)tdsqlite3_value_text(apArg[0]); + const char *zTab; + if( nArg==1 ){ + zTab = zDb; + zDb = "main"; + }else{ + zTab = (const char*)tdsqlite3_value_text(apArg[1]); + } + rc = rtreeCheckTable(tdsqlite3_context_db_handle(ctx), zDb, zTab, &zReport); + if( rc==SQLITE_OK ){ + tdsqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT); + }else{ + tdsqlite3_result_error_code(ctx, rc); + } + tdsqlite3_free(zReport); + } +} + +/* Conditionally include the geopoly code */ +#ifdef SQLITE_ENABLE_GEOPOLY +/************** Include geopoly.c in the middle of rtree.c *******************/ +/************** Begin file geopoly.c *****************************************/ +/* +** 2018-05-25 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file implements an alternative R-Tree virtual table that +** uses polygons to express the boundaries of 2-dimensional objects. +** +** This file is #include-ed onto the end of "rtree.c" so that it has +** access to all of the R-Tree internals. +*/ +/* #include <stdlib.h> */ + +/* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */ +#ifdef GEOPOLY_ENABLE_DEBUG + static int geo_debug = 0; +# define GEODEBUG(X) if(geo_debug)printf X +#else +# define GEODEBUG(X) +#endif + +#ifndef JSON_NULL /* The following stuff repeats things found in json1 */ +/* +** Versions of isspace(), isalnum() and isdigit() to which it is safe +** to pass signed char values. +*/ +#ifdef tdsqlite3Isdigit + /* Use the SQLite core versions if this routine is part of the + ** SQLite amalgamation */ +# define safe_isdigit(x) tdsqlite3Isdigit(x) +# define safe_isalnum(x) tdsqlite3Isalnum(x) +# define safe_isxdigit(x) tdsqlite3Isxdigit(x) +#else + /* Use the standard library for separate compilation */ +#include <ctype.h> /* amalgamator: keep */ +# define safe_isdigit(x) isdigit((unsigned char)(x)) +# define safe_isalnum(x) isalnum((unsigned char)(x)) +# define safe_isxdigit(x) isxdigit((unsigned char)(x)) +#endif + +/* +** Growing our own isspace() routine this way is twice as fast as +** the library isspace() function. +*/ +static const char geopolyIsSpace[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +}; +#define safe_isspace(x) (geopolyIsSpace[(unsigned char)x]) +#endif /* JSON NULL - back to original code */ + +/* Compiler and version */ +#ifndef GCC_VERSION +#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) +# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) +#else +# define GCC_VERSION 0 +#endif +#endif +#ifndef MSVC_VERSION +#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) +# define MSVC_VERSION _MSC_VER +#else +# define MSVC_VERSION 0 +#endif +#endif + +/* Datatype for coordinates +*/ +typedef float GeoCoord; + +/* +** Internal representation of a polygon. +** +** The polygon consists of a sequence of vertexes. There is a line +** segment between each pair of vertexes, and one final segment from +** the last vertex back to the first. (This differs from the GeoJSON +** standard in which the final vertex is a repeat of the first.) +** +** The polygon follows the right-hand rule. The area to the right of +** each segment is "outside" and the area to the left is "inside". +** +** The on-disk representation consists of a 4-byte header followed by +** the values. The 4-byte header is: +** +** encoding (1 byte) 0=big-endian, 1=little-endian +** nvertex (3 bytes) Number of vertexes as a big-endian integer +** +** Enough space is allocated for 4 coordinates, to work around over-zealous +** warnings coming from some compiler (notably, clang). In reality, the size +** of each GeoPoly memory allocate is adjusted as necessary so that the +** GeoPoly.a[] array at the end is the appropriate size. +*/ +typedef struct GeoPoly GeoPoly; +struct GeoPoly { + int nVertex; /* Number of vertexes */ + unsigned char hdr[4]; /* Header for on-disk representation */ + GeoCoord a[8]; /* 2*nVertex values. X (longitude) first, then Y */ +}; + +/* The size of a memory allocation needed for a GeoPoly object sufficient +** to hold N coordinate pairs. +*/ +#define GEOPOLY_SZ(N) (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4)) + +/* Macros to access coordinates of a GeoPoly. +** We have to use these macros, rather than just say p->a[i] in order +** to silence (incorrect) UBSAN warnings if the array index is too large. +*/ +#define GeoX(P,I) (((GeoCoord*)(P)->a)[(I)*2]) +#define GeoY(P,I) (((GeoCoord*)(P)->a)[(I)*2+1]) + + +/* +** State of a parse of a GeoJSON input. +*/ +typedef struct GeoParse GeoParse; +struct GeoParse { + const unsigned char *z; /* Unparsed input */ + int nVertex; /* Number of vertexes in a[] */ + int nAlloc; /* Space allocated to a[] */ + int nErr; /* Number of errors encountered */ + GeoCoord *a; /* Array of vertexes. From tdsqlite3_malloc64() */ +}; + +/* Do a 4-byte byte swap */ +static void geopolySwab32(unsigned char *a){ + unsigned char t = a[0]; + a[0] = a[3]; + a[3] = t; + t = a[1]; + a[1] = a[2]; + a[2] = t; +} + +/* Skip whitespace. Return the next non-whitespace character. */ +static char geopolySkipSpace(GeoParse *p){ + while( safe_isspace(p->z[0]) ) p->z++; + return p->z[0]; +} + +/* Parse out a number. Write the value into *pVal if pVal!=0. +** return non-zero on success and zero if the next token is not a number. +*/ +static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){ + char c = geopolySkipSpace(p); + const unsigned char *z = p->z; + int j = 0; + int seenDP = 0; + int seenE = 0; + if( c=='-' ){ + j = 1; + c = z[j]; + } + if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0; + for(;; j++){ + c = z[j]; + if( safe_isdigit(c) ) continue; + if( c=='.' ){ + if( z[j-1]=='-' ) return 0; + if( seenDP ) return 0; + seenDP = 1; + continue; + } + if( c=='e' || c=='E' ){ + if( z[j-1]<'0' ) return 0; + if( seenE ) return -1; + seenDP = seenE = 1; + c = z[j+1]; + if( c=='+' || c=='-' ){ + j++; + c = z[j+1]; + } + if( c<'0' || c>'9' ) return 0; + continue; + } + break; + } + if( z[j-1]<'0' ) return 0; + if( pVal ){ +#ifdef SQLITE_AMALGAMATION + /* The tdsqlite3AtoF() routine is much much faster than atof(), if it + ** is available */ + double r; + (void)tdsqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8); + *pVal = r; +#else + *pVal = (GeoCoord)atof((const char*)p->z); +#endif + } + p->z += j; + return 1; +} + +/* +** If the input is a well-formed JSON array of coordinates with at least +** four coordinates and where each coordinate is itself a two-value array, +** then convert the JSON into a GeoPoly object and return a pointer to +** that object. +** +** If any error occurs, return NULL. +*/ +static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){ + GeoParse s; + int rc = SQLITE_OK; + memset(&s, 0, sizeof(s)); + s.z = z; + if( geopolySkipSpace(&s)=='[' ){ + s.z++; + while( geopolySkipSpace(&s)=='[' ){ + int ii = 0; + char c; + s.z++; + if( s.nVertex>=s.nAlloc ){ + GeoCoord *aNew; + s.nAlloc = s.nAlloc*2 + 16; + aNew = tdsqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 ); + if( aNew==0 ){ + rc = SQLITE_NOMEM; + s.nErr++; + break; + } + s.a = aNew; + } + while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){ + ii++; + if( ii==2 ) s.nVertex++; + c = geopolySkipSpace(&s); + s.z++; + if( c==',' ) continue; + if( c==']' && ii>=2 ) break; + s.nErr++; + rc = SQLITE_ERROR; + goto parse_json_err; + } + if( geopolySkipSpace(&s)==',' ){ + s.z++; + continue; + } + break; + } + if( geopolySkipSpace(&s)==']' + && s.nVertex>=4 + && s.a[0]==s.a[s.nVertex*2-2] + && s.a[1]==s.a[s.nVertex*2-1] + && (s.z++, geopolySkipSpace(&s)==0) + ){ + GeoPoly *pOut; + int x = 1; + s.nVertex--; /* Remove the redundant vertex at the end */ + pOut = tdsqlite3_malloc64( GEOPOLY_SZ((tdsqlite3_int64)s.nVertex) ); + x = 1; + if( pOut==0 ) goto parse_json_err; + pOut->nVertex = s.nVertex; + memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord)); + pOut->hdr[0] = *(unsigned char*)&x; + pOut->hdr[1] = (s.nVertex>>16)&0xff; + pOut->hdr[2] = (s.nVertex>>8)&0xff; + pOut->hdr[3] = s.nVertex&0xff; + tdsqlite3_free(s.a); + if( pRc ) *pRc = SQLITE_OK; + return pOut; + }else{ + s.nErr++; + rc = SQLITE_ERROR; + } + } +parse_json_err: + if( pRc ) *pRc = rc; + tdsqlite3_free(s.a); + return 0; +} + +/* +** Given a function parameter, try to interpret it as a polygon, either +** in the binary format or JSON text. Compute a GeoPoly object and +** return a pointer to that object. Or if the input is not a well-formed +** polygon, put an error message in tdsqlite3_context and return NULL. +*/ +static GeoPoly *geopolyFuncParam( + tdsqlite3_context *pCtx, /* Context for error messages */ + tdsqlite3_value *pVal, /* The value to decode */ + int *pRc /* Write error here */ +){ + GeoPoly *p = 0; + int nByte; + if( tdsqlite3_value_type(pVal)==SQLITE_BLOB + && (nByte = tdsqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord)) ){ - sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); + const unsigned char *a = tdsqlite3_value_blob(pVal); + int nVertex; + nVertex = (a[1]<<16) + (a[2]<<8) + a[3]; + if( (a[0]==0 || a[0]==1) + && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte + ){ + p = tdsqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) ); + if( p==0 ){ + if( pRc ) *pRc = SQLITE_NOMEM; + if( pCtx ) tdsqlite3_result_error_nomem(pCtx); + }else{ + int x = 1; + p->nVertex = nVertex; + memcpy(p->hdr, a, nByte); + if( a[0] != *(unsigned char*)&x ){ + int ii; + for(ii=0; ii<nVertex; ii++){ + geopolySwab32((unsigned char*)&GeoX(p,ii)); + geopolySwab32((unsigned char*)&GeoY(p,ii)); + } + p->hdr[0] ^= 1; + } + } + } + if( pRc ) *pRc = SQLITE_OK; + return p; + }else if( tdsqlite3_value_type(pVal)==SQLITE_TEXT ){ + const unsigned char *zJson = tdsqlite3_value_text(pVal); + if( zJson==0 ){ + if( pRc ) *pRc = SQLITE_NOMEM; + return 0; + } + return geopolyParseJson(zJson, pRc); + }else{ + if( pRc ) *pRc = SQLITE_ERROR; + return 0; + } +} + +/* +** Implementation of the geopoly_blob(X) function. +** +** If the input is a well-formed Geopoly BLOB or JSON string +** then return the BLOB representation of the polygon. Otherwise +** return NULL. +*/ +static void geopolyBlobFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p = geopolyFuncParam(context, argv[0], 0); + if( p ){ + tdsqlite3_result_blob(context, p->hdr, + 4+8*p->nVertex, SQLITE_TRANSIENT); + tdsqlite3_free(p); + } +} + +/* +** SQL function: geopoly_json(X) +** +** Interpret X as a polygon and render it as a JSON array +** of coordinates. Or, if X is not a valid polygon, return NULL. +*/ +static void geopolyJsonFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p = geopolyFuncParam(context, argv[0], 0); + if( p ){ + tdsqlite3 *db = tdsqlite3_context_db_handle(context); + tdsqlite3_str *x = tdsqlite3_str_new(db); + int i; + tdsqlite3_str_append(x, "[", 1); + for(i=0; i<p->nVertex; i++){ + tdsqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i)); + } + tdsqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0)); + tdsqlite3_result_text(context, tdsqlite3_str_finish(x), -1, tdsqlite3_free); + tdsqlite3_free(p); + } +} + +/* +** SQL function: geopoly_svg(X, ....) +** +** Interpret X as a polygon and render it as a SVG <polyline>. +** Additional arguments are added as attributes to the <polyline>. +*/ +static void geopolySvgFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p; + if( argc<1 ) return; + p = geopolyFuncParam(context, argv[0], 0); + if( p ){ + tdsqlite3 *db = tdsqlite3_context_db_handle(context); + tdsqlite3_str *x = tdsqlite3_str_new(db); + int i; + char cSep = '\''; + tdsqlite3_str_appendf(x, "<polyline points="); + for(i=0; i<p->nVertex; i++){ + tdsqlite3_str_appendf(x, "%c%g,%g", cSep, GeoX(p,i), GeoY(p,i)); + cSep = ' '; + } + tdsqlite3_str_appendf(x, " %g,%g'", GeoX(p,0), GeoY(p,0)); + for(i=1; i<argc; i++){ + const char *z = (const char*)tdsqlite3_value_text(argv[i]); + if( z && z[0] ){ + tdsqlite3_str_appendf(x, " %s", z); + } + } + tdsqlite3_str_appendf(x, "></polyline>"); + tdsqlite3_result_text(context, tdsqlite3_str_finish(x), -1, tdsqlite3_free); + tdsqlite3_free(p); + } +} + +/* +** SQL Function: geopoly_xform(poly, A, B, C, D, E, F) +** +** Transform and/or translate a polygon as follows: +** +** x1 = A*x0 + B*y0 + E +** y1 = C*x0 + D*y0 + F +** +** For a translation: +** +** geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset) +** +** Rotate by R around the point (0,0): +** +** geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0) +*/ +static void geopolyXformFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p = geopolyFuncParam(context, argv[0], 0); + double A = tdsqlite3_value_double(argv[1]); + double B = tdsqlite3_value_double(argv[2]); + double C = tdsqlite3_value_double(argv[3]); + double D = tdsqlite3_value_double(argv[4]); + double E = tdsqlite3_value_double(argv[5]); + double F = tdsqlite3_value_double(argv[6]); + GeoCoord x1, y1, x0, y0; + int ii; + if( p ){ + for(ii=0; ii<p->nVertex; ii++){ + x0 = GeoX(p,ii); + y0 = GeoY(p,ii); + x1 = (GeoCoord)(A*x0 + B*y0 + E); + y1 = (GeoCoord)(C*x0 + D*y0 + F); + GeoX(p,ii) = x1; + GeoY(p,ii) = y1; + } + tdsqlite3_result_blob(context, p->hdr, + 4+8*p->nVertex, SQLITE_TRANSIENT); + tdsqlite3_free(p); + } +} + +/* +** Compute the area enclosed by the polygon. +** +** This routine can also be used to detect polygons that rotate in +** the wrong direction. Polygons are suppose to be counter-clockwise (CCW). +** This routine returns a negative value for clockwise (CW) polygons. +*/ +static double geopolyArea(GeoPoly *p){ + double rArea = 0.0; + int ii; + for(ii=0; ii<p->nVertex-1; ii++){ + rArea += (GeoX(p,ii) - GeoX(p,ii+1)) /* (x0 - x1) */ + * (GeoY(p,ii) + GeoY(p,ii+1)) /* (y0 + y1) */ + * 0.5; + } + rArea += (GeoX(p,ii) - GeoX(p,0)) /* (xN - x0) */ + * (GeoY(p,ii) + GeoY(p,0)) /* (yN + y0) */ + * 0.5; + return rArea; +} + +/* +** Implementation of the geopoly_area(X) function. +** +** If the input is a well-formed Geopoly BLOB then return the area +** enclosed by the polygon. If the polygon circulates clockwise instead +** of counterclockwise (as it should) then return the negative of the +** enclosed area. Otherwise return NULL. +*/ +static void geopolyAreaFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p = geopolyFuncParam(context, argv[0], 0); + if( p ){ + tdsqlite3_result_double(context, geopolyArea(p)); + tdsqlite3_free(p); + } +} + +/* +** Implementation of the geopoly_ccw(X) function. +** +** If the rotation of polygon X is clockwise (incorrect) instead of +** counter-clockwise (the correct winding order according to RFC7946) +** then reverse the order of the vertexes in polygon X. +** +** In other words, this routine returns a CCW polygon regardless of the +** winding order of its input. +** +** Use this routine to sanitize historical inputs that that sometimes +** contain polygons that wind in the wrong direction. +*/ +static void geopolyCcwFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p = geopolyFuncParam(context, argv[0], 0); + if( p ){ + if( geopolyArea(p)<0.0 ){ + int ii, jj; + for(ii=1, jj=p->nVertex-1; ii<jj; ii++, jj--){ + GeoCoord t = GeoX(p,ii); + GeoX(p,ii) = GeoX(p,jj); + GeoX(p,jj) = t; + t = GeoY(p,ii); + GeoY(p,ii) = GeoY(p,jj); + GeoY(p,jj) = t; + } + } + tdsqlite3_result_blob(context, p->hdr, + 4+8*p->nVertex, SQLITE_TRANSIENT); + tdsqlite3_free(p); + } +} + +#define GEOPOLY_PI 3.1415926535897932385 + +/* Fast approximation for sine(X) for X between -0.5*pi and 2*pi +*/ +static double geopolySine(double r){ + assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI ); + if( r>=1.5*GEOPOLY_PI ){ + r -= 2.0*GEOPOLY_PI; + } + if( r>=0.5*GEOPOLY_PI ){ + return -geopolySine(r-GEOPOLY_PI); + }else{ + double r2 = r*r; + double r3 = r2*r; + double r5 = r3*r2; + return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5; + } +} + +/* +** Function: geopoly_regular(X,Y,R,N) +** +** Construct a simple, convex, regular polygon centered at X, Y +** with circumradius R and with N sides. +*/ +static void geopolyRegularFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + double x = tdsqlite3_value_double(argv[0]); + double y = tdsqlite3_value_double(argv[1]); + double r = tdsqlite3_value_double(argv[2]); + int n = tdsqlite3_value_int(argv[3]); + int i; + GeoPoly *p; + + if( n<3 || r<=0.0 ) return; + if( n>1000 ) n = 1000; + p = tdsqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) ); + if( p==0 ){ + tdsqlite3_result_error_nomem(context); + return; + } + i = 1; + p->hdr[0] = *(unsigned char*)&i; + p->hdr[1] = 0; + p->hdr[2] = (n>>8)&0xff; + p->hdr[3] = n&0xff; + for(i=0; i<n; i++){ + double rAngle = 2.0*GEOPOLY_PI*i/n; + GeoX(p,i) = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI); + GeoY(p,i) = y + r*geopolySine(rAngle); + } + tdsqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT); + tdsqlite3_free(p); +} + +/* +** If pPoly is a polygon, compute its bounding box. Then: +** +** (1) if aCoord!=0 store the bounding box in aCoord, returning NULL +** (2) otherwise, compute a GeoPoly for the bounding box and return the +** new GeoPoly +** +** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from +** the bounding box in aCoord and return a pointer to that GeoPoly. +*/ +static GeoPoly *geopolyBBox( + tdsqlite3_context *context, /* For recording the error */ + tdsqlite3_value *pPoly, /* The polygon */ + RtreeCoord *aCoord, /* Results here */ + int *pRc /* Error code here */ +){ + GeoPoly *pOut = 0; + GeoPoly *p; + float mnX, mxX, mnY, mxY; + if( pPoly==0 && aCoord!=0 ){ + p = 0; + mnX = aCoord[0].f; + mxX = aCoord[1].f; + mnY = aCoord[2].f; + mxY = aCoord[3].f; + goto geopolyBboxFill; }else{ - u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]); - sqlite3_result_int(ctx, readInt16(zBlob)); + p = geopolyFuncParam(context, pPoly, pRc); + } + if( p ){ + int ii; + mnX = mxX = GeoX(p,0); + mnY = mxY = GeoY(p,0); + for(ii=1; ii<p->nVertex; ii++){ + double r = GeoX(p,ii); + if( r<mnX ) mnX = (float)r; + else if( r>mxX ) mxX = (float)r; + r = GeoY(p,ii); + if( r<mnY ) mnY = (float)r; + else if( r>mxY ) mxY = (float)r; + } + if( pRc ) *pRc = SQLITE_OK; + if( aCoord==0 ){ + geopolyBboxFill: + pOut = tdsqlite3_realloc64(p, GEOPOLY_SZ(4)); + if( pOut==0 ){ + tdsqlite3_free(p); + if( context ) tdsqlite3_result_error_nomem(context); + if( pRc ) *pRc = SQLITE_NOMEM; + return 0; + } + pOut->nVertex = 4; + ii = 1; + pOut->hdr[0] = *(unsigned char*)ⅈ + pOut->hdr[1] = 0; + pOut->hdr[2] = 0; + pOut->hdr[3] = 4; + GeoX(pOut,0) = mnX; + GeoY(pOut,0) = mnY; + GeoX(pOut,1) = mxX; + GeoY(pOut,1) = mnY; + GeoX(pOut,2) = mxX; + GeoY(pOut,2) = mxY; + GeoX(pOut,3) = mnX; + GeoY(pOut,3) = mxY; + }else{ + tdsqlite3_free(p); + aCoord[0].f = mnX; + aCoord[1].f = mxX; + aCoord[2].f = mnY; + aCoord[3].f = mxY; + } + } + return pOut; +} + +/* +** Implementation of the geopoly_bbox(X) SQL function. +*/ +static void geopolyBBoxFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p = geopolyBBox(context, argv[0], 0, 0); + if( p ){ + tdsqlite3_result_blob(context, p->hdr, + 4+8*p->nVertex, SQLITE_TRANSIENT); + tdsqlite3_free(p); + } +} + +/* +** State vector for the geopoly_group_bbox() aggregate function. +*/ +typedef struct GeoBBox GeoBBox; +struct GeoBBox { + int isInit; + RtreeCoord a[4]; +}; + + +/* +** Implementation of the geopoly_group_bbox(X) aggregate SQL function. +*/ +static void geopolyBBoxStep( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + RtreeCoord a[4]; + int rc = SQLITE_OK; + (void)geopolyBBox(context, argv[0], a, &rc); + if( rc==SQLITE_OK ){ + GeoBBox *pBBox; + pBBox = (GeoBBox*)tdsqlite3_aggregate_context(context, sizeof(*pBBox)); + if( pBBox==0 ) return; + if( pBBox->isInit==0 ){ + pBBox->isInit = 1; + memcpy(pBBox->a, a, sizeof(RtreeCoord)*4); + }else{ + if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0]; + if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1]; + if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2]; + if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3]; + } + } +} +static void geopolyBBoxFinal( + tdsqlite3_context *context +){ + GeoPoly *p; + GeoBBox *pBBox; + pBBox = (GeoBBox*)tdsqlite3_aggregate_context(context, 0); + if( pBBox==0 ) return; + p = geopolyBBox(context, 0, pBBox->a, 0); + if( p ){ + tdsqlite3_result_blob(context, p->hdr, + 4+8*p->nVertex, SQLITE_TRANSIENT); + tdsqlite3_free(p); + } +} + + +/* +** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2). +** Returns: +** +** +2 x0,y0 is on the line segement +** +** +1 x0,y0 is beneath line segment +** +** 0 x0,y0 is not on or beneath the line segment or the line segment +** is vertical and x0,y0 is not on the line segment +** +** The left-most coordinate min(x1,x2) is not considered to be part of +** the line segment for the purposes of this analysis. +*/ +static int pointBeneathLine( + double x0, double y0, + double x1, double y1, + double x2, double y2 +){ + double y; + if( x0==x1 && y0==y1 ) return 2; + if( x1<x2 ){ + if( x0<=x1 || x0>x2 ) return 0; + }else if( x1>x2 ){ + if( x0<=x2 || x0>x1 ) return 0; + }else{ + /* Vertical line segment */ + if( x0!=x1 ) return 0; + if( y0<y1 && y0<y2 ) return 0; + if( y0>y1 && y0>y2 ) return 0; + return 2; + } + y = y1 + (y2-y1)*(x0-x1)/(x2-x1); + if( y0==y ) return 2; + if( y0<y ) return 1; + return 0; +} + +/* +** SQL function: geopoly_contains_point(P,X,Y) +** +** Return +2 if point X,Y is within polygon P. +** Return +1 if point X,Y is on the polygon boundary. +** Return 0 if point X,Y is outside the polygon +*/ +static void geopolyContainsPointFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0); + double x0 = tdsqlite3_value_double(argv[1]); + double y0 = tdsqlite3_value_double(argv[2]); + int v = 0; + int cnt = 0; + int ii; + if( p1==0 ) return; + for(ii=0; ii<p1->nVertex-1; ii++){ + v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii), + GeoX(p1,ii+1),GeoY(p1,ii+1)); + if( v==2 ) break; + cnt += v; + } + if( v!=2 ){ + v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii), + GeoX(p1,0), GeoY(p1,0)); + } + if( v==2 ){ + tdsqlite3_result_int(context, 1); + }else if( ((v+cnt)&1)==0 ){ + tdsqlite3_result_int(context, 0); + }else{ + tdsqlite3_result_int(context, 2); + } + tdsqlite3_free(p1); +} + +/* Forward declaration */ +static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2); + +/* +** SQL function: geopoly_within(P1,P2) +** +** Return +2 if P1 and P2 are the same polygon +** Return +1 if P2 is contained within P1 +** Return 0 if any part of P2 is on the outside of P1 +** +*/ +static void geopolyWithinFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0); + GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0); + if( p1 && p2 ){ + int x = geopolyOverlap(p1, p2); + if( x<0 ){ + tdsqlite3_result_error_nomem(context); + }else{ + tdsqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0); + } + } + tdsqlite3_free(p1); + tdsqlite3_free(p2); +} + +/* Objects used by the overlap algorihm. */ +typedef struct GeoEvent GeoEvent; +typedef struct GeoSegment GeoSegment; +typedef struct GeoOverlap GeoOverlap; +struct GeoEvent { + double x; /* X coordinate at which event occurs */ + int eType; /* 0 for ADD, 1 for REMOVE */ + GeoSegment *pSeg; /* The segment to be added or removed */ + GeoEvent *pNext; /* Next event in the sorted list */ +}; +struct GeoSegment { + double C, B; /* y = C*x + B */ + double y; /* Current y value */ + float y0; /* Initial y value */ + unsigned char side; /* 1 for p1, 2 for p2 */ + unsigned int idx; /* Which segment within the side */ + GeoSegment *pNext; /* Next segment in a list sorted by y */ +}; +struct GeoOverlap { + GeoEvent *aEvent; /* Array of all events */ + GeoSegment *aSegment; /* Array of all segments */ + int nEvent; /* Number of events */ + int nSegment; /* Number of segments */ +}; + +/* +** Add a single segment and its associated events. +*/ +static void geopolyAddOneSegment( + GeoOverlap *p, + GeoCoord x0, + GeoCoord y0, + GeoCoord x1, + GeoCoord y1, + unsigned char side, + unsigned int idx +){ + GeoSegment *pSeg; + GeoEvent *pEvent; + if( x0==x1 ) return; /* Ignore vertical segments */ + if( x0>x1 ){ + GeoCoord t = x0; + x0 = x1; + x1 = t; + t = y0; + y0 = y1; + y1 = t; + } + pSeg = p->aSegment + p->nSegment; + p->nSegment++; + pSeg->C = (y1-y0)/(x1-x0); + pSeg->B = y1 - x1*pSeg->C; + pSeg->y0 = y0; + pSeg->side = side; + pSeg->idx = idx; + pEvent = p->aEvent + p->nEvent; + p->nEvent++; + pEvent->x = x0; + pEvent->eType = 0; + pEvent->pSeg = pSeg; + pEvent = p->aEvent + p->nEvent; + p->nEvent++; + pEvent->x = x1; + pEvent->eType = 1; + pEvent->pSeg = pSeg; +} + + + +/* +** Insert all segments and events for polygon pPoly. +*/ +static void geopolyAddSegments( + GeoOverlap *p, /* Add segments to this Overlap object */ + GeoPoly *pPoly, /* Take all segments from this polygon */ + unsigned char side /* The side of pPoly */ +){ + unsigned int i; + GeoCoord *x; + for(i=0; i<(unsigned)pPoly->nVertex-1; i++){ + x = &GeoX(pPoly,i); + geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i); + } + x = &GeoX(pPoly,i); + geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i); +} + +/* +** Merge two lists of sorted events by X coordinate +*/ +static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){ + GeoEvent head, *pLast; + head.pNext = 0; + pLast = &head; + while( pRight && pLeft ){ + if( pRight->x <= pLeft->x ){ + pLast->pNext = pRight; + pLast = pRight; + pRight = pRight->pNext; + }else{ + pLast->pNext = pLeft; + pLast = pLeft; + pLeft = pLeft->pNext; + } + } + pLast->pNext = pRight ? pRight : pLeft; + return head.pNext; +} + +/* +** Sort an array of nEvent event objects into a list. +*/ +static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){ + int mx = 0; + int i, j; + GeoEvent *p; + GeoEvent *a[50]; + for(i=0; i<nEvent; i++){ + p = &aEvent[i]; + p->pNext = 0; + for(j=0; j<mx && a[j]; j++){ + p = geopolyEventMerge(a[j], p); + a[j] = 0; + } + a[j] = p; + if( j>=mx ) mx = j+1; + } + p = 0; + for(i=0; i<mx; i++){ + p = geopolyEventMerge(a[i], p); + } + return p; +} + +/* +** Merge two lists of sorted segments by Y, and then by C. +*/ +static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){ + GeoSegment head, *pLast; + head.pNext = 0; + pLast = &head; + while( pRight && pLeft ){ + double r = pRight->y - pLeft->y; + if( r==0.0 ) r = pRight->C - pLeft->C; + if( r<0.0 ){ + pLast->pNext = pRight; + pLast = pRight; + pRight = pRight->pNext; + }else{ + pLast->pNext = pLeft; + pLast = pLeft; + pLeft = pLeft->pNext; + } + } + pLast->pNext = pRight ? pRight : pLeft; + return head.pNext; +} + +/* +** Sort a list of GeoSegments in order of increasing Y and in the event of +** a tie, increasing C (slope). +*/ +static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){ + int mx = 0; + int i; + GeoSegment *p; + GeoSegment *a[50]; + while( pList ){ + p = pList; + pList = pList->pNext; + p->pNext = 0; + for(i=0; i<mx && a[i]; i++){ + p = geopolySegmentMerge(a[i], p); + a[i] = 0; + } + a[i] = p; + if( i>=mx ) mx = i+1; + } + p = 0; + for(i=0; i<mx; i++){ + p = geopolySegmentMerge(a[i], p); + } + return p; +} + +/* +** Determine the overlap between two polygons +*/ +static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){ + tdsqlite3_int64 nVertex = p1->nVertex + p2->nVertex + 2; + GeoOverlap *p; + tdsqlite3_int64 nByte; + GeoEvent *pThisEvent; + double rX; + int rc = 0; + int needSort = 0; + GeoSegment *pActive = 0; + GeoSegment *pSeg; + unsigned char aOverlap[4]; + + nByte = sizeof(GeoEvent)*nVertex*2 + + sizeof(GeoSegment)*nVertex + + sizeof(GeoOverlap); + p = tdsqlite3_malloc64( nByte ); + if( p==0 ) return -1; + p->aEvent = (GeoEvent*)&p[1]; + p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2]; + p->nEvent = p->nSegment = 0; + geopolyAddSegments(p, p1, 1); + geopolyAddSegments(p, p2, 2); + pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent); + rX = pThisEvent->x==0.0 ? -1.0 : 0.0; + memset(aOverlap, 0, sizeof(aOverlap)); + while( pThisEvent ){ + if( pThisEvent->x!=rX ){ + GeoSegment *pPrev = 0; + int iMask = 0; + GEODEBUG(("Distinct X: %g\n", pThisEvent->x)); + rX = pThisEvent->x; + if( needSort ){ + GEODEBUG(("SORT\n")); + pActive = geopolySortSegmentsByYAndC(pActive); + needSort = 0; + } + for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){ + if( pPrev ){ + if( pPrev->y!=pSeg->y ){ + GEODEBUG(("MASK: %d\n", iMask)); + aOverlap[iMask] = 1; + } + } + iMask ^= pSeg->side; + pPrev = pSeg; + } + pPrev = 0; + for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){ + double y = pSeg->C*rX + pSeg->B; + GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y)); + pSeg->y = y; + if( pPrev ){ + if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){ + rc = 1; + GEODEBUG(("Crossing: %d.%d and %d.%d\n", + pPrev->side, pPrev->idx, + pSeg->side, pSeg->idx)); + goto geopolyOverlapDone; + }else if( pPrev->y!=pSeg->y ){ + GEODEBUG(("MASK: %d\n", iMask)); + aOverlap[iMask] = 1; + } + } + iMask ^= pSeg->side; + pPrev = pSeg; + } + } + GEODEBUG(("%s %d.%d C=%g B=%g\n", + pThisEvent->eType ? "RM " : "ADD", + pThisEvent->pSeg->side, pThisEvent->pSeg->idx, + pThisEvent->pSeg->C, + pThisEvent->pSeg->B)); + if( pThisEvent->eType==0 ){ + /* Add a segment */ + pSeg = pThisEvent->pSeg; + pSeg->y = pSeg->y0; + pSeg->pNext = pActive; + pActive = pSeg; + needSort = 1; + }else{ + /* Remove a segment */ + if( pActive==pThisEvent->pSeg ){ + pActive = pActive->pNext; + }else{ + for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){ + if( pSeg->pNext==pThisEvent->pSeg ){ + pSeg->pNext = pSeg->pNext->pNext; + break; + } + } + } + } + pThisEvent = pThisEvent->pNext; + } + if( aOverlap[3]==0 ){ + rc = 0; + }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){ + rc = 3; + }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){ + rc = 2; + }else if( aOverlap[1]==0 && aOverlap[2]==0 ){ + rc = 4; + }else{ + rc = 1; + } + +geopolyOverlapDone: + tdsqlite3_free(p); + return rc; +} + +/* +** SQL function: geopoly_overlap(P1,P2) +** +** Determine whether or not P1 and P2 overlap. Return value: +** +** 0 The two polygons are disjoint +** 1 They overlap +** 2 P1 is completely contained within P2 +** 3 P2 is completely contained within P1 +** 4 P1 and P2 are the same polygon +** NULL Either P1 or P2 or both are not valid polygons +*/ +static void geopolyOverlapFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ + GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0); + GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0); + if( p1 && p2 ){ + int x = geopolyOverlap(p1, p2); + if( x<0 ){ + tdsqlite3_result_error_nomem(context); + }else{ + tdsqlite3_result_int(context, x); + } + } + tdsqlite3_free(p1); + tdsqlite3_free(p2); +} + +/* +** Enable or disable debugging output +*/ +static void geopolyDebugFunc( + tdsqlite3_context *context, + int argc, + tdsqlite3_value **argv +){ +#ifdef GEOPOLY_ENABLE_DEBUG + geo_debug = tdsqlite3_value_int(argv[0]); +#endif +} + +/* +** This function is the implementation of both the xConnect and xCreate +** methods of the geopoly virtual table. +** +** argv[0] -> module name +** argv[1] -> database name +** argv[2] -> table name +** argv[...] -> column names... +*/ +static int geopolyInit( + tdsqlite3 *db, /* Database connection */ + void *pAux, /* One of the RTREE_COORD_* constants */ + int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ + tdsqlite3_vtab **ppVtab, /* OUT: New virtual table */ + char **pzErr, /* OUT: Error message, if any */ + int isCreate /* True for xCreate, false for xConnect */ +){ + int rc = SQLITE_OK; + Rtree *pRtree; + tdsqlite3_int64 nDb; /* Length of string argv[1] */ + tdsqlite3_int64 nName; /* Length of string argv[2] */ + tdsqlite3_str *pSql; + char *zSql; + int ii; + + tdsqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); + + /* Allocate the tdsqlite3_vtab structure */ + nDb = strlen(argv[1]); + nName = strlen(argv[2]); + pRtree = (Rtree *)tdsqlite3_malloc64(sizeof(Rtree)+nDb+nName+2); + if( !pRtree ){ + return SQLITE_NOMEM; + } + memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); + pRtree->nBusy = 1; + pRtree->base.pModule = &rtreeModule; + pRtree->zDb = (char *)&pRtree[1]; + pRtree->zName = &pRtree->zDb[nDb+1]; + pRtree->eCoordType = RTREE_COORD_REAL32; + pRtree->nDim = 2; + pRtree->nDim2 = 4; + memcpy(pRtree->zDb, argv[1], nDb); + memcpy(pRtree->zName, argv[2], nName); + + + /* Create/Connect to the underlying relational database schema. If + ** that is successful, call tdsqlite3_declare_vtab() to configure + ** the r-tree table schema. + */ + pSql = tdsqlite3_str_new(db); + tdsqlite3_str_appendf(pSql, "CREATE TABLE x(_shape"); + pRtree->nAux = 1; /* Add one for _shape */ + pRtree->nAuxNotNull = 1; /* The _shape column is always not-null */ + for(ii=3; ii<argc; ii++){ + pRtree->nAux++; + tdsqlite3_str_appendf(pSql, ",%s", argv[ii]); + } + tdsqlite3_str_appendf(pSql, ");"); + zSql = tdsqlite3_str_finish(pSql); + if( !zSql ){ + rc = SQLITE_NOMEM; + }else if( SQLITE_OK!=(rc = tdsqlite3_declare_vtab(db, zSql)) ){ + *pzErr = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); + } + tdsqlite3_free(zSql); + if( rc ) goto geopolyInit_fail; + pRtree->nBytesPerCell = 8 + pRtree->nDim2*4; + + /* Figure out the node size to use. */ + rc = getNodeSize(db, pRtree, isCreate, pzErr); + if( rc ) goto geopolyInit_fail; + rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate); + if( rc ){ + *pzErr = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); + goto geopolyInit_fail; + } + + *ppVtab = (tdsqlite3_vtab *)pRtree; + return SQLITE_OK; + +geopolyInit_fail: + if( rc==SQLITE_OK ) rc = SQLITE_ERROR; + assert( *ppVtab==0 ); + assert( pRtree->nBusy==1 ); + rtreeRelease(pRtree); + return rc; +} + + +/* +** GEOPOLY virtual table module xCreate method. +*/ +static int geopolyCreate( + tdsqlite3 *db, + void *pAux, + int argc, const char *const*argv, + tdsqlite3_vtab **ppVtab, + char **pzErr +){ + return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1); +} + +/* +** GEOPOLY virtual table module xConnect method. +*/ +static int geopolyConnect( + tdsqlite3 *db, + void *pAux, + int argc, const char *const*argv, + tdsqlite3_vtab **ppVtab, + char **pzErr +){ + return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0); +} + + +/* +** GEOPOLY virtual table module xFilter method. +** +** Query plans: +** +** 1 rowid lookup +** 2 search for objects overlapping the same bounding box +** that contains polygon argv[0] +** 3 search for objects overlapping the same bounding box +** that contains polygon argv[0] +** 4 full table scan +*/ +static int geopolyFilter( + tdsqlite3_vtab_cursor *pVtabCursor, /* The cursor to initialize */ + int idxNum, /* Query plan */ + const char *idxStr, /* Not Used */ + int argc, tdsqlite3_value **argv /* Parameters to the query plan */ +){ + Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; + RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; + RtreeNode *pRoot = 0; + int rc = SQLITE_OK; + int iCell = 0; + + rtreeReference(pRtree); + + /* Reset the cursor to the same state as rtreeOpen() leaves it in. */ + resetCursor(pCsr); + + pCsr->iStrategy = idxNum; + if( idxNum==1 ){ + /* Special case - lookup by rowid. */ + RtreeNode *pLeaf; /* Leaf on which the required cell resides */ + RtreeSearchPoint *p; /* Search point for the leaf */ + i64 iRowid = tdsqlite3_value_int64(argv[0]); + i64 iNode = 0; + rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode); + if( rc==SQLITE_OK && pLeaf!=0 ){ + p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0); + assert( p!=0 ); /* Always returns pCsr->sPoint */ + pCsr->aNode[0] = pLeaf; + p->id = iNode; + p->eWithin = PARTLY_WITHIN; + rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell); + p->iCell = (u8)iCell; + RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:"); + }else{ + pCsr->atEOF = 1; + } + }else{ + /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array + ** with the configured constraints. + */ + rc = nodeAcquire(pRtree, 1, 0, &pRoot); + if( rc==SQLITE_OK && idxNum<=3 ){ + RtreeCoord bbox[4]; + RtreeConstraint *p; + assert( argc==1 ); + geopolyBBox(0, argv[0], bbox, &rc); + if( rc ){ + goto geopoly_filter_end; + } + pCsr->aConstraint = p = tdsqlite3_malloc(sizeof(RtreeConstraint)*4); + pCsr->nConstraint = 4; + if( p==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4); + memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1)); + if( idxNum==2 ){ + /* Overlap query */ + p->op = 'B'; + p->iCoord = 0; + p->u.rValue = bbox[1].f; + p++; + p->op = 'D'; + p->iCoord = 1; + p->u.rValue = bbox[0].f; + p++; + p->op = 'B'; + p->iCoord = 2; + p->u.rValue = bbox[3].f; + p++; + p->op = 'D'; + p->iCoord = 3; + p->u.rValue = bbox[2].f; + }else{ + /* Within query */ + p->op = 'D'; + p->iCoord = 0; + p->u.rValue = bbox[0].f; + p++; + p->op = 'B'; + p->iCoord = 1; + p->u.rValue = bbox[1].f; + p++; + p->op = 'D'; + p->iCoord = 2; + p->u.rValue = bbox[2].f; + p++; + p->op = 'B'; + p->iCoord = 3; + p->u.rValue = bbox[3].f; + } + } + } + if( rc==SQLITE_OK ){ + RtreeSearchPoint *pNew; + pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1)); + if( pNew==0 ){ + rc = SQLITE_NOMEM; + goto geopoly_filter_end; + } + pNew->id = 1; + pNew->iCell = 0; + pNew->eWithin = PARTLY_WITHIN; + assert( pCsr->bPoint==1 ); + pCsr->aNode[0] = pRoot; + pRoot = 0; + RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:"); + rc = rtreeStepToLeaf(pCsr); + } + } + +geopoly_filter_end: + nodeRelease(pRtree, pRoot); + rtreeRelease(pRtree); + return rc; +} + +/* +** Rtree virtual table module xBestIndex method. There are three +** table scan strategies to choose from (in order from most to +** least desirable): +** +** idxNum idxStr Strategy +** ------------------------------------------------ +** 1 "rowid" Direct lookup by rowid. +** 2 "rtree" R-tree overlap query using geopoly_overlap() +** 3 "rtree" R-tree within query using geopoly_within() +** 4 "fullscan" full-table scan. +** ------------------------------------------------ +*/ +static int geopolyBestIndex(tdsqlite3_vtab *tab, tdsqlite3_index_info *pIdxInfo){ + int ii; + int iRowidTerm = -1; + int iFuncTerm = -1; + int idxNum = 0; + + for(ii=0; ii<pIdxInfo->nConstraint; ii++){ + struct tdsqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; + if( !p->usable ) continue; + if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + iRowidTerm = ii; + break; + } + if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){ + /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap() + ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within(). + ** See geopolyFindFunction() */ + iFuncTerm = ii; + idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2; + } + } + + if( iRowidTerm>=0 ){ + pIdxInfo->idxNum = 1; + pIdxInfo->idxStr = "rowid"; + pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1; + pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1; + pIdxInfo->estimatedCost = 30.0; + pIdxInfo->estimatedRows = 1; + pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE; + return SQLITE_OK; + } + if( iFuncTerm>=0 ){ + pIdxInfo->idxNum = idxNum; + pIdxInfo->idxStr = "rtree"; + pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1; + pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0; + pIdxInfo->estimatedCost = 300.0; + pIdxInfo->estimatedRows = 10; + return SQLITE_OK; + } + pIdxInfo->idxNum = 4; + pIdxInfo->idxStr = "fullscan"; + pIdxInfo->estimatedCost = 3000000.0; + pIdxInfo->estimatedRows = 100000; + return SQLITE_OK; +} + + +/* +** GEOPOLY virtual table module xColumn method. +*/ +static int geopolyColumn(tdsqlite3_vtab_cursor *cur, tdsqlite3_context *ctx, int i){ + Rtree *pRtree = (Rtree *)cur->pVtab; + RtreeCursor *pCsr = (RtreeCursor *)cur; + RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); + int rc = SQLITE_OK; + RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); + + if( rc ) return rc; + if( p==0 ) return SQLITE_OK; + if( i==0 && tdsqlite3_vtab_nochange(ctx) ) return SQLITE_OK; + if( i<=pRtree->nAux ){ + if( !pCsr->bAuxValid ){ + if( pCsr->pReadAux==0 ){ + rc = tdsqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0, + &pCsr->pReadAux, 0); + if( rc ) return rc; + } + tdsqlite3_bind_int64(pCsr->pReadAux, 1, + nodeGetRowid(pRtree, pNode, p->iCell)); + rc = tdsqlite3_step(pCsr->pReadAux); + if( rc==SQLITE_ROW ){ + pCsr->bAuxValid = 1; + }else{ + tdsqlite3_reset(pCsr->pReadAux); + if( rc==SQLITE_DONE ) rc = SQLITE_OK; + return rc; + } + } + tdsqlite3_result_value(ctx, tdsqlite3_column_value(pCsr->pReadAux, i+2)); } + return SQLITE_OK; } + +/* +** The xUpdate method for GEOPOLY module virtual tables. +** +** For DELETE: +** +** argv[0] = the rowid to be deleted +** +** For INSERT: +** +** argv[0] = SQL NULL +** argv[1] = rowid to insert, or an SQL NULL to select automatically +** argv[2] = _shape column +** argv[3] = first application-defined column.... +** +** For UPDATE: +** +** argv[0] = rowid to modify. Never NULL +** argv[1] = rowid after the change. Never NULL +** argv[2] = new value for _shape +** argv[3] = new value for first application-defined column.... +*/ +static int geopolyUpdate( + tdsqlite3_vtab *pVtab, + int nData, + tdsqlite3_value **aData, + sqlite_int64 *pRowid +){ + Rtree *pRtree = (Rtree *)pVtab; + int rc = SQLITE_OK; + RtreeCell cell; /* New cell to insert if nData>1 */ + i64 oldRowid; /* The old rowid */ + int oldRowidValid; /* True if oldRowid is valid */ + i64 newRowid; /* The new rowid */ + int newRowidValid; /* True if newRowid is valid */ + int coordChange = 0; /* Change in coordinates */ + + if( pRtree->nNodeRef ){ + /* Unable to write to the btree while another cursor is reading from it, + ** since the write might do a rebalance which would disrupt the read + ** cursor. */ + return SQLITE_LOCKED_VTAB; + } + rtreeReference(pRtree); + assert(nData>=1); + + oldRowidValid = tdsqlite3_value_type(aData[0])!=SQLITE_NULL;; + oldRowid = oldRowidValid ? tdsqlite3_value_int64(aData[0]) : 0; + newRowidValid = nData>1 && tdsqlite3_value_type(aData[1])!=SQLITE_NULL; + newRowid = newRowidValid ? tdsqlite3_value_int64(aData[1]) : 0; + cell.iRowid = newRowid; + + if( nData>1 /* not a DELETE */ + && (!oldRowidValid /* INSERT */ + || !tdsqlite3_value_nochange(aData[2]) /* UPDATE _shape */ + || oldRowid!=newRowid) /* Rowid change */ + ){ + geopolyBBox(0, aData[2], cell.aCoord, &rc); + if( rc ){ + if( rc==SQLITE_ERROR ){ + pVtab->zErrMsg = + tdsqlite3_mprintf("_shape does not contain a valid polygon"); + } + goto geopoly_update_end; + } + coordChange = 1; + + /* If a rowid value was supplied, check if it is already present in + ** the table. If so, the constraint has failed. */ + if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){ + int steprc; + tdsqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); + steprc = tdsqlite3_step(pRtree->pReadRowid); + rc = tdsqlite3_reset(pRtree->pReadRowid); + if( SQLITE_ROW==steprc ){ + if( tdsqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ + rc = rtreeDeleteRowid(pRtree, cell.iRowid); + }else{ + rc = rtreeConstraintError(pRtree, 0); + } + } + } + } + + /* If aData[0] is not an SQL NULL value, it is the rowid of a + ** record to delete from the r-tree table. The following block does + ** just that. + */ + if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){ + rc = rtreeDeleteRowid(pRtree, oldRowid); + } + + /* If the aData[] array contains more than one element, elements + ** (aData[2]..aData[argc-1]) contain a new record to insert into + ** the r-tree structure. + */ + if( rc==SQLITE_OK && nData>1 && coordChange ){ + /* Insert the new record into the r-tree */ + RtreeNode *pLeaf = 0; + if( !newRowidValid ){ + rc = rtreeNewRowid(pRtree, &cell.iRowid); + } + *pRowid = cell.iRowid; + if( rc==SQLITE_OK ){ + rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); + } + if( rc==SQLITE_OK ){ + int rc2; + pRtree->iReinsertHeight = -1; + rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); + rc2 = nodeRelease(pRtree, pLeaf); + if( rc==SQLITE_OK ){ + rc = rc2; + } + } + } + + /* Change the data */ + if( rc==SQLITE_OK && nData>1 ){ + tdsqlite3_stmt *pUp = pRtree->pWriteAux; + int jj; + int nChange = 0; + tdsqlite3_bind_int64(pUp, 1, cell.iRowid); + assert( pRtree->nAux>=1 ); + if( tdsqlite3_value_nochange(aData[2]) ){ + tdsqlite3_bind_null(pUp, 2); + }else{ + GeoPoly *p = 0; + if( tdsqlite3_value_type(aData[2])==SQLITE_TEXT + && (p = geopolyFuncParam(0, aData[2], &rc))!=0 + && rc==SQLITE_OK + ){ + tdsqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT); + }else{ + tdsqlite3_bind_value(pUp, 2, aData[2]); + } + tdsqlite3_free(p); + nChange = 1; + } + for(jj=1; jj<pRtree->nAux; jj++){ + nChange++; + tdsqlite3_bind_value(pUp, jj+2, aData[jj+2]); + } + if( nChange ){ + tdsqlite3_step(pUp); + rc = tdsqlite3_reset(pUp); + } + } + +geopoly_update_end: + rtreeRelease(pRtree); + return rc; +} + +/* +** Report that geopoly_overlap() is an overloaded function suitable +** for use in xBestIndex. +*/ +static int geopolyFindFunction( + tdsqlite3_vtab *pVtab, + int nArg, + const char *zName, + void (**pxFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void **ppArg +){ + if( tdsqlite3_stricmp(zName, "geopoly_overlap")==0 ){ + *pxFunc = geopolyOverlapFunc; + *ppArg = 0; + return SQLITE_INDEX_CONSTRAINT_FUNCTION; + } + if( tdsqlite3_stricmp(zName, "geopoly_within")==0 ){ + *pxFunc = geopolyWithinFunc; + *ppArg = 0; + return SQLITE_INDEX_CONSTRAINT_FUNCTION+1; + } + return 0; +} + + +static tdsqlite3_module geopolyModule = { + 3, /* iVersion */ + geopolyCreate, /* xCreate - create a table */ + geopolyConnect, /* xConnect - connect to an existing table */ + geopolyBestIndex, /* xBestIndex - Determine search strategy */ + rtreeDisconnect, /* xDisconnect - Disconnect from a table */ + rtreeDestroy, /* xDestroy - Drop a table */ + rtreeOpen, /* xOpen - open a cursor */ + rtreeClose, /* xClose - close a cursor */ + geopolyFilter, /* xFilter - configure scan constraints */ + rtreeNext, /* xNext - advance a cursor */ + rtreeEof, /* xEof */ + geopolyColumn, /* xColumn - read data */ + rtreeRowid, /* xRowid - read data */ + geopolyUpdate, /* xUpdate - write data */ + rtreeBeginTransaction, /* xBegin - begin transaction */ + rtreeEndTransaction, /* xSync - sync transaction */ + rtreeEndTransaction, /* xCommit - commit transaction */ + rtreeEndTransaction, /* xRollback - rollback transaction */ + geopolyFindFunction, /* xFindFunction - function overloading */ + rtreeRename, /* xRename - rename the table */ + rtreeSavepoint, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + rtreeShadowName /* xShadowName */ +}; + +static int tdsqlite3_geopoly_init(tdsqlite3 *db){ + int rc = SQLITE_OK; + static const struct { + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**); + signed char nArg; + unsigned char bPure; + const char *zName; + } aFunc[] = { + { geopolyAreaFunc, 1, 1, "geopoly_area" }, + { geopolyBlobFunc, 1, 1, "geopoly_blob" }, + { geopolyJsonFunc, 1, 1, "geopoly_json" }, + { geopolySvgFunc, -1, 1, "geopoly_svg" }, + { geopolyWithinFunc, 2, 1, "geopoly_within" }, + { geopolyContainsPointFunc, 3, 1, "geopoly_contains_point" }, + { geopolyOverlapFunc, 2, 1, "geopoly_overlap" }, + { geopolyDebugFunc, 1, 0, "geopoly_debug" }, + { geopolyBBoxFunc, 1, 1, "geopoly_bbox" }, + { geopolyXformFunc, 7, 1, "geopoly_xform" }, + { geopolyRegularFunc, 4, 1, "geopoly_regular" }, + { geopolyCcwFunc, 1, 1, "geopoly_ccw" }, + }; + static const struct { + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**); + void (*xFinal)(tdsqlite3_context*); + const char *zName; + } aAgg[] = { + { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox" }, + }; + int i; + for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){ + int enc; + if( aFunc[i].bPure ){ + enc = SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS; + }else{ + enc = SQLITE_UTF8|SQLITE_DIRECTONLY; + } + rc = tdsqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, + enc, 0, + aFunc[i].xFunc, 0, 0); + } + for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){ + rc = tdsqlite3_create_function(db, aAgg[i].zName, 1, + SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS, 0, + 0, aAgg[i].xStep, aAgg[i].xFinal); + } + if( rc==SQLITE_OK ){ + rc = tdsqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0); + } + return rc; +} + +/************** End of geopoly.c *********************************************/ +/************** Continuing where we left off in rtree.c **********************/ +#endif + /* ** Register the r-tree module with database handle db. This creates the ** virtual table module "rtree" and the debugging/analysis scalar ** function "rtreenode". */ -SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){ +SQLITE_PRIVATE int tdsqlite3RtreeInit(tdsqlite3 *db){ const int utf8 = SQLITE_UTF8; int rc; - rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0); + rc = tdsqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0); + if( rc==SQLITE_OK ){ + rc = tdsqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0); + } if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0); + rc = tdsqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0); } if( rc==SQLITE_OK ){ #ifdef SQLITE_RTREE_INT_ONLY @@ -167866,27 +195855,32 @@ SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){ #else void *c = (void *)RTREE_COORD_REAL32; #endif - rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0); + rc = tdsqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0); } if( rc==SQLITE_OK ){ void *c = (void *)RTREE_COORD_INT32; - rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0); + rc = tdsqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0); } +#ifdef SQLITE_ENABLE_GEOPOLY + if( rc==SQLITE_OK ){ + rc = tdsqlite3_geopoly_init(db); + } +#endif return rc; } /* ** This routine deletes the RtreeGeomCallback object that was attached -** one of the SQL functions create by sqlite3_rtree_geometry_callback() -** or sqlite3_rtree_query_callback(). In other words, this routine is the +** one of the SQL functions create by tdsqlite3_rtree_geometry_callback() +** or tdsqlite3_rtree_query_callback(). In other words, this routine is the ** destructor for an RtreeGeomCallback objecct. This routine is called when ** the corresponding SQL function is deleted. */ static void rtreeFreeCallback(void *p){ RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p; if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext); - sqlite3_free(p); + tdsqlite3_free(p); } /* @@ -167896,14 +195890,14 @@ static void rtreeMatchArgFree(void *pArg){ int i; RtreeMatchArg *p = (RtreeMatchArg*)pArg; for(i=0; i<p->nParam; i++){ - sqlite3_value_free(p->apSqlParam[i]); + tdsqlite3_value_free(p->apSqlParam[i]); } - sqlite3_free(p); + tdsqlite3_free(p); } /* -** Each call to sqlite3_rtree_geometry_callback() or -** sqlite3_rtree_query_callback() creates an ordinary SQLite +** Each call to tdsqlite3_rtree_geometry_callback() or +** tdsqlite3_rtree_query_callback() creates an ordinary SQLite ** scalar function that is implemented by this routine. ** ** All this function does is construct an RtreeMatchArg object that @@ -167915,37 +195909,37 @@ static void rtreeMatchArgFree(void *pArg){ ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure ** out which elements of the R-Tree should be returned by the query. */ -static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ - RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx); +static void geomCallback(tdsqlite3_context *ctx, int nArg, tdsqlite3_value **aArg){ + RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)tdsqlite3_user_data(ctx); RtreeMatchArg *pBlob; - int nBlob; + tdsqlite3_int64 nBlob; int memErr = 0; nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue) - + nArg*sizeof(sqlite3_value*); - pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob); + + nArg*sizeof(tdsqlite3_value*); + pBlob = (RtreeMatchArg *)tdsqlite3_malloc64(nBlob); if( !pBlob ){ - sqlite3_result_error_nomem(ctx); + tdsqlite3_result_error_nomem(ctx); }else{ int i; - pBlob->magic = RTREE_GEOMETRY_MAGIC; + pBlob->iSize = nBlob; pBlob->cb = pGeomCtx[0]; - pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg]; + pBlob->apSqlParam = (tdsqlite3_value**)&pBlob->aParam[nArg]; pBlob->nParam = nArg; for(i=0; i<nArg; i++){ - pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]); + pBlob->apSqlParam[i] = tdsqlite3_value_dup(aArg[i]); if( pBlob->apSqlParam[i]==0 ) memErr = 1; #ifdef SQLITE_RTREE_INT_ONLY - pBlob->aParam[i] = sqlite3_value_int64(aArg[i]); + pBlob->aParam[i] = tdsqlite3_value_int64(aArg[i]); #else - pBlob->aParam[i] = sqlite3_value_double(aArg[i]); + pBlob->aParam[i] = tdsqlite3_value_double(aArg[i]); #endif } if( memErr ){ - sqlite3_result_error_nomem(ctx); + tdsqlite3_result_error_nomem(ctx); rtreeMatchArgFree(pBlob); }else{ - sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree); + tdsqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree); } } } @@ -167953,22 +195947,22 @@ static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ /* ** Register a new geometry function for use with the r-tree MATCH operator. */ -SQLITE_API int sqlite3_rtree_geometry_callback( - sqlite3 *db, /* Register SQL function on this connection */ +SQLITE_API int tdsqlite3_rtree_geometry_callback( + tdsqlite3 *db, /* Register SQL function on this connection */ const char *zGeom, /* Name of the new SQL function */ - int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */ + int (*xGeom)(tdsqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */ void *pContext /* Extra data associated with the callback */ ){ RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ /* Allocate and populate the context object. */ - pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); + pGeomCtx = (RtreeGeomCallback *)tdsqlite3_malloc(sizeof(RtreeGeomCallback)); if( !pGeomCtx ) return SQLITE_NOMEM; pGeomCtx->xGeom = xGeom; pGeomCtx->xQueryFunc = 0; pGeomCtx->xDestructor = 0; pGeomCtx->pContext = pContext; - return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, + return tdsqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback ); } @@ -167977,23 +195971,23 @@ SQLITE_API int sqlite3_rtree_geometry_callback( ** Register a new 2nd-generation geometry function for use with the ** r-tree MATCH operator. */ -SQLITE_API int sqlite3_rtree_query_callback( - sqlite3 *db, /* Register SQL function on this connection */ +SQLITE_API int tdsqlite3_rtree_query_callback( + tdsqlite3 *db, /* Register SQL function on this connection */ const char *zQueryFunc, /* Name of new SQL function */ - int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */ + int (*xQueryFunc)(tdsqlite3_rtree_query_info*), /* Callback */ void *pContext, /* Extra data passed into the callback */ void (*xDestructor)(void*) /* Destructor for the extra data */ ){ RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ /* Allocate and populate the context object. */ - pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); + pGeomCtx = (RtreeGeomCallback *)tdsqlite3_malloc(sizeof(RtreeGeomCallback)); if( !pGeomCtx ) return SQLITE_NOMEM; pGeomCtx->xGeom = 0; pGeomCtx->xQueryFunc = xQueryFunc; pGeomCtx->xDestructor = xDestructor; pGeomCtx->pContext = pContext; - return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, + return tdsqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback ); } @@ -168002,13 +195996,13 @@ SQLITE_API int sqlite3_rtree_query_callback( #ifdef _WIN32 __declspec(dllexport) #endif -SQLITE_API int sqlite3_rtree_init( - sqlite3 *db, +SQLITE_API int tdsqlite3_rtree_init( + tdsqlite3 *db, char **pzErrMsg, - const sqlite3_api_routines *pApi + const tdsqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) - return sqlite3RtreeInit(db); + return tdsqlite3RtreeInit(db); } #endif @@ -168046,7 +196040,9 @@ SQLITE_API int sqlite3_rtree_init( ** provide case-independent matching. */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) +#if !defined(SQLITE_CORE) \ + || defined(SQLITE_ENABLE_ICU) \ + || defined(SQLITE_ENABLE_ICU_COLLATIONS) /* Include ICU headers */ #include <unicode/utypes.h> @@ -168057,13 +196053,33 @@ SQLITE_API int sqlite3_rtree_init( /* #include <assert.h> */ #ifndef SQLITE_CORE -/* #include "sqlite3ext.h" */ +/* #include "tdsqlite3ext.h" */ SQLITE_EXTENSION_INIT1 #else /* #include "sqlite3.h" */ #endif /* +** This function is called when an ICU function called from within +** the implementation of an SQL scalar function returns an error. +** +** The scalar function context passed as the first argument is +** loaded with an error message based on the following two args. +*/ +static void icuFunctionError( + tdsqlite3_context *pCtx, /* SQLite scalar function context */ + const char *zName, /* Name of ICU function that failed */ + UErrorCode e /* Error code returned by ICU function */ +){ + char zBuf[128]; + tdsqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e)); + zBuf[127] = '\0'; + tdsqlite3_result_error(pCtx, zBuf, -1); +} + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) + +/* ** Maximum length (in bytes) of the pattern in a LIKE or GLOB ** operator. */ @@ -168072,10 +196088,10 @@ SQLITE_API int sqlite3_rtree_init( #endif /* -** Version of sqlite3_free() that is always a function, never a macro. +** Version of tdsqlite3_free() that is always a function, never a macro. */ static void xFree(void *p){ - sqlite3_free(p); + tdsqlite3_free(p); } /* @@ -168120,15 +196136,15 @@ static int icuLikeCompare( const uint8_t *zString, /* The UTF-8 string to compare against */ const UChar32 uEsc /* The escape character */ ){ - static const int MATCH_ONE = (UChar32)'_'; - static const int MATCH_ALL = (UChar32)'%'; + static const uint32_t MATCH_ONE = (uint32_t)'_'; + static const uint32_t MATCH_ALL = (uint32_t)'%'; int prevEscape = 0; /* True if the previous character was uEsc */ while( 1 ){ /* Read (and consume) the next character from the input pattern. */ - UChar32 uPattern; + uint32_t uPattern; SQLITE_ICU_READ_UTF8(zPattern, uPattern); if( uPattern==0 ) break; @@ -168170,16 +196186,16 @@ static int icuLikeCompare( if( *zString==0 ) return 0; SQLITE_ICU_SKIP_UTF8(zString); - }else if( !prevEscape && uPattern==uEsc){ + }else if( !prevEscape && uPattern==(uint32_t)uEsc){ /* Case 3. */ prevEscape = 1; }else{ /* Case 4. */ - UChar32 uString; + uint32_t uString; SQLITE_ICU_READ_UTF8(zString, uString); - uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT); - uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT); + uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT); + uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT); if( uString!=uPattern ){ return 0; } @@ -168204,19 +196220,19 @@ static int icuLikeCompare( ** is mapped to like(B, A, E). */ static void icuLikeFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ - const unsigned char *zA = sqlite3_value_text(argv[0]); - const unsigned char *zB = sqlite3_value_text(argv[1]); + const unsigned char *zA = tdsqlite3_value_text(argv[0]); + const unsigned char *zB = tdsqlite3_value_text(argv[1]); UChar32 uEsc = 0; /* Limit the length of the LIKE or GLOB pattern to avoid problems ** of deep recursion and N*N behavior in patternCompare(). */ - if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){ - sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); + if( tdsqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){ + tdsqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); return; } @@ -168225,44 +196241,26 @@ static void icuLikeFunc( /* The escape character string must consist of a single UTF-8 character. ** Otherwise, return an error. */ - int nE= sqlite3_value_bytes(argv[2]); - const unsigned char *zE = sqlite3_value_text(argv[2]); + int nE= tdsqlite3_value_bytes(argv[2]); + const unsigned char *zE = tdsqlite3_value_text(argv[2]); int i = 0; if( zE==0 ) return; U8_NEXT(zE, i, nE, uEsc); if( i!=nE){ - sqlite3_result_error(context, + tdsqlite3_result_error(context, "ESCAPE expression must be a single character", -1); return; } } if( zA && zB ){ - sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc)); + tdsqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc)); } } /* -** This function is called when an ICU function called from within -** the implementation of an SQL scalar function returns an error. -** -** The scalar function context passed as the first argument is -** loaded with an error message based on the following two args. -*/ -static void icuFunctionError( - sqlite3_context *pCtx, /* SQLite scalar function context */ - const char *zName, /* Name of ICU function that failed */ - UErrorCode e /* Error code returned by ICU function */ -){ - char zBuf[128]; - sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e)); - zBuf[127] = '\0'; - sqlite3_result_error(pCtx, zBuf, -1); -} - -/* ** Function to delete compiled regexp objects. Registered as -** a destructor function with sqlite3_set_auxdata(). +** a destructor function with tdsqlite3_set_auxdata(). */ static void icuRegexpDelete(void *p){ URegularExpression *pExpr = (URegularExpression *)p; @@ -168288,11 +196286,11 @@ static void icuRegexpDelete(void *p){ ** uregex_matches() ** uregex_close() */ -static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ +static void icuRegexpFunc(tdsqlite3_context *p, int nArg, tdsqlite3_value **apArg){ UErrorCode status = U_ZERO_ERROR; URegularExpression *pExpr; UBool res; - const UChar *zString = sqlite3_value_text16(apArg[1]); + const UChar *zString = tdsqlite3_value_text16(apArg[1]); (void)nArg; /* Unused parameter */ @@ -168303,16 +196301,16 @@ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ return; } - pExpr = sqlite3_get_auxdata(p, 0); + pExpr = tdsqlite3_get_auxdata(p, 0); if( !pExpr ){ - const UChar *zPattern = sqlite3_value_text16(apArg[0]); + const UChar *zPattern = tdsqlite3_value_text16(apArg[0]); if( !zPattern ){ return; } pExpr = uregex_open(zPattern, -1, 0, 0, &status); if( U_SUCCESS(status) ){ - sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete); + tdsqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete); }else{ assert(!pExpr); icuFunctionError(p, "uregex_open", status); @@ -168342,7 +196340,7 @@ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ uregex_setText(pExpr, 0, 0, &status); /* Return 1 or 0. */ - sqlite3_result_int(p, res ? 1 : 0); + tdsqlite3_result_int(p, res ? 1 : 0); } /* @@ -168371,7 +196369,7 @@ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ ** ** http://www.icu-project.org/userguide/posix.html#case_mappings */ -static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ +static void icuCaseFunc16(tdsqlite3_context *p, int nArg, tdsqlite3_value **apArg){ const UChar *zInput; /* Pointer to input string */ UChar *zOutput = 0; /* Pointer to output buffer */ int nInput; /* Size of utf-16 input string in bytes */ @@ -168382,26 +196380,26 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ const char *zLocale = 0; assert(nArg==1 || nArg==2); - bToUpper = (sqlite3_user_data(p)!=0); + bToUpper = (tdsqlite3_user_data(p)!=0); if( nArg==2 ){ - zLocale = (const char *)sqlite3_value_text(apArg[1]); + zLocale = (const char *)tdsqlite3_value_text(apArg[1]); } - zInput = sqlite3_value_text16(apArg[0]); + zInput = tdsqlite3_value_text16(apArg[0]); if( !zInput ){ return; } - nOut = nInput = sqlite3_value_bytes16(apArg[0]); + nOut = nInput = tdsqlite3_value_bytes16(apArg[0]); if( nOut==0 ){ - sqlite3_result_text16(p, "", 0, SQLITE_STATIC); + tdsqlite3_result_text16(p, "", 0, SQLITE_STATIC); return; } for(cnt=0; cnt<2; cnt++){ - UChar *zNew = sqlite3_realloc(zOutput, nOut); + UChar *zNew = tdsqlite3_realloc(zOutput, nOut); if( zNew==0 ){ - sqlite3_free(zOutput); - sqlite3_result_error_nomem(p); + tdsqlite3_free(zOutput); + tdsqlite3_result_error_nomem(p); return; } zOutput = zNew; @@ -168413,7 +196411,7 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ } if( U_SUCCESS(status) ){ - sqlite3_result_text16(p, zOutput, nOut, xFree); + tdsqlite3_result_text16(p, zOutput, nOut, xFree); }else if( status==U_BUFFER_OVERFLOW_ERROR ){ assert( cnt==0 ); continue; @@ -168425,6 +196423,8 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ assert( 0 ); /* Unreachable */ } +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */ + /* ** Collation sequence destructor function. The pCtx argument points to ** a UCollator structure previously allocated using ucol_open(). @@ -168471,21 +196471,21 @@ static int icuCollationColl( ** collation sequence to create. */ static void icuLoadCollation( - sqlite3_context *p, + tdsqlite3_context *p, int nArg, - sqlite3_value **apArg + tdsqlite3_value **apArg ){ - sqlite3 *db = (sqlite3 *)sqlite3_user_data(p); + tdsqlite3 *db = (tdsqlite3 *)tdsqlite3_user_data(p); UErrorCode status = U_ZERO_ERROR; const char *zLocale; /* Locale identifier - (eg. "jp_JP") */ const char *zName; /* SQL Collation sequence name (eg. "japanese") */ UCollator *pUCollator; /* ICU library collation object */ - int rc; /* Return code from sqlite3_create_collation_x() */ + int rc; /* Return code from tdsqlite3_create_collation_x() */ assert(nArg==2); (void)nArg; /* Unused parameter */ - zLocale = (const char *)sqlite3_value_text(apArg[0]); - zName = (const char *)sqlite3_value_text(apArg[1]); + zLocale = (const char *)tdsqlite3_value_text(apArg[0]); + zName = (const char *)tdsqlite3_value_text(apArg[1]); if( !zLocale || !zName ){ return; @@ -168498,51 +196498,51 @@ static void icuLoadCollation( } assert(p); - rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, + rc = tdsqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, icuCollationColl, icuCollationDel ); if( rc!=SQLITE_OK ){ ucol_close(pUCollator); - sqlite3_result_error(p, "Error registering collation function", -1); + tdsqlite3_result_error(p, "Error registering collation function", -1); } } /* ** Register the ICU extension functions with database db. */ -SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){ - struct IcuScalar { +SQLITE_PRIVATE int tdsqlite3IcuInit(tdsqlite3 *db){ +# define SQLITEICU_EXTRAFLAGS (SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS) + static const struct IcuScalar { const char *zName; /* Function name */ - int nArg; /* Number of arguments */ - int enc; /* Optimal text encoding */ - void *pContext; /* sqlite3_user_data() context */ - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); + unsigned char nArg; /* Number of arguments */ + unsigned int enc; /* Optimal text encoding */ + unsigned char iContext; /* tdsqlite3_user_data() context */ + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**); } scalars[] = { - {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc}, - - {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, - {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, - {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, (void*)1, icuCaseFunc16}, - {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, (void*)1, icuCaseFunc16}, - - {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, - {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, - {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, (void*)1, icuCaseFunc16}, - {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, (void*)1, icuCaseFunc16}, - - {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc}, - {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc}, - - {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation}, + {"icu_load_collation",2,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation}, +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) + {"regexp", 2, SQLITE_ANY|SQLITEICU_EXTRAFLAGS, 0, icuRegexpFunc}, + {"lower", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16}, + {"lower", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16}, + {"upper", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16}, + {"upper", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16}, + {"lower", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16}, + {"lower", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16}, + {"upper", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16}, + {"upper", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16}, + {"like", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc}, + {"like", 3, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc}, +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */ }; - int rc = SQLITE_OK; int i; - + for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){ - struct IcuScalar *p = &scalars[i]; - rc = sqlite3_create_function( - db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0 + const struct IcuScalar *p = &scalars[i]; + rc = tdsqlite3_create_function( + db, p->zName, p->nArg, p->enc, + p->iContext ? (void*)db : (void*)0, + p->xFunc, 0, 0 ); } @@ -168553,13 +196553,13 @@ SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){ #ifdef _WIN32 __declspec(dllexport) #endif -SQLITE_API int sqlite3_icu_init( - sqlite3 *db, +SQLITE_API int tdsqlite3_icu_init( + tdsqlite3 *db, char **pzErrMsg, - const sqlite3_api_routines *pApi + const tdsqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) - return sqlite3IcuInit(db); + return tdsqlite3IcuInit(db); } #endif @@ -168597,12 +196597,12 @@ typedef struct IcuTokenizer IcuTokenizer; typedef struct IcuCursor IcuCursor; struct IcuTokenizer { - sqlite3_tokenizer base; + tdsqlite3_tokenizer base; char *zLocale; }; struct IcuCursor { - sqlite3_tokenizer_cursor base; + tdsqlite3_tokenizer_cursor base; UBreakIterator *pIter; /* ICU break-iterator object */ int nChar; /* Number of UChar elements in pInput */ @@ -168621,7 +196621,7 @@ struct IcuCursor { static int icuCreate( int argc, /* Number of entries in argv[] */ const char * const *argv, /* Tokenizer creation arguments */ - sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + tdsqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ ){ IcuTokenizer *p; int n = 0; @@ -168629,7 +196629,7 @@ static int icuCreate( if( argc>0 ){ n = strlen(argv[0])+1; } - p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n); + p = (IcuTokenizer *)tdsqlite3_malloc64(sizeof(IcuTokenizer)+n); if( !p ){ return SQLITE_NOMEM; } @@ -168640,7 +196640,7 @@ static int icuCreate( memcpy(p->zLocale, argv[0], n); } - *ppTokenizer = (sqlite3_tokenizer *)p; + *ppTokenizer = (tdsqlite3_tokenizer *)p; return SQLITE_OK; } @@ -168648,9 +196648,9 @@ static int icuCreate( /* ** Destroy a tokenizer */ -static int icuDestroy(sqlite3_tokenizer *pTokenizer){ +static int icuDestroy(tdsqlite3_tokenizer *pTokenizer){ IcuTokenizer *p = (IcuTokenizer *)pTokenizer; - sqlite3_free(p); + tdsqlite3_free(p); return SQLITE_OK; } @@ -168661,10 +196661,10 @@ static int icuDestroy(sqlite3_tokenizer *pTokenizer){ ** *ppCursor. */ static int icuOpen( - sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + tdsqlite3_tokenizer *pTokenizer, /* The tokenizer */ const char *zInput, /* Input string */ int nInput, /* Length of zInput in bytes */ - sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ + tdsqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ ){ IcuTokenizer *p = (IcuTokenizer *)pTokenizer; IcuCursor *pCsr; @@ -168686,7 +196686,7 @@ static int icuOpen( nInput = strlen(zInput); } nChar = nInput+1; - pCsr = (IcuCursor *)sqlite3_malloc( + pCsr = (IcuCursor *)tdsqlite3_malloc64( sizeof(IcuCursor) + /* IcuCursor */ ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */ (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */ @@ -168705,7 +196705,7 @@ static int icuOpen( c = u_foldCase(c, opt); U16_APPEND(pCsr->aChar, iOut, nChar, c, isError); if( isError ){ - sqlite3_free(pCsr); + tdsqlite3_free(pCsr); return SQLITE_ERROR; } pCsr->aOffset[iOut] = iInput; @@ -168719,24 +196719,24 @@ static int icuOpen( pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status); if( !U_SUCCESS(status) ){ - sqlite3_free(pCsr); + tdsqlite3_free(pCsr); return SQLITE_ERROR; } pCsr->nChar = iOut; ubrk_first(pCsr->pIter); - *ppCursor = (sqlite3_tokenizer_cursor *)pCsr; + *ppCursor = (tdsqlite3_tokenizer_cursor *)pCsr; return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to icuOpen(). */ -static int icuClose(sqlite3_tokenizer_cursor *pCursor){ +static int icuClose(tdsqlite3_tokenizer_cursor *pCursor){ IcuCursor *pCsr = (IcuCursor *)pCursor; ubrk_close(pCsr->pIter); - sqlite3_free(pCsr->zBuffer); - sqlite3_free(pCsr); + tdsqlite3_free(pCsr->zBuffer); + tdsqlite3_free(pCsr); return SQLITE_OK; } @@ -168744,7 +196744,7 @@ static int icuClose(sqlite3_tokenizer_cursor *pCursor){ ** Extract the next token from a tokenization cursor. */ static int icuNext( - sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + tdsqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ const char **ppToken, /* OUT: *ppToken is the token text */ int *pnBytes, /* OUT: Number of bytes in token */ int *piStartOffset, /* OUT: Starting offset of token */ @@ -168781,7 +196781,7 @@ static int icuNext( do { UErrorCode status = U_ZERO_ERROR; if( nByte ){ - char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte); + char *zNew = tdsqlite3_realloc(pCsr->zBuffer, nByte); if( !zNew ){ return SQLITE_NOMEM; } @@ -168808,7 +196808,7 @@ static int icuNext( /* ** The set of routines that implement the simple tokenizer */ -static const sqlite3_tokenizer_module icuTokenizerModule = { +static const tdsqlite3_tokenizer_module icuTokenizerModule = { 0, /* iVersion */ icuCreate, /* xCreate */ icuDestroy, /* xCreate */ @@ -168821,8 +196821,8 @@ static const sqlite3_tokenizer_module icuTokenizerModule = { /* ** Set *ppModule to point at the implementation of the ICU tokenizer. */ -SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( - sqlite3_tokenizer_module const**ppModule +SQLITE_PRIVATE void tdsqlite3Fts3IcuTokenizerModule( + tdsqlite3_tokenizer_module const**ppModule ){ *ppModule = &icuTokenizerModule; } @@ -168831,7 +196831,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_icu.c ********************************************/ -/************** Begin file sqlite3rbu.c **************************************/ +/************** Begin file tdsqlite3rbu.c **************************************/ /* ** 2014 August 30 ** @@ -168849,7 +196849,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( ** ** The RBU extension requires that the RBU update be packaged as an ** SQLite database. The tables it expects to find are described in -** sqlite3rbu.h. Essentially, for each table xyz in the target database +** tdsqlite3rbu.h. Essentially, for each table xyz in the target database ** that the user wishes to write to, a corresponding data_xyz table is ** created in the RBU database and populated with one row for each row to ** update, insert or delete from the target table. @@ -168882,7 +196882,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( ** ** 3) The new *-wal file is checkpointed. This proceeds in the same way ** as a regular database checkpoint, except that a single frame is -** checkpointed each time sqlite3rbu_step() is called. If the RBU +** checkpointed each time tdsqlite3rbu_step() is called. If the RBU ** handle is closed before the entire *-wal file is checkpointed, ** the checkpoint progress is saved in the RBU database and the ** checkpoint can be resumed by another RBU client at some point in @@ -168921,8 +196921,8 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( /* #include "sqlite3.h" */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) -/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/ -/************** Begin file sqlite3rbu.h **************************************/ +/************** Include tdsqlite3rbu.h in the middle of tdsqlite3rbu.c ***********/ +/************** Begin file tdsqlite3rbu.h **************************************/ /* ** 2014 August 30 ** @@ -169146,19 +197146,19 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( ** stored on disk to an existing target database. Essentially, the ** application: ** -** 1) Opens an RBU handle using the sqlite3rbu_open() function. +** 1) Opens an RBU handle using the tdsqlite3rbu_open() function. ** ** 2) Registers any required virtual table modules with the database -** handle returned by sqlite3rbu_db(). Also, if required, register +** handle returned by tdsqlite3rbu_db(). Also, if required, register ** the rbu_delta() implementation. ** -** 3) Calls the sqlite3rbu_step() function one or more times on -** the new handle. Each call to sqlite3rbu_step() performs a single +** 3) Calls the tdsqlite3rbu_step() function one or more times on +** the new handle. Each call to tdsqlite3rbu_step() performs a single ** b-tree operation, so thousands of calls may be required to apply ** a complete update. ** -** 4) Calls sqlite3rbu_close() to close the RBU update handle. If -** sqlite3rbu_step() has been called enough times to completely +** 4) Calls tdsqlite3rbu_close() to close the RBU update handle. If +** tdsqlite3rbu_step() has been called enough times to completely ** apply the update to the target database, then the RBU database ** is marked as fully applied. Otherwise, the state of the RBU ** update application is saved in the RBU database for later @@ -169167,7 +197167,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( ** See comments below for more detail on APIs. ** ** If an update is only partially applied to the target database by the -** time sqlite3rbu_close() is called, various state information is saved +** time tdsqlite3rbu_close() is called, various state information is saved ** within the RBU database. This allows subsequent processes to automatically ** resume the RBU update from where it left off. ** @@ -169198,15 +197198,15 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( extern "C" { #endif -typedef struct sqlite3rbu sqlite3rbu; +typedef struct tdsqlite3rbu tdsqlite3rbu; /* ** Open an RBU handle. ** ** Argument zTarget is the path to the target database. Argument zRbu is ** the path to the RBU database. Each call to this function must be matched -** by a call to sqlite3rbu_close(). When opening the databases, RBU passes -** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget +** by a call to tdsqlite3rbu_close(). When opening the databases, RBU passes +** the SQLITE_CONFIG_URI flag to tdsqlite3_open_v2(). So if either zTarget ** or zRbu begin with "file:", it will be interpreted as an SQLite ** database URI, not a regular file name. ** @@ -169233,7 +197233,7 @@ typedef struct sqlite3rbu sqlite3rbu; ** not work out of the box with zipvfs. Refer to the comment describing ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs. */ -SQLITE_API sqlite3rbu *sqlite3rbu_open( +SQLITE_API tdsqlite3rbu *tdsqlite3rbu_open( const char *zTarget, const char *zRbu, const char *zState @@ -169246,10 +197246,10 @@ SQLITE_API sqlite3rbu *sqlite3rbu_open( ** ** The second argument to this function identifies a database in which ** to store the state of the RBU vacuum operation if it is suspended. The -** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum +** first time tdsqlite3rbu_vacuum() is called, to start an RBU vacuum ** operation, the state database should either not exist or be empty ** (contain no tables). If an RBU vacuum is suspended by calling -** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has +** tdsqlite3rbu_close() on the RBU handle before tdsqlite3rbu_step() has ** returned SQLITE_DONE, the vacuum state is stored in the state database. ** The vacuum can be resumed by calling this function to open a new RBU ** handle specifying the same target and state databases. @@ -169258,26 +197258,52 @@ SQLITE_API sqlite3rbu *sqlite3rbu_open( ** name of the state database is "<database>-vacuum", where <database> ** is the name of the target database file. In this case, on UNIX, if the ** state database is not already present in the file-system, it is created -** with the same permissions as the target db is made. +** with the same permissions as the target db is made. +** +** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the +** state database ends with "-vactmp". This name is reserved for internal +** use. ** ** This function does not delete the state database after an RBU vacuum ** is completed, even if it created it. However, if the call to -** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents +** tdsqlite3rbu_close() returns any value other than SQLITE_OK, the contents ** of the state tables within the state database are zeroed. This way, -** the next call to sqlite3rbu_vacuum() opens a handle that starts a +** the next call to tdsqlite3rbu_vacuum() opens a handle that starts a ** new RBU vacuum operation. ** -** As with sqlite3rbu_open(), Zipvfs users should rever to the comment -** describing the sqlite3rbu_create_vfs() API function below for +** As with tdsqlite3rbu_open(), Zipvfs users should rever to the comment +** describing the tdsqlite3rbu_create_vfs() API function below for ** a description of the complications associated with using RBU with ** zipvfs databases. */ -SQLITE_API sqlite3rbu *sqlite3rbu_vacuum( +SQLITE_API tdsqlite3rbu *tdsqlite3rbu_vacuum( const char *zTarget, const char *zState ); /* +** Configure a limit for the amount of temp space that may be used by +** the RBU handle passed as the first argument. The new limit is specified +** in bytes by the second parameter. If it is positive, the limit is updated. +** If the second parameter to this function is passed zero, then the limit +** is removed entirely. If the second parameter is negative, the limit is +** not modified (this is useful for querying the current limit). +** +** In all cases the returned value is the current limit in bytes (zero +** indicates unlimited). +** +** If the temp space limit is exceeded during operation, an SQLITE_FULL +** error is returned. +*/ +SQLITE_API tdsqlite3_int64 tdsqlite3rbu_temp_size_limit(tdsqlite3rbu*, tdsqlite3_int64); + +/* +** Return the current amount of temp file space, in bytes, currently used by +** the RBU handle passed as the only argument. +*/ +SQLITE_API tdsqlite3_int64 tdsqlite3rbu_temp_size(tdsqlite3rbu*); + +/* ** Internally, each RBU connection uses a separate SQLite database ** connection to access the target and rbu update databases. This ** API allows the application direct access to these database handles. @@ -169289,26 +197315,26 @@ SQLITE_API sqlite3rbu *sqlite3rbu_vacuum( ** following scenarios: ** ** * If any target tables are virtual tables, it may be necessary to -** call sqlite3_create_module() on the target database handle to +** call tdsqlite3_create_module() on the target database handle to ** register the required virtual table implementations. ** ** * If the data_xxx tables in the RBU source database are virtual -** tables, the application may need to call sqlite3_create_module() on +** tables, the application may need to call tdsqlite3_create_module() on ** the rbu update db handle to any required virtual table ** implementations. ** ** * If the application uses the "rbu_delta()" feature described above, -** it must use sqlite3_create_function() or similar to register the +** it must use tdsqlite3_create_function() or similar to register the ** rbu_delta() implementation with the target database handle. ** ** If an error has occurred, either while opening or stepping the RBU object, ** this function may return NULL. The error code and message may be collected -** when sqlite3rbu_close() is called. +** when tdsqlite3rbu_close() is called. ** ** Database handles returned by this function remain valid until the next -** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db(). +** call to any tdsqlite3rbu_xxx() function other than tdsqlite3rbu_db(). */ -SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu); +SQLITE_API tdsqlite3 *tdsqlite3rbu_db(tdsqlite3rbu*, int bRbu); /* ** Do some work towards applying the RBU update to the target db. @@ -169318,11 +197344,11 @@ SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu); ** the RBU update. If an error does occur, some other error code is ** returned. ** -** Once a call to sqlite3rbu_step() has returned a value other than +** Once a call to tdsqlite3rbu_step() has returned a value other than ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops ** that immediately return the same value. */ -SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu); +SQLITE_API int tdsqlite3rbu_step(tdsqlite3rbu *pRbu); /* ** Force RBU to save its state to disk. @@ -169330,11 +197356,11 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu); ** If a power failure or application crash occurs during an update, following ** system recovery RBU may resume the update from the point at which the state ** was last saved. In other words, from the most recent successful call to -** sqlite3rbu_close() or this function. +** tdsqlite3rbu_close() or this function. ** ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. */ -SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu); +SQLITE_API int tdsqlite3rbu_savestate(tdsqlite3rbu *pRbu); /* ** Close an RBU handle. @@ -169343,25 +197369,25 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu); ** as fully applied. Otherwise, assuming no error has occurred, save the ** current state of the RBU update appliation to the RBU database. ** -** If an error has already occurred as part of an sqlite3rbu_step() -** or sqlite3rbu_open() call, or if one occurs within this function, an -** SQLite error code is returned. Additionally, *pzErrmsg may be set to -** point to a buffer containing a utf-8 formatted English language error -** message. It is the responsibility of the caller to eventually free any -** such buffer using sqlite3_free(). +** If an error has already occurred as part of an tdsqlite3rbu_step() +** or tdsqlite3rbu_open() call, or if one occurs within this function, an +** SQLite error code is returned. Additionally, if pzErrmsg is not NULL, +** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted +** English language error message. It is the responsibility of the caller to +** eventually free any such buffer using tdsqlite3_free(). ** ** Otherwise, if no error occurs, this function returns SQLITE_OK if the ** update has been partially applied, or SQLITE_DONE if it has been ** completely applied. */ -SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg); +SQLITE_API int tdsqlite3rbu_close(tdsqlite3rbu *pRbu, char **pzErrmsg); /* ** Return the total number of key-value operations (inserts, deletes or ** updates) that have been performed on the target database since the ** current RBU update was started. */ -SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu); +SQLITE_API tdsqlite3_int64 tdsqlite3rbu_progress(tdsqlite3rbu *pRbu); /* ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100) @@ -169403,7 +197429,7 @@ SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu); ** table exists but is not correctly populated, the value of the *pnOne ** output variable during stage 1 is undefined. */ -SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo); +SQLITE_API void tdsqlite3rbu_bp_progress(tdsqlite3rbu *pRbu, int *pnOne, int*pnTwo); /* ** Obtain an indication as to the current stage of an RBU update or vacuum. @@ -169411,28 +197437,28 @@ SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo) ** defined in this file. Return values should be interpreted as follows: ** ** SQLITE_RBU_STATE_OAL: -** RBU is currently building a *-oal file. The next call to sqlite3rbu_step() +** RBU is currently building a *-oal file. The next call to tdsqlite3rbu_step() ** may either add further data to the *-oal file, or compute data that will ** be added by a subsequent call. ** ** SQLITE_RBU_STATE_MOVE: -** RBU has finished building the *-oal file. The next call to sqlite3rbu_step() +** RBU has finished building the *-oal file. The next call to tdsqlite3rbu_step() ** will move the *-oal file to the equivalent *-wal path. If the current ** operation is an RBU update, then the updated version of the database ** file will become visible to ordinary SQLite clients following the next -** call to sqlite3rbu_step(). +** call to tdsqlite3rbu_step(). ** ** SQLITE_RBU_STATE_CHECKPOINT: ** RBU is currently performing an incremental checkpoint. The next call to -** sqlite3rbu_step() will copy a page of data from the *-wal file into +** tdsqlite3rbu_step() will copy a page of data from the *-wal file into ** the target database file. ** ** SQLITE_RBU_STATE_DONE: -** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step() +** The RBU operation has finished. Any subsequent calls to tdsqlite3rbu_step() ** will immediately return SQLITE_DONE. ** ** SQLITE_RBU_STATE_ERROR: -** An error has occurred. Any subsequent calls to sqlite3rbu_step() will +** An error has occurred. Any subsequent calls to tdsqlite3rbu_step() will ** immediately return the SQLite error code associated with the error. */ #define SQLITE_RBU_STATE_OAL 1 @@ -169441,7 +197467,7 @@ SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo) #define SQLITE_RBU_STATE_DONE 4 #define SQLITE_RBU_STATE_ERROR 5 -SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu); +SQLITE_API int tdsqlite3rbu_state(tdsqlite3rbu *pRbu); /* ** Create an RBU VFS named zName that accesses the underlying file-system @@ -169462,19 +197488,19 @@ SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu); ** multiplexor (error checking omitted): ** ** // Create a VFS named "multiplex" (not the default). -** sqlite3_multiplex_initialize(0, 0); +** tdsqlite3_multiplex_initialize(0, 0); ** ** // Create an rbu VFS named "rbu" that uses multiplexor. If the ** // second argument were replaced with NULL, the "rbu" VFS would ** // access the file-system via the system default VFS, bypassing the ** // multiplexor. -** sqlite3rbu_create_vfs("rbu", "multiplex"); +** tdsqlite3rbu_create_vfs("rbu", "multiplex"); ** ** // Create a zipvfs VFS named "zipvfs" that uses rbu. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector); ** ** // Make zipvfs the default VFS. -** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1); +** tdsqlite3_vfs_register(tdsqlite3_vfs_find("zipvfs"), 1); ** ** Because the default VFS created above includes a RBU functionality, it ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack @@ -169485,17 +197511,17 @@ SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu); ** file-system via "rbu" all the time, even if it only uses RBU functionality ** occasionally. */ -SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent); +SQLITE_API int tdsqlite3rbu_create_vfs(const char *zName, const char *zParent); /* ** Deregister and destroy an RBU vfs created by an earlier call to -** sqlite3rbu_create_vfs(). +** tdsqlite3rbu_create_vfs(). ** ** VFS objects are not reference counted. If a VFS object is destroyed ** before all database handles that use it have been closed, the results ** are undefined. */ -SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); +SQLITE_API void tdsqlite3rbu_destroy_vfs(const char *zName); #if 0 } /* end of the 'extern "C"' block */ @@ -169503,8 +197529,8 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); #endif /* _SQLITE3RBU_H */ -/************** End of sqlite3rbu.h ******************************************/ -/************** Continuing where we left off in sqlite3rbu.c *****************/ +/************** End of tdsqlite3rbu.h ******************************************/ +/************** Continuing where we left off in tdsqlite3rbu.c *****************/ #if defined(_WIN32_WCE) /* #include "windows.h" */ @@ -169513,6 +197539,13 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); /* Maximum number of prepared UPDATE statements held by this module */ #define SQLITE_RBU_UPDATE_CACHESIZE 16 +/* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM +** to enable checksum verification. +*/ +#ifndef RBU_ENABLE_DELTA_CKSUM +# define RBU_ENABLE_DELTA_CKSUM 0 +#endif + /* ** Swap two objects of type TYPE. */ @@ -169547,7 +197580,7 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); ** table/index. ** ** RBU_STATE_PROGRESS: -** Trbul number of sqlite3rbu_step() calls made so far as part of this +** Trbul number of tdsqlite3rbu_step() calls made so far as part of this ** rbu update. ** ** RBU_STATE_CKPT: @@ -169563,6 +197596,10 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); ** ** RBU_STATE_OALSZ: ** Valid if STAGE==1. The size in bytes of the *-oal file. +** +** RBU_STATE_DATATBL: +** Only valid if STAGE==1. The RBU database name of the table +** currently being read. */ #define RBU_STATE_STAGE 1 #define RBU_STATE_TBL 2 @@ -169573,6 +197610,7 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); #define RBU_STATE_COOKIE 7 #define RBU_STATE_OALSZ 8 #define RBU_STATE_PHASEONESTEP 9 +#define RBU_STATE_DATATBL 10 #define RBU_STAGE_OAL 1 #define RBU_STAGE_MOVE 2 @@ -169587,6 +197625,7 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); typedef struct RbuFrame RbuFrame; typedef struct RbuObjIter RbuObjIter; typedef struct RbuState RbuState; +typedef struct RbuSpan RbuSpan; typedef struct rbu_vfs rbu_vfs; typedef struct rbu_file rbu_file; typedef struct RbuUpdateStmt RbuUpdateStmt; @@ -169595,7 +197634,7 @@ typedef struct RbuUpdateStmt RbuUpdateStmt; typedef unsigned int u32; typedef unsigned short u16; typedef unsigned char u8; -typedef sqlite3_int64 i64; +typedef tdsqlite3_int64 i64; #endif /* @@ -169615,6 +197654,7 @@ typedef sqlite3_int64 i64; struct RbuState { int eStage; char *zTbl; + char *zDataTbl; char *zIdx; i64 iWalCksum; int nRow; @@ -169626,10 +197666,15 @@ struct RbuState { struct RbuUpdateStmt { char *zMask; /* Copy of update mask used with pUpdate */ - sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */ + tdsqlite3_stmt *pUpdate; /* Last update statement (or NULL) */ RbuUpdateStmt *pNext; }; +struct RbuSpan { + const char *zSpan; + int nSpan; +}; + /* ** An iterator of this type is used to iterate through all objects in ** the target database that require updating. For each such table, the @@ -169644,11 +197689,16 @@ struct RbuUpdateStmt { ** it points to an array of flags nTblCol elements in size. The flag is ** set for each column that is either a part of the PK or a part of an ** index. Or clear otherwise. +** +** If there are one or more partial indexes on the table, all fields of +** this array set set to 1. This is because in that case, the module has +** no way to tell which fields will be required to add and remove entries +** from the partial indexes. ** */ struct RbuObjIter { - sqlite3_stmt *pTblIter; /* Iterate through tables */ - sqlite3_stmt *pIdxIter; /* Index iterator */ + tdsqlite3_stmt *pTblIter; /* Iterate through tables */ + tdsqlite3_stmt *pIdxIter; /* Index iterator */ int nTblCol; /* Size of azTblCol[] array */ char **azTblCol; /* Array of unquoted target column names */ char **azTblType; /* Array of target column types */ @@ -169670,10 +197720,13 @@ struct RbuObjIter { /* Statements created by rbuObjIterPrepareAll() */ int nCol; /* Number of columns in current object */ - sqlite3_stmt *pSelect; /* Source data */ - sqlite3_stmt *pInsert; /* Statement for INSERT operations */ - sqlite3_stmt *pDelete; /* Statement for DELETE ops */ - sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */ + tdsqlite3_stmt *pSelect; /* Source data */ + tdsqlite3_stmt *pInsert; /* Statement for INSERT operations */ + tdsqlite3_stmt *pDelete; /* Statement for DELETE ops */ + tdsqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */ + int nIdxCol; + RbuSpan *aIdxCol; + char *zIdxSql; /* Last UPDATE used (for PK b-tree updates only), or NULL. */ RbuUpdateStmt *pRbuUpdate; @@ -169698,7 +197751,7 @@ struct RbuObjIter { /* -** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs +** Within the RBU_STAGE_OAL stage, each call to tdsqlite3rbu_step() performs ** one of the following operations. */ #define RBU_INSERT 1 /* Insert on a main table b-tree */ @@ -169724,7 +197777,7 @@ struct RbuFrame { ** nPhaseOneStep: ** If the RBU database contains an rbu_count table, this value is set to ** a running estimate of the number of b-tree operations required to -** finish populating the *-oal file. This allows the sqlite3_bp_progress() +** finish populating the *-oal file. This allows the tdsqlite3_bp_progress() ** API to calculate the permyriadage progress of populating the *-oal file ** using the formula: ** @@ -169758,10 +197811,10 @@ struct RbuFrame { ** first pass of each source table. The updated nPhaseOneStep value is ** stored in the rbu_state table if the RBU update is suspended. */ -struct sqlite3rbu { +struct tdsqlite3rbu { int eStage; /* Value of RBU_STATE_STAGE field */ - sqlite3 *dbMain; /* target database handle */ - sqlite3 *dbRbu; /* rbu database handle */ + tdsqlite3 *dbMain; /* target database handle */ + tdsqlite3 *dbRbu; /* rbu database handle */ char *zTarget; /* Path to target db */ char *zRbu; /* Path to rbu db */ char *zState; /* Path to state db (or NULL if zRbu) */ @@ -169773,6 +197826,7 @@ struct sqlite3rbu { RbuObjIter objiter; /* Iterator for skipping through tbl/idx */ const char *zVfsName; /* Name of automatically created rbu vfs */ rbu_file *pTargetFd; /* File handle open on target db */ + int nPagePerSector; /* Pages per sector for pTargetFd */ i64 iOalSz; i64 nPhaseOneStep; @@ -169787,6 +197841,8 @@ struct sqlite3rbu { int pgsz; u8 *aBuf; i64 iWalCksum; + i64 szTemp; /* Current size of all temp files in use */ + i64 szTempLimit; /* Total size limit for temp files */ /* Used in RBU vacuum mode only */ int nRbu; /* Number of RBU VFS in the stack */ @@ -169795,23 +197851,34 @@ struct sqlite3rbu { /* ** An rbu VFS is implemented using an instance of this structure. +** +** Variable pRbu is only non-NULL for automatically created RBU VFS objects. +** It is NULL for RBU VFS objects created explicitly using +** tdsqlite3rbu_create_vfs(). It is used to track the total amount of temp +** space used by the RBU handle. */ struct rbu_vfs { - sqlite3_vfs base; /* rbu VFS shim methods */ - sqlite3_vfs *pRealVfs; /* Underlying VFS */ - sqlite3_mutex *mutex; /* Mutex to protect pMain */ - rbu_file *pMain; /* Linked list of main db files */ + tdsqlite3_vfs base; /* rbu VFS shim methods */ + tdsqlite3_vfs *pRealVfs; /* Underlying VFS */ + tdsqlite3_mutex *mutex; /* Mutex to protect pMain */ + tdsqlite3rbu *pRbu; /* Owner RBU object */ + rbu_file *pMain; /* List of main db files */ + rbu_file *pMainRbu; /* List of main db files with pRbu!=0 */ }; /* ** Each file opened by an rbu VFS is represented by an instance of ** the following structure. +** +** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable +** "sz" is set to the current size of the database file. */ struct rbu_file { - sqlite3_file base; /* sqlite3_file methods */ - sqlite3_file *pReal; /* Underlying file handle */ + tdsqlite3_file base; /* tdsqlite3_file methods */ + tdsqlite3_file *pReal; /* Underlying file handle */ rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */ - sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */ + tdsqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */ + i64 sz; /* Size of file in bytes (temp only) */ int openFlags; /* Flags this file was opened with */ u32 iCookie; /* Cookie value for main db files */ @@ -169825,6 +197892,7 @@ struct rbu_file { const char *zWal; /* Wal filename for this main db file */ rbu_file *pWalFd; /* Wal file descriptor for this main db */ rbu_file *pMainNext; /* Next MAIN_DB file */ + rbu_file *pMainRbuNext; /* Next MAIN_DB file with pRbu!=0 */ }; /* @@ -169874,6 +197942,7 @@ static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){ return v; } +#if RBU_ENABLE_DELTA_CKSUM /* ** Compute a 32-bit checksum on the N-byte buffer. Return the result. */ @@ -169908,6 +197977,7 @@ static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){ } return sum3; } +#endif /* ** Apply a delta. @@ -169938,7 +198008,7 @@ static int rbuDeltaApply( ){ unsigned int limit; unsigned int total = 0; -#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST +#if RBU_ENABLE_DELTA_CKSUM char *zOrigOut = zOut; #endif @@ -169993,7 +198063,7 @@ static int rbuDeltaApply( case ';': { zDelta++; lenDelta--; zOut[0] = 0; -#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST +#if RBU_ENABLE_DELTA_CKSUM if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){ /* ERROR: bad checksum */ return -1; @@ -170038,9 +198108,9 @@ static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){ ** function returns the patched blob. */ static void rbuFossilDeltaFunc( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ const char *aDelta; int nDelta; @@ -170053,27 +198123,28 @@ static void rbuFossilDeltaFunc( assert( argc==2 ); - nOrig = sqlite3_value_bytes(argv[0]); - aOrig = (const char*)sqlite3_value_blob(argv[0]); - nDelta = sqlite3_value_bytes(argv[1]); - aDelta = (const char*)sqlite3_value_blob(argv[1]); + nOrig = tdsqlite3_value_bytes(argv[0]); + aOrig = (const char*)tdsqlite3_value_blob(argv[0]); + nDelta = tdsqlite3_value_bytes(argv[1]); + aDelta = (const char*)tdsqlite3_value_blob(argv[1]); /* Figure out the size of the output */ nOut = rbuDeltaOutputSize(aDelta, nDelta); if( nOut<0 ){ - sqlite3_result_error(context, "corrupt fossil delta", -1); + tdsqlite3_result_error(context, "corrupt fossil delta", -1); return; } - aOut = sqlite3_malloc(nOut+1); + aOut = tdsqlite3_malloc(nOut+1); if( aOut==0 ){ - sqlite3_result_error_nomem(context); + tdsqlite3_result_error_nomem(context); }else{ nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut); if( nOut2!=nOut ){ - sqlite3_result_error(context, "corrupt fossil delta", -1); + tdsqlite3_free(aOut); + tdsqlite3_result_error(context, "corrupt fossil delta", -1); }else{ - sqlite3_result_blob(context, aOut, nOut, sqlite3_free); + tdsqlite3_result_blob(context, aOut, nOut, tdsqlite3_free); } } } @@ -170087,17 +198158,17 @@ static void rbuFossilDeltaFunc( ** Otherwise, if an error does occur, set *ppStmt to NULL and return ** an SQLite error code. Additionally, set output variable *pzErrmsg to ** point to a buffer containing an error message. It is the responsibility -** of the caller to (eventually) free this buffer using sqlite3_free(). +** of the caller to (eventually) free this buffer using tdsqlite3_free(). */ static int prepareAndCollectError( - sqlite3 *db, - sqlite3_stmt **ppStmt, + tdsqlite3 *db, + tdsqlite3_stmt **ppStmt, char **pzErrmsg, const char *zSql ){ - int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); + int rc = tdsqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); if( rc!=SQLITE_OK ){ - *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + *pzErrmsg = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); *ppStmt = 0; } return rc; @@ -170105,23 +198176,23 @@ static int prepareAndCollectError( /* ** Reset the SQL statement passed as the first argument. Return a copy -** of the value returned by sqlite3_reset(). +** of the value returned by tdsqlite3_reset(). ** ** If an error has occurred, then set *pzErrmsg to point to a buffer ** containing an error message. It is the responsibility of the caller -** to eventually free this buffer using sqlite3_free(). +** to eventually free this buffer using tdsqlite3_free(). */ -static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){ - int rc = sqlite3_reset(pStmt); +static int resetAndCollectError(tdsqlite3_stmt *pStmt, char **pzErrmsg){ + int rc = tdsqlite3_reset(pStmt); if( rc!=SQLITE_OK ){ - *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt))); + *pzErrmsg = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(tdsqlite3_db_handle(pStmt))); } return rc; } /* ** Unless it is NULL, argument zSql points to a buffer allocated using -** sqlite3_malloc containing an SQL statement. This function prepares the SQL +** tdsqlite3_malloc containing an SQL statement. This function prepares the SQL ** statement against database db and frees the buffer. If statement ** compilation is successful, *ppStmt is set to point to the new statement ** handle and SQLITE_OK is returned. @@ -170129,14 +198200,14 @@ static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){ ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code ** returned. In this case, *pzErrmsg may also be set to point to an error ** message. It is the responsibility of the caller to free this error message -** buffer using sqlite3_free(). +** buffer using tdsqlite3_free(). ** ** If argument zSql is NULL, this function assumes that an OOM has occurred. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL. */ static int prepareFreeAndCollectError( - sqlite3 *db, - sqlite3_stmt **ppStmt, + tdsqlite3 *db, + tdsqlite3_stmt **ppStmt, char **pzErrmsg, char *zSql ){ @@ -170147,7 +198218,7 @@ static int prepareFreeAndCollectError( *ppStmt = 0; }else{ rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql); - sqlite3_free(zSql); + tdsqlite3_free(zSql); } return rc; } @@ -170159,10 +198230,10 @@ static int prepareFreeAndCollectError( static void rbuObjIterFreeCols(RbuObjIter *pIter){ int i; for(i=0; i<pIter->nTblCol; i++){ - sqlite3_free(pIter->azTblCol[i]); - sqlite3_free(pIter->azTblType[i]); + tdsqlite3_free(pIter->azTblCol[i]); + tdsqlite3_free(pIter->azTblType[i]); } - sqlite3_free(pIter->azTblCol); + tdsqlite3_free(pIter->azTblCol); pIter->azTblCol = 0; pIter->azTblType = 0; pIter->aiSrcOrder = 0; @@ -170179,17 +198250,19 @@ static void rbuObjIterFreeCols(RbuObjIter *pIter){ static void rbuObjIterClearStatements(RbuObjIter *pIter){ RbuUpdateStmt *pUp; - sqlite3_finalize(pIter->pSelect); - sqlite3_finalize(pIter->pInsert); - sqlite3_finalize(pIter->pDelete); - sqlite3_finalize(pIter->pTmpInsert); + tdsqlite3_finalize(pIter->pSelect); + tdsqlite3_finalize(pIter->pInsert); + tdsqlite3_finalize(pIter->pDelete); + tdsqlite3_finalize(pIter->pTmpInsert); pUp = pIter->pRbuUpdate; while( pUp ){ RbuUpdateStmt *pTmp = pUp->pNext; - sqlite3_finalize(pUp->pUpdate); - sqlite3_free(pUp); + tdsqlite3_finalize(pUp->pUpdate); + tdsqlite3_free(pUp); pUp = pTmp; } + tdsqlite3_free(pIter->aIdxCol); + tdsqlite3_free(pIter->zIdxSql); pIter->pSelect = 0; pIter->pInsert = 0; @@ -170197,6 +198270,9 @@ static void rbuObjIterClearStatements(RbuObjIter *pIter){ pIter->pRbuUpdate = 0; pIter->pTmpInsert = 0; pIter->nCol = 0; + pIter->nIdxCol = 0; + pIter->aIdxCol = 0; + pIter->zIdxSql = 0; } /* @@ -170205,8 +198281,8 @@ static void rbuObjIterClearStatements(RbuObjIter *pIter){ */ static void rbuObjIterFinalize(RbuObjIter *pIter){ rbuObjIterClearStatements(pIter); - sqlite3_finalize(pIter->pTblIter); - sqlite3_finalize(pIter->pIdxIter); + tdsqlite3_finalize(pIter->pTblIter); + tdsqlite3_finalize(pIter->pIdxIter); rbuObjIterFreeCols(pIter); memset(pIter, 0, sizeof(RbuObjIter)); } @@ -170219,14 +198295,14 @@ static void rbuObjIterFinalize(RbuObjIter *pIter){ ** left in the RBU handle passed as the first argument. A copy of the ** error code is returned. */ -static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){ +static int rbuObjIterNext(tdsqlite3rbu *p, RbuObjIter *pIter){ int rc = p->rc; if( rc==SQLITE_OK ){ /* Free any SQLite statements used while processing the previous object */ rbuObjIterClearStatements(pIter); if( pIter->zIdx==0 ){ - rc = sqlite3_exec(p->dbMain, + rc = tdsqlite3_exec(p->dbMain, "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;" "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;" "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;" @@ -170239,30 +198315,30 @@ static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){ if( pIter->bCleanup ){ rbuObjIterFreeCols(pIter); pIter->bCleanup = 0; - rc = sqlite3_step(pIter->pTblIter); + rc = tdsqlite3_step(pIter->pTblIter); if( rc!=SQLITE_ROW ){ rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg); pIter->zTbl = 0; }else{ - pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0); - pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1); + pIter->zTbl = (const char*)tdsqlite3_column_text(pIter->pTblIter, 0); + pIter->zDataTbl = (const char*)tdsqlite3_column_text(pIter->pTblIter,1); rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM; } }else{ if( pIter->zIdx==0 ){ - sqlite3_stmt *pIdx = pIter->pIdxIter; - rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC); + tdsqlite3_stmt *pIdx = pIter->pIdxIter; + rc = tdsqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC); } if( rc==SQLITE_OK ){ - rc = sqlite3_step(pIter->pIdxIter); + rc = tdsqlite3_step(pIter->pIdxIter); if( rc!=SQLITE_ROW ){ rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg); pIter->bCleanup = 1; pIter->zIdx = 0; }else{ - pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0); - pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1); - pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2); + pIter->zIdx = (const char*)tdsqlite3_column_text(pIter->pIdxIter, 0); + pIter->iTnum = tdsqlite3_column_int(pIter->pIdxIter, 1); + pIter->bUnique = tdsqlite3_column_int(pIter->pIdxIter, 2); rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM; } } @@ -170300,26 +198376,27 @@ static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){ ** the second argument is either missing or 0 (not a view). */ static void rbuTargetNameFunc( - sqlite3_context *pCtx, + tdsqlite3_context *pCtx, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ - sqlite3rbu *p = sqlite3_user_data(pCtx); + tdsqlite3rbu *p = tdsqlite3_user_data(pCtx); const char *zIn; assert( argc==1 || argc==2 ); - zIn = (const char*)sqlite3_value_text(argv[0]); + zIn = (const char*)tdsqlite3_value_text(argv[0]); if( zIn ){ if( rbuIsVacuum(p) ){ - if( argc==1 || 0==sqlite3_value_int(argv[1]) ){ - sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC); + assert( argc==2 || argc==1 ); + if( argc==1 || 0==tdsqlite3_value_int(argv[1]) ){ + tdsqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC); } }else{ if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){ int i; for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++); if( zIn[i]=='_' && zIn[i+1] ){ - sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC); + tdsqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC); } } } @@ -170334,12 +198411,12 @@ static void rbuTargetNameFunc( ** left in the RBU handle passed as the first argument. A copy of the ** error code is returned. */ -static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){ +static int rbuObjIterFirst(tdsqlite3rbu *p, RbuObjIter *pIter){ int rc; memset(pIter, 0, sizeof(RbuObjIter)); rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, - sqlite3_mprintf( + tdsqlite3_mprintf( "SELECT rbu_target_name(name, type='view') AS target, name " "FROM sqlite_master " "WHERE type IN ('table', 'view') AND target IS NOT NULL " @@ -170361,23 +198438,23 @@ static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){ } /* -** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs, +** This is a wrapper around "tdsqlite3_mprintf(zFmt, ...)". If an OOM occurs, ** an error code is stored in the RBU handle passed as the first argument. ** ** If an error has already occurred (p->rc is already set to something other ** than SQLITE_OK), then this function returns NULL without modifying the -** stored error code. In this case it still calls sqlite3_free() on any +** stored error code. In this case it still calls tdsqlite3_free() on any ** printf() parameters associated with %z conversions. */ -static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){ +static char *rbuMPrintf(tdsqlite3rbu *p, const char *zFmt, ...){ char *zSql = 0; va_list ap; va_start(ap, zFmt); - zSql = sqlite3_vmprintf(zFmt, ap); + zSql = tdsqlite3_vmprintf(zFmt, ap); if( p->rc==SQLITE_OK ){ if( zSql==0 ) p->rc = SQLITE_NOMEM; }else{ - sqlite3_free(zSql); + tdsqlite3_free(zSql); zSql = 0; } va_end(ap); @@ -170385,7 +198462,7 @@ static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){ } /* -** Argument zFmt is a sqlite3_mprintf() style format string. The trailing +** Argument zFmt is a tdsqlite3_mprintf() style format string. The trailing ** arguments are the usual subsitution values. This function performs ** the printf() style substitutions and executes the result as an SQL ** statement on the RBU handles database. @@ -170394,19 +198471,19 @@ static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){ ** RBU handle. If an error has already occurred when this function is ** called, it is a no-op. */ -static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){ +static int rbuMPrintfExec(tdsqlite3rbu *p, tdsqlite3 *db, const char *zFmt, ...){ va_list ap; char *zSql; va_start(ap, zFmt); - zSql = sqlite3_vmprintf(zFmt, ap); + zSql = tdsqlite3_vmprintf(zFmt, ap); if( p->rc==SQLITE_OK ){ if( zSql==0 ){ p->rc = SQLITE_NOMEM; }else{ - p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg); + p->rc = tdsqlite3_exec(db, zSql, 0, 0, &p->zErrmsg); } } - sqlite3_free(zSql); + tdsqlite3_free(zSql); va_end(ap); return p->rc; } @@ -170421,11 +198498,11 @@ static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){ ** immediately without attempting the allocation or modifying the stored ** error code. */ -static void *rbuMalloc(sqlite3rbu *p, int nByte){ +static void *rbuMalloc(tdsqlite3rbu *p, tdsqlite3_int64 nByte){ void *pRet = 0; if( p->rc==SQLITE_OK ){ assert( nByte>0 ); - pRet = sqlite3_malloc64(nByte); + pRet = tdsqlite3_malloc64(nByte); if( pRet==0 ){ p->rc = SQLITE_NOMEM; }else{ @@ -170441,8 +198518,8 @@ static void *rbuMalloc(sqlite3rbu *p, int nByte){ ** there is room for at least nCol elements. If an OOM occurs, store an ** error code in the RBU handle passed as the first argument. */ -static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){ - int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol; +static void rbuAllocateIterArrays(tdsqlite3rbu *p, RbuObjIter *pIter, int nCol){ + tdsqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol; char **azNew; azNew = (char**)rbuMalloc(p, nByte); @@ -170458,9 +198535,9 @@ static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){ /* ** The first argument must be a nul-terminated string. This function -** returns a copy of the string in memory obtained from sqlite3_malloc(). +** returns a copy of the string in memory obtained from tdsqlite3_malloc(). ** It is the responsibility of the caller to eventually free this memory -** using sqlite3_free(). +** using tdsqlite3_free(). ** ** If an OOM condition is encountered when attempting to allocate memory, ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise, @@ -170469,14 +198546,15 @@ static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){ static char *rbuStrndup(const char *zStr, int *pRc){ char *zRet = 0; - assert( *pRc==SQLITE_OK ); - if( zStr ){ - size_t nCopy = strlen(zStr) + 1; - zRet = (char*)sqlite3_malloc64(nCopy); - if( zRet ){ - memcpy(zRet, zStr, nCopy); - }else{ - *pRc = SQLITE_NOMEM; + if( *pRc==SQLITE_OK ){ + if( zStr ){ + size_t nCopy = strlen(zStr) + 1; + zRet = (char*)tdsqlite3_malloc64(nCopy); + if( zRet ){ + memcpy(zRet, zStr, nCopy); + }else{ + *pRc = SQLITE_NOMEM; + } } } @@ -170486,16 +198564,16 @@ static char *rbuStrndup(const char *zStr, int *pRc){ /* ** Finalize the statement passed as the second argument. ** -** If the sqlite3_finalize() call indicates that an error occurs, and the +** If the tdsqlite3_finalize() call indicates that an error occurs, and the ** rbu handle error code is not already set, set the error code and error ** message accordingly. */ -static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){ - sqlite3 *db = sqlite3_db_handle(pStmt); - int rc = sqlite3_finalize(pStmt); +static void rbuFinalize(tdsqlite3rbu *p, tdsqlite3_stmt *pStmt){ + tdsqlite3 *db = tdsqlite3_db_handle(pStmt); + int rc = tdsqlite3_finalize(pStmt); if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ p->rc = rc; - p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + p->zErrmsg = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); } } @@ -170539,7 +198617,7 @@ static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){ ** } */ static void rbuTableType( - sqlite3rbu *p, + tdsqlite3rbu *p, const char *zTab, int *peType, int *piTnum, @@ -170551,43 +198629,43 @@ static void rbuTableType( ** 2) SELECT count(*) FROM sqlite_master where name=%Q ** 3) PRAGMA table_info = ? */ - sqlite3_stmt *aStmt[4] = {0, 0, 0, 0}; + tdsqlite3_stmt *aStmt[4] = {0, 0, 0, 0}; *peType = RBU_PK_NOTABLE; *piPk = 0; assert( p->rc==SQLITE_OK ); p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, - sqlite3_mprintf( + tdsqlite3_mprintf( "SELECT (sql LIKE 'create virtual%%'), rootpage" " FROM sqlite_master" " WHERE name=%Q", zTab )); - if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){ + if( p->rc!=SQLITE_OK || tdsqlite3_step(aStmt[0])!=SQLITE_ROW ){ /* Either an error, or no such table. */ goto rbuTableType_end; } - if( sqlite3_column_int(aStmt[0], 0) ){ + if( tdsqlite3_column_int(aStmt[0], 0) ){ *peType = RBU_PK_VTAB; /* virtual table */ goto rbuTableType_end; } - *piTnum = sqlite3_column_int(aStmt[0], 1); + *piTnum = tdsqlite3_column_int(aStmt[0], 1); p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, - sqlite3_mprintf("PRAGMA index_list=%Q",zTab) + tdsqlite3_mprintf("PRAGMA index_list=%Q",zTab) ); if( p->rc ) goto rbuTableType_end; - while( sqlite3_step(aStmt[1])==SQLITE_ROW ){ - const u8 *zOrig = sqlite3_column_text(aStmt[1], 3); - const u8 *zIdx = sqlite3_column_text(aStmt[1], 1); + while( tdsqlite3_step(aStmt[1])==SQLITE_ROW ){ + const u8 *zOrig = tdsqlite3_column_text(aStmt[1], 3); + const u8 *zIdx = tdsqlite3_column_text(aStmt[1], 1); if( zOrig && zIdx && zOrig[0]=='p' ){ p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, - sqlite3_mprintf( + tdsqlite3_mprintf( "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx )); if( p->rc==SQLITE_OK ){ - if( sqlite3_step(aStmt[2])==SQLITE_ROW ){ - *piPk = sqlite3_column_int(aStmt[2], 0); + if( tdsqlite3_step(aStmt[2])==SQLITE_ROW ){ + *piPk = tdsqlite3_column_int(aStmt[2], 0); *peType = RBU_PK_EXTERNAL; }else{ *peType = RBU_PK_WITHOUT_ROWID; @@ -170598,11 +198676,11 @@ static void rbuTableType( } p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, - sqlite3_mprintf("PRAGMA table_info=%Q",zTab) + tdsqlite3_mprintf("PRAGMA table_info=%Q",zTab) ); if( p->rc==SQLITE_OK ){ - while( sqlite3_step(aStmt[3])==SQLITE_ROW ){ - if( sqlite3_column_int(aStmt[3],5)>0 ){ + while( tdsqlite3_step(aStmt[3])==SQLITE_ROW ){ + if( tdsqlite3_column_int(aStmt[3],5)>0 ){ *peType = RBU_PK_IPK; /* explicit IPK column */ goto rbuTableType_end; } @@ -170622,28 +198700,35 @@ rbuTableType_end: { ** This is a helper function for rbuObjIterCacheTableInfo(). It populates ** the pIter->abIndexed[] array. */ -static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){ - sqlite3_stmt *pList = 0; +static void rbuObjIterCacheIndexedCols(tdsqlite3rbu *p, RbuObjIter *pIter){ + tdsqlite3_stmt *pList = 0; int bIndex = 0; if( p->rc==SQLITE_OK ){ memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol); p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) + tdsqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) ); } pIter->nIndex = 0; - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){ - const char *zIdx = (const char*)sqlite3_column_text(pList, 1); - sqlite3_stmt *pXInfo = 0; + while( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pList) ){ + const char *zIdx = (const char*)tdsqlite3_column_text(pList, 1); + int bPartial = tdsqlite3_column_int(pList, 4); + tdsqlite3_stmt *pXInfo = 0; if( zIdx==0 ) break; + if( bPartial ){ + memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol); + } p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) + tdsqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) ); - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ - int iCid = sqlite3_column_int(pXInfo, 1); + while( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pXInfo) ){ + int iCid = tdsqlite3_column_int(pXInfo, 1); if( iCid>=0 ) pIter->abIndexed[iCid] = 1; + if( iCid==-2 ){ + memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol); + } } rbuFinalize(p, pXInfo); bIndex = 1; @@ -170669,9 +198754,9 @@ static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){ ** an error does occur, an error code and error message are also left in ** the RBU handle. */ -static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ +static int rbuObjIterCacheTableInfo(tdsqlite3rbu *p, RbuObjIter *pIter){ if( pIter->azTblCol==0 ){ - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; int nCol = 0; int i; /* for() loop iterator variable */ int bRbuRowid = 0; /* If input table has column "rbu_rowid" */ @@ -170683,7 +198768,7 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum); if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){ p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl); + p->zErrmsg = tdsqlite3_mprintf("no such table: %s", pIter->zTbl); } if( p->rc ) return p->rc; if( pIter->zIdx==0 ) pIter->iTnum = iTnum; @@ -170697,24 +198782,24 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ ** of the input table. Ignore any input table columns that begin with ** "rbu_". */ p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, - sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl) + tdsqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl) ); if( p->rc==SQLITE_OK ){ - nCol = sqlite3_column_count(pStmt); + nCol = tdsqlite3_column_count(pStmt); rbuAllocateIterArrays(p, pIter, nCol); } for(i=0; p->rc==SQLITE_OK && i<nCol; i++){ - const char *zName = (const char*)sqlite3_column_name(pStmt, i); - if( sqlite3_strnicmp("rbu_", zName, 4) ){ + const char *zName = (const char*)tdsqlite3_column_name(pStmt, i); + if( tdsqlite3_strnicmp("rbu_", zName, 4) ){ char *zCopy = rbuStrndup(zName, &p->rc); pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol; pIter->azTblCol[pIter->nTblCol++] = zCopy; } - else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){ + else if( 0==tdsqlite3_stricmp("rbu_rowid", zName) ){ bRbuRowid = 1; } } - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); pStmt = 0; if( p->rc==SQLITE_OK @@ -170722,7 +198807,7 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) ){ p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf( + p->zErrmsg = tdsqlite3_mprintf( "table %q %s rbu_rowid column", pIter->zDataTbl, (bRbuRowid ? "may not have" : "requires") ); @@ -170733,24 +198818,24 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ ** aiTblOrder[] arrays at the same time. */ if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, - sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl) + tdsqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl) ); } - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - const char *zName = (const char*)sqlite3_column_text(pStmt, 1); + while( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pStmt) ){ + const char *zName = (const char*)tdsqlite3_column_text(pStmt, 1); if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */ for(i=iOrder; i<pIter->nTblCol; i++){ if( 0==strcmp(zName, pIter->azTblCol[i]) ) break; } if( i==pIter->nTblCol ){ p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("column missing from %q: %s", + p->zErrmsg = tdsqlite3_mprintf("column missing from %q: %s", pIter->zDataTbl, zName ); }else{ - int iPk = sqlite3_column_int(pStmt, 5); - int bNotNull = sqlite3_column_int(pStmt, 3); - const char *zType = (const char*)sqlite3_column_text(pStmt, 2); + int iPk = tdsqlite3_column_int(pStmt, 5); + int bNotNull = tdsqlite3_column_int(pStmt, 3); + const char *zType = (const char*)tdsqlite3_column_text(pStmt, 2); if( i!=iOrder ){ SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]); @@ -170758,7 +198843,8 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ } pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc); - pIter->abTblPk[iOrder] = (iPk!=0); + assert( iPk>=0 ); + pIter->abTblPk[iOrder] = (u8)iPk; pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0); iOrder++; } @@ -170779,7 +198865,7 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ ** column names currently stored in the pIter->azTblCol[] array. */ static char *rbuObjIterGetCollist( - sqlite3rbu *p, /* RBU object */ + tdsqlite3rbu *p, /* RBU object */ RbuObjIter *pIter /* Object iterator for column names */ ){ char *zList = 0; @@ -170794,6 +198880,213 @@ static char *rbuObjIterGetCollist( } /* +** Return a comma separated list of the quoted PRIMARY KEY column names, +** in order, for the current table. Before each column name, add the text +** zPre. After each column name, add the zPost text. Use zSeparator as +** the separator text (usually ", "). +*/ +static char *rbuObjIterGetPkList( + tdsqlite3rbu *p, /* RBU object */ + RbuObjIter *pIter, /* Object iterator for column names */ + const char *zPre, /* Before each quoted column name */ + const char *zSeparator, /* Separator to use between columns */ + const char *zPost /* After each quoted column name */ +){ + int iPk = 1; + char *zRet = 0; + const char *zSep = ""; + while( 1 ){ + int i; + for(i=0; i<pIter->nTblCol; i++){ + if( (int)pIter->abTblPk[i]==iPk ){ + const char *zCol = pIter->azTblCol[i]; + zRet = rbuMPrintf(p, "%z%s%s\"%w\"%s", zRet, zSep, zPre, zCol, zPost); + zSep = zSeparator; + break; + } + } + if( i==pIter->nTblCol ) break; + iPk++; + } + return zRet; +} + +/* +** This function is called as part of restarting an RBU vacuum within +** stage 1 of the process (while the *-oal file is being built) while +** updating a table (not an index). The table may be a rowid table or +** a WITHOUT ROWID table. It queries the target database to find the +** largest key that has already been written to the target table and +** constructs a WHERE clause that can be used to extract the remaining +** rows from the source table. For a rowid table, the WHERE clause +** is of the form: +** +** "WHERE _rowid_ > ?" +** +** and for WITHOUT ROWID tables: +** +** "WHERE (key1, key2) > (?, ?)" +** +** Instead of "?" placeholders, the actual WHERE clauses created by +** this function contain literal SQL values. +*/ +static char *rbuVacuumTableStart( + tdsqlite3rbu *p, /* RBU handle */ + RbuObjIter *pIter, /* RBU iterator object */ + int bRowid, /* True for a rowid table */ + const char *zWrite /* Target table name prefix */ +){ + tdsqlite3_stmt *pMax = 0; + char *zRet = 0; + if( bRowid ){ + p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, + tdsqlite3_mprintf( + "SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl + ) + ); + if( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pMax) ){ + tdsqlite3_int64 iMax = tdsqlite3_column_int64(pMax, 0); + zRet = rbuMPrintf(p, " WHERE _rowid_ > %lld ", iMax); + } + rbuFinalize(p, pMax); + }else{ + char *zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", " DESC"); + char *zSelect = rbuObjIterGetPkList(p, pIter, "quote(", "||','||", ")"); + char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", ""); + + if( p->rc==SQLITE_OK ){ + p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, + tdsqlite3_mprintf( + "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1", + zSelect, zWrite, pIter->zTbl, zOrder + ) + ); + if( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pMax) ){ + const char *zVal = (const char*)tdsqlite3_column_text(pMax, 0); + zRet = rbuMPrintf(p, " WHERE (%s) > (%s) ", zList, zVal); + } + rbuFinalize(p, pMax); + } + + tdsqlite3_free(zOrder); + tdsqlite3_free(zSelect); + tdsqlite3_free(zList); + } + return zRet; +} + +/* +** This function is called as part of restating an RBU vacuum when the +** current operation is writing content to an index. If possible, it +** queries the target index b-tree for the largest key already written to +** it, then composes and returns an expression that can be used in a WHERE +** clause to select the remaining required rows from the source table. +** It is only possible to return such an expression if: +** +** * The index contains no DESC columns, and +** * The last key written to the index before the operation was +** suspended does not contain any NULL values. +** +** The expression is of the form: +** +** (index-field1, index-field2, ...) > (?, ?, ...) +** +** except that the "?" placeholders are replaced with literal values. +** +** If the expression cannot be created, NULL is returned. In this case, +** the caller has to use an OFFSET clause to extract only the required +** rows from the sourct table, just as it does for an RBU update operation. +*/ +char *rbuVacuumIndexStart( + tdsqlite3rbu *p, /* RBU handle */ + RbuObjIter *pIter /* RBU iterator object */ +){ + char *zOrder = 0; + char *zLhs = 0; + char *zSelect = 0; + char *zVector = 0; + char *zRet = 0; + int bFailed = 0; + const char *zSep = ""; + int iCol = 0; + tdsqlite3_stmt *pXInfo = 0; + + p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, + tdsqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) + ); + while( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pXInfo) ){ + int iCid = tdsqlite3_column_int(pXInfo, 1); + const char *zCollate = (const char*)tdsqlite3_column_text(pXInfo, 4); + const char *zCol; + if( tdsqlite3_column_int(pXInfo, 3) ){ + bFailed = 1; + break; + } + + if( iCid<0 ){ + if( pIter->eType==RBU_PK_IPK ){ + int i; + for(i=0; pIter->abTblPk[i]==0; i++); + assert( i<pIter->nTblCol ); + zCol = pIter->azTblCol[i]; + }else{ + zCol = "_rowid_"; + } + }else{ + zCol = pIter->azTblCol[iCid]; + } + + zLhs = rbuMPrintf(p, "%z%s \"%w\" COLLATE %Q", + zLhs, zSep, zCol, zCollate + ); + zOrder = rbuMPrintf(p, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC", + zOrder, zSep, iCol, zCol, zCollate + ); + zSelect = rbuMPrintf(p, "%z%s quote(\"rbu_imp_%d%w\")", + zSelect, zSep, iCol, zCol + ); + zSep = ", "; + iCol++; + } + rbuFinalize(p, pXInfo); + if( bFailed ) goto index_start_out; + + if( p->rc==SQLITE_OK ){ + tdsqlite3_stmt *pSel = 0; + + p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg, + tdsqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1", + zSelect, pIter->zTbl, zOrder + ) + ); + if( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pSel) ){ + zSep = ""; + for(iCol=0; iCol<pIter->nCol; iCol++){ + const char *zQuoted = (const char*)tdsqlite3_column_text(pSel, iCol); + if( zQuoted[0]=='N' ){ + bFailed = 1; + break; + } + zVector = rbuMPrintf(p, "%z%s%s", zVector, zSep, zQuoted); + zSep = ", "; + } + + if( !bFailed ){ + zRet = rbuMPrintf(p, "(%s) > (%s)", zLhs, zVector); + } + } + rbuFinalize(p, pSel); + } + + index_start_out: + tdsqlite3_free(zOrder); + tdsqlite3_free(zSelect); + tdsqlite3_free(zVector); + tdsqlite3_free(zLhs); + return zRet; +} + +/* ** This function is used to create a SELECT list (the list of SQL ** expressions that follows a SELECT keyword) for a SELECT statement ** used to read from an data_xxx or rbu_tmp_xxx table while updating the @@ -170818,7 +199111,7 @@ static char *rbuObjIterGetCollist( ** pzWhere: ... */ static char *rbuObjIterGetIndexCols( - sqlite3rbu *p, /* RBU object */ + tdsqlite3rbu *p, /* RBU object */ RbuObjIter *pIter, /* Object iterator for column names */ char **pzImposterCols, /* OUT: Columns for imposter table */ char **pzImposterPk, /* OUT: Imposter PK clause */ @@ -170826,7 +199119,7 @@ static char *rbuObjIterGetIndexCols( int *pnBind /* OUT: Trbul number of columns */ ){ int rc = p->rc; /* Error code */ - int rc2; /* sqlite3_finalize() return code */ + int rc2; /* tdsqlite3_finalize() return code */ char *zRet = 0; /* String to return */ char *zImpCols = 0; /* String to return via *pzImposterCols */ char *zImpPK = 0; /* String to return via *pzImposterPK */ @@ -170834,52 +199127,60 @@ static char *rbuObjIterGetIndexCols( int nBind = 0; /* Value to return via *pnBind */ const char *zCom = ""; /* Set to ", " later on */ const char *zAnd = ""; /* Set to " AND " later on */ - sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */ + tdsqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */ if( rc==SQLITE_OK ){ assert( p->zErrmsg==0 ); rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) + tdsqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) ); } - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ - int iCid = sqlite3_column_int(pXInfo, 1); - int bDesc = sqlite3_column_int(pXInfo, 3); - const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); - const char *zCol; + while( rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pXInfo) ){ + int iCid = tdsqlite3_column_int(pXInfo, 1); + int bDesc = tdsqlite3_column_int(pXInfo, 3); + const char *zCollate = (const char*)tdsqlite3_column_text(pXInfo, 4); + const char *zCol = 0; const char *zType; - if( iCid<0 ){ - /* An integer primary key. If the table has an explicit IPK, use - ** its name. Otherwise, use "rbu_rowid". */ - if( pIter->eType==RBU_PK_IPK ){ - int i; - for(i=0; pIter->abTblPk[i]==0; i++); - assert( i<pIter->nTblCol ); - zCol = pIter->azTblCol[i]; - }else if( rbuIsVacuum(p) ){ - zCol = "_rowid_"; + if( iCid==-2 ){ + int iSeq = tdsqlite3_column_int(pXInfo, 0); + zRet = tdsqlite3_mprintf("%z%s(%.*s) COLLATE %Q", zRet, zCom, + pIter->aIdxCol[iSeq].nSpan, pIter->aIdxCol[iSeq].zSpan, zCollate + ); + zType = ""; + }else { + if( iCid<0 ){ + /* An integer primary key. If the table has an explicit IPK, use + ** its name. Otherwise, use "rbu_rowid". */ + if( pIter->eType==RBU_PK_IPK ){ + int i; + for(i=0; pIter->abTblPk[i]==0; i++); + assert( i<pIter->nTblCol ); + zCol = pIter->azTblCol[i]; + }else if( rbuIsVacuum(p) ){ + zCol = "_rowid_"; + }else{ + zCol = "rbu_rowid"; + } + zType = "INTEGER"; }else{ - zCol = "rbu_rowid"; + zCol = pIter->azTblCol[iCid]; + zType = pIter->azTblType[iCid]; } - zType = "INTEGER"; - }else{ - zCol = pIter->azTblCol[iCid]; - zType = pIter->azTblType[iCid]; + zRet = tdsqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom,zCol,zCollate); } - zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate); - if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){ + if( pIter->bUnique==0 || tdsqlite3_column_int(pXInfo, 5) ){ const char *zOrder = (bDesc ? " DESC" : ""); - zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", + zImpPK = tdsqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", zImpPK, zCom, nBind, zCol, zOrder ); } - zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", + zImpCols = tdsqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", zImpCols, zCom, nBind, zCol, zType, zCollate ); - zWhere = sqlite3_mprintf( + zWhere = tdsqlite3_mprintf( "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol ); if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM; @@ -170888,14 +199189,14 @@ static char *rbuObjIterGetIndexCols( nBind++; } - rc2 = sqlite3_finalize(pXInfo); + rc2 = tdsqlite3_finalize(pXInfo); if( rc==SQLITE_OK ) rc = rc2; if( rc!=SQLITE_OK ){ - sqlite3_free(zRet); - sqlite3_free(zImpCols); - sqlite3_free(zImpPK); - sqlite3_free(zWhere); + tdsqlite3_free(zRet); + tdsqlite3_free(zImpCols); + tdsqlite3_free(zImpPK); + tdsqlite3_free(zWhere); zRet = 0; zImpCols = 0; zImpPK = 0; @@ -170922,7 +199223,7 @@ static char *rbuObjIterGetIndexCols( ** the text ", old._rowid_" to the returned value. */ static char *rbuObjIterGetOldlist( - sqlite3rbu *p, + tdsqlite3rbu *p, RbuObjIter *pIter, const char *zObj ){ @@ -170933,9 +199234,9 @@ static char *rbuObjIterGetOldlist( for(i=0; i<pIter->nTblCol; i++){ if( pIter->abIndexed[i] ){ const char *zCol = pIter->azTblCol[i]; - zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol); + zList = tdsqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol); }else{ - zList = sqlite3_mprintf("%z%sNULL", zList, zS); + zList = tdsqlite3_mprintf("%z%sNULL", zList, zS); } zS = ", "; if( zList==0 ){ @@ -170963,7 +199264,7 @@ static char *rbuObjIterGetOldlist( ** "b = ?1 AND c = ?2" */ static char *rbuObjIterGetWhere( - sqlite3rbu *p, + tdsqlite3rbu *p, RbuObjIter *pIter ){ char *zList = 0; @@ -171003,9 +199304,9 @@ static char *rbuObjIterGetWhere( ** stored in the (p->nCol+1)'th column. Set the error code and error message ** of the RBU handle to something reflecting this. */ -static void rbuBadControlError(sqlite3rbu *p){ +static void rbuBadControlError(tdsqlite3rbu *p){ p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("invalid rbu_control value"); + p->zErrmsg = tdsqlite3_mprintf("invalid rbu_control value"); } @@ -171016,9 +199317,9 @@ static void rbuBadControlError(sqlite3rbu *p){ ** passed as the second argument currently points to if the rbu_control ** column of the data_xxx table entry is set to zMask. ** -** The memory for the returned string is obtained from sqlite3_malloc(). +** The memory for the returned string is obtained from tdsqlite3_malloc(). ** It is the responsibility of the caller to eventually free it using -** sqlite3_free(). +** tdsqlite3_free(). ** ** If an OOM error is encountered when allocating space for the new ** string, an error code is left in the rbu handle passed as the first @@ -171027,7 +199328,7 @@ static void rbuBadControlError(sqlite3rbu *p){ ** attempting the allocation or modifying the stored error code. */ static char *rbuObjIterGetSetlist( - sqlite3rbu *p, + tdsqlite3rbu *p, RbuObjIter *pIter, const char *zMask ){ @@ -171070,9 +199371,9 @@ static char *rbuObjIterGetSetlist( ** "?" expressions. For example, if nByte is 3, return a pointer to ** a buffer containing the string "?,?,?". ** -** The memory for the returned string is obtained from sqlite3_malloc(). +** The memory for the returned string is obtained from tdsqlite3_malloc(). ** It is the responsibility of the caller to eventually free it using -** sqlite3_free(). +** tdsqlite3_free(). ** ** If an OOM error is encountered when allocating space for the new ** string, an error code is left in the rbu handle passed as the first @@ -171080,9 +199381,9 @@ static char *rbuObjIterGetSetlist( ** when this function is called, NULL is returned immediately, without ** attempting the allocation or modifying the stored error code. */ -static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){ +static char *rbuObjIterGetBindlist(tdsqlite3rbu *p, int nBind){ char *zRet = 0; - int nByte = nBind*2 + 1; + tdsqlite3_int64 nByte = 2*(tdsqlite3_int64)nBind + 1; zRet = (char*)rbuMalloc(p, nByte); if( zRet ){ @@ -171107,24 +199408,24 @@ static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){ ** ** PRIMARY KEY("b", "a" DESC) */ -static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){ +static char *rbuWithoutRowidPK(tdsqlite3rbu *p, RbuObjIter *pIter){ char *z = 0; assert( pIter->zIdx==0 ); if( p->rc==SQLITE_OK ){ const char *zSep = "PRIMARY KEY("; - sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */ - sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */ + tdsqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */ + tdsqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */ p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) + tdsqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) ); - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){ - const char *zOrig = (const char*)sqlite3_column_text(pXList,3); + while( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pXList) ){ + const char *zOrig = (const char*)tdsqlite3_column_text(pXList,3); if( zOrig && strcmp(zOrig, "pk")==0 ){ - const char *zIdx = (const char*)sqlite3_column_text(pXList,1); + const char *zIdx = (const char*)tdsqlite3_column_text(pXList,1); if( zIdx ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) + tdsqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) ); } break; @@ -171132,11 +199433,11 @@ static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){ } rbuFinalize(p, pXList); - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ - if( sqlite3_column_int(pXInfo, 5) ){ - /* int iCid = sqlite3_column_int(pXInfo, 0); */ - const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2); - const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : ""; + while( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pXInfo) ){ + if( tdsqlite3_column_int(pXInfo, 5) ){ + /* int iCid = tdsqlite3_column_int(pXInfo, 0); */ + const char *zCol = (const char*)tdsqlite3_column_text(pXInfo, 2); + const char *zDesc = tdsqlite3_column_int(pXInfo, 3) ? " DESC" : ""; z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc); zSep = ", "; } @@ -171166,12 +199467,12 @@ static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){ ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID; ** */ -static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ +static void rbuCreateImposterTable2(tdsqlite3rbu *p, RbuObjIter *pIter){ if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){ int tnum = pIter->iPkTnum; /* Root page of PK index */ - sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */ + tdsqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */ const char *zIdx = 0; /* Name of PK index */ - sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */ + tdsqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */ const char *zComma = ""; char *zCols = 0; /* Used to build up list of table cols */ char *zPk = 0; /* Used to build up table PK declaration */ @@ -171183,25 +199484,25 @@ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ "SELECT name FROM sqlite_master WHERE rootpage = ?" ); if( p->rc==SQLITE_OK ){ - sqlite3_bind_int(pQuery, 1, tnum); - if( SQLITE_ROW==sqlite3_step(pQuery) ){ - zIdx = (const char*)sqlite3_column_text(pQuery, 0); + tdsqlite3_bind_int(pQuery, 1, tnum); + if( SQLITE_ROW==tdsqlite3_step(pQuery) ){ + zIdx = (const char*)tdsqlite3_column_text(pQuery, 0); } } if( zIdx ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) + tdsqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) ); } rbuFinalize(p, pQuery); - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ - int bKey = sqlite3_column_int(pXInfo, 5); + while( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pXInfo) ){ + int bKey = tdsqlite3_column_int(pXInfo, 5); if( bKey ){ - int iCid = sqlite3_column_int(pXInfo, 1); - int bDesc = sqlite3_column_int(pXInfo, 3); - const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); - zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma, + int iCid = tdsqlite3_column_int(pXInfo, 1); + int bDesc = tdsqlite3_column_int(pXInfo, 3); + const char *zCollate = (const char*)tdsqlite3_column_text(pXInfo, 4); + zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma, iCid, pIter->azTblType[iCid], zCollate ); zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":""); @@ -171211,12 +199512,12 @@ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ zCols = rbuMPrintf(p, "%z, id INTEGER", zCols); rbuFinalize(p, pXInfo); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); + tdsqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); rbuMPrintfExec(p, p->dbMain, "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", zCols, zPk ); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); + tdsqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); } } @@ -171224,7 +199525,7 @@ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ ** If an error has already occurred when this function is called, it ** immediately returns zero (without doing any work). Or, if an error ** occurs during the execution of this function, it sets the error code -** in the sqlite3rbu object indicated by the first argument and returns +** in the tdsqlite3rbu object indicated by the first argument and returns ** zero. ** ** The iterator passed as the second argument is guaranteed to point to @@ -171240,20 +199541,20 @@ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ ** collation sequences. For tables that do not have an external PRIMARY ** KEY, it also means the same PRIMARY KEY declaration. */ -static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){ +static void rbuCreateImposterTable(tdsqlite3rbu *p, RbuObjIter *pIter){ if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){ int tnum = pIter->iTnum; const char *zComma = ""; char *zSql = 0; int iCol; - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); + tdsqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){ const char *zPk = ""; const char *zCol = pIter->azTblCol[iCol]; const char *zColl = 0; - p->rc = sqlite3_table_column_metadata( + p->rc = tdsqlite3_table_column_metadata( p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0 ); @@ -171262,7 +199563,7 @@ static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){ ** "PRIMARY KEY" to the imposter table column declaration. */ zPk = "PRIMARY KEY "; } - zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s", + zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s", zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl, (pIter->abNotNull[iCol] ? " NOT NULL" : "") ); @@ -171276,12 +199577,12 @@ static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){ } } - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); + tdsqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", pIter->zTbl, zSql, (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "") ); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); + tdsqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); } } @@ -171297,7 +199598,7 @@ static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){ ** virtual table. */ static void rbuObjIterPrepareTmpInsert( - sqlite3rbu *p, + tdsqlite3rbu *p, RbuObjIter *pIter, const char *zCollist, const char *zRbuRowid @@ -171307,7 +199608,7 @@ static void rbuObjIterPrepareTmpInsert( if( zBind ){ assert( pIter->pTmpInsert==0 ); p->rc = prepareFreeAndCollectError( - p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf( + p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, tdsqlite3_mprintf( "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind )); @@ -171315,42 +199616,137 @@ static void rbuObjIterPrepareTmpInsert( } static void rbuTmpInsertFunc( - sqlite3_context *pCtx, + tdsqlite3_context *pCtx, int nVal, - sqlite3_value **apVal + tdsqlite3_value **apVal ){ - sqlite3rbu *p = sqlite3_user_data(pCtx); + tdsqlite3rbu *p = tdsqlite3_user_data(pCtx); int rc = SQLITE_OK; int i; - assert( sqlite3_value_int(apVal[0])!=0 + assert( tdsqlite3_value_int(apVal[0])!=0 || p->objiter.eType==RBU_PK_EXTERNAL || p->objiter.eType==RBU_PK_NONE ); - if( sqlite3_value_int(apVal[0])!=0 ){ + if( tdsqlite3_value_int(apVal[0])!=0 ){ p->nPhaseOneStep += p->objiter.nIndex; } for(i=0; rc==SQLITE_OK && i<nVal; i++){ - rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]); + rc = tdsqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]); } if( rc==SQLITE_OK ){ - sqlite3_step(p->objiter.pTmpInsert); - rc = sqlite3_reset(p->objiter.pTmpInsert); + tdsqlite3_step(p->objiter.pTmpInsert); + rc = tdsqlite3_reset(p->objiter.pTmpInsert); } if( rc!=SQLITE_OK ){ - sqlite3_result_error_code(pCtx, rc); + tdsqlite3_result_error_code(pCtx, rc); } } +static char *rbuObjIterGetIndexWhere(tdsqlite3rbu *p, RbuObjIter *pIter){ + tdsqlite3_stmt *pStmt = 0; + int rc = p->rc; + char *zRet = 0; + + assert( pIter->zIdxSql==0 && pIter->nIdxCol==0 && pIter->aIdxCol==0 ); + + if( rc==SQLITE_OK ){ + rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, + "SELECT trim(sql) FROM sqlite_master WHERE type='index' AND name=?" + ); + } + if( rc==SQLITE_OK ){ + int rc2; + rc = tdsqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC); + if( rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pStmt) ){ + char *zSql = (char*)tdsqlite3_column_text(pStmt, 0); + if( zSql ){ + pIter->zIdxSql = zSql = rbuStrndup(zSql, &rc); + } + if( zSql ){ + int nParen = 0; /* Number of open parenthesis */ + int i; + int iIdxCol = 0; + int nIdxAlloc = 0; + for(i=0; zSql[i]; i++){ + char c = zSql[i]; + + /* If necessary, grow the pIter->aIdxCol[] array */ + if( iIdxCol==nIdxAlloc ){ + RbuSpan *aIdxCol = (RbuSpan*)tdsqlite3_realloc( + pIter->aIdxCol, (nIdxAlloc+16)*sizeof(RbuSpan) + ); + if( aIdxCol==0 ){ + rc = SQLITE_NOMEM; + break; + } + pIter->aIdxCol = aIdxCol; + nIdxAlloc += 16; + } + + if( c=='(' ){ + if( nParen==0 ){ + assert( iIdxCol==0 ); + pIter->aIdxCol[0].zSpan = &zSql[i+1]; + } + nParen++; + } + else if( c==')' ){ + nParen--; + if( nParen==0 ){ + int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan; + pIter->aIdxCol[iIdxCol++].nSpan = nSpan; + i++; + break; + } + }else if( c==',' && nParen==1 ){ + int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan; + pIter->aIdxCol[iIdxCol++].nSpan = nSpan; + pIter->aIdxCol[iIdxCol].zSpan = &zSql[i+1]; + }else if( c=='"' || c=='\'' || c=='`' ){ + for(i++; 1; i++){ + if( zSql[i]==c ){ + if( zSql[i+1]!=c ) break; + i++; + } + } + }else if( c=='[' ){ + for(i++; 1; i++){ + if( zSql[i]==']' ) break; + } + }else if( c=='-' && zSql[i+1]=='-' ){ + for(i=i+2; zSql[i] && zSql[i]!='\n'; i++); + if( zSql[i]=='\0' ) break; + }else if( c=='/' && zSql[i+1]=='*' ){ + for(i=i+2; zSql[i] && (zSql[i]!='*' || zSql[i+1]!='/'); i++); + if( zSql[i]=='\0' ) break; + i++; + } + } + if( zSql[i] ){ + zRet = rbuStrndup(&zSql[i], &rc); + } + pIter->nIdxCol = iIdxCol; + } + } + + rc2 = tdsqlite3_finalize(pStmt); + if( rc==SQLITE_OK ) rc = rc2; + } + + p->rc = rc; + return zRet; +} + /* ** Ensure that the SQLite statement handles required to update the ** target database object currently indicated by the iterator passed ** as the second argument are available. */ static int rbuObjIterPrepareAll( - sqlite3rbu *p, + tdsqlite3rbu *p, RbuObjIter *pIter, int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */ ){ @@ -171363,7 +199759,7 @@ static int rbuObjIterPrepareAll( char *zLimit = 0; if( nOffset ){ - zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset); + zLimit = tdsqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset); if( !zLimit ) p->rc = SQLITE_NOMEM; } @@ -171373,29 +199769,31 @@ static int rbuObjIterPrepareAll( char *zImposterPK = 0; /* Primary key declaration for imposter */ char *zWhere = 0; /* WHERE clause on PK columns */ char *zBind = 0; + char *zPart = 0; int nBind = 0; assert( pIter->eType!=RBU_PK_VTAB ); + zPart = rbuObjIterGetIndexWhere(p, pIter); zCollist = rbuObjIterGetIndexCols( p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind ); zBind = rbuObjIterGetBindlist(p, nBind); /* Create the imposter table used to write to this index. */ - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum); + tdsqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); + tdsqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum); rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID", zTbl, zImposterCols, zImposterPK ); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); + tdsqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); /* Create the statement to insert index entries */ pIter->nCol = nBind; if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError( p->dbMain, &pIter->pInsert, &p->zErrmsg, - sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind) + tdsqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind) ); } @@ -171403,7 +199801,7 @@ static int rbuObjIterPrepareAll( if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError( p->dbMain, &pIter->pDelete, &p->zErrmsg, - sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere) + tdsqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere) ); } @@ -171411,39 +199809,58 @@ static int rbuObjIterPrepareAll( if( p->rc==SQLITE_OK ){ char *zSql; if( rbuIsVacuum(p) ){ - zSql = sqlite3_mprintf( - "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s", + char *zStart = 0; + if( nOffset ){ + zStart = rbuVacuumIndexStart(p, pIter); + if( zStart ){ + tdsqlite3_free(zLimit); + zLimit = 0; + } + } + + zSql = tdsqlite3_mprintf( + "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s", zCollist, pIter->zDataTbl, + zPart, + (zStart ? (zPart ? "AND" : "WHERE") : ""), zStart, zCollist, zLimit ); + tdsqlite3_free(zStart); }else if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ - zSql = sqlite3_mprintf( - "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s", + zSql = tdsqlite3_mprintf( + "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s", zCollist, p->zStateDb, pIter->zDataTbl, - zCollist, zLimit + zPart, zCollist, zLimit ); }else{ - zSql = sqlite3_mprintf( - "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' " + zSql = tdsqlite3_mprintf( + "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s " "UNION ALL " "SELECT %s, rbu_control FROM '%q' " - "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 " + "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 " "ORDER BY %s%s", - zCollist, p->zStateDb, pIter->zDataTbl, + zCollist, p->zStateDb, pIter->zDataTbl, zPart, zCollist, pIter->zDataTbl, + zPart, + (zPart ? "AND" : "WHERE"), zCollist, zLimit ); } - p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql); + if( p->rc==SQLITE_OK ){ + p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql); + }else{ + tdsqlite3_free(zSql); + } } - sqlite3_free(zImposterCols); - sqlite3_free(zImposterPK); - sqlite3_free(zWhere); - sqlite3_free(zBind); + tdsqlite3_free(zImposterCols); + tdsqlite3_free(zImposterPK); + tdsqlite3_free(zWhere); + tdsqlite3_free(zBind); + tdsqlite3_free(zPart); }else{ int bRbuRowid = (pIter->eType==RBU_PK_VTAB) ||(pIter->eType==RBU_PK_NONE) @@ -171467,7 +199884,7 @@ static int rbuObjIterPrepareAll( /* Create the INSERT statement to write to the target PK b-tree */ if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz, - sqlite3_mprintf( + tdsqlite3_mprintf( "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings ) @@ -171479,7 +199896,7 @@ static int rbuObjIterPrepareAll( ** an rbu vacuum handle. */ if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz, - sqlite3_mprintf( + tdsqlite3_mprintf( "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere ) ); @@ -171536,27 +199953,51 @@ static int rbuObjIterPrepareAll( /* Create the SELECT statement to read keys from data_xxx */ if( p->rc==SQLITE_OK ){ const char *zRbuRowid = ""; + char *zStart = 0; + char *zOrder = 0; if( bRbuRowid ){ zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid"; } - p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, - sqlite3_mprintf( - "SELECT %s,%s rbu_control%s FROM '%q'%s", - zCollist, - (rbuIsVacuum(p) ? "0 AS " : ""), - zRbuRowid, - pIter->zDataTbl, zLimit - ) - ); + + if( rbuIsVacuum(p) ){ + if( nOffset ){ + zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite); + if( zStart ){ + tdsqlite3_free(zLimit); + zLimit = 0; + } + } + if( bRbuRowid ){ + zOrder = rbuMPrintf(p, "_rowid_"); + }else{ + zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", ""); + } + } + + if( p->rc==SQLITE_OK ){ + p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, + tdsqlite3_mprintf( + "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s", + zCollist, + (rbuIsVacuum(p) ? "0 AS " : ""), + zRbuRowid, + pIter->zDataTbl, (zStart ? zStart : ""), + (zOrder ? "ORDER BY" : ""), zOrder, + zLimit + ) + ); + } + tdsqlite3_free(zStart); + tdsqlite3_free(zOrder); } - sqlite3_free(zWhere); - sqlite3_free(zOldlist); - sqlite3_free(zNewlist); - sqlite3_free(zBindings); + tdsqlite3_free(zWhere); + tdsqlite3_free(zOldlist); + tdsqlite3_free(zNewlist); + tdsqlite3_free(zBindings); } - sqlite3_free(zCollist); - sqlite3_free(zLimit); + tdsqlite3_free(zCollist); + tdsqlite3_free(zLimit); } return p->rc; @@ -171572,10 +200013,10 @@ static int rbuObjIterPrepareAll( ** is not an error. Output variable *ppStmt is set to NULL in this case. */ static int rbuGetUpdateStmt( - sqlite3rbu *p, /* RBU handle */ + tdsqlite3rbu *p, /* RBU handle */ RbuObjIter *pIter, /* Object iterator */ const char *zMask, /* rbu_control value ('x.x.') */ - sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */ + tdsqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */ ){ RbuUpdateStmt **pp; RbuUpdateStmt *pUp = 0; @@ -171604,7 +200045,7 @@ static int rbuGetUpdateStmt( if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){ for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext)); *pp = 0; - sqlite3_finalize(pUp->pUpdate); + tdsqlite3_finalize(pUp->pUpdate); pUp->pUpdate = 0; }else{ pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1); @@ -171624,7 +200065,7 @@ static int rbuGetUpdateStmt( const char *zPrefix = ""; if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_"; - zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", + zUpdate = tdsqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", zPrefix, pIter->zTbl, zSet, zWhere ); p->rc = prepareFreeAndCollectError( @@ -171632,25 +200073,25 @@ static int rbuGetUpdateStmt( ); *ppStmt = pUp->pUpdate; } - sqlite3_free(zWhere); - sqlite3_free(zSet); + tdsqlite3_free(zWhere); + tdsqlite3_free(zSet); } return p->rc; } -static sqlite3 *rbuOpenDbhandle( - sqlite3rbu *p, +static tdsqlite3 *rbuOpenDbhandle( + tdsqlite3rbu *p, const char *zName, int bUseVfs ){ - sqlite3 *db = 0; + tdsqlite3 *db = 0; if( p->rc==SQLITE_OK ){ const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI; - p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0); + p->rc = tdsqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0); if( p->rc ){ - p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - sqlite3_close(db); + p->zErrmsg = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(db)); + tdsqlite3_close(db); db = 0; } } @@ -171662,9 +200103,10 @@ static sqlite3 *rbuOpenDbhandle( */ static void rbuFreeState(RbuState *p){ if( p ){ - sqlite3_free(p->zTbl); - sqlite3_free(p->zIdx); - sqlite3_free(p); + tdsqlite3_free(p->zTbl); + tdsqlite3_free(p->zDataTbl); + tdsqlite3_free(p->zIdx); + tdsqlite3_free(p); } } @@ -171672,14 +200114,14 @@ static void rbuFreeState(RbuState *p){ ** Allocate an RbuState object and load the contents of the rbu_state ** table into it. Return a pointer to the new object. It is the ** responsibility of the caller to eventually free the object using -** sqlite3_free(). +** tdsqlite3_free(). ** ** If an error occurs, leave an error code and message in the rbu handle ** and return NULL. */ -static RbuState *rbuLoadState(sqlite3rbu *p){ +static RbuState *rbuLoadState(tdsqlite3rbu *p){ RbuState *pRet = 0; - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; int rc; int rc2; @@ -171687,12 +200129,12 @@ static RbuState *rbuLoadState(sqlite3rbu *p){ if( pRet==0 ) return 0; rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, - sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb) + tdsqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb) ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - switch( sqlite3_column_int(pStmt, 0) ){ + while( rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pStmt) ){ + switch( tdsqlite3_column_int(pStmt, 0) ){ case RBU_STATE_STAGE: - pRet->eStage = sqlite3_column_int(pStmt, 1); + pRet->eStage = tdsqlite3_column_int(pStmt, 1); if( pRet->eStage!=RBU_STAGE_OAL && pRet->eStage!=RBU_STAGE_MOVE && pRet->eStage!=RBU_STAGE_CKPT @@ -171702,35 +200144,39 @@ static RbuState *rbuLoadState(sqlite3rbu *p){ break; case RBU_STATE_TBL: - pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); + pRet->zTbl = rbuStrndup((char*)tdsqlite3_column_text(pStmt, 1), &rc); break; case RBU_STATE_IDX: - pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); + pRet->zIdx = rbuStrndup((char*)tdsqlite3_column_text(pStmt, 1), &rc); break; case RBU_STATE_ROW: - pRet->nRow = sqlite3_column_int(pStmt, 1); + pRet->nRow = tdsqlite3_column_int(pStmt, 1); break; case RBU_STATE_PROGRESS: - pRet->nProgress = sqlite3_column_int64(pStmt, 1); + pRet->nProgress = tdsqlite3_column_int64(pStmt, 1); break; case RBU_STATE_CKPT: - pRet->iWalCksum = sqlite3_column_int64(pStmt, 1); + pRet->iWalCksum = tdsqlite3_column_int64(pStmt, 1); break; case RBU_STATE_COOKIE: - pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1); + pRet->iCookie = (u32)tdsqlite3_column_int64(pStmt, 1); break; case RBU_STATE_OALSZ: - pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1); + pRet->iOalSz = (u32)tdsqlite3_column_int64(pStmt, 1); break; case RBU_STATE_PHASEONESTEP: - pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1); + pRet->nPhaseOneStep = tdsqlite3_column_int64(pStmt, 1); + break; + + case RBU_STATE_DATATBL: + pRet->zDataTbl = rbuStrndup((char*)tdsqlite3_column_text(pStmt, 1), &rc); break; default: @@ -171738,7 +200184,7 @@ static RbuState *rbuLoadState(sqlite3rbu *p){ break; } } - rc2 = sqlite3_finalize(pStmt); + rc2 = tdsqlite3_finalize(pStmt); if( rc==SQLITE_OK ) rc = rc2; p->rc = rc; @@ -171750,7 +200196,7 @@ static RbuState *rbuLoadState(sqlite3rbu *p){ ** Open the database handle and attach the RBU database as "rbu". If an ** error occurs, leave an error code and message in the RBU handle. */ -static void rbuOpenDatabase(sqlite3rbu *p){ +static void rbuOpenDatabase(tdsqlite3rbu *p, int *pbRetry){ assert( p->rc || (p->dbMain==0 && p->dbRbu==0) ); assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 ); @@ -171758,9 +200204,9 @@ static void rbuOpenDatabase(sqlite3rbu *p){ p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1); if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ - sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); + tdsqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); if( p->zState==0 ){ - const char *zFile = sqlite3_db_filename(p->dbRbu, "main"); + const char *zFile = tdsqlite3_db_filename(p->dbRbu, "main"); p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile); } } @@ -171776,7 +200222,7 @@ static void rbuOpenDatabase(sqlite3rbu *p){ #if 0 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ - p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0); + p->rc = tdsqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0); } #endif @@ -171788,26 +200234,26 @@ static void rbuOpenDatabase(sqlite3rbu *p){ if( p->rc==SQLITE_OK ){ int rc2; int bOk = 0; - sqlite3_stmt *pCnt = 0; + tdsqlite3_stmt *pCnt = 0; p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg, "SELECT count(*) FROM stat.sqlite_master" ); if( p->rc==SQLITE_OK - && sqlite3_step(pCnt)==SQLITE_ROW - && 1==sqlite3_column_int(pCnt, 0) + && tdsqlite3_step(pCnt)==SQLITE_ROW + && 1==tdsqlite3_column_int(pCnt, 0) ){ bOk = 1; } - rc2 = sqlite3_finalize(pCnt); + rc2 = tdsqlite3_finalize(pCnt); if( p->rc==SQLITE_OK ) p->rc = rc2; if( p->rc==SQLITE_OK && bOk==0 ){ p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("invalid state database"); + p->zErrmsg = tdsqlite3_mprintf("invalid state database"); } if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); + p->rc = tdsqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); } } } @@ -171818,14 +200264,14 @@ static void rbuOpenDatabase(sqlite3rbu *p){ int rc; p->nRbu = 0; p->pRbuFd = 0; - rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); + rc = tdsqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); if( rc!=SQLITE_NOTFOUND ) p->rc = rc; if( p->eStage>=RBU_STAGE_MOVE ){ bOpen = 1; }else{ RbuState *pState = rbuLoadState(p); if( pState ){ - bOpen = (pState->eStage>RBU_STAGE_MOVE); + bOpen = (pState->eStage>=RBU_STAGE_MOVE); rbuFreeState(pState); } } @@ -171837,8 +200283,17 @@ static void rbuOpenDatabase(sqlite3rbu *p){ if( !rbuIsVacuum(p) ){ p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1); }else if( p->pRbuFd->pWalFd ){ + if( pbRetry ){ + p->pRbuFd->bNolock = 0; + tdsqlite3_close(p->dbRbu); + tdsqlite3_close(p->dbMain); + p->dbMain = 0; + p->dbRbu = 0; + *pbRetry = 1; + return; + } p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database"); + p->zErrmsg = tdsqlite3_mprintf("cannot vacuum wal mode database"); }else{ char *zTarget; char *zExtra = 0; @@ -171850,8 +200305,8 @@ static void rbuOpenDatabase(sqlite3rbu *p){ if( *zExtra=='\0' ) zExtra = 0; } - zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s", - sqlite3_db_filename(p->dbRbu, "main"), + zTarget = tdsqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s", + tdsqlite3_db_filename(p->dbRbu, "main"), (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra) ); @@ -171860,30 +200315,30 @@ static void rbuOpenDatabase(sqlite3rbu *p){ return; } p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1); - sqlite3_free(zTarget); + tdsqlite3_free(zTarget); } } if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_create_function(p->dbMain, + p->rc = tdsqlite3_create_function(p->dbMain, "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0 ); } if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_create_function(p->dbMain, + p->rc = tdsqlite3_create_function(p->dbMain, "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0 ); } if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_create_function(p->dbRbu, + p->rc = tdsqlite3_create_function(p->dbRbu, "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0 ); } if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); + p->rc = tdsqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); } rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master"); @@ -171891,17 +200346,17 @@ static void rbuOpenDatabase(sqlite3rbu *p){ ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use. ** This is an error. */ if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); + p->rc = tdsqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); } if( p->rc==SQLITE_NOTFOUND ){ p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("rbu vfs not found"); + p->zErrmsg = tdsqlite3_mprintf("rbu vfs not found"); } } /* -** This routine is a copy of the sqlite3FileSuffix3() routine from the core. +** This routine is a copy of the tdsqlite3FileSuffix3() routine from the core. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined. ** ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database @@ -171923,7 +200378,7 @@ static void rbuOpenDatabase(sqlite3rbu *p){ static void rbuFileSuffix3(const char *zBase, char *z){ #ifdef SQLITE_ENABLE_8_3_NAMES #if SQLITE_ENABLE_8_3_NAMES<2 - if( sqlite3_uri_boolean(zBase, "8_3_names", 0) ) + if( tdsqlite3_uri_boolean(zBase, "8_3_names", 0) ) #endif { int i, sz; @@ -171941,10 +200396,10 @@ static void rbuFileSuffix3(const char *zBase, char *z){ ** The checksum is store in the first page of xShmMap memory as an 8-byte ** blob starting at byte offset 40. */ -static i64 rbuShmChecksum(sqlite3rbu *p){ +static i64 rbuShmChecksum(tdsqlite3rbu *p){ i64 iRet = 0; if( p->rc==SQLITE_OK ){ - sqlite3_file *pDb = p->pTargetFd->pReal; + tdsqlite3_file *pDb = p->pTargetFd->pReal; u32 volatile *ptr; p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr); if( p->rc==SQLITE_OK ){ @@ -171958,7 +200413,7 @@ static i64 rbuShmChecksum(sqlite3rbu *p){ ** This function is called as part of initializing or reinitializing an ** incremental checkpoint. ** -** It populates the sqlite3rbu.aFrame[] array with the set of +** It populates the tdsqlite3rbu.aFrame[] array with the set of ** (wal frame -> db page) copy operations required to checkpoint the ** current wal file, and obtains the set of shm locks required to safely ** perform the copy operations directly on the file-system. @@ -171970,7 +200425,7 @@ static i64 rbuShmChecksum(sqlite3rbu *p){ ** other client appends a transaction to the wal file in the middle of ** an incremental checkpoint. */ -static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ +static void rbuSetupCheckpoint(tdsqlite3rbu *p, RbuState *pState){ /* If pState is NULL, then the wal file may not have been opened and ** recovered. Running a read-statement here to ensure that doing so @@ -171978,12 +200433,12 @@ static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ if( pState==0 ){ p->eStage = 0; if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0); + p->rc = tdsqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0); } } /* Assuming no error has occurred, run a "restart" checkpoint with the - ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following + ** tdsqlite3rbu.eStage variable set to CAPTURE. This turns on the following ** special behaviour in the rbu VFS: ** ** * If the exclusive shm WRITER or READ0 lock cannot be obtained, @@ -171992,7 +200447,7 @@ static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ ** ** * Attempts to read from the *-wal file or write to the database file ** do not perform any IO. Instead, the frame/page combinations that - ** would be read/written are recorded in the sqlite3rbu.aFrame[] + ** would be read/written are recorded in the tdsqlite3rbu.aFrame[] ** array. ** ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, @@ -172013,20 +200468,39 @@ static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ if( p->rc==SQLITE_OK ){ int rc2; p->eStage = RBU_STAGE_CAPTURE; - rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0); + rc2 = tdsqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0); if( rc2!=SQLITE_INTERNAL ) p->rc = rc2; } - if( p->rc==SQLITE_OK ){ + if( p->rc==SQLITE_OK && p->nFrame>0 ){ p->eStage = RBU_STAGE_CKPT; p->nStep = (pState ? pState->nRow : 0); p->aBuf = rbuMalloc(p, p->pgsz); p->iWalCksum = rbuShmChecksum(p); } - if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){ - p->rc = SQLITE_DONE; - p->eStage = RBU_STAGE_DONE; + if( p->rc==SQLITE_OK ){ + if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){ + p->rc = SQLITE_DONE; + p->eStage = RBU_STAGE_DONE; + }else{ + int nSectorSize; + tdsqlite3_file *pDb = p->pTargetFd->pReal; + tdsqlite3_file *pWal = p->pTargetFd->pWalFd->pReal; + assert( p->nPagePerSector==0 ); + nSectorSize = pDb->pMethods->xSectorSize(pDb); + if( nSectorSize>p->pgsz ){ + p->nPagePerSector = nSectorSize / p->pgsz; + }else{ + p->nPagePerSector = 1; + } + + /* Call xSync() on the wal file. This causes SQLite to sync the + ** directory in which the target database and the wal file reside, in + ** case it has not been synced since the rename() call in + ** rbuMoveOalFile(). */ + p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL); + } } } @@ -172035,7 +200509,7 @@ static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ ** the rbu object is in capture mode. Record the frame number of the frame ** being read in the aFrame[] array. */ -static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){ +static int rbuCaptureWalRead(tdsqlite3rbu *pRbu, i64 iOff, int iAmt){ const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0); u32 iFrame; @@ -172048,7 +200522,7 @@ static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){ if( pRbu->nFrame==pRbu->nFrameAlloc ){ int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2; RbuFrame *aNew; - aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame)); + aNew = (RbuFrame*)tdsqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame)); if( aNew==0 ) return SQLITE_NOMEM; pRbu->aFrame = aNew; pRbu->nFrameAlloc = nNew; @@ -172067,7 +200541,7 @@ static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){ ** file while the rbu handle is in capture mode. Record the page number ** of the page being written in the aFrame[] array. */ -static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){ +static int rbuCaptureDbWrite(tdsqlite3rbu *pRbu, i64 iOff){ pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1; return SQLITE_OK; } @@ -172077,9 +200551,9 @@ static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){ ** a single frame of data from the wal file into the database file, as ** indicated by the RbuFrame object. */ -static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){ - sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal; - sqlite3_file *pDb = p->pTargetFd->pReal; +static void rbuCheckpointFrame(tdsqlite3rbu *p, RbuFrame *pFrame){ + tdsqlite3_file *pWal = p->pTargetFd->pWalFd->pReal; + tdsqlite3_file *pDb = p->pTargetFd->pReal; i64 iOff; assert( p->rc==SQLITE_OK ); @@ -172095,8 +200569,8 @@ static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){ /* ** Take an EXCLUSIVE lock on the database file. */ -static void rbuLockDatabase(sqlite3rbu *p){ - sqlite3_file *pReal = p->pTargetFd->pReal; +static void rbuLockDatabase(tdsqlite3rbu *p){ + tdsqlite3_file *pReal = p->pTargetFd->pReal; assert( p->rc==SQLITE_OK ); p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED); if( p->rc==SQLITE_OK ){ @@ -172113,7 +200587,7 @@ static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){ if( nChar==0 ){ return 0; } - zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) ); + zWideFilename = tdsqlite3_malloc64( nChar*sizeof(zWideFilename[0]) ); if( zWideFilename==0 ){ return 0; } @@ -172121,7 +200595,7 @@ static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){ nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar); if( nChar==0 ){ - sqlite3_free(zWideFilename); + tdsqlite3_free(zWideFilename); zWideFilename = 0; } return zWideFilename; @@ -172135,17 +200609,17 @@ static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){ ** If an error occurs, leave an error code and error message in the rbu ** handle. */ -static void rbuMoveOalFile(sqlite3rbu *p){ - const char *zBase = sqlite3_db_filename(p->dbMain, "main"); +static void rbuMoveOalFile(tdsqlite3rbu *p){ + const char *zBase = tdsqlite3_db_filename(p->dbMain, "main"); const char *zMove = zBase; char *zOal; char *zWal; if( rbuIsVacuum(p) ){ - zMove = sqlite3_db_filename(p->dbRbu, "main"); + zMove = tdsqlite3_db_filename(p->dbRbu, "main"); } - zOal = sqlite3_mprintf("%s-oal", zMove); - zWal = sqlite3_mprintf("%s-wal", zMove); + zOal = tdsqlite3_mprintf("%s-oal", zMove); + zWal = tdsqlite3_mprintf("%s-wal", zMove); assert( p->eStage==RBU_STAGE_MOVE ); assert( p->rc==SQLITE_OK && p->zErrmsg==0 ); @@ -172166,8 +200640,8 @@ static void rbuMoveOalFile(sqlite3rbu *p){ /* Re-open the databases. */ rbuObjIterFinalize(&p->objiter); - sqlite3_close(p->dbRbu); - sqlite3_close(p->dbMain); + tdsqlite3_close(p->dbRbu); + tdsqlite3_close(p->dbMain); p->dbMain = 0; p->dbRbu = 0; @@ -172185,11 +200659,11 @@ static void rbuMoveOalFile(sqlite3rbu *p){ }else{ p->rc = SQLITE_IOERR; } - sqlite3_free(zWideWal); + tdsqlite3_free(zWideWal); }else{ p->rc = SQLITE_IOERR_NOMEM; } - sqlite3_free(zWideOal); + tdsqlite3_free(zWideOal); }else{ p->rc = SQLITE_IOERR_NOMEM; } @@ -172199,14 +200673,14 @@ static void rbuMoveOalFile(sqlite3rbu *p){ #endif if( p->rc==SQLITE_OK ){ - rbuOpenDatabase(p); + rbuOpenDatabase(p, 0); rbuSetupCheckpoint(p, 0); } } } - sqlite3_free(zWal); - sqlite3_free(zOal); + tdsqlite3_free(zWal); + tdsqlite3_free(zOal); } /* @@ -172226,13 +200700,13 @@ static void rbuMoveOalFile(sqlite3rbu *p){ ** If the rbu_control field contains an invalid value, an error code and ** message are left in the RBU handle and zero returned. */ -static int rbuStepType(sqlite3rbu *p, const char **pzMask){ +static int rbuStepType(tdsqlite3rbu *p, const char **pzMask){ int iCol = p->objiter.nCol; /* Index of rbu_control column */ int res = 0; /* Return value */ - switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){ + switch( tdsqlite3_column_type(p->objiter.pSelect, iCol) ){ case SQLITE_INTEGER: { - int iVal = sqlite3_column_int(p->objiter.pSelect, iCol); + int iVal = tdsqlite3_column_int(p->objiter.pSelect, iCol); switch( iVal ){ case 0: res = RBU_INSERT; break; case 1: res = RBU_DELETE; break; @@ -172244,7 +200718,7 @@ static int rbuStepType(sqlite3rbu *p, const char **pzMask){ } case SQLITE_TEXT: { - const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol); + const unsigned char *z = tdsqlite3_column_text(p->objiter.pSelect, iCol); if( z==0 ){ p->rc = SQLITE_NOMEM; }else{ @@ -172269,9 +200743,9 @@ static int rbuStepType(sqlite3rbu *p, const char **pzMask){ /* ** Assert that column iCol of statement pStmt is named zName. */ -static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){ - const char *zCol = sqlite3_column_name(pStmt, iCol); - assert( 0==sqlite3_stricmp(zName, zCol) ); +static void assertColumnName(tdsqlite3_stmt *pStmt, int iCol, const char *zName){ + const char *zCol = tdsqlite3_column_name(pStmt, iCol); + assert( 0==tdsqlite3_stricmp(zName, zCol) ); } #else # define assertColumnName(x,y,z) @@ -172280,12 +200754,12 @@ static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){ /* ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or ** RBU_IDX_DELETE. This function performs the work of a single -** sqlite3rbu_step() call for the type of operation specified by eType. +** tdsqlite3rbu_step() call for the type of operation specified by eType. */ -static void rbuStepOneOp(sqlite3rbu *p, int eType){ +static void rbuStepOneOp(tdsqlite3rbu *p, int eType){ RbuObjIter *pIter = &p->objiter; - sqlite3_value *pVal; - sqlite3_stmt *pWriter; + tdsqlite3_value *pVal; + tdsqlite3_stmt *pWriter; int i; assert( p->rc==SQLITE_OK ); @@ -172314,10 +200788,10 @@ static void rbuStepOneOp(sqlite3rbu *p, int eType){ ** to write a NULL into the IPK column. That is not permitted. */ if( eType==RBU_INSERT && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i] - && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL + && tdsqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL ){ p->rc = SQLITE_MISMATCH; - p->zErrmsg = sqlite3_mprintf("datatype mismatch"); + p->zErrmsg = tdsqlite3_mprintf("datatype mismatch"); return; } @@ -172325,8 +200799,8 @@ static void rbuStepOneOp(sqlite3rbu *p, int eType){ continue; } - pVal = sqlite3_column_value(pIter->pSelect, i); - p->rc = sqlite3_bind_value(pWriter, i+1, pVal); + pVal = tdsqlite3_column_value(pIter->pSelect, i); + p->rc = tdsqlite3_bind_value(pWriter, i+1, pVal); if( p->rc ) return; } if( pIter->zIdx==0 ){ @@ -172344,18 +200818,18 @@ static void rbuStepOneOp(sqlite3rbu *p, int eType){ assertColumnName(pIter->pSelect, pIter->nCol+1, rbuIsVacuum(p) ? "rowid" : "rbu_rowid" ); - pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1); - p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal); + pVal = tdsqlite3_column_value(pIter->pSelect, pIter->nCol+1); + p->rc = tdsqlite3_bind_value(pWriter, pIter->nCol+1, pVal); } } if( p->rc==SQLITE_OK ){ - sqlite3_step(pWriter); + tdsqlite3_step(pWriter); p->rc = resetAndCollectError(pWriter, &p->zErrmsg); } } /* -** This function does the work for an sqlite3rbu_step() call. +** This function does the work for an tdsqlite3rbu_step() call. ** ** The object-iterator (p->objiter) currently points to a valid object, ** and the input cursor (p->objiter.pSelect) currently points to a valid @@ -172365,7 +200839,7 @@ static void rbuStepOneOp(sqlite3rbu *p, int eType){ ** and message is left in the RBU handle and a copy of the error code ** returned. */ -static int rbuStep(sqlite3rbu *p){ +static int rbuStep(tdsqlite3rbu *p){ RbuObjIter *pIter = &p->objiter; const char *zMask = 0; int eType = rbuStepType(p, &zMask); @@ -172391,8 +200865,8 @@ static int rbuStep(sqlite3rbu *p){ rbuStepOneOp(p, eType); } else{ - sqlite3_value *pVal; - sqlite3_stmt *pUpdate = 0; + tdsqlite3_value *pVal; + tdsqlite3_stmt *pUpdate = 0; assert( eType==RBU_UPDATE ); p->nPhaseOneStep -= p->objiter.nIndex; rbuGetUpdateStmt(p, pIter, zMask, &pUpdate); @@ -172400,9 +200874,9 @@ static int rbuStep(sqlite3rbu *p){ int i; for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){ char c = zMask[pIter->aiSrcOrder[i]]; - pVal = sqlite3_column_value(pIter->pSelect, i); + pVal = tdsqlite3_column_value(pIter->pSelect, i); if( pIter->abTblPk[i] || c!='.' ){ - p->rc = sqlite3_bind_value(pUpdate, i+1, pVal); + p->rc = tdsqlite3_bind_value(pUpdate, i+1, pVal); } } if( p->rc==SQLITE_OK @@ -172410,11 +200884,11 @@ static int rbuStep(sqlite3rbu *p){ ){ /* Bind the rbu_rowid value to column _rowid_ */ assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid"); - pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1); - p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal); + pVal = tdsqlite3_column_value(pIter->pSelect, pIter->nCol+1); + p->rc = tdsqlite3_bind_value(pUpdate, pIter->nCol+1, pVal); } if( p->rc==SQLITE_OK ){ - sqlite3_step(pUpdate); + tdsqlite3_step(pUpdate); p->rc = resetAndCollectError(pUpdate, &p->zErrmsg); } } @@ -172430,23 +200904,23 @@ static int rbuStep(sqlite3rbu *p){ ** opened by p->dbMain to one more than the schema cookie of the main ** db opened by p->dbRbu. */ -static void rbuIncrSchemaCookie(sqlite3rbu *p){ +static void rbuIncrSchemaCookie(tdsqlite3rbu *p){ if( p->rc==SQLITE_OK ){ - sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain); + tdsqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain); int iCookie = 1000000; - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg, "PRAGMA schema_version" ); if( p->rc==SQLITE_OK ){ - /* Coverage: it may be that this sqlite3_step() cannot fail. There + /* Coverage: it may be that this tdsqlite3_step() cannot fail. There ** is already a transaction open, so the prepared statement cannot ** throw an SQLITE_SCHEMA exception. The only database page the ** statement reads is page 1, which is guaranteed to be in the cache. ** And no memory allocations are required. */ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - iCookie = sqlite3_column_int(pStmt, 0); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + iCookie = tdsqlite3_column_int(pStmt, 0); } rbuFinalize(p, pStmt); } @@ -172461,15 +200935,15 @@ static void rbuIncrSchemaCookie(sqlite3rbu *p){ ** value stored in the RBU_STATE_STAGE column is eStage. All other values ** are determined by inspecting the rbu handle passed as the first argument. */ -static void rbuSaveState(sqlite3rbu *p, int eStage){ +static void rbuSaveState(tdsqlite3rbu *p, int eStage){ if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){ - sqlite3_stmt *pInsert = 0; + tdsqlite3_stmt *pInsert = 0; rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd); int rc; assert( p->zErrmsg==0 ); rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg, - sqlite3_mprintf( + tdsqlite3_mprintf( "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES " "(%d, %d), " "(%d, %Q), " @@ -172479,7 +200953,8 @@ static void rbuSaveState(sqlite3rbu *p, int eStage){ "(%d, %lld), " "(%d, %lld), " "(%d, %lld), " - "(%d, %lld) ", + "(%d, %lld), " + "(%d, %Q) ", p->zStateDb, RBU_STATE_STAGE, eStage, RBU_STATE_TBL, p->objiter.zTbl, @@ -172489,14 +200964,15 @@ static void rbuSaveState(sqlite3rbu *p, int eStage){ RBU_STATE_CKPT, p->iWalCksum, RBU_STATE_COOKIE, (i64)pFd->iCookie, RBU_STATE_OALSZ, p->iOalSz, - RBU_STATE_PHASEONESTEP, p->nPhaseOneStep + RBU_STATE_PHASEONESTEP, p->nPhaseOneStep, + RBU_STATE_DATATBL, p->objiter.zDataTbl ) ); assert( pInsert==0 || rc==SQLITE_OK ); if( rc==SQLITE_OK ){ - sqlite3_step(pInsert); - rc = sqlite3_finalize(pInsert); + tdsqlite3_step(pInsert); + rc = tdsqlite3_finalize(pInsert); } if( rc!=SQLITE_OK ) p->rc = rc; } @@ -172506,12 +200982,12 @@ static void rbuSaveState(sqlite3rbu *p, int eStage){ /* ** The second argument passed to this function is the name of a PRAGMA ** setting - "page_size", "auto_vacuum", "user_version" or "application_id". -** This function executes the following on sqlite3rbu.dbRbu: +** This function executes the following on tdsqlite3rbu.dbRbu: ** ** "PRAGMA main.$zPragma" ** ** where $zPragma is the string passed as the second argument, then -** on sqlite3rbu.dbMain: +** on tdsqlite3rbu.dbMain: ** ** "PRAGMA main.$zPragma = $val" ** @@ -172520,15 +200996,15 @@ static void rbuSaveState(sqlite3rbu *p, int eStage){ ** In short, it copies the value of the specified PRAGMA setting from ** dbRbu to dbMain. */ -static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){ +static void rbuCopyPragma(tdsqlite3rbu *p, const char *zPragma){ if( p->rc==SQLITE_OK ){ - sqlite3_stmt *pPragma = 0; + tdsqlite3_stmt *pPragma = 0; p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.%s", zPragma) + tdsqlite3_mprintf("PRAGMA main.%s", zPragma) ); - if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){ + if( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pPragma) ){ p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d", - zPragma, sqlite3_column_int(pPragma, 0) + zPragma, tdsqlite3_column_int(pPragma, 0) ); } rbuFinalize(p, pPragma); @@ -172540,12 +201016,12 @@ static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){ ** the state database is empty. If this RBU handle was opened for an ** RBU vacuum operation, create the schema in the target db. */ -static void rbuCreateTargetSchema(sqlite3rbu *p){ - sqlite3_stmt *pSql = 0; - sqlite3_stmt *pInsert = 0; +static void rbuCreateTargetSchema(tdsqlite3rbu *p){ + tdsqlite3_stmt *pSql = 0; + tdsqlite3_stmt *pInsert = 0; assert( rbuIsVacuum(p) ); - p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg); + p->rc = tdsqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg); if( p->rc==SQLITE_OK ){ p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0" @@ -172554,9 +201030,9 @@ static void rbuCreateTargetSchema(sqlite3rbu *p){ ); } - while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){ - const char *zSql = (const char*)sqlite3_column_text(pSql, 0); - p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg); + while( p->rc==SQLITE_OK && tdsqlite3_step(pSql)==SQLITE_ROW ){ + const char *zSql = (const char*)tdsqlite3_column_text(pSql, 0); + p->rc = tdsqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg); } rbuFinalize(p, pSql); if( p->rc!=SQLITE_OK ) return; @@ -172573,16 +201049,16 @@ static void rbuCreateTargetSchema(sqlite3rbu *p){ ); } - while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){ + while( p->rc==SQLITE_OK && tdsqlite3_step(pSql)==SQLITE_ROW ){ int i; for(i=0; i<5; i++){ - sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i)); + tdsqlite3_bind_value(pInsert, i+1, tdsqlite3_column_value(pSql, i)); } - sqlite3_step(pInsert); - p->rc = sqlite3_reset(pInsert); + tdsqlite3_step(pInsert); + p->rc = tdsqlite3_reset(pInsert); } if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg); + p->rc = tdsqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg); } rbuFinalize(p, pSql); @@ -172592,7 +201068,7 @@ static void rbuCreateTargetSchema(sqlite3rbu *p){ /* ** Step the RBU object. */ -SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){ +SQLITE_API int tdsqlite3rbu_step(tdsqlite3rbu *p){ if( p ){ switch( p->eStage ){ case RBU_STAGE_OAL: { @@ -172622,13 +201098,13 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){ /* Advance to the next row to process. */ if( p->rc==SQLITE_OK ){ - int rc = sqlite3_step(pIter->pSelect); + int rc = tdsqlite3_step(pIter->pSelect); if( rc==SQLITE_ROW ){ p->nProgress++; p->nStep++; return rbuStep(p); } - p->rc = sqlite3_reset(pIter->pSelect); + p->rc = tdsqlite3_reset(pIter->pSelect); p->nStep = 0; } } @@ -172641,10 +201117,10 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){ rbuSaveState(p, RBU_STAGE_MOVE); rbuIncrSchemaCookie(p); if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg); + p->rc = tdsqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg); } if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg); + p->rc = tdsqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg); } p->eStage = RBU_STAGE_MOVE; } @@ -172662,7 +201138,7 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){ case RBU_STAGE_CKPT: { if( p->rc==SQLITE_OK ){ if( p->nStep>=p->nFrame ){ - sqlite3_file *pDb = p->pTargetFd->pReal; + tdsqlite3_file *pDb = p->pTargetFd->pReal; /* Sync the db file */ p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL); @@ -172681,9 +201157,26 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){ p->rc = SQLITE_DONE; } }else{ - RbuFrame *pFrame = &p->aFrame[p->nStep]; - rbuCheckpointFrame(p, pFrame); - p->nStep++; + /* At one point the following block copied a single frame from the + ** wal file to the database file. So that one call to tdsqlite3rbu_step() + ** checkpointed a single frame. + ** + ** However, if the sector-size is larger than the page-size, and the + ** application calls tdsqlite3rbu_savestate() or close() immediately + ** after this step, then rbu_step() again, then a power failure occurs, + ** then the database page written here may be damaged. Work around + ** this by checkpointing frames until the next page in the aFrame[] + ** lies on a different disk sector to the current one. */ + u32 iSector; + do{ + RbuFrame *pFrame = &p->aFrame[p->nStep]; + iSector = (pFrame->iDbPage-1) / p->nPagePerSector; + rbuCheckpointFrame(p, pFrame); + p->nStep++; + }while( p->nStep<p->nFrame + && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector) + && p->rc==SQLITE_OK + ); } p->nProgress++; } @@ -172707,20 +201200,20 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){ static int rbuStrCompare(const char *z1, const char *z2){ if( z1==0 && z2==0 ) return 0; if( z1==0 || z2==0 ) return 1; - return (sqlite3_stricmp(z1, z2)!=0); + return (tdsqlite3_stricmp(z1, z2)!=0); } /* -** This function is called as part of sqlite3rbu_open() when initializing +** This function is called as part of tdsqlite3rbu_open() when initializing ** an rbu handle in OAL stage. If the rbu update has not started (i.e. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges -** things so that the next call to sqlite3rbu_step() continues on from +** things so that the next call to tdsqlite3rbu_step() continues on from ** where the previous rbu handle left off. ** ** If an error occurs, an error code and error message are left in the ** rbu handle passed as the first argument. */ -static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){ +static void rbuSetupOal(tdsqlite3rbu *p, RbuState *pState){ assert( p->rc==SQLITE_OK ); if( pState->zTbl ){ RbuObjIter *pIter = &p->objiter; @@ -172728,14 +201221,15 @@ static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){ while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup || rbuStrCompare(pIter->zIdx, pState->zIdx) - || rbuStrCompare(pIter->zTbl, pState->zTbl) + || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl)) + || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl)) )){ rc = rbuObjIterNext(p, pIter); } if( rc==SQLITE_OK && !pIter->zTbl ){ rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error"); + p->zErrmsg = tdsqlite3_mprintf("rbu_state mismatch error"); } if( rc==SQLITE_OK ){ @@ -172752,34 +201246,35 @@ static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){ ** target database in the file-system, delete it. If an error occurs, ** leave an error code and error message in the rbu handle. */ -static void rbuDeleteOalFile(sqlite3rbu *p){ +static void rbuDeleteOalFile(tdsqlite3rbu *p){ char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget); if( zOal ){ - sqlite3_vfs *pVfs = sqlite3_vfs_find(0); + tdsqlite3_vfs *pVfs = tdsqlite3_vfs_find(0); assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 ); pVfs->xDelete(pVfs, zOal, 0); - sqlite3_free(zOal); + tdsqlite3_free(zOal); } } /* ** Allocate a private rbu VFS for the rbu handle passed as the only -** argument. This VFS will be used unless the call to sqlite3rbu_open() +** argument. This VFS will be used unless the call to tdsqlite3rbu_open() ** specified a URI with a vfs=? option in place of a target database ** file name. */ -static void rbuCreateVfs(sqlite3rbu *p){ +static void rbuCreateVfs(tdsqlite3rbu *p){ int rnd; char zRnd[64]; assert( p->rc==SQLITE_OK ); - sqlite3_randomness(sizeof(int), (void*)&rnd); - sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd); - p->rc = sqlite3rbu_create_vfs(zRnd, 0); + tdsqlite3_randomness(sizeof(int), (void*)&rnd); + tdsqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd); + p->rc = tdsqlite3rbu_create_vfs(zRnd, 0); if( p->rc==SQLITE_OK ){ - sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd); + tdsqlite3_vfs *pVfs = tdsqlite3_vfs_find(zRnd); assert( pVfs ); p->zVfsName = pVfs->zName; + ((rbu_vfs*)pVfs)->pRbu = p; } } @@ -172787,9 +201282,9 @@ static void rbuCreateVfs(sqlite3rbu *p){ ** Destroy the private VFS created for the rbu handle passed as the only ** argument by an earlier call to rbuCreateVfs(). */ -static void rbuDeleteVfs(sqlite3rbu *p){ +static void rbuDeleteVfs(tdsqlite3rbu *p){ if( p->zVfsName ){ - sqlite3rbu_destroy_vfs(p->zVfsName); + tdsqlite3rbu_destroy_vfs(p->zVfsName); p->zVfsName = 0; } } @@ -172800,42 +201295,43 @@ static void rbuDeleteVfs(sqlite3rbu *p){ ** the number of auxilliary indexes on the table. */ static void rbuIndexCntFunc( - sqlite3_context *pCtx, + tdsqlite3_context *pCtx, int nVal, - sqlite3_value **apVal + tdsqlite3_value **apVal ){ - sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx); - sqlite3_stmt *pStmt = 0; + tdsqlite3rbu *p = (tdsqlite3rbu*)tdsqlite3_user_data(pCtx); + tdsqlite3_stmt *pStmt = 0; char *zErrmsg = 0; int rc; + tdsqlite3 *db = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain); assert( nVal==1 ); - rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg, - sqlite3_mprintf("SELECT count(*) FROM sqlite_master " - "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0])) + rc = prepareFreeAndCollectError(db, &pStmt, &zErrmsg, + tdsqlite3_mprintf("SELECT count(*) FROM sqlite_master " + "WHERE type='index' AND tbl_name = %Q", tdsqlite3_value_text(apVal[0])) ); if( rc!=SQLITE_OK ){ - sqlite3_result_error(pCtx, zErrmsg, -1); + tdsqlite3_result_error(pCtx, zErrmsg, -1); }else{ int nIndex = 0; - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - nIndex = sqlite3_column_int(pStmt, 0); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + nIndex = tdsqlite3_column_int(pStmt, 0); } - rc = sqlite3_finalize(pStmt); + rc = tdsqlite3_finalize(pStmt); if( rc==SQLITE_OK ){ - sqlite3_result_int(pCtx, nIndex); + tdsqlite3_result_int(pCtx, nIndex); }else{ - sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1); + tdsqlite3_result_error(pCtx, tdsqlite3_errmsg(db), -1); } } - sqlite3_free(zErrmsg); + tdsqlite3_free(zErrmsg); } /* ** If the RBU database contains the rbu_count table, use it to initialize -** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table +** the tdsqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table ** is assumed to contain the same columns as: ** ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID; @@ -172844,18 +201340,18 @@ static void rbuIndexCntFunc( ** database. The 'tbl' column should contain the name of a data_xxx table, ** and the cnt column the number of rows it contains. ** -** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt +** tdsqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt ** for all rows in the rbu_count table, where nIndex is the number of ** indexes on the corresponding target database table. */ -static void rbuInitPhaseOneSteps(sqlite3rbu *p){ +static void rbuInitPhaseOneSteps(tdsqlite3rbu *p){ if( p->rc==SQLITE_OK ){ - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; int bExists = 0; /* True if rbu_count exists */ p->nPhaseOneStep = -1; - p->rc = sqlite3_create_function(p->dbRbu, + p->rc = tdsqlite3_create_function(p->dbRbu, "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0 ); @@ -172867,10 +201363,10 @@ static void rbuInitPhaseOneSteps(sqlite3rbu *p){ ); } if( p->rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ bExists = 1; } - p->rc = sqlite3_finalize(pStmt); + p->rc = tdsqlite3_finalize(pStmt); } if( p->rc==SQLITE_OK && bExists ){ @@ -172879,37 +201375,38 @@ static void rbuInitPhaseOneSteps(sqlite3rbu *p){ "FROM rbu_count" ); if( p->rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + p->nPhaseOneStep = tdsqlite3_column_int64(pStmt, 0); } - p->rc = sqlite3_finalize(pStmt); + p->rc = tdsqlite3_finalize(pStmt); } } } } -static sqlite3rbu *openRbuHandle( +static tdsqlite3rbu *openRbuHandle( const char *zTarget, const char *zRbu, const char *zState ){ - sqlite3rbu *p; + tdsqlite3rbu *p; size_t nTarget = zTarget ? strlen(zTarget) : 0; size_t nRbu = strlen(zRbu); - size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1; + size_t nByte = sizeof(tdsqlite3rbu) + nTarget+1 + nRbu+1; - p = (sqlite3rbu*)sqlite3_malloc64(nByte); + p = (tdsqlite3rbu*)tdsqlite3_malloc64(nByte); if( p ){ RbuState *pState = 0; /* Create the custom VFS. */ - memset(p, 0, sizeof(sqlite3rbu)); + memset(p, 0, sizeof(tdsqlite3rbu)); rbuCreateVfs(p); /* Open the target, RBU and state databases */ if( p->rc==SQLITE_OK ){ char *pCsr = (char*)&p[1]; + int bRetry = 0; if( zTarget ){ p->zTarget = pCsr; memcpy(p->zTarget, zTarget, nTarget+1); @@ -172921,7 +201418,18 @@ static sqlite3rbu *openRbuHandle( if( zState ){ p->zState = rbuMPrintf(p, "%s", zState); } - rbuOpenDatabase(p); + + /* If the first attempt to open the database file fails and the bRetry + ** flag it set, this means that the db was not opened because it seemed + ** to be a wal-mode db. But, this may have happened due to an earlier + ** RBU vacuum operation leaving an old wal file in the directory. + ** If this is the case, it will have been checkpointed and deleted + ** when the handle was closed and a second attempt to open the + ** database may succeed. */ + rbuOpenDatabase(p, &bRetry); + if( bRetry ){ + rbuOpenDatabase(p, 0); + } } if( p->rc==SQLITE_OK ){ @@ -172946,7 +201454,7 @@ static sqlite3rbu *openRbuHandle( if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){ if( p->eStage==RBU_STAGE_OAL ){ p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("cannot update wal mode database"); + p->zErrmsg = tdsqlite3_mprintf("cannot update wal mode database"); }else if( p->eStage==RBU_STAGE_MOVE ){ p->eStage = RBU_STAGE_CKPT; p->nStep = 0; @@ -172964,7 +201472,7 @@ static sqlite3rbu *openRbuHandle( ** transaction is committed in rollback mode) currently stored on ** page 1 of the database file. */ p->rc = SQLITE_BUSY; - p->zErrmsg = sqlite3_mprintf("database modified during rbu %s", + p->zErrmsg = tdsqlite3_mprintf("database modified during rbu %s", (rbuIsVacuum(p) ? "vacuum" : "update") ); } @@ -172972,8 +201480,8 @@ static sqlite3rbu *openRbuHandle( if( p->rc==SQLITE_OK ){ if( p->eStage==RBU_STAGE_OAL ){ - sqlite3 *db = p->dbMain; - p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg); + tdsqlite3 *db = p->dbMain; + p->rc = tdsqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg); /* Point the object iterator at the first object */ if( p->rc==SQLITE_OK ){ @@ -172994,16 +201502,16 @@ static sqlite3rbu *openRbuHandle( /* Open transactions both databases. The *-oal file is opened or ** created at this point. */ if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg); + p->rc = tdsqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg); } /* Check if the main database is a zipvfs db. If it is, set the upper ** level pager to use "journal_mode=off". This prevents it from ** generating a large journal using a temp file. */ if( p->rc==SQLITE_OK ){ - int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0); + int frc = tdsqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0); if( frc==SQLITE_OK ){ - p->rc = sqlite3_exec( + p->rc = tdsqlite3_exec( db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg); } } @@ -173033,11 +201541,11 @@ static sqlite3rbu *openRbuHandle( ** Allocate and return an RBU handle with all fields zeroed except for the ** error code, which is set to SQLITE_MISUSE. */ -static sqlite3rbu *rbuMisuseError(void){ - sqlite3rbu *pRet; - pRet = sqlite3_malloc64(sizeof(sqlite3rbu)); +static tdsqlite3rbu *rbuMisuseError(void){ + tdsqlite3rbu *pRet; + pRet = tdsqlite3_malloc64(sizeof(tdsqlite3rbu)); if( pRet ){ - memset(pRet, 0, sizeof(sqlite3rbu)); + memset(pRet, 0, sizeof(tdsqlite3rbu)); pRet->rc = SQLITE_MISUSE; } return pRet; @@ -173046,7 +201554,7 @@ static sqlite3rbu *rbuMisuseError(void){ /* ** Open and return a new RBU handle. */ -SQLITE_API sqlite3rbu *sqlite3rbu_open( +SQLITE_API tdsqlite3rbu *tdsqlite3rbu_open( const char *zTarget, const char *zRbu, const char *zState @@ -173059,11 +201567,17 @@ SQLITE_API sqlite3rbu *sqlite3rbu_open( /* ** Open a handle to begin or resume an RBU VACUUM operation. */ -SQLITE_API sqlite3rbu *sqlite3rbu_vacuum( +SQLITE_API tdsqlite3rbu *tdsqlite3rbu_vacuum( const char *zTarget, const char *zState ){ if( zTarget==0 ){ return rbuMisuseError(); } + if( zState ){ + int n = strlen(zState); + if( n>=7 && 0==memcmp("-vactmp", &zState[n-7], 7) ){ + return rbuMisuseError(); + } + } /* TODO: Check that both arguments are non-NULL */ return openRbuHandle(0, zTarget, zState); } @@ -173071,8 +201585,8 @@ SQLITE_API sqlite3rbu *sqlite3rbu_vacuum( /* ** Return the database handle used by pRbu. */ -SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){ - sqlite3 *db = 0; +SQLITE_API tdsqlite3 *tdsqlite3rbu_db(tdsqlite3rbu *pRbu, int bRbu){ + tdsqlite3 *db = 0; if( pRbu ){ db = (bRbu ? pRbu->dbRbu : pRbu->dbMain); } @@ -173085,7 +201599,7 @@ SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){ ** then edit any error message string so as to remove all occurrences of ** the pattern "rbu_imp_[0-9]*". */ -static void rbuEditErrmsg(sqlite3rbu *p){ +static void rbuEditErrmsg(tdsqlite3rbu *p){ if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){ unsigned int i; size_t nErrmsg = strlen(p->zErrmsg); @@ -173103,19 +201617,25 @@ static void rbuEditErrmsg(sqlite3rbu *p){ /* ** Close the RBU handle. */ -SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){ +SQLITE_API int tdsqlite3rbu_close(tdsqlite3rbu *p, char **pzErrmsg){ int rc; if( p ){ /* Commit the transaction to the *-oal file. */ if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){ - p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg); + p->rc = tdsqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg); + } + + /* Sync the db file if currently doing an incremental checkpoint */ + if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){ + tdsqlite3_file *pDb = p->pTargetFd->pReal; + p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL); } rbuSaveState(p, p->eStage); if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){ - p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg); + p->rc = tdsqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg); } /* Close any open statement handles. */ @@ -173123,26 +201643,31 @@ SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){ /* If this is an RBU vacuum handle and the vacuum has either finished ** successfully or encountered an error, delete the contents of the - ** state table. This causes the next call to sqlite3rbu_vacuum() + ** state table. This causes the next call to tdsqlite3rbu_vacuum() ** specifying the current target and state databases to start a new ** vacuum from scratch. */ if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){ - int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0); + int rc2 = tdsqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0); if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2; } /* Close the open database handle and VFS object. */ - sqlite3_close(p->dbRbu); - sqlite3_close(p->dbMain); + tdsqlite3_close(p->dbRbu); + tdsqlite3_close(p->dbMain); + assert( p->szTemp==0 ); rbuDeleteVfs(p); - sqlite3_free(p->aBuf); - sqlite3_free(p->aFrame); + tdsqlite3_free(p->aBuf); + tdsqlite3_free(p->aFrame); rbuEditErrmsg(p); rc = p->rc; - *pzErrmsg = p->zErrmsg; - sqlite3_free(p->zState); - sqlite3_free(p); + if( pzErrmsg ){ + *pzErrmsg = p->zErrmsg; + }else{ + tdsqlite3_free(p->zErrmsg); + } + tdsqlite3_free(p->zState); + tdsqlite3_free(p); }else{ rc = SQLITE_NOMEM; *pzErrmsg = 0; @@ -173155,7 +201680,7 @@ SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){ ** updates) that have been performed on the target database since the ** current RBU update was started. */ -SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){ +SQLITE_API tdsqlite3_int64 tdsqlite3rbu_progress(tdsqlite3rbu *pRbu){ return pRbu->nProgress; } @@ -173163,7 +201688,7 @@ SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){ ** Return permyriadage progress indications for the two main stages of ** an RBU update. */ -SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){ +SQLITE_API void tdsqlite3rbu_bp_progress(tdsqlite3rbu *p, int *pnOne, int *pnTwo){ const int MAX_PROGRESS = 10000; switch( p->eStage ){ case RBU_STAGE_OAL: @@ -173198,7 +201723,7 @@ SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){ /* ** Return the current state of the RBU vacuum or update operation. */ -SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){ +SQLITE_API int tdsqlite3rbu_state(tdsqlite3rbu *p){ int aRes[] = { 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE, 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE @@ -173226,14 +201751,20 @@ SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){ } } -SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){ +SQLITE_API int tdsqlite3rbu_savestate(tdsqlite3rbu *p){ int rc = p->rc; if( rc==SQLITE_DONE ) return SQLITE_OK; assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE ); if( p->eStage==RBU_STAGE_OAL ){ assert( rc!=SQLITE_DONE ); - if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0); + if( rc==SQLITE_OK ) rc = tdsqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0); + } + + /* Sync the db file */ + if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){ + tdsqlite3_file *pDb = p->pTargetFd->pReal; + rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL); } p->rc = rc; @@ -173242,9 +201773,12 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){ if( p->eStage==RBU_STAGE_OAL ){ assert( rc!=SQLITE_DONE ); - if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); - if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0); - if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0); + if( rc==SQLITE_OK ) rc = tdsqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); + if( rc==SQLITE_OK ){ + const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE"; + rc = tdsqlite3_exec(p->dbRbu, zBegin, 0, 0, 0); + } + if( rc==SQLITE_OK ) rc = tdsqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0); } p->rc = rc; @@ -173297,7 +201831,7 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){ ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it ** fails with an SQLITE_BUSY error. This is to stop RBU connections ** from automatically checkpointing a *-wal (or *-oal) file from within -** sqlite3_close(). +** tdsqlite3_close(). ** ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and ** all xWrite() calls on the target database file perform no IO. @@ -173311,8 +201845,9 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){ */ static void rbuUnlockShm(rbu_file *p){ + assert( p->openFlags & SQLITE_OPEN_MAIN_DB ); if( p->pRbu ){ - int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock; + int (*xShmLock)(tdsqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock; int i; for(i=0; i<SQLITE_SHM_NLOCK;i++){ if( (1<<i) & p->pRbu->mLock ){ @@ -173324,30 +201859,105 @@ static void rbuUnlockShm(rbu_file *p){ } /* +*/ +static int rbuUpdateTempSize(rbu_file *pFd, tdsqlite3_int64 nNew){ + tdsqlite3rbu *pRbu = pFd->pRbu; + i64 nDiff = nNew - pFd->sz; + pRbu->szTemp += nDiff; + pFd->sz = nNew; + assert( pRbu->szTemp>=0 ); + if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL; + return SQLITE_OK; +} + +/* +** Add an item to the main-db lists, if it is not already present. +** +** There are two main-db lists. One for all file descriptors, and one +** for all file descriptors with rbu_file.pDb!=0. If the argument has +** rbu_file.pDb!=0, then it is assumed to already be present on the +** main list and is only added to the pDb!=0 list. +*/ +static void rbuMainlistAdd(rbu_file *p){ + rbu_vfs *pRbuVfs = p->pRbuVfs; + rbu_file *pIter; + assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) ); + tdsqlite3_mutex_enter(pRbuVfs->mutex); + if( p->pRbu==0 ){ + for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext); + p->pMainNext = pRbuVfs->pMain; + pRbuVfs->pMain = p; + }else{ + for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){} + if( pIter==0 ){ + p->pMainRbuNext = pRbuVfs->pMainRbu; + pRbuVfs->pMainRbu = p; + } + } + tdsqlite3_mutex_leave(pRbuVfs->mutex); +} + +/* +** Remove an item from the main-db lists. +*/ +static void rbuMainlistRemove(rbu_file *p){ + rbu_file **pp; + tdsqlite3_mutex_enter(p->pRbuVfs->mutex); + for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){} + if( *pp ) *pp = p->pMainNext; + p->pMainNext = 0; + for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){} + if( *pp ) *pp = p->pMainRbuNext; + p->pMainRbuNext = 0; + tdsqlite3_mutex_leave(p->pRbuVfs->mutex); +} + +/* +** Given that zWal points to a buffer containing a wal file name passed to +** either the xOpen() or xAccess() VFS method, search the main-db list for +** a file-handle opened by the same database connection on the corresponding +** database file. +** +** If parameter bRbu is true, only search for file-descriptors with +** rbu_file.pDb!=0. +*/ +static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){ + rbu_file *pDb; + tdsqlite3_mutex_enter(pRbuVfs->mutex); + if( bRbu ){ + for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){} + }else{ + for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){} + } + tdsqlite3_mutex_leave(pRbuVfs->mutex); + return pDb; +} + +/* ** Close an rbu file. */ -static int rbuVfsClose(sqlite3_file *pFile){ +static int rbuVfsClose(tdsqlite3_file *pFile){ rbu_file *p = (rbu_file*)pFile; int rc; int i; /* Free the contents of the apShm[] array. And the array itself. */ for(i=0; i<p->nShm; i++){ - sqlite3_free(p->apShm[i]); + tdsqlite3_free(p->apShm[i]); } - sqlite3_free(p->apShm); + tdsqlite3_free(p->apShm); p->apShm = 0; - sqlite3_free(p->zDel); + tdsqlite3_free(p->zDel); if( p->openFlags & SQLITE_OPEN_MAIN_DB ){ - rbu_file **pp; - sqlite3_mutex_enter(p->pRbuVfs->mutex); - for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext)); - *pp = p->pMainNext; - sqlite3_mutex_leave(p->pRbuVfs->mutex); + rbuMainlistRemove(p); rbuUnlockShm(p); p->pReal->pMethods->xShmUnmap(p->pReal, 0); } + else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){ + rbuUpdateTempSize(p, 0); + } + assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p ); /* Close the underlying file handle */ rc = p->pReal->pMethods->xClose(p->pReal); @@ -173386,13 +201996,13 @@ static void rbuPutU16(u8 *aBuf, u16 iVal){ ** Read data from an rbuVfs-file. */ static int rbuVfsRead( - sqlite3_file *pFile, + tdsqlite3_file *pFile, void *zBuf, int iAmt, sqlite_int64 iOfst ){ rbu_file *p = (rbu_file*)pFile; - sqlite3rbu *pRbu = p->pRbu; + tdsqlite3rbu *pRbu = p->pRbu; int rc; if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){ @@ -173417,7 +202027,7 @@ static int rbuVfsRead( && (p->openFlags & SQLITE_OPEN_MAIN_DB) && pRbu->rc==SQLITE_OK ){ - sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd; + tdsqlite3_file *pFd = (tdsqlite3_file*)pRbu->pRbuFd; rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst); if( rc==SQLITE_OK ){ u8 *aBuf = (u8*)zBuf; @@ -173452,24 +202062,32 @@ static int rbuVfsRead( ** Write data to an rbuVfs-file. */ static int rbuVfsWrite( - sqlite3_file *pFile, + tdsqlite3_file *pFile, const void *zBuf, int iAmt, sqlite_int64 iOfst ){ rbu_file *p = (rbu_file*)pFile; - sqlite3rbu *pRbu = p->pRbu; + tdsqlite3rbu *pRbu = p->pRbu; int rc; if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){ assert( p->openFlags & SQLITE_OPEN_MAIN_DB ); rc = rbuCaptureDbWrite(p->pRbu, iOfst); }else{ - if( pRbu && pRbu->eStage==RBU_STAGE_OAL - && (p->openFlags & SQLITE_OPEN_WAL) - && iOfst>=pRbu->iOalSz - ){ - pRbu->iOalSz = iAmt + iOfst; + if( pRbu ){ + if( pRbu->eStage==RBU_STAGE_OAL + && (p->openFlags & SQLITE_OPEN_WAL) + && iOfst>=pRbu->iOalSz + ){ + pRbu->iOalSz = iAmt + iOfst; + }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){ + i64 szNew = iAmt+iOfst; + if( szNew>p->sz ){ + rc = rbuUpdateTempSize(p, szNew); + if( rc!=SQLITE_OK ) return rc; + } + } } rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst); if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){ @@ -173486,15 +202104,19 @@ static int rbuVfsWrite( /* ** Truncate an rbuVfs-file. */ -static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){ +static int rbuVfsTruncate(tdsqlite3_file *pFile, sqlite_int64 size){ rbu_file *p = (rbu_file*)pFile; + if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){ + int rc = rbuUpdateTempSize(p, size); + if( rc!=SQLITE_OK ) return rc; + } return p->pReal->pMethods->xTruncate(p->pReal, size); } /* ** Sync an rbuVfs-file. */ -static int rbuVfsSync(sqlite3_file *pFile, int flags){ +static int rbuVfsSync(tdsqlite3_file *pFile, int flags){ rbu_file *p = (rbu_file *)pFile; if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){ if( p->openFlags & SQLITE_OPEN_MAIN_DB ){ @@ -173508,7 +202130,7 @@ static int rbuVfsSync(sqlite3_file *pFile, int flags){ /* ** Return the current file-size of an rbuVfs-file. */ -static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ +static int rbuVfsFileSize(tdsqlite3_file *pFile, sqlite_int64 *pSize){ rbu_file *p = (rbu_file *)pFile; int rc; rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); @@ -173529,9 +202151,9 @@ static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ /* ** Lock an rbuVfs-file. */ -static int rbuVfsLock(sqlite3_file *pFile, int eLock){ +static int rbuVfsLock(tdsqlite3_file *pFile, int eLock){ rbu_file *p = (rbu_file*)pFile; - sqlite3rbu *pRbu = p->pRbu; + tdsqlite3rbu *pRbu = p->pRbu; int rc = SQLITE_OK; assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); @@ -173539,7 +202161,7 @@ static int rbuVfsLock(sqlite3_file *pFile, int eLock){ && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE)) ){ /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this - ** prevents it from checkpointing the database from sqlite3_close(). */ + ** prevents it from checkpointing the database from tdsqlite3_close(). */ rc = SQLITE_BUSY; }else{ rc = p->pReal->pMethods->xLock(p->pReal, eLock); @@ -173551,7 +202173,7 @@ static int rbuVfsLock(sqlite3_file *pFile, int eLock){ /* ** Unlock an rbuVfs-file. */ -static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){ +static int rbuVfsUnlock(tdsqlite3_file *pFile, int eLock){ rbu_file *p = (rbu_file *)pFile; return p->pReal->pMethods->xUnlock(p->pReal, eLock); } @@ -173559,7 +202181,7 @@ static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){ /* ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file. */ -static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){ +static int rbuVfsCheckReservedLock(tdsqlite3_file *pFile, int *pResOut){ rbu_file *p = (rbu_file *)pFile; return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); } @@ -173567,16 +202189,16 @@ static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){ /* ** File control method. For custom operations on an rbuVfs-file. */ -static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){ +static int rbuVfsFileControl(tdsqlite3_file *pFile, int op, void *pArg){ rbu_file *p = (rbu_file *)pFile; - int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl; + int (*xControl)(tdsqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl; int rc; assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL) ); if( op==SQLITE_FCNTL_RBU ){ - sqlite3rbu *pRbu = (sqlite3rbu*)pArg; + tdsqlite3rbu *pRbu = (tdsqlite3rbu*)pArg; /* First try to find another RBU vfs lower down in the vfs stack. If ** one is found, this vfs will operate in pass-through mode. The lower @@ -173590,10 +202212,11 @@ static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){ rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy); if( rc==SQLITE_OK ){ rc = SQLITE_ERROR; - pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error"); + pRbu->zErrmsg = tdsqlite3_mprintf("rbu/zipvfs setup error"); }else if( rc==SQLITE_NOTFOUND ){ pRbu->pTargetFd = p; p->pRbu = pRbu; + rbuMainlistAdd(p); if( p->pWalFd ) p->pWalFd->pRbu = pRbu; rc = SQLITE_OK; } @@ -173601,7 +202224,7 @@ static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){ return rc; } else if( op==SQLITE_FCNTL_RBUCNT ){ - sqlite3rbu *pRbu = (sqlite3rbu*)pArg; + tdsqlite3rbu *pRbu = (tdsqlite3rbu*)pArg; pRbu->nRbu++; pRbu->pRbuFd = p; p->bNolock = 1; @@ -173611,7 +202234,7 @@ static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){ if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){ rbu_vfs *pRbuVfs = p->pRbuVfs; char *zIn = *(char**)pArg; - char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn); + char *zOut = tdsqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn); *(char**)pArg = zOut; if( zOut==0 ) rc = SQLITE_NOMEM; } @@ -173622,7 +202245,7 @@ static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){ /* ** Return the sector-size in bytes for an rbuVfs-file. */ -static int rbuVfsSectorSize(sqlite3_file *pFile){ +static int rbuVfsSectorSize(tdsqlite3_file *pFile){ rbu_file *p = (rbu_file *)pFile; return p->pReal->pMethods->xSectorSize(p->pReal); } @@ -173630,7 +202253,7 @@ static int rbuVfsSectorSize(sqlite3_file *pFile){ /* ** Return the device characteristic flags supported by an rbuVfs-file. */ -static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){ +static int rbuVfsDeviceCharacteristics(tdsqlite3_file *pFile){ rbu_file *p = (rbu_file *)pFile; return p->pReal->pMethods->xDeviceCharacteristics(p->pReal); } @@ -173638,9 +202261,9 @@ static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){ /* ** Take or release a shared-memory lock. */ -static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ +static int rbuVfsShmLock(tdsqlite3_file *pFile, int ofst, int n, int flags){ rbu_file *p = (rbu_file*)pFile; - sqlite3rbu *pRbu = p->pRbu; + tdsqlite3rbu *pRbu = p->pRbu; int rc = SQLITE_OK; #ifdef SQLITE_AMALGAMATION @@ -173656,10 +202279,7 @@ static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY; }else{ int bCapture = 0; - if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE) - && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE - && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0) - ){ + if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){ bCapture = 1; } @@ -173678,7 +202298,7 @@ static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file. */ static int rbuVfsShmMap( - sqlite3_file *pFile, + tdsqlite3_file *pFile, int iRegion, int szRegion, int isWrite, @@ -173692,21 +202312,25 @@ static int rbuVfsShmMap( ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space ** instead of a file on disk. */ assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) ); - if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){ - if( iRegion<=p->nShm ){ - int nByte = (iRegion+1) * sizeof(char*); - char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte); - if( apNew==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm)); - p->apShm = apNew; - p->nShm = iRegion+1; - } + if( eStage==RBU_STAGE_OAL ){ + tdsqlite3_int64 nByte = (iRegion+1) * sizeof(char*); + char **apNew = (char**)tdsqlite3_realloc64(p->apShm, nByte); + + /* This is an RBU connection that uses its own heap memory for the + ** pages of the *-shm file. Since no other process can have run + ** recovery, the connection must request *-shm pages in order + ** from start to finish. */ + assert( iRegion==p->nShm ); + if( apNew==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm)); + p->apShm = apNew; + p->nShm = iRegion+1; } - if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){ - char *pNew = (char*)sqlite3_malloc64(szRegion); + if( rc==SQLITE_OK ){ + char *pNew = (char*)tdsqlite3_malloc64(szRegion); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ @@ -173731,7 +202355,7 @@ static int rbuVfsShmMap( /* ** Memory barrier. */ -static void rbuVfsShmBarrier(sqlite3_file *pFile){ +static void rbuVfsShmBarrier(tdsqlite3_file *pFile){ rbu_file *p = (rbu_file *)pFile; p->pReal->pMethods->xShmBarrier(p->pReal); } @@ -173739,7 +202363,7 @@ static void rbuVfsShmBarrier(sqlite3_file *pFile){ /* ** The xShmUnmap method. */ -static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){ +static int rbuVfsShmUnmap(tdsqlite3_file *pFile, int delFlag){ rbu_file *p = (rbu_file*)pFile; int rc = SQLITE_OK; int eStage = (p->pRbu ? p->pRbu->eStage : 0); @@ -173756,57 +202380,16 @@ static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){ } /* -** Given that zWal points to a buffer containing a wal file name passed to -** either the xOpen() or xAccess() VFS method, return a pointer to the -** file-handle opened by the same database connection on the corresponding -** database file. -*/ -static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){ - rbu_file *pDb; - sqlite3_mutex_enter(pRbuVfs->mutex); - for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){} - sqlite3_mutex_leave(pRbuVfs->mutex); - return pDb; -} - -/* -** A main database named zName has just been opened. The following -** function returns a pointer to a buffer owned by SQLite that contains -** the name of the *-wal file this db connection will use. SQLite -** happens to pass a pointer to this buffer when using xAccess() -** or xOpen() to operate on the *-wal file. -*/ -static const char *rbuMainToWal(const char *zName, int flags){ - int n = (int)strlen(zName); - const char *z = &zName[n]; - if( flags & SQLITE_OPEN_URI ){ - int odd = 0; - while( 1 ){ - if( z[0]==0 ){ - odd = 1 - odd; - if( odd && z[1]==0 ) break; - } - z++; - } - z += 2; - }else{ - while( *z==0 ) z++; - } - z += (n + 8 + 1); - return z; -} - -/* ** Open an rbu file handle. */ static int rbuVfsOpen( - sqlite3_vfs *pVfs, + tdsqlite3_vfs *pVfs, const char *zName, - sqlite3_file *pFile, + tdsqlite3_file *pFile, int flags, int *pOutFlags ){ - static sqlite3_io_methods rbuvfs_io_methods = { + static tdsqlite3_io_methods rbuvfs_io_methods = { 2, /* iVersion */ rbuVfsClose, /* xClose */ rbuVfsRead, /* xRead */ @@ -173827,14 +202410,14 @@ static int rbuVfsOpen( 0, 0 /* xFetch, xUnfetch */ }; rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs; - sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs; + tdsqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs; rbu_file *pFd = (rbu_file *)pFile; int rc = SQLITE_OK; const char *zOpen = zName; int oflags = flags; memset(pFd, 0, sizeof(rbu_file)); - pFd->pReal = (sqlite3_file*)&pFd[1]; + pFd->pReal = (tdsqlite3_file*)&pFd[1]; pFd->pRbuVfs = pRbuVfs; pFd->openFlags = flags; if( zName ){ @@ -173844,10 +202427,10 @@ static int rbuVfsOpen( ** the name of the *-wal file this db connection will use. SQLite ** happens to pass a pointer to this buffer when using xAccess() ** or xOpen() to operate on the *-wal file. */ - pFd->zWal = rbuMainToWal(zName, flags); + pFd->zWal = tdsqlite3_filename_wal(zName); } else if( flags & SQLITE_OPEN_WAL ){ - rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName); + rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0); if( pDb ){ if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){ /* This call is to open a *-wal file. Intead, open the *-oal. This @@ -173858,11 +202441,11 @@ static int rbuVfsOpen( size_t nCopy; char *zCopy; if( rbuIsVacuum(pDb->pRbu) ){ - zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main"); - zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI); + zBase = tdsqlite3_db_filename(pDb->pRbu->dbRbu, "main"); + zBase = tdsqlite3_filename_wal(zBase); } nCopy = strlen(zBase); - zCopy = sqlite3_malloc64(nCopy+2); + zCopy = tdsqlite3_malloc64(nCopy+2); if( zCopy ){ memcpy(zCopy, zBase, nCopy); zCopy[nCopy-3] = 'o'; @@ -173877,10 +202460,12 @@ static int rbuVfsOpen( pDb->pWalFd = pFd; } } + }else{ + pFd->pRbu = pRbuVfs->pRbu; } if( oflags & SQLITE_OPEN_MAIN_DB - && sqlite3_uri_boolean(zName, "rbu_memory", 0) + && tdsqlite3_uri_boolean(zName, "rbu_memory", 0) ){ assert( oflags & SQLITE_OPEN_MAIN_DB ); oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | @@ -173892,18 +202477,15 @@ static int rbuVfsOpen( rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags); } if( pFd->pReal->pMethods ){ - /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods + /* The xOpen() operation has succeeded. Set the tdsqlite3_file.pMethods ** pointer and, if the file is a main database file, link it into the ** mutex protected linked list of all such files. */ pFile->pMethods = &rbuvfs_io_methods; if( flags & SQLITE_OPEN_MAIN_DB ){ - sqlite3_mutex_enter(pRbuVfs->mutex); - pFd->pMainNext = pRbuVfs->pMain; - pRbuVfs->pMain = pFd; - sqlite3_mutex_leave(pRbuVfs->mutex); + rbuMainlistAdd(pFd); } }else{ - sqlite3_free(pFd->zDel); + tdsqlite3_free(pFd->zDel); } return rc; @@ -173912,8 +202494,8 @@ static int rbuVfsOpen( /* ** Delete the file located at zPath. */ -static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ - sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; +static int rbuVfsDelete(tdsqlite3_vfs *pVfs, const char *zPath, int dirSync){ + tdsqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xDelete(pRealVfs, zPath, dirSync); } @@ -173922,13 +202504,13 @@ static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ ** is available, or false otherwise. */ static int rbuVfsAccess( - sqlite3_vfs *pVfs, + tdsqlite3_vfs *pVfs, const char *zPath, int flags, int *pResOut ){ rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs; - sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs; + tdsqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs; int rc; rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut); @@ -173948,12 +202530,15 @@ static int rbuVfsAccess( ** file opened instead. */ if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){ - rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath); - if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){ + rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1); + if( pDb && pDb->pRbu->eStage==RBU_STAGE_OAL ){ + assert( pDb->pRbu ); if( *pResOut ){ rc = SQLITE_CANTOPEN; }else{ - *pResOut = 1; + tdsqlite3_int64 sz = 0; + rc = rbuVfsFileSize(&pDb->base, &sz); + *pResOut = (sz>0); } } } @@ -173967,12 +202552,12 @@ static int rbuVfsAccess( ** of at least (DEVSYM_MAX_PATHNAME+1) bytes. */ static int rbuVfsFullPathname( - sqlite3_vfs *pVfs, + tdsqlite3_vfs *pVfs, const char *zPath, int nOut, char *zOut ){ - sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; + tdsqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut); } @@ -173980,8 +202565,8 @@ static int rbuVfsFullPathname( /* ** Open the dynamic library located at zPath and return a handle. */ -static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ - sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; +static void *rbuVfsDlOpen(tdsqlite3_vfs *pVfs, const char *zPath){ + tdsqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xDlOpen(pRealVfs, zPath); } @@ -173990,8 +202575,8 @@ static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ ** utf-8 string describing the most recent error encountered associated ** with dynamic libraries. */ -static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ - sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; +static void rbuVfsDlError(tdsqlite3_vfs *pVfs, int nByte, char *zErrMsg){ + tdsqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; pRealVfs->xDlError(pRealVfs, nByte, zErrMsg); } @@ -173999,19 +202584,19 @@ static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ ** Return a pointer to the symbol zSymbol in the dynamic library pHandle. */ static void (*rbuVfsDlSym( - sqlite3_vfs *pVfs, + tdsqlite3_vfs *pVfs, void *pArg, const char *zSym ))(void){ - sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; + tdsqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xDlSym(pRealVfs, pArg, zSym); } /* ** Close the dynamic library handle pHandle. */ -static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){ - sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; +static void rbuVfsDlClose(tdsqlite3_vfs *pVfs, void *pHandle){ + tdsqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; pRealVfs->xDlClose(pRealVfs, pHandle); } #endif /* SQLITE_OMIT_LOAD_EXTENSION */ @@ -174020,8 +202605,8 @@ static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){ ** Populate the buffer pointed to by zBufOut with nByte bytes of ** random data. */ -static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ - sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; +static int rbuVfsRandomness(tdsqlite3_vfs *pVfs, int nByte, char *zBufOut){ + tdsqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut); } @@ -174029,36 +202614,36 @@ static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ ** Sleep for nMicro microseconds. Return the number of microseconds ** actually slept. */ -static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){ - sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; +static int rbuVfsSleep(tdsqlite3_vfs *pVfs, int nMicro){ + tdsqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xSleep(pRealVfs, nMicro); } /* ** Return the current time as a Julian Day number in *pTimeOut. */ -static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ - sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; +static int rbuVfsCurrentTime(tdsqlite3_vfs *pVfs, double *pTimeOut){ + tdsqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs; return pRealVfs->xCurrentTime(pRealVfs, pTimeOut); } /* ** No-op. */ -static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){ +static int rbuVfsGetLastError(tdsqlite3_vfs *pVfs, int a, char *b){ return 0; } /* ** Deregister and destroy an RBU vfs created by an earlier call to -** sqlite3rbu_create_vfs(). +** tdsqlite3rbu_create_vfs(). */ -SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){ - sqlite3_vfs *pVfs = sqlite3_vfs_find(zName); +SQLITE_API void tdsqlite3rbu_destroy_vfs(const char *zName){ + tdsqlite3_vfs *pVfs = tdsqlite3_vfs_find(zName); if( pVfs && pVfs->xOpen==rbuVfsOpen ){ - sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex); - sqlite3_vfs_unregister(pVfs); - sqlite3_free(pVfs); + tdsqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex); + tdsqlite3_vfs_unregister(pVfs); + tdsqlite3_free(pVfs); } } @@ -174067,10 +202652,10 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){ ** via existing VFS zParent. The new object is registered as a non-default ** VFS with SQLite before returning. */ -SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){ +SQLITE_API int tdsqlite3rbu_create_vfs(const char *zName, const char *zParent){ /* Template for VFS */ - static sqlite3_vfs vfs_template = { + static tdsqlite3_vfs vfs_template = { 1, /* iVersion */ 0, /* szOsFile */ 0, /* mxPathname */ @@ -174106,18 +202691,18 @@ SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){ nName = strlen(zName); nByte = sizeof(rbu_vfs) + nName + 1; - pNew = (rbu_vfs*)sqlite3_malloc64(nByte); + pNew = (rbu_vfs*)tdsqlite3_malloc64(nByte); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ - sqlite3_vfs *pParent; /* Parent VFS */ + tdsqlite3_vfs *pParent; /* Parent VFS */ memset(pNew, 0, nByte); - pParent = sqlite3_vfs_find(zParent); + pParent = tdsqlite3_vfs_find(zParent); if( pParent==0 ){ rc = SQLITE_NOTFOUND; }else{ char *zSpace; - memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs)); + memcpy(&pNew->base, &vfs_template, sizeof(tdsqlite3_vfs)); pNew->base.mxPathname = pParent->mxPathname; pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile; pNew->pRealVfs = pParent; @@ -174125,29 +202710,43 @@ SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){ memcpy(zSpace, zName, nName); /* Allocate the mutex and register the new VFS (not as the default) */ - pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE); + pNew->mutex = tdsqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE); if( pNew->mutex==0 ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_vfs_register(&pNew->base, 0); + rc = tdsqlite3_vfs_register(&pNew->base, 0); } } if( rc!=SQLITE_OK ){ - sqlite3_mutex_free(pNew->mutex); - sqlite3_free(pNew); + tdsqlite3_mutex_free(pNew->mutex); + tdsqlite3_free(pNew); } } return rc; } +/* +** Configure the aggregate temp file size limit for this RBU handle. +*/ +SQLITE_API tdsqlite3_int64 tdsqlite3rbu_temp_size_limit(tdsqlite3rbu *pRbu, tdsqlite3_int64 n){ + if( n>=0 ){ + pRbu->szTempLimit = n; + } + return pRbu->szTempLimit; +} + +SQLITE_API tdsqlite3_int64 tdsqlite3rbu_temp_size(tdsqlite3rbu *pRbu){ + return pRbu->szTemp; +} + /**************************************************************************/ #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */ -/************** End of sqlite3rbu.c ******************************************/ +/************** End of tdsqlite3rbu.c ******************************************/ /************** Begin file dbstat.c ******************************************/ /* ** 2010 July 12 @@ -174163,9 +202762,9 @@ SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){ ** ** This file contains an implementation of the "dbstat" virtual table. ** -** The dbstat virtual table is used to extract low-level formatting +** The dbstat virtual table is used to extract low-level storage ** information from an SQLite database in order to implement the -** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script +** "tdsqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script ** for an example implementation. ** ** Additional information is available on the "dbstat.html" page of the @@ -174207,27 +202806,30 @@ SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){ ** ** '/1c2/000/' // Left-most child of 451st child of root */ -#define VTAB_SCHEMA \ - "CREATE TABLE xx( " \ - " name TEXT, /* Name of table or index */" \ - " path TEXT, /* Path to page from root */" \ - " pageno INTEGER, /* Page number */" \ - " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \ - " ncell INTEGER, /* Cells on page (0 for overflow) */" \ - " payload INTEGER, /* Bytes of payload on this page */" \ - " unused INTEGER, /* Bytes of unused space on this page */" \ - " mx_payload INTEGER, /* Largest payload size of all cells */" \ - " pgoffset INTEGER, /* Offset of page in file */" \ - " pgsize INTEGER, /* Size of the page */" \ - " schema TEXT HIDDEN /* Database schema being analyzed */" \ - ");" - - +static const char zDbstatSchema[] = + "CREATE TABLE x(" + " name TEXT," /* 0 Name of table or index */ + " path TEXT," /* 1 Path to page from root (NULL for agg) */ + " pageno INTEGER," /* 2 Page number (page count for aggregates) */ + " pagetype TEXT," /* 3 'internal', 'leaf', 'overflow', or NULL */ + " ncell INTEGER," /* 4 Cells on page (0 for overflow) */ + " payload INTEGER," /* 5 Bytes of payload on this page */ + " unused INTEGER," /* 6 Bytes of unused space on this page */ + " mx_payload INTEGER," /* 7 Largest payload size of all cells */ + " pgoffset INTEGER," /* 8 Offset of page in file (NULL for agg) */ + " pgsize INTEGER," /* 9 Size of the page (sum for aggregate) */ + " schema TEXT HIDDEN," /* 10 Database schema being analyzed */ + " aggregate BOOLEAN HIDDEN" /* 11 aggregate info for each table */ + ")" +; + +/* Forward reference to data structured used in this module */ typedef struct StatTable StatTable; typedef struct StatCursor StatCursor; typedef struct StatPage StatPage; typedef struct StatCell StatCell; +/* Size information for a single cell within a btree page */ struct StatCell { int nLocal; /* Bytes of local payload */ u32 iChildPg; /* Child node (or 0 if this is a leaf) */ @@ -174237,10 +202839,11 @@ struct StatCell { int iOvfl; /* Iterates through aOvfl[] */ }; +/* Size information for a single btree page */ struct StatPage { - u32 iPgno; - DbPage *pPg; - int iCell; + u32 iPgno; /* Page number */ + DbPage *pPg; /* Page content */ + int iCell; /* Current cell */ char *zPath; /* Path to this page */ @@ -174250,34 +202853,38 @@ struct StatPage { int nUnused; /* Number of unused bytes on page */ StatCell *aCell; /* Array of parsed cells */ u32 iRightChildPg; /* Right-child page number (or 0) */ - int nMxPayload; /* Largest payload of any cell on this page */ + int nMxPayload; /* Largest payload of any cell on the page */ }; +/* The cursor for scanning the dbstat virtual table */ struct StatCursor { - sqlite3_vtab_cursor base; - sqlite3_stmt *pStmt; /* Iterates through set of root pages */ - int isEof; /* After pStmt has returned SQLITE_DONE */ + tdsqlite3_vtab_cursor base; /* base class. MUST BE FIRST! */ + tdsqlite3_stmt *pStmt; /* Iterates through set of root pages */ + u8 isEof; /* After pStmt has returned SQLITE_DONE */ + u8 isAgg; /* Aggregate results for each table */ int iDb; /* Schema used for this query */ - StatPage aPage[32]; + StatPage aPage[32]; /* Pages in path to current page */ int iPage; /* Current entry in aPage[] */ /* Values to return. */ + u32 iPageno; /* Value of 'pageno' column */ char *zName; /* Value of 'name' column */ char *zPath; /* Value of 'path' column */ - u32 iPageno; /* Value of 'pageno' column */ char *zPagetype; /* Value of 'pagetype' column */ + int nPage; /* Number of pages in current btree */ int nCell; /* Value of 'ncell' column */ - int nPayload; /* Value of 'payload' column */ - int nUnused; /* Value of 'unused' column */ int nMxPayload; /* Value of 'mx_payload' column */ + i64 nUnused; /* Value of 'unused' column */ + i64 nPayload; /* Value of 'payload' column */ i64 iOffset; /* Value of 'pgOffset' column */ - int szPage; /* Value of 'pgSize' column */ + i64 szPage; /* Value of 'pgSize' column */ }; +/* An instance of the DBSTAT virtual table */ struct StatTable { - sqlite3_vtab base; - sqlite3 *db; + tdsqlite3_vtab base; /* base class. MUST BE FIRST! */ + tdsqlite3 *db; /* Database connection that owns this vtab */ int iDb; /* Index of database to analyze */ }; @@ -174286,13 +202893,13 @@ struct StatTable { #endif /* -** Connect to or create a statvfs virtual table. +** Connect to or create a new DBSTAT virtual table. */ static int statConnect( - sqlite3 *db, + tdsqlite3 *db, void *pAux, int argc, const char *const*argv, - sqlite3_vtab **ppVtab, + tdsqlite3_vtab **ppVtab, char **pzErr ){ StatTable *pTab = 0; @@ -174301,18 +202908,19 @@ static int statConnect( if( argc>=4 ){ Token nm; - sqlite3TokenInit(&nm, (char*)argv[3]); - iDb = sqlite3FindDb(db, &nm); + tdsqlite3TokenInit(&nm, (char*)argv[3]); + iDb = tdsqlite3FindDb(db, &nm); if( iDb<0 ){ - *pzErr = sqlite3_mprintf("no such database: %s", argv[3]); + *pzErr = tdsqlite3_mprintf("no such database: %s", argv[3]); return SQLITE_ERROR; } }else{ iDb = 0; } - rc = sqlite3_declare_vtab(db, VTAB_SCHEMA); + tdsqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY); + rc = tdsqlite3_declare_vtab(db, zDbstatSchema); if( rc==SQLITE_OK ){ - pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable)); + pTab = (StatTable *)tdsqlite3_malloc64(sizeof(StatTable)); if( pTab==0 ) rc = SQLITE_NOMEM_BKPT; } @@ -174323,29 +202931,33 @@ static int statConnect( pTab->iDb = iDb; } - *ppVtab = (sqlite3_vtab*)pTab; + *ppVtab = (tdsqlite3_vtab*)pTab; return rc; } /* -** Disconnect from or destroy a statvfs virtual table. +** Disconnect from or destroy the DBSTAT virtual table. */ -static int statDisconnect(sqlite3_vtab *pVtab){ - sqlite3_free(pVtab); +static int statDisconnect(tdsqlite3_vtab *pVtab){ + tdsqlite3_free(pVtab); return SQLITE_OK; } /* -** There is no "best-index". This virtual table always does a linear -** scan. However, a schema=? constraint should cause this table to -** operate on a different database schema, so check for it. +** Compute the best query strategy and return the result in idxNum. ** -** idxNum is normally 0, but will be 1 if a schema=? constraint exists. +** idxNum-Bit Meaning +** ---------- ---------------------------------------------- +** 0x01 There is a schema=? term in the WHERE clause +** 0x02 There is a name=? term in the WHERE clause +** 0x04 There is an aggregate=? term in the WHERE clause +** 0x08 Output should be ordered by name and path */ -static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ +static int statBestIndex(tdsqlite3_vtab *tab, tdsqlite3_index_info *pIdxInfo){ int i; - - pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */ + int iSchema = -1; + int iName = -1; + int iAgg = -1; /* Look for a valid schema=? constraint. If found, change the idxNum to ** 1 and request the value of that constraint be sent to xFilter. And @@ -174353,16 +202965,40 @@ static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ ** used. */ for(i=0; i<pIdxInfo->nConstraint; i++){ - if( pIdxInfo->aConstraint[i].usable==0 ) continue; if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; - if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue; - pIdxInfo->idxNum = 1; - pIdxInfo->estimatedCost = 1.0; - pIdxInfo->aConstraintUsage[i].argvIndex = 1; - pIdxInfo->aConstraintUsage[i].omit = 1; - break; + if( pIdxInfo->aConstraint[i].usable==0 ){ + /* Force DBSTAT table should always be the right-most table in a join */ + return SQLITE_CONSTRAINT; + } + switch( pIdxInfo->aConstraint[i].iColumn ){ + case 0: { /* name */ + iName = i; + break; + } + case 10: { /* schema */ + iSchema = i; + break; + } + case 11: { /* aggregate */ + iAgg = i; + break; + } + } } - + i = 0; + if( iSchema>=0 ){ + pIdxInfo->aConstraintUsage[iSchema].argvIndex = ++i; + pIdxInfo->idxNum |= 0x01; + } + if( iName>=0 ){ + pIdxInfo->aConstraintUsage[iName].argvIndex = ++i; + pIdxInfo->idxNum |= 0x02; + } + if( iAgg>=0 ){ + pIdxInfo->aConstraintUsage[iAgg].argvIndex = ++i; + pIdxInfo->idxNum |= 0x04; + } + pIdxInfo->estimatedCost = 1.0; /* Records are always returned in ascending order of (name, path). ** If this will satisfy the client, set the orderByConsumed flag so that @@ -174380,19 +203016,20 @@ static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ ) ){ pIdxInfo->orderByConsumed = 1; + pIdxInfo->idxNum |= 0x08; } return SQLITE_OK; } /* -** Open a new statvfs cursor. +** Open a new DBSTAT cursor. */ -static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ +static int statOpen(tdsqlite3_vtab *pVTab, tdsqlite3_vtab_cursor **ppCursor){ StatTable *pTab = (StatTable *)pVTab; StatCursor *pCsr; - pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor)); + pCsr = (StatCursor *)tdsqlite3_malloc64(sizeof(StatCursor)); if( pCsr==0 ){ return SQLITE_NOMEM_BKPT; }else{ @@ -174401,51 +203038,71 @@ static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ pCsr->iDb = pTab->iDb; } - *ppCursor = (sqlite3_vtab_cursor *)pCsr; + *ppCursor = (tdsqlite3_vtab_cursor *)pCsr; return SQLITE_OK; } -static void statClearPage(StatPage *p){ +static void statClearCells(StatPage *p){ int i; if( p->aCell ){ for(i=0; i<p->nCell; i++){ - sqlite3_free(p->aCell[i].aOvfl); + tdsqlite3_free(p->aCell[i].aOvfl); } - sqlite3_free(p->aCell); + tdsqlite3_free(p->aCell); } - sqlite3PagerUnref(p->pPg); - sqlite3_free(p->zPath); + p->nCell = 0; + p->aCell = 0; +} + +static void statClearPage(StatPage *p){ + statClearCells(p); + tdsqlite3PagerUnref(p->pPg); + tdsqlite3_free(p->zPath); memset(p, 0, sizeof(StatPage)); } static void statResetCsr(StatCursor *pCsr){ int i; - sqlite3_reset(pCsr->pStmt); + tdsqlite3_reset(pCsr->pStmt); for(i=0; i<ArraySize(pCsr->aPage); i++){ statClearPage(&pCsr->aPage[i]); } pCsr->iPage = 0; - sqlite3_free(pCsr->zPath); + tdsqlite3_free(pCsr->zPath); pCsr->zPath = 0; pCsr->isEof = 0; } +/* Resize the space-used counters inside of the cursor */ +static void statResetCounts(StatCursor *pCsr){ + pCsr->nCell = 0; + pCsr->nMxPayload = 0; + pCsr->nUnused = 0; + pCsr->nPayload = 0; + pCsr->szPage = 0; + pCsr->nPage = 0; +} + /* -** Close a statvfs cursor. +** Close a DBSTAT cursor. */ -static int statClose(sqlite3_vtab_cursor *pCursor){ +static int statClose(tdsqlite3_vtab_cursor *pCursor){ StatCursor *pCsr = (StatCursor *)pCursor; statResetCsr(pCsr); - sqlite3_finalize(pCsr->pStmt); - sqlite3_free(pCsr); + tdsqlite3_finalize(pCsr->pStmt); + tdsqlite3_free(pCsr); return SQLITE_OK; } -static void getLocalPayload( +/* +** For a single cell on a btree page, compute the number of bytes of +** content (payload) stored on that page. That is to say, compute the +** number of bytes of content not found on overflow pages. +*/ +static int getLocalPayload( int nUsable, /* Usable bytes per page */ u8 flags, /* Page flags */ - int nTotal, /* Total record (payload) size */ - int *pnLocal /* OUT: Bytes stored locally */ + int nTotal /* Total record (payload) size */ ){ int nLocal; int nMinLocal; @@ -174461,9 +203118,12 @@ static void getLocalPayload( nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4); if( nLocal>nMaxLocal ) nLocal = nMinLocal; - *pnLocal = nLocal; + return nLocal; } +/* Populate the StatPage object with information about the all +** cells found on the page currently under analysis. +*/ static int statDecodePage(Btree *pBt, StatPage *p){ int nUnused; int iOff; @@ -174471,35 +203131,46 @@ static int statDecodePage(Btree *pBt, StatPage *p){ int isLeaf; int szPage; - u8 *aData = sqlite3PagerGetData(p->pPg); + u8 *aData = tdsqlite3PagerGetData(p->pPg); u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0]; p->flags = aHdr[0]; + if( p->flags==0x0A || p->flags==0x0D ){ + isLeaf = 1; + nHdr = 8; + }else if( p->flags==0x05 || p->flags==0x02 ){ + isLeaf = 0; + nHdr = 12; + }else{ + goto statPageIsCorrupt; + } + if( p->iPgno==1 ) nHdr += 100; p->nCell = get2byte(&aHdr[3]); p->nMxPayload = 0; - - isLeaf = (p->flags==0x0A || p->flags==0x0D); - nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100; + szPage = tdsqlite3BtreeGetPageSize(pBt); nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell; nUnused += (int)aHdr[7]; iOff = get2byte(&aHdr[1]); while( iOff ){ + int iNext; + if( iOff>=szPage ) goto statPageIsCorrupt; nUnused += get2byte(&aData[iOff+2]); - iOff = get2byte(&aData[iOff]); + iNext = get2byte(&aData[iOff]); + if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt; + iOff = iNext; } p->nUnused = nUnused; - p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]); - szPage = sqlite3BtreeGetPageSize(pBt); + p->iRightChildPg = isLeaf ? 0 : tdsqlite3Get4byte(&aHdr[8]); if( p->nCell ){ int i; /* Used to iterate through cells */ int nUsable; /* Usable bytes per page */ - sqlite3BtreeEnter(pBt); - nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt); - sqlite3BtreeLeave(pBt); - p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell)); + tdsqlite3BtreeEnter(pBt); + nUsable = szPage - tdsqlite3BtreeGetReserveNoMutex(pBt); + tdsqlite3BtreeLeave(pBt); + p->aCell = tdsqlite3_malloc64((p->nCell+1) * sizeof(StatCell)); if( p->aCell==0 ) return SQLITE_NOMEM_BKPT; memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell)); @@ -174507,8 +203178,9 @@ static int statDecodePage(Btree *pBt, StatPage *p){ StatCell *pCell = &p->aCell[i]; iOff = get2byte(&aData[nHdr+i*2]); + if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt; if( !isLeaf ){ - pCell->iChildPg = sqlite3Get4byte(&aData[iOff]); + pCell->iChildPg = tdsqlite3Get4byte(&aData[iOff]); iOff += 4; } if( p->flags==0x05 ){ @@ -174519,33 +203191,34 @@ static int statDecodePage(Btree *pBt, StatPage *p){ iOff += getVarint32(&aData[iOff], nPayload); if( p->flags==0x0D ){ u64 dummy; - iOff += sqlite3GetVarint(&aData[iOff], &dummy); + iOff += tdsqlite3GetVarint(&aData[iOff], &dummy); } if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload; - getLocalPayload(nUsable, p->flags, nPayload, &nLocal); + nLocal = getLocalPayload(nUsable, p->flags, nPayload); + if( nLocal<0 ) goto statPageIsCorrupt; pCell->nLocal = nLocal; - assert( nLocal>=0 ); assert( nPayload>=(u32)nLocal ); assert( nLocal<=(nUsable-35) ); if( nPayload>(u32)nLocal ){ int j; int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4); + if( iOff+nLocal>nUsable ) goto statPageIsCorrupt; pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4); pCell->nOvfl = nOvfl; - pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl); + pCell->aOvfl = tdsqlite3_malloc64(sizeof(u32)*nOvfl); if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT; - pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]); + pCell->aOvfl[0] = tdsqlite3Get4byte(&aData[iOff+nLocal]); for(j=1; j<nOvfl; j++){ int rc; u32 iPrev = pCell->aOvfl[j-1]; DbPage *pPg = 0; - rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0); + rc = tdsqlite3PagerGet(tdsqlite3BtreePager(pBt), iPrev, &pPg, 0); if( rc!=SQLITE_OK ){ assert( pPg==0 ); return rc; } - pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg)); - sqlite3PagerUnref(pPg); + pCell->aOvfl[j] = tdsqlite3Get4byte(tdsqlite3PagerGetData(pPg)); + tdsqlite3PagerUnref(pPg); } } } @@ -174553,6 +203226,11 @@ static int statDecodePage(Btree *pBt, StatPage *p){ } return SQLITE_OK; + +statPageIsCorrupt: + p->flags = 0; + statClearCells(p); + return SQLITE_OK; } /* @@ -174560,94 +203238,101 @@ static int statDecodePage(Btree *pBt, StatPage *p){ ** the current value of pCsr->iPageno. */ static void statSizeAndOffset(StatCursor *pCsr){ - StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab; + StatTable *pTab = (StatTable *)((tdsqlite3_vtab_cursor *)pCsr)->pVtab; Btree *pBt = pTab->db->aDb[pTab->iDb].pBt; - Pager *pPager = sqlite3BtreePager(pBt); - sqlite3_file *fd; - sqlite3_int64 x[2]; + Pager *pPager = tdsqlite3BtreePager(pBt); + tdsqlite3_file *fd; + tdsqlite3_int64 x[2]; - /* The default page size and offset */ - pCsr->szPage = sqlite3BtreeGetPageSize(pBt); - pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1); - - /* If connected to a ZIPVFS backend, override the page size and - ** offset with actual values obtained from ZIPVFS. + /* If connected to a ZIPVFS backend, find the page size and + ** offset from ZIPVFS. */ - fd = sqlite3PagerFile(pPager); + fd = tdsqlite3PagerFile(pPager); x[0] = pCsr->iPageno; - if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){ + if( tdsqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){ pCsr->iOffset = x[0]; - pCsr->szPage = (int)x[1]; + pCsr->szPage += x[1]; + }else{ + /* Not ZIPVFS: The default page size and offset */ + pCsr->szPage += tdsqlite3BtreeGetPageSize(pBt); + pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1); } } /* -** Move a statvfs cursor to the next entry in the file. +** Move a DBSTAT cursor to the next entry. Normally, the next +** entry will be the next page, but in aggregated mode (pCsr->isAgg!=0), +** the next entry is the next btree. */ -static int statNext(sqlite3_vtab_cursor *pCursor){ +static int statNext(tdsqlite3_vtab_cursor *pCursor){ int rc; int nPayload; char *z; StatCursor *pCsr = (StatCursor *)pCursor; StatTable *pTab = (StatTable *)pCursor->pVtab; Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt; - Pager *pPager = sqlite3BtreePager(pBt); + Pager *pPager = tdsqlite3BtreePager(pBt); - sqlite3_free(pCsr->zPath); + tdsqlite3_free(pCsr->zPath); pCsr->zPath = 0; statNextRestart: if( pCsr->aPage[0].pPg==0 ){ - rc = sqlite3_step(pCsr->pStmt); + /* Start measuring space on the next btree */ + statResetCounts(pCsr); + rc = tdsqlite3_step(pCsr->pStmt); if( rc==SQLITE_ROW ){ int nPage; - u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1); - sqlite3PagerPagecount(pPager, &nPage); + u32 iRoot = (u32)tdsqlite3_column_int64(pCsr->pStmt, 1); + tdsqlite3PagerPagecount(pPager, &nPage); if( nPage==0 ){ pCsr->isEof = 1; - return sqlite3_reset(pCsr->pStmt); + return tdsqlite3_reset(pCsr->pStmt); } - rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0); + rc = tdsqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0); pCsr->aPage[0].iPgno = iRoot; pCsr->aPage[0].iCell = 0; - pCsr->aPage[0].zPath = z = sqlite3_mprintf("/"); + if( !pCsr->isAgg ){ + pCsr->aPage[0].zPath = z = tdsqlite3_mprintf("/"); + if( z==0 ) rc = SQLITE_NOMEM_BKPT; + } pCsr->iPage = 0; - if( z==0 ) rc = SQLITE_NOMEM_BKPT; + pCsr->nPage = 1; }else{ pCsr->isEof = 1; - return sqlite3_reset(pCsr->pStmt); + return tdsqlite3_reset(pCsr->pStmt); } }else{ - - /* Page p itself has already been visited. */ + /* Continue analyzing the btree previously started */ StatPage *p = &pCsr->aPage[pCsr->iPage]; - + if( !pCsr->isAgg ) statResetCounts(pCsr); while( p->iCell<p->nCell ){ StatCell *pCell = &p->aCell[p->iCell]; - if( pCell->iOvfl<pCell->nOvfl ){ - int nUsable; - sqlite3BtreeEnter(pBt); - nUsable = sqlite3BtreeGetPageSize(pBt) - - sqlite3BtreeGetReserveNoMutex(pBt); - sqlite3BtreeLeave(pBt); - pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0); - pCsr->iPageno = pCell->aOvfl[pCell->iOvfl]; - pCsr->zPagetype = "overflow"; - pCsr->nCell = 0; - pCsr->nMxPayload = 0; - pCsr->zPath = z = sqlite3_mprintf( - "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl - ); + while( pCell->iOvfl<pCell->nOvfl ){ + int nUsable, iOvfl; + tdsqlite3BtreeEnter(pBt); + nUsable = tdsqlite3BtreeGetPageSize(pBt) - + tdsqlite3BtreeGetReserveNoMutex(pBt); + tdsqlite3BtreeLeave(pBt); + pCsr->nPage++; + statSizeAndOffset(pCsr); if( pCell->iOvfl<pCell->nOvfl-1 ){ - pCsr->nUnused = 0; - pCsr->nPayload = nUsable - 4; + pCsr->nPayload += nUsable - 4; }else{ - pCsr->nPayload = pCell->nLastOvfl; - pCsr->nUnused = nUsable - 4 - pCsr->nPayload; + pCsr->nPayload += pCell->nLastOvfl; + pCsr->nUnused += nUsable - 4 - pCell->nLastOvfl; } + iOvfl = pCell->iOvfl; pCell->iOvfl++; - statSizeAndOffset(pCsr); - return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK; + if( !pCsr->isAgg ){ + pCsr->zName = (char *)tdsqlite3_column_text(pCsr->pStmt, 0); + pCsr->iPageno = pCell->aOvfl[iOvfl]; + pCsr->zPagetype = "overflow"; + pCsr->zPath = z = tdsqlite3_mprintf( + "%s%.3x+%.6x", p->zPath, p->iCell, iOvfl + ); + return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK; + } } if( p->iRightChildPg ) break; p->iCell++; @@ -174655,11 +203340,20 @@ statNextRestart: if( !p->iRightChildPg || p->iCell>p->nCell ){ statClearPage(p); - if( pCsr->iPage==0 ) return statNext(pCursor); - pCsr->iPage--; + if( pCsr->iPage>0 ){ + pCsr->iPage--; + }else if( pCsr->isAgg ){ + /* label-statNext-done: When computing aggregate space usage over + ** an entire btree, this is the exit point from this function */ + return SQLITE_OK; + } goto statNextRestart; /* Tail recursion */ } pCsr->iPage++; + if( pCsr->iPage>=ArraySize(pCsr->aPage) ){ + statResetCsr(pCsr); + return SQLITE_CORRUPT_BKPT; + } assert( p==&pCsr->aPage[pCsr->iPage-1] ); if( p->iCell==p->nCell ){ @@ -174667,11 +203361,14 @@ statNextRestart: }else{ p[1].iPgno = p->aCell[p->iCell].iChildPg; } - rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0); + rc = tdsqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0); + pCsr->nPage++; p[1].iCell = 0; - p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell); + if( !pCsr->isAgg ){ + p[1].zPath = z = tdsqlite3_mprintf("%s%.3x/", p->zPath, p->iCell); + if( z==0 ) rc = SQLITE_NOMEM_BKPT; + } p->iCell++; - if( z==0 ) rc = SQLITE_NOMEM_BKPT; } @@ -174681,7 +203378,7 @@ statNextRestart: if( rc==SQLITE_OK ){ int i; StatPage *p = &pCsr->aPage[pCsr->iPage]; - pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0); + pCsr->zName = (char *)tdsqlite3_column_text(pCsr->pStmt, 0); pCsr->iPageno = p->iPgno; rc = statDecodePage(pBt, p); @@ -174701,64 +203398,96 @@ statNextRestart: pCsr->zPagetype = "corrupted"; break; } - pCsr->nCell = p->nCell; - pCsr->nUnused = p->nUnused; - pCsr->nMxPayload = p->nMxPayload; - pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath); - if( z==0 ) rc = SQLITE_NOMEM_BKPT; + pCsr->nCell += p->nCell; + pCsr->nUnused += p->nUnused; + if( p->nMxPayload>pCsr->nMxPayload ) pCsr->nMxPayload = p->nMxPayload; + if( !pCsr->isAgg ){ + pCsr->zPath = z = tdsqlite3_mprintf("%s", p->zPath); + if( z==0 ) rc = SQLITE_NOMEM_BKPT; + } nPayload = 0; for(i=0; i<p->nCell; i++){ nPayload += p->aCell[i].nLocal; } - pCsr->nPayload = nPayload; + pCsr->nPayload += nPayload; + + /* If computing aggregate space usage by btree, continue with the + ** next page. The loop will exit via the return at label-statNext-done + */ + if( pCsr->isAgg ) goto statNextRestart; } } return rc; } -static int statEof(sqlite3_vtab_cursor *pCursor){ +static int statEof(tdsqlite3_vtab_cursor *pCursor){ StatCursor *pCsr = (StatCursor *)pCursor; return pCsr->isEof; } +/* Initialize a cursor according to the query plan idxNum using the +** arguments in argv[0]. See statBestIndex() for a description of the +** meaning of the bits in idxNum. +*/ static int statFilter( - sqlite3_vtab_cursor *pCursor, + tdsqlite3_vtab_cursor *pCursor, int idxNum, const char *idxStr, - int argc, sqlite3_value **argv + int argc, tdsqlite3_value **argv ){ StatCursor *pCsr = (StatCursor *)pCursor; StatTable *pTab = (StatTable*)(pCursor->pVtab); - char *zSql; - int rc = SQLITE_OK; - char *zMaster; + tdsqlite3_str *pSql; /* Query of btrees to analyze */ + char *zSql; /* String value of pSql */ + int iArg = 0; /* Count of argv[] parameters used so far */ + int rc = SQLITE_OK; /* Result of this operation */ + const char *zName = 0; /* Only provide analysis of this table */ - if( idxNum==1 ){ - const char *zDbase = (const char*)sqlite3_value_text(argv[0]); - pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase); + statResetCsr(pCsr); + tdsqlite3_finalize(pCsr->pStmt); + pCsr->pStmt = 0; + if( idxNum & 0x01 ){ + /* schema=? constraint is present. Get its value */ + const char *zDbase = (const char*)tdsqlite3_value_text(argv[iArg++]); + pCsr->iDb = tdsqlite3FindDbName(pTab->db, zDbase); if( pCsr->iDb<0 ){ - sqlite3_free(pCursor->pVtab->zErrMsg); - pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase); - return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT; + pCsr->iDb = 0; + pCsr->isEof = 1; + return SQLITE_OK; } }else{ pCsr->iDb = pTab->iDb; } - statResetCsr(pCsr); - sqlite3_finalize(pCsr->pStmt); - pCsr->pStmt = 0; - zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master"; - zSql = sqlite3_mprintf( - "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type" - " UNION ALL " - "SELECT name, rootpage, type" - " FROM \"%w\".%s WHERE rootpage!=0" - " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster); + if( idxNum & 0x02 ){ + /* name=? constraint is present */ + zName = (const char*)tdsqlite3_value_text(argv[iArg++]); + } + if( idxNum & 0x04 ){ + /* aggregate=? constraint is present */ + pCsr->isAgg = tdsqlite3_value_double(argv[iArg++])!=0.0; + }else{ + pCsr->isAgg = 0; + } + pSql = tdsqlite3_str_new(pTab->db); + tdsqlite3_str_appendf(pSql, + "SELECT * FROM (" + "SELECT 'sqlite_master' AS name,1 AS rootpage,'table' AS type" + " UNION ALL " + "SELECT name,rootpage,type" + " FROM \"%w\".sqlite_master WHERE rootpage!=0)", + pTab->db->aDb[pCsr->iDb].zDbSName); + if( zName ){ + tdsqlite3_str_appendf(pSql, "WHERE name=%Q", zName); + } + if( idxNum & 0x08 ){ + tdsqlite3_str_appendf(pSql, " ORDER BY name"); + } + zSql = tdsqlite3_str_finish(pSql); if( zSql==0 ){ return SQLITE_NOMEM_BKPT; }else{ - rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0); - sqlite3_free(zSql); + rc = tdsqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0); + tdsqlite3_free(zSql); } if( rc==SQLITE_OK ){ @@ -174768,53 +203497,67 @@ static int statFilter( } static int statColumn( - sqlite3_vtab_cursor *pCursor, - sqlite3_context *ctx, + tdsqlite3_vtab_cursor *pCursor, + tdsqlite3_context *ctx, int i ){ StatCursor *pCsr = (StatCursor *)pCursor; switch( i ){ case 0: /* name */ - sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT); + tdsqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT); break; case 1: /* path */ - sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT); + if( !pCsr->isAgg ){ + tdsqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT); + } break; case 2: /* pageno */ - sqlite3_result_int64(ctx, pCsr->iPageno); + if( pCsr->isAgg ){ + tdsqlite3_result_int64(ctx, pCsr->nPage); + }else{ + tdsqlite3_result_int64(ctx, pCsr->iPageno); + } break; case 3: /* pagetype */ - sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC); + if( !pCsr->isAgg ){ + tdsqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC); + } break; case 4: /* ncell */ - sqlite3_result_int(ctx, pCsr->nCell); + tdsqlite3_result_int(ctx, pCsr->nCell); break; case 5: /* payload */ - sqlite3_result_int(ctx, pCsr->nPayload); + tdsqlite3_result_int(ctx, pCsr->nPayload); break; case 6: /* unused */ - sqlite3_result_int(ctx, pCsr->nUnused); + tdsqlite3_result_int(ctx, pCsr->nUnused); break; case 7: /* mx_payload */ - sqlite3_result_int(ctx, pCsr->nMxPayload); + tdsqlite3_result_int(ctx, pCsr->nMxPayload); break; case 8: /* pgoffset */ - sqlite3_result_int64(ctx, pCsr->iOffset); + if( !pCsr->isAgg ){ + tdsqlite3_result_int64(ctx, pCsr->iOffset); + } break; case 9: /* pgsize */ - sqlite3_result_int(ctx, pCsr->szPage); + tdsqlite3_result_int(ctx, pCsr->szPage); break; - default: { /* schema */ - sqlite3 *db = sqlite3_context_db_handle(ctx); + case 10: { /* schema */ + tdsqlite3 *db = tdsqlite3_context_db_handle(ctx); int iDb = pCsr->iDb; - sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC); + tdsqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC); + break; + } + default: { /* aggregate */ + tdsqlite3_result_int(ctx, pCsr->isAgg); break; } } return SQLITE_OK; } -static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ +static int statRowid(tdsqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ StatCursor *pCsr = (StatCursor *)pCursor; *pRowid = pCsr->iPageno; return SQLITE_OK; @@ -174823,8 +203566,8 @@ static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ /* ** Invoke this routine to register the "dbstat" virtual table module */ -SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ - static sqlite3_module dbstat_module = { +SQLITE_PRIVATE int tdsqlite3DbstatRegister(tdsqlite3 *db){ + static tdsqlite3_module dbstat_module = { 0, /* iVersion */ statConnect, /* xCreate */ statConnect, /* xConnect */ @@ -174845,18 +203588,441 @@ SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ 0, /* xRollback */ 0, /* xFindMethod */ 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0 /* xShadowName */ }; - return sqlite3_create_module(db, "dbstat", &dbstat_module, 0); + return tdsqlite3_create_module(db, "dbstat", &dbstat_module, 0); } #elif defined(SQLITE_ENABLE_DBSTAT_VTAB) -SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; } +SQLITE_PRIVATE int tdsqlite3DbstatRegister(tdsqlite3 *db){ return SQLITE_OK; } #endif /* SQLITE_ENABLE_DBSTAT_VTAB */ /************** End of dbstat.c **********************************************/ -/************** Begin file sqlite3session.c **********************************/ +/************** Begin file dbpage.c ******************************************/ +/* +** 2017-10-11 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains an implementation of the "sqlite_dbpage" virtual table. +** +** The sqlite_dbpage virtual table is used to read or write whole raw +** pages of the database file. The pager interface is used so that +** uncommitted changes and changes recorded in the WAL file are correctly +** retrieved. +** +** Usage example: +** +** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123; +** +** This is an eponymous virtual table so it does not need to be created before +** use. The optional argument to the sqlite_dbpage() table name is the +** schema for the database file that is to be read. The default schema is +** "main". +** +** The data field of sqlite_dbpage table can be updated. The new +** value must be a BLOB which is the correct page size, otherwise the +** update fails. Rows may not be deleted or inserted. +*/ + +/* #include "sqliteInt.h" ** Requires access to internal data structures ** */ +#if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \ + && !defined(SQLITE_OMIT_VIRTUALTABLE) + +typedef struct DbpageTable DbpageTable; +typedef struct DbpageCursor DbpageCursor; + +struct DbpageCursor { + tdsqlite3_vtab_cursor base; /* Base class. Must be first */ + int pgno; /* Current page number */ + int mxPgno; /* Last page to visit on this scan */ + Pager *pPager; /* Pager being read/written */ + DbPage *pPage1; /* Page 1 of the database */ + int iDb; /* Index of database to analyze */ + int szPage; /* Size of each page in bytes */ +}; + +struct DbpageTable { + tdsqlite3_vtab base; /* Base class. Must be first */ + tdsqlite3 *db; /* The database */ +}; + +/* Columns */ +#define DBPAGE_COLUMN_PGNO 0 +#define DBPAGE_COLUMN_DATA 1 +#define DBPAGE_COLUMN_SCHEMA 2 + + + +/* +** Connect to or create a dbpagevfs virtual table. +*/ +static int dbpageConnect( + tdsqlite3 *db, + void *pAux, + int argc, const char *const*argv, + tdsqlite3_vtab **ppVtab, + char **pzErr +){ + DbpageTable *pTab = 0; + int rc = SQLITE_OK; + + tdsqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY); + rc = tdsqlite3_declare_vtab(db, + "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)"); + if( rc==SQLITE_OK ){ + pTab = (DbpageTable *)tdsqlite3_malloc64(sizeof(DbpageTable)); + if( pTab==0 ) rc = SQLITE_NOMEM_BKPT; + } + + assert( rc==SQLITE_OK || pTab==0 ); + if( rc==SQLITE_OK ){ + memset(pTab, 0, sizeof(DbpageTable)); + pTab->db = db; + } + + *ppVtab = (tdsqlite3_vtab*)pTab; + return rc; +} + +/* +** Disconnect from or destroy a dbpagevfs virtual table. +*/ +static int dbpageDisconnect(tdsqlite3_vtab *pVtab){ + tdsqlite3_free(pVtab); + return SQLITE_OK; +} + +/* +** idxNum: +** +** 0 schema=main, full table scan +** 1 schema=main, pgno=?1 +** 2 schema=?1, full table scan +** 3 schema=?1, pgno=?2 +*/ +static int dbpageBestIndex(tdsqlite3_vtab *tab, tdsqlite3_index_info *pIdxInfo){ + int i; + int iPlan = 0; + + /* If there is a schema= constraint, it must be honored. Report a + ** ridiculously large estimated cost if the schema= constraint is + ** unavailable + */ + for(i=0; i<pIdxInfo->nConstraint; i++){ + struct tdsqlite3_index_constraint *p = &pIdxInfo->aConstraint[i]; + if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue; + if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; + if( !p->usable ){ + /* No solution. */ + return SQLITE_CONSTRAINT; + } + iPlan = 2; + pIdxInfo->aConstraintUsage[i].argvIndex = 1; + pIdxInfo->aConstraintUsage[i].omit = 1; + break; + } + + /* If we reach this point, it means that either there is no schema= + ** constraint (in which case we use the "main" schema) or else the + ** schema constraint was accepted. Lower the estimated cost accordingly + */ + pIdxInfo->estimatedCost = 1.0e6; + + /* Check for constraints against pgno */ + for(i=0; i<pIdxInfo->nConstraint; i++){ + struct tdsqlite3_index_constraint *p = &pIdxInfo->aConstraint[i]; + if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + pIdxInfo->estimatedRows = 1; + pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE; + pIdxInfo->estimatedCost = 1.0; + pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1; + pIdxInfo->aConstraintUsage[i].omit = 1; + iPlan |= 1; + break; + } + } + pIdxInfo->idxNum = iPlan; + + if( pIdxInfo->nOrderBy>=1 + && pIdxInfo->aOrderBy[0].iColumn<=0 + && pIdxInfo->aOrderBy[0].desc==0 + ){ + pIdxInfo->orderByConsumed = 1; + } + return SQLITE_OK; +} + +/* +** Open a new dbpagevfs cursor. +*/ +static int dbpageOpen(tdsqlite3_vtab *pVTab, tdsqlite3_vtab_cursor **ppCursor){ + DbpageCursor *pCsr; + + pCsr = (DbpageCursor *)tdsqlite3_malloc64(sizeof(DbpageCursor)); + if( pCsr==0 ){ + return SQLITE_NOMEM_BKPT; + }else{ + memset(pCsr, 0, sizeof(DbpageCursor)); + pCsr->base.pVtab = pVTab; + pCsr->pgno = -1; + } + + *ppCursor = (tdsqlite3_vtab_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** Close a dbpagevfs cursor. +*/ +static int dbpageClose(tdsqlite3_vtab_cursor *pCursor){ + DbpageCursor *pCsr = (DbpageCursor *)pCursor; + if( pCsr->pPage1 ) tdsqlite3PagerUnrefPageOne(pCsr->pPage1); + tdsqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** Move a dbpagevfs cursor to the next entry in the file. +*/ +static int dbpageNext(tdsqlite3_vtab_cursor *pCursor){ + int rc = SQLITE_OK; + DbpageCursor *pCsr = (DbpageCursor *)pCursor; + pCsr->pgno++; + return rc; +} + +static int dbpageEof(tdsqlite3_vtab_cursor *pCursor){ + DbpageCursor *pCsr = (DbpageCursor *)pCursor; + return pCsr->pgno > pCsr->mxPgno; +} + +/* +** idxNum: +** +** 0 schema=main, full table scan +** 1 schema=main, pgno=?1 +** 2 schema=?1, full table scan +** 3 schema=?1, pgno=?2 +** +** idxStr is not used +*/ +static int dbpageFilter( + tdsqlite3_vtab_cursor *pCursor, + int idxNum, const char *idxStr, + int argc, tdsqlite3_value **argv +){ + DbpageCursor *pCsr = (DbpageCursor *)pCursor; + DbpageTable *pTab = (DbpageTable *)pCursor->pVtab; + int rc; + tdsqlite3 *db = pTab->db; + Btree *pBt; + + /* Default setting is no rows of result */ + pCsr->pgno = 1; + pCsr->mxPgno = 0; + + if( idxNum & 2 ){ + const char *zSchema; + assert( argc>=1 ); + zSchema = (const char*)tdsqlite3_value_text(argv[0]); + pCsr->iDb = tdsqlite3FindDbName(db, zSchema); + if( pCsr->iDb<0 ) return SQLITE_OK; + }else{ + pCsr->iDb = 0; + } + pBt = db->aDb[pCsr->iDb].pBt; + if( pBt==0 ) return SQLITE_OK; + pCsr->pPager = tdsqlite3BtreePager(pBt); + pCsr->szPage = tdsqlite3BtreeGetPageSize(pBt); + pCsr->mxPgno = tdsqlite3BtreeLastPage(pBt); + if( idxNum & 1 ){ + assert( argc>(idxNum>>1) ); + pCsr->pgno = tdsqlite3_value_int(argv[idxNum>>1]); + if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){ + pCsr->pgno = 1; + pCsr->mxPgno = 0; + }else{ + pCsr->mxPgno = pCsr->pgno; + } + }else{ + assert( pCsr->pgno==1 ); + } + if( pCsr->pPage1 ) tdsqlite3PagerUnrefPageOne(pCsr->pPage1); + rc = tdsqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0); + return rc; +} + +static int dbpageColumn( + tdsqlite3_vtab_cursor *pCursor, + tdsqlite3_context *ctx, + int i +){ + DbpageCursor *pCsr = (DbpageCursor *)pCursor; + int rc = SQLITE_OK; + switch( i ){ + case 0: { /* pgno */ + tdsqlite3_result_int(ctx, pCsr->pgno); + break; + } + case 1: { /* data */ + DbPage *pDbPage = 0; + rc = tdsqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0); + if( rc==SQLITE_OK ){ + tdsqlite3_result_blob(ctx, tdsqlite3PagerGetData(pDbPage), pCsr->szPage, + SQLITE_TRANSIENT); + } + tdsqlite3PagerUnref(pDbPage); + break; + } + default: { /* schema */ + tdsqlite3 *db = tdsqlite3_context_db_handle(ctx); + tdsqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC); + break; + } + } + return SQLITE_OK; +} + +static int dbpageRowid(tdsqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + DbpageCursor *pCsr = (DbpageCursor *)pCursor; + *pRowid = pCsr->pgno; + return SQLITE_OK; +} + +static int dbpageUpdate( + tdsqlite3_vtab *pVtab, + int argc, + tdsqlite3_value **argv, + sqlite_int64 *pRowid +){ + DbpageTable *pTab = (DbpageTable *)pVtab; + Pgno pgno; + DbPage *pDbPage = 0; + int rc = SQLITE_OK; + char *zErr = 0; + const char *zSchema; + int iDb; + Btree *pBt; + Pager *pPager; + int szPage; + + if( pTab->db->flags & SQLITE_Defensive ){ + zErr = "read-only"; + goto update_fail; + } + if( argc==1 ){ + zErr = "cannot delete"; + goto update_fail; + } + pgno = tdsqlite3_value_int(argv[0]); + if( (Pgno)tdsqlite3_value_int(argv[1])!=pgno ){ + zErr = "cannot insert"; + goto update_fail; + } + zSchema = (const char*)tdsqlite3_value_text(argv[4]); + iDb = zSchema ? tdsqlite3FindDbName(pTab->db, zSchema) : -1; + if( iDb<0 ){ + zErr = "no such schema"; + goto update_fail; + } + pBt = pTab->db->aDb[iDb].pBt; + if( pgno<1 || pBt==0 || pgno>(int)tdsqlite3BtreeLastPage(pBt) ){ + zErr = "bad page number"; + goto update_fail; + } + szPage = tdsqlite3BtreeGetPageSize(pBt); + if( tdsqlite3_value_type(argv[3])!=SQLITE_BLOB + || tdsqlite3_value_bytes(argv[3])!=szPage + ){ + zErr = "bad page value"; + goto update_fail; + } + pPager = tdsqlite3BtreePager(pBt); + rc = tdsqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0); + if( rc==SQLITE_OK ){ + rc = tdsqlite3PagerWrite(pDbPage); + if( rc==SQLITE_OK ){ + memcpy(tdsqlite3PagerGetData(pDbPage), + tdsqlite3_value_blob(argv[3]), + szPage); + } + } + tdsqlite3PagerUnref(pDbPage); + return rc; + +update_fail: + tdsqlite3_free(pVtab->zErrMsg); + pVtab->zErrMsg = tdsqlite3_mprintf("%s", zErr); + return SQLITE_ERROR; +} + +/* Since we do not know in advance which database files will be +** written by the sqlite_dbpage virtual table, start a write transaction +** on them all. +*/ +static int dbpageBegin(tdsqlite3_vtab *pVtab){ + DbpageTable *pTab = (DbpageTable *)pVtab; + tdsqlite3 *db = pTab->db; + int i; + for(i=0; i<db->nDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ) tdsqlite3BtreeBeginTrans(pBt, 1, 0); + } + return SQLITE_OK; +} + + +/* +** Invoke this routine to register the "dbpage" virtual table module +*/ +SQLITE_PRIVATE int tdsqlite3DbpageRegister(tdsqlite3 *db){ + static tdsqlite3_module dbpage_module = { + 0, /* iVersion */ + dbpageConnect, /* xCreate */ + dbpageConnect, /* xConnect */ + dbpageBestIndex, /* xBestIndex */ + dbpageDisconnect, /* xDisconnect */ + dbpageDisconnect, /* xDestroy */ + dbpageOpen, /* xOpen - open a cursor */ + dbpageClose, /* xClose - close a cursor */ + dbpageFilter, /* xFilter - configure scan constraints */ + dbpageNext, /* xNext - advance a cursor */ + dbpageEof, /* xEof - check for end of scan */ + dbpageColumn, /* xColumn - read data */ + dbpageRowid, /* xRowid - read data */ + dbpageUpdate, /* xUpdate */ + dbpageBegin, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0 /* xShadowName */ + }; + return tdsqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0); +} +#elif defined(SQLITE_ENABLE_DBPAGE_VTAB) +SQLITE_PRIVATE int tdsqlite3DbpageRegister(tdsqlite3 *db){ return SQLITE_OK; } +#endif /* SQLITE_ENABLE_DBSTAT_VTAB */ + +/************** End of dbpage.c **********************************************/ +/************** Begin file tdsqlite3session.c **********************************/ #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK) -/* #include "sqlite3session.h" */ +/* #include "tdsqlite3session.h" */ /* #include <assert.h> */ /* #include <string.h> */ @@ -174881,11 +204047,13 @@ typedef struct SessionInput SessionInput; # endif #endif +static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE; + typedef struct SessionHook SessionHook; struct SessionHook { void *pCtx; - int (*xOld)(void*,int,sqlite3_value**); - int (*xNew)(void*,int,sqlite3_value**); + int (*xOld)(void*,int,tdsqlite3_value**); + int (*xNew)(void*,int,tdsqlite3_value**); int (*xCount)(void*); int (*xDepth)(void*); }; @@ -174893,8 +204061,8 @@ struct SessionHook { /* ** Session handle structure. */ -struct sqlite3_session { - sqlite3 *db; /* Database handle session is attached to */ +struct tdsqlite3_session { + tdsqlite3 *db; /* Database handle session is attached to */ char *zDb; /* Name of database session is attached to */ int bEnable; /* True if currently recording */ int bIndirect; /* True if all changes are indirect */ @@ -174902,7 +204070,8 @@ struct sqlite3_session { int rc; /* Non-zero if an error has occurred */ void *pFilterCtx; /* First argument to pass to xTableFilter */ int (*xTableFilter)(void *pCtx, const char *zTab); - sqlite3_session *pNext; /* Next session object on same db. */ + tdsqlite3_value *pZeroBlob; /* Value containing X'' */ + tdsqlite3_session *pNext; /* Next session object on same db. */ SessionTable *pTable; /* List of attached tables */ SessionHook hook; /* APIs to grab new and old data with */ }; @@ -174919,11 +204088,11 @@ struct SessionBuffer { /* ** An object of this type is used internally as an abstraction for ** input data. Input data may be supplied either as a single large buffer -** (e.g. sqlite3changeset_start()) or using a stream function (e.g. -** sqlite3changeset_start_strm()). +** (e.g. tdsqlite3changeset_start()) or using a stream function (e.g. +** tdsqlite3changeset_start_strm()). */ struct SessionInput { - int bNoDiscard; /* If true, discard no data */ + int bNoDiscard; /* If true, do not discard in InputBuffer() */ int iCurrent; /* Offset in aData[] of current change */ int iNext; /* Offset in aData[] of next change */ u8 *aData; /* Pointer to buffer containing changeset */ @@ -174938,24 +204107,25 @@ struct SessionInput { /* ** Structure for changeset iterators. */ -struct sqlite3_changeset_iter { +struct tdsqlite3_changeset_iter { SessionInput in; /* Input buffer or stream */ SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */ int bPatchset; /* True if this is a patchset */ + int bInvert; /* True to invert changeset */ int rc; /* Iterator error code */ - sqlite3_stmt *pConflict; /* Points to conflicting row, if any */ + tdsqlite3_stmt *pConflict; /* Points to conflicting row, if any */ char *zTab; /* Current table */ int nCol; /* Number of columns in zTab */ int op; /* Current operation */ int bIndirect; /* True if current change was indirect */ u8 *abPK; /* Primary key array */ - sqlite3_value **apValue; /* old.* and new.* values */ + tdsqlite3_value **apValue; /* old.* and new.* values */ }; /* ** Each session object maintains a set of the following structures, one ** for each table the session object is monitoring. The structures are -** stored in a linked list starting at sqlite3_session.pTable. +** stored in a linked list starting at tdsqlite3_session.pTable. ** ** The keys of the SessionTable.aChange[] hash table are all rows that have ** been modified in any way since the session object was attached to the @@ -174969,6 +204139,7 @@ struct SessionTable { SessionTable *pNext; char *zName; /* Local name of table */ int nCol; /* Number of columns in table zName */ + int bStat1; /* True if this is sqlite_stat1 */ const char **azCol; /* Column names */ u8 *abPK; /* Array of primary key flags */ int nEntry; /* Total number of entries in hash table */ @@ -175086,8 +204257,8 @@ struct SessionTable { ** statement. ** ** For a DELETE change, all fields within the record except those associated -** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields -** contain the values identifying the row to delete. +** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the +** values identifying the row to delete. ** ** For an UPDATE change, all fields except those associated with PRIMARY KEY ** columns and columns that are modified by the UPDATE are set to "undefined". @@ -175097,6 +204268,42 @@ struct SessionTable { ** The records associated with INSERT changes are in the same format as for ** changesets. It is not possible for a record associated with an INSERT ** change to contain a field set to "undefined". +** +** REBASE BLOB FORMAT: +** +** A rebase blob may be output by tdsqlite3changeset_apply_v2() and its +** streaming equivalent for use with the tdsqlite3_rebaser APIs to rebase +** existing changesets. A rebase blob contains one entry for each conflict +** resolved using either the OMIT or REPLACE strategies within the apply_v2() +** call. +** +** The format used for a rebase blob is very similar to that used for +** changesets. All entries related to a single table are grouped together. +** +** Each group of entries begins with a table header in changeset format: +** +** 1 byte: Constant 0x54 (capital 'T') +** Varint: Number of columns in the table. +** nCol bytes: 0x01 for PK columns, 0x00 otherwise. +** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated. +** +** Followed by one or more entries associated with the table. +** +** 1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09). +** 1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT. +** record: (in the record format defined above). +** +** In a rebase blob, the first field is set to SQLITE_INSERT if the change +** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if +** it was a DELETE. The second field is set to 0x01 if the conflict +** resolution strategy was REPLACE, or 0x00 if it was OMIT. +** +** If the change that caused the conflict was a DELETE, then the single +** record is a copy of the old.* record from the original changeset. If it +** was an INSERT, then the single record is a copy of the new.* record. If +** the conflicting change was an UPDATE, then the single record is a copy +** of the new.* record with the PK fields filled in based on the original +** old.* record. */ /* @@ -175123,7 +204330,7 @@ static int sessionVarintPut(u8 *aBuf, int iVal){ ** Return the number of bytes required to store value iVal as a varint. */ static int sessionVarintLen(int iVal){ - return sqlite3VarintLen(iVal); + return tdsqlite3VarintLen(iVal); } /* @@ -175141,17 +204348,17 @@ static int sessionVarintGet(u8 *aBuf, int *piVal){ ** Read a 64-bit big-endian integer value from buffer aRec[]. Return ** the value read. */ -static sqlite3_int64 sessionGetI64(u8 *aRec){ +static tdsqlite3_int64 sessionGetI64(u8 *aRec){ u64 x = SESSION_UINT32(aRec); u32 y = SESSION_UINT32(aRec+4); x = (x<<32) + y; - return (sqlite3_int64)x; + return (tdsqlite3_int64)x; } /* ** Write a 64-bit big-endian integer value to the buffer aBuf[]. */ -static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){ +static void sessionPutI64(u8 *aBuf, tdsqlite3_int64 i){ aBuf[0] = (i>>56) & 0xFF; aBuf[1] = (i>>48) & 0xFF; aBuf[2] = (i>>40) & 0xFF; @@ -175172,20 +204379,20 @@ static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){ ** set *pnWrite. ** ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs -** within a call to sqlite3_value_text() (may fail if the db is utf-16)) +** within a call to tdsqlite3_value_text() (may fail if the db is utf-16)) ** SQLITE_NOMEM is returned. */ static int sessionSerializeValue( u8 *aBuf, /* If non-NULL, write serialized value here */ - sqlite3_value *pValue, /* Value to serialize */ - int *pnWrite /* IN/OUT: Increment by bytes written */ + tdsqlite3_value *pValue, /* Value to serialize */ + tdsqlite3_int64 *pnWrite /* IN/OUT: Increment by bytes written */ ){ int nByte; /* Size of serialized value in bytes */ if( pValue ){ int eType; /* Value type (SQLITE_NULL, TEXT etc.) */ - eType = sqlite3_value_type(pValue); + eType = tdsqlite3_value_type(pValue); if( aBuf ) aBuf[0] = eType; switch( eType ){ @@ -175201,11 +204408,11 @@ static int sessionSerializeValue( ** too. */ u64 i; if( eType==SQLITE_INTEGER ){ - i = (u64)sqlite3_value_int64(pValue); + i = (u64)tdsqlite3_value_int64(pValue); }else{ double r; assert( sizeof(double)==8 && sizeof(u64)==8 ); - r = sqlite3_value_double(pValue); + r = tdsqlite3_value_double(pValue); memcpy(&i, &r, 8); } sessionPutI64(&aBuf[1], i); @@ -175220,19 +204427,17 @@ static int sessionSerializeValue( assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); if( eType==SQLITE_TEXT ){ - z = (u8 *)sqlite3_value_text(pValue); + z = (u8 *)tdsqlite3_value_text(pValue); }else{ - z = (u8 *)sqlite3_value_blob(pValue); + z = (u8 *)tdsqlite3_value_blob(pValue); } - n = sqlite3_value_bytes(pValue); + n = tdsqlite3_value_bytes(pValue); if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM; nVarint = sessionVarintLen(n); if( aBuf ){ sessionVarintPut(&aBuf[1], n); - memcpy(&aBuf[nVarint + 1], eType==SQLITE_TEXT ? - sqlite3_value_text(pValue) : sqlite3_value_blob(pValue), n - ); + if( n ) memcpy(&aBuf[nVarint + 1], z, n); } nByte = 1 + nVarint + n; @@ -175305,7 +204510,7 @@ static unsigned int sessionHashAppendType(unsigned int h, int eType){ ** and the output variables are set as described above. */ static int sessionPreupdateHash( - sqlite3_session *pSession, /* Session object that owns pTab */ + tdsqlite3_session *pSession, /* Session object that owns pTab */ SessionTable *pTab, /* Session table handle */ int bNew, /* True to hash the new.* PK */ int *piHash, /* OUT: Hash value */ @@ -175320,7 +204525,7 @@ static int sessionPreupdateHash( if( pTab->abPK[i] ){ int rc; int eType; - sqlite3_value *pVal; + tdsqlite3_value *pVal; if( bNew ){ rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal); @@ -175329,14 +204534,14 @@ static int sessionPreupdateHash( } if( rc!=SQLITE_OK ) return rc; - eType = sqlite3_value_type(pVal); + eType = tdsqlite3_value_type(pVal); h = sessionHashAppendType(h, eType); if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ i64 iVal; if( eType==SQLITE_INTEGER ){ - iVal = sqlite3_value_int64(pVal); + iVal = tdsqlite3_value_int64(pVal); }else{ - double rVal = sqlite3_value_double(pVal); + double rVal = tdsqlite3_value_double(pVal); assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); memcpy(&iVal, &rVal, 8); } @@ -175345,15 +204550,16 @@ static int sessionPreupdateHash( const u8 *z; int n; if( eType==SQLITE_TEXT ){ - z = (const u8 *)sqlite3_value_text(pVal); + z = (const u8 *)tdsqlite3_value_text(pVal); }else{ - z = (const u8 *)sqlite3_value_blob(pVal); + z = (const u8 *)tdsqlite3_value_blob(pVal); } - n = sqlite3_value_bytes(pVal); + n = tdsqlite3_value_bytes(pVal); if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM; h = sessionHashAppendBlob(h, n, z); }else{ assert( eType==SQLITE_NULL ); + assert( pTab->bStat1==0 || i!=1 ); *pbNullPK = 1; } } @@ -175371,7 +204577,7 @@ static int sessionPreupdateHash( static int sessionSerialLen(u8 *a){ int e = *a; int n; - if( e==0 ) return 1; + if( e==0 || e==0xFF ) return 1; if( e==SQLITE_NULL ) return 1; if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9; return sessionVarintGet(&a[1], &n) + 1 + n; @@ -175451,7 +204657,7 @@ static int sessionChangeEqual( int n1 = sessionSerialLen(a1); int n2 = sessionSerialLen(a2); - if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){ + if( n1!=n2 || memcmp(a1, a2, n1) ){ return 0; } a1 += n1; @@ -175636,7 +204842,7 @@ static int sessionMergeUpdate( ** false. */ static int sessionPreupdateEqual( - sqlite3_session *pSession, /* Session object that owns SessionTable */ + tdsqlite3_session *pSession, /* Session object that owns SessionTable */ SessionTable *pTab, /* Table associated with change */ SessionChange *pChange, /* Change to compare to */ int op /* Current pre-update operation */ @@ -175649,7 +204855,7 @@ static int sessionPreupdateEqual( if( !pTab->abPK[iCol] ){ a += sessionSerialLen(a); }else{ - sqlite3_value *pVal; /* Value returned by preupdate_new/old */ + tdsqlite3_value *pVal; /* Value returned by preupdate_new/old */ int rc; /* Error code from preupdate_new/old */ int eType = *a++; /* Type of value from change record */ @@ -175666,7 +204872,7 @@ static int sessionPreupdateEqual( rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal); } assert( rc==SQLITE_OK ); - if( sqlite3_value_type(pVal)!=eType ) return 0; + if( tdsqlite3_value_type(pVal)!=eType ) return 0; /* A SessionChange object never has a NULL value in a PK column */ assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT @@ -175677,26 +204883,25 @@ static int sessionPreupdateEqual( i64 iVal = sessionGetI64(a); a += 8; if( eType==SQLITE_INTEGER ){ - if( sqlite3_value_int64(pVal)!=iVal ) return 0; + if( tdsqlite3_value_int64(pVal)!=iVal ) return 0; }else{ double rVal; assert( sizeof(iVal)==8 && sizeof(rVal)==8 ); memcpy(&rVal, &iVal, 8); - if( sqlite3_value_double(pVal)!=rVal ) return 0; + if( tdsqlite3_value_double(pVal)!=rVal ) return 0; } }else{ int n; const u8 *z; a += sessionVarintGet(a, &n); - if( sqlite3_value_bytes(pVal)!=n ) return 0; + if( tdsqlite3_value_bytes(pVal)!=n ) return 0; if( eType==SQLITE_TEXT ){ - z = sqlite3_value_text(pVal); + z = tdsqlite3_value_text(pVal); }else{ - z = sqlite3_value_blob(pVal); + z = tdsqlite3_value_blob(pVal); } - if( memcmp(a, z, n) ) return 0; + if( n>0 && memcmp(a, z, n) ) return 0; a += n; - break; } } } @@ -175719,9 +204924,9 @@ static int sessionGrowHash(int bPatchset, SessionTable *pTab){ if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){ int i; SessionChange **apNew; - int nNew = (pTab->nChange ? pTab->nChange : 128) * 2; + tdsqlite3_int64 nNew = 2*(tdsqlite3_int64)(pTab->nChange ? pTab->nChange : 128); - apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew); + apNew = (SessionChange **)tdsqlite3_malloc64(sizeof(SessionChange *) * nNew); if( apNew==0 ){ if( pTab->nChange==0 ){ return SQLITE_ERROR; @@ -175742,7 +204947,7 @@ static int sessionGrowHash(int bPatchset, SessionTable *pTab){ } } - sqlite3_free(pTab->apChange); + tdsqlite3_free(pTab->apChange); pTab->nChange = nNew; pTab->apChange = apNew; } @@ -175752,9 +204957,7 @@ static int sessionGrowHash(int bPatchset, SessionTable *pTab){ /* ** This function queries the database for the names of the columns of table -** zThis, in schema zDb. It is expected that the table has nCol columns. If -** not, SQLITE_SCHEMA is returned and none of the output variables are -** populated. +** zThis, in schema zDb. ** ** Otherwise, if they are not NULL, variable *pnCol is set to the number ** of columns in the database table and variable *pzTab is set to point to a @@ -175775,12 +204978,10 @@ static int sessionGrowHash(int bPatchset, SessionTable *pTab){ ** *pabPK = {1, 0, 0, 1} ** ** All returned buffers are part of the same single allocation, which must -** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then -** pointer *pazCol should be freed to release all memory. Otherwise, pointer -** *pabPK. It is illegal for both pazCol and pabPK to be NULL. +** be freed using tdsqlite3_free() by the caller */ static int sessionTableInfo( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ const char *zDb, /* Name of attached database (e.g. "main") */ const char *zThis, /* Table name */ int *pnCol, /* OUT: number of columns */ @@ -175789,9 +204990,9 @@ static int sessionTableInfo( u8 **pabPK /* OUT: Array of booleans - true for PK col */ ){ char *zPragma; - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; int rc; - int nByte; + tdsqlite3_int64 nByte; int nDbCol = 0; int nThis; int i; @@ -175801,24 +205002,40 @@ static int sessionTableInfo( assert( pazCol && pabPK ); - nThis = sqlite3Strlen30(zThis); - zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis); + nThis = tdsqlite3Strlen30(zThis); + if( nThis==12 && 0==tdsqlite3_stricmp("sqlite_stat1", zThis) ){ + rc = tdsqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0); + if( rc==SQLITE_OK ){ + /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */ + zPragma = tdsqlite3_mprintf( + "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL " + "SELECT 1, 'idx', '', 0, '', 2 UNION ALL " + "SELECT 2, 'stat', '', 0, '', 0" + ); + }else if( rc==SQLITE_ERROR ){ + zPragma = tdsqlite3_mprintf(""); + }else{ + return rc; + } + }else{ + zPragma = tdsqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis); + } if( !zPragma ) return SQLITE_NOMEM; - rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0); - sqlite3_free(zPragma); + rc = tdsqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0); + tdsqlite3_free(zPragma); if( rc!=SQLITE_OK ) return rc; nByte = nThis + 1; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ - nByte += sqlite3_column_bytes(pStmt, 1); + while( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + nByte += tdsqlite3_column_bytes(pStmt, 1); nDbCol++; } - rc = sqlite3_reset(pStmt); + rc = tdsqlite3_reset(pStmt); if( rc==SQLITE_OK ){ nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1); - pAlloc = sqlite3_malloc(nByte); + pAlloc = tdsqlite3_malloc64(nByte); if( pAlloc==0 ){ rc = SQLITE_NOMEM; } @@ -175835,17 +205052,17 @@ static int sessionTableInfo( } i = 0; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ - int nName = sqlite3_column_bytes(pStmt, 1); - const unsigned char *zName = sqlite3_column_text(pStmt, 1); + while( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + int nName = tdsqlite3_column_bytes(pStmt, 1); + const unsigned char *zName = tdsqlite3_column_text(pStmt, 1); if( zName==0 ) break; memcpy(pAlloc, zName, nName+1); azCol[i] = (char *)pAlloc; pAlloc += nName+1; - abPK[i] = sqlite3_column_int(pStmt, 5); + abPK[i] = tdsqlite3_column_int(pStmt, 5); i++; } - rc = sqlite3_reset(pStmt); + rc = tdsqlite3_reset(pStmt); } @@ -175861,9 +205078,9 @@ static int sessionTableInfo( *pabPK = 0; *pnCol = 0; if( pzTab ) *pzTab = 0; - sqlite3_free(azCol); + tdsqlite3_free(azCol); } - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); return rc; } @@ -175873,13 +205090,13 @@ static int sessionTableInfo( ** write to this table, initalize the SessionTable.nCol, azCol[] and ** abPK[] arrays accordingly. ** -** If an error occurs, an error code is stored in sqlite3_session.rc and +** If an error occurs, an error code is stored in tdsqlite3_session.rc and ** non-zero returned. Or, if no error occurs but the table has no primary -** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to +** key, tdsqlite3_session.rc is left set to SQLITE_OK and non-zero returned to ** indicate that updates on this table should be ignored. SessionTable.abPK ** is set to NULL in this case. */ -static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){ +static int sessionInitTable(tdsqlite3_session *pSession, SessionTable *pTab){ if( pTab->nCol==0 ){ u8 *abPK; assert( pTab->azCol==0 || pTab->abPK==0 ); @@ -175894,12 +205111,56 @@ static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){ break; } } + if( 0==tdsqlite3_stricmp("sqlite_stat1", pTab->zName) ){ + pTab->bStat1 = 1; + } } } return (pSession->rc || pTab->abPK==0); } /* +** Versions of the four methods in object SessionHook for use with the +** sqlite_stat1 table. The purpose of this is to substitute a zero-length +** blob each time a NULL value is read from the "idx" column of the +** sqlite_stat1 table. +*/ +typedef struct SessionStat1Ctx SessionStat1Ctx; +struct SessionStat1Ctx { + SessionHook hook; + tdsqlite3_session *pSession; +}; +static int sessionStat1Old(void *pCtx, int iCol, tdsqlite3_value **ppVal){ + SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; + tdsqlite3_value *pVal = 0; + int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal); + if( rc==SQLITE_OK && iCol==1 && tdsqlite3_value_type(pVal)==SQLITE_NULL ){ + pVal = p->pSession->pZeroBlob; + } + *ppVal = pVal; + return rc; +} +static int sessionStat1New(void *pCtx, int iCol, tdsqlite3_value **ppVal){ + SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; + tdsqlite3_value *pVal = 0; + int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal); + if( rc==SQLITE_OK && iCol==1 && tdsqlite3_value_type(pVal)==SQLITE_NULL ){ + pVal = p->pSession->pZeroBlob; + } + *ppVal = pVal; + return rc; +} +static int sessionStat1Count(void *pCtx){ + SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; + return p->hook.xCount(p->hook.pCtx); +} +static int sessionStat1Depth(void *pCtx){ + SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx; + return p->hook.xDepth(p->hook.pCtx); +} + + +/* ** This function is only called from with a pre-update-hook reporting a ** change on table pTab (attached to session pSession). The type of change ** (UPDATE, INSERT, DELETE) is specified by the first argument. @@ -175909,12 +205170,13 @@ static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){ */ static void sessionPreupdateOneChange( int op, /* One of SQLITE_UPDATE, INSERT, DELETE */ - sqlite3_session *pSession, /* Session object pTab is attached to */ + tdsqlite3_session *pSession, /* Session object pTab is attached to */ SessionTable *pTab /* Table that change applies to */ ){ int iHash; int bNull = 0; int rc = SQLITE_OK; + SessionStat1Ctx stat1 = {{0,0,0,0,0},0}; if( pSession->rc ) return; @@ -175934,6 +205196,25 @@ static void sessionPreupdateOneChange( return; } + if( pTab->bStat1 ){ + stat1.hook = pSession->hook; + stat1.pSession = pSession; + pSession->hook.pCtx = (void*)&stat1; + pSession->hook.xNew = sessionStat1New; + pSession->hook.xOld = sessionStat1Old; + pSession->hook.xCount = sessionStat1Count; + pSession->hook.xDepth = sessionStat1Depth; + if( pSession->pZeroBlob==0 ){ + tdsqlite3_value *p = tdsqlite3ValueNew(0); + if( p==0 ){ + rc = SQLITE_NOMEM; + goto error_out; + } + tdsqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC); + pSession->pZeroBlob = p; + } + } + /* Calculate the hash-key for this change. If the primary key of the row ** includes a NULL value, exit early. Such changes are ignored by the ** session module. */ @@ -175952,7 +205233,7 @@ static void sessionPreupdateOneChange( ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK ** values (if this is an INSERT). */ SessionChange *pChange; /* New change object */ - int nByte; /* Number of bytes to allocate */ + tdsqlite3_int64 nByte; /* Number of bytes to allocate */ int i; /* Used to iterate through columns */ assert( rc==SQLITE_OK ); @@ -175961,7 +205242,7 @@ static void sessionPreupdateOneChange( /* Figure out how large an allocation is required */ nByte = sizeof(SessionChange); for(i=0; i<pTab->nCol; i++){ - sqlite3_value *p = 0; + tdsqlite3_value *p = 0; if( op!=SQLITE_INSERT ){ TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p); assert( trc==SQLITE_OK ); @@ -175977,7 +205258,7 @@ static void sessionPreupdateOneChange( } /* Allocate the change object */ - pChange = (SessionChange *)sqlite3_malloc(nByte); + pChange = (SessionChange *)tdsqlite3_malloc64(nByte); if( !pChange ){ rc = SQLITE_NOMEM; goto error_out; @@ -175992,7 +205273,7 @@ static void sessionPreupdateOneChange( ** It is not possible for an OOM to occur in this block. */ nByte = 0; for(i=0; i<pTab->nCol; i++){ - sqlite3_value *p = 0; + tdsqlite3_value *p = 0; if( op!=SQLITE_INSERT ){ pSession->hook.xOld(pSession->hook.pCtx, i, &p); }else if( pTab->abPK[i] ){ @@ -176023,23 +205304,26 @@ static void sessionPreupdateOneChange( /* If an error has occurred, mark the session object as failed. */ error_out: + if( pTab->bStat1 ){ + pSession->hook = stat1.hook; + } if( rc!=SQLITE_OK ){ pSession->rc = rc; } } static int sessionFindTable( - sqlite3_session *pSession, + tdsqlite3_session *pSession, const char *zName, SessionTable **ppTab ){ int rc = SQLITE_OK; - int nName = sqlite3Strlen30(zName); + int nName = tdsqlite3Strlen30(zName); SessionTable *pRet; /* Search for an existing table */ for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){ - if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break; + if( 0==tdsqlite3_strnicmp(pRet->zName, zName, nName+1) ) break; } if( pRet==0 && pSession->bAutoAttach ){ @@ -176048,10 +205332,10 @@ static int sessionFindTable( if( pSession->xTableFilter==0 || pSession->xTableFilter(pSession->pFilterCtx, zName) ){ - rc = sqlite3session_attach(pSession, zName); + rc = tdsqlite3session_attach(pSession, zName); if( rc==SQLITE_OK ){ for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext); - assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ); + assert( 0==tdsqlite3_strnicmp(pRet->zName, zName, nName+1) ); } } } @@ -176066,19 +205350,19 @@ static int sessionFindTable( */ static void xPreUpdate( void *pCtx, /* Copy of third arg to preupdate_hook() */ - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ int op, /* SQLITE_UPDATE, DELETE or INSERT */ char const *zDb, /* Database name */ char const *zName, /* Table name */ - sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ - sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ + tdsqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ + tdsqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ ){ - sqlite3_session *pSession; - int nDb = sqlite3Strlen30(zDb); + tdsqlite3_session *pSession; + int nDb = tdsqlite3Strlen30(zDb); - assert( sqlite3_mutex_held(db->mutex) ); + assert( tdsqlite3_mutex_held(db->mutex) ); - for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){ + for(pSession=(tdsqlite3_session *)pCtx; pSession; pSession=pSession->pNext){ SessionTable *pTab; /* If this session is attached to a different database ("main", "temp" @@ -176086,7 +205370,7 @@ static void xPreUpdate( ** to the next session object attached to this database. */ if( pSession->bEnable==0 ) continue; if( pSession->rc ) continue; - if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue; + if( tdsqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue; pSession->rc = sessionFindTable(pSession, zName, &pTab); if( pTab ){ @@ -176102,17 +205386,17 @@ static void xPreUpdate( /* ** The pre-update hook implementations. */ -static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){ - return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal); +static int sessionPreupdateOld(void *pCtx, int iVal, tdsqlite3_value **ppVal){ + return tdsqlite3_preupdate_old((tdsqlite3*)pCtx, iVal, ppVal); } -static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){ - return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal); +static int sessionPreupdateNew(void *pCtx, int iVal, tdsqlite3_value **ppVal){ + return tdsqlite3_preupdate_new((tdsqlite3*)pCtx, iVal, ppVal); } static int sessionPreupdateCount(void *pCtx){ - return sqlite3_preupdate_count((sqlite3*)pCtx); + return tdsqlite3_preupdate_count((tdsqlite3*)pCtx); } static int sessionPreupdateDepth(void *pCtx){ - return sqlite3_preupdate_depth((sqlite3*)pCtx); + return tdsqlite3_preupdate_depth((tdsqlite3*)pCtx); } /* @@ -176120,7 +205404,7 @@ static int sessionPreupdateDepth(void *pCtx){ ** argument. */ static void sessionPreupdateHooks( - sqlite3_session *pSession + tdsqlite3_session *pSession ){ pSession->hook.pCtx = (void*)pSession->db; pSession->hook.xOld = sessionPreupdateOld; @@ -176131,26 +205415,26 @@ static void sessionPreupdateHooks( typedef struct SessionDiffCtx SessionDiffCtx; struct SessionDiffCtx { - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; int nOldOff; }; /* ** The diff hook implementations. */ -static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){ +static int sessionDiffOld(void *pCtx, int iVal, tdsqlite3_value **ppVal){ SessionDiffCtx *p = (SessionDiffCtx*)pCtx; - *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff); + *ppVal = tdsqlite3_column_value(p->pStmt, iVal+p->nOldOff); return SQLITE_OK; } -static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){ +static int sessionDiffNew(void *pCtx, int iVal, tdsqlite3_value **ppVal){ SessionDiffCtx *p = (SessionDiffCtx*)pCtx; - *ppVal = sqlite3_column_value(p->pStmt, iVal); + *ppVal = tdsqlite3_column_value(p->pStmt, iVal); return SQLITE_OK; } static int sessionDiffCount(void *pCtx){ SessionDiffCtx *p = (SessionDiffCtx*)pCtx; - return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt); + return p->nOldOff ? p->nOldOff : tdsqlite3_column_count(p->pStmt); } static int sessionDiffDepth(void *pCtx){ return 0; @@ -176161,7 +205445,7 @@ static int sessionDiffDepth(void *pCtx){ ** argument. */ static void sessionDiffHooks( - sqlite3_session *pSession, + tdsqlite3_session *pSession, SessionDiffCtx *pDiffCtx ){ pSession->hook.pCtx = (void*)pDiffCtx; @@ -176183,7 +205467,7 @@ static char *sessionExprComparePK( for(i=0; i<nCol; i++){ if( abPK[i] ){ - zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"", + zRet = tdsqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"", zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i] ); zSep = " AND "; @@ -176208,7 +205492,7 @@ static char *sessionExprCompareOther( for(i=0; i<nCol; i++){ if( abPK[i]==0 ){ bHave = 1; - zRet = sqlite3_mprintf( + zRet = tdsqlite3_mprintf( "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"", zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i] ); @@ -176219,7 +205503,7 @@ static char *sessionExprCompareOther( if( bHave==0 ){ assert( zRet==0 ); - zRet = sqlite3_mprintf("0"); + zRet = tdsqlite3_mprintf("0"); } return zRet; @@ -176232,7 +205516,7 @@ static char *sessionSelectFindNew( const char *zTbl, /* Table name */ const char *zExpr ){ - char *zRet = sqlite3_mprintf( + char *zRet = tdsqlite3_mprintf( "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS (" " SELECT 1 FROM \"%w\".\"%w\" WHERE %s" ")", @@ -176243,7 +205527,7 @@ static char *sessionSelectFindNew( static int sessionDiffFindNew( int op, - sqlite3_session *pSession, + tdsqlite3_session *pSession, SessionTable *pTab, const char *zDb1, const char *zDb2, @@ -176255,25 +205539,25 @@ static int sessionDiffFindNew( if( zStmt==0 ){ rc = SQLITE_NOMEM; }else{ - sqlite3_stmt *pStmt; - rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); + tdsqlite3_stmt *pStmt; + rc = tdsqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); if( rc==SQLITE_OK ){ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; pDiffCtx->pStmt = pStmt; pDiffCtx->nOldOff = 0; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ + while( SQLITE_ROW==tdsqlite3_step(pStmt) ){ sessionPreupdateOneChange(op, pSession, pTab); } - rc = sqlite3_finalize(pStmt); + rc = tdsqlite3_finalize(pStmt); } - sqlite3_free(zStmt); + tdsqlite3_free(zStmt); } return rc; } static int sessionDiffFindModified( - sqlite3_session *pSession, + tdsqlite3_session *pSession, SessionTable *pTab, const char *zFrom, const char *zExpr @@ -176286,34 +205570,34 @@ static int sessionDiffFindModified( if( zExpr2==0 ){ rc = SQLITE_NOMEM; }else{ - char *zStmt = sqlite3_mprintf( + char *zStmt = tdsqlite3_mprintf( "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)", pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2 ); if( zStmt==0 ){ rc = SQLITE_NOMEM; }else{ - sqlite3_stmt *pStmt; - rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); + tdsqlite3_stmt *pStmt; + rc = tdsqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); if( rc==SQLITE_OK ){ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; pDiffCtx->pStmt = pStmt; pDiffCtx->nOldOff = pTab->nCol; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ + while( SQLITE_ROW==tdsqlite3_step(pStmt) ){ sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab); } - rc = sqlite3_finalize(pStmt); + rc = tdsqlite3_finalize(pStmt); } - sqlite3_free(zStmt); + tdsqlite3_free(zStmt); } } return rc; } -SQLITE_API int sqlite3session_diff( - sqlite3_session *pSession, +SQLITE_API int tdsqlite3session_diff( + tdsqlite3_session *pSession, const char *zFrom, const char *zTbl, char **pzErrMsg @@ -176325,11 +205609,11 @@ SQLITE_API int sqlite3session_diff( memset(&d, 0, sizeof(d)); sessionDiffHooks(pSession, &d); - sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_enter(tdsqlite3_db_mutex(pSession->db)); if( pzErrMsg ) *pzErrMsg = 0; if( rc==SQLITE_OK ){ char *zExpr = 0; - sqlite3 *db = pSession->db; + tdsqlite3 *db = pSession->db; SessionTable *pTo; /* Table zTbl */ /* Locate and if necessary initialize the target table object */ @@ -176355,15 +205639,16 @@ SQLITE_API int sqlite3session_diff( int i; for(i=0; i<nCol; i++){ if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1; - if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1; + if( tdsqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1; if( abPK[i] ) bHasPk = 1; } } - } - sqlite3_free((char*)azCol); + tdsqlite3_free((char*)azCol); if( bMismatch ){ - *pzErrMsg = sqlite3_mprintf("table schemas do not match"); + if( pzErrMsg ){ + *pzErrMsg = tdsqlite3_mprintf("table schemas do not match"); + } rc = SQLITE_SCHEMA; } if( bHasPk==0 ){ @@ -176393,12 +205678,12 @@ SQLITE_API int sqlite3session_diff( rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr); } - sqlite3_free(zExpr); + tdsqlite3_free(zExpr); } diff_out: sessionPreupdateHooks(pSession); - sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_leave(tdsqlite3_db_mutex(pSession->db)); return rc; } @@ -176406,22 +205691,22 @@ SQLITE_API int sqlite3session_diff( ** Create a session object. This session object will record changes to ** database zDb attached to connection db. */ -SQLITE_API int sqlite3session_create( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3session_create( + tdsqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (e.g. "main") */ - sqlite3_session **ppSession /* OUT: New session object */ + tdsqlite3_session **ppSession /* OUT: New session object */ ){ - sqlite3_session *pNew; /* Newly allocated session object */ - sqlite3_session *pOld; /* Session object already attached to db */ - int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */ + tdsqlite3_session *pNew; /* Newly allocated session object */ + tdsqlite3_session *pOld; /* Session object already attached to db */ + int nDb = tdsqlite3Strlen30(zDb); /* Length of zDb in bytes */ /* Zero the output value in case an error occurs. */ *ppSession = 0; /* Allocate and populate the new session object. */ - pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1); + pNew = (tdsqlite3_session *)tdsqlite3_malloc64(sizeof(tdsqlite3_session) + nDb + 1); if( !pNew ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(sqlite3_session)); + memset(pNew, 0, sizeof(tdsqlite3_session)); pNew->db = db; pNew->zDb = (char *)&pNew[1]; pNew->bEnable = 1; @@ -176431,10 +205716,10 @@ SQLITE_API int sqlite3session_create( /* Add the new session object to the linked list of session objects ** attached to database handle $db. Do this under the cover of the db ** handle mutex. */ - sqlite3_mutex_enter(sqlite3_db_mutex(db)); - pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew); + tdsqlite3_mutex_enter(tdsqlite3_db_mutex(db)); + pOld = (tdsqlite3_session*)tdsqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew); pNew->pNext = pOld; - sqlite3_mutex_leave(sqlite3_db_mutex(db)); + tdsqlite3_mutex_leave(tdsqlite3_db_mutex(db)); *ppSession = pNew; return SQLITE_OK; @@ -176456,49 +205741,50 @@ static void sessionDeleteTable(SessionTable *pList){ SessionChange *pNextChange; for(p=pTab->apChange[i]; p; p=pNextChange){ pNextChange = p->pNext; - sqlite3_free(p); + tdsqlite3_free(p); } } - sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */ - sqlite3_free(pTab->apChange); - sqlite3_free(pTab); + tdsqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */ + tdsqlite3_free(pTab->apChange); + tdsqlite3_free(pTab); } } /* -** Delete a session object previously allocated using sqlite3session_create(). +** Delete a session object previously allocated using tdsqlite3session_create(). */ -SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){ - sqlite3 *db = pSession->db; - sqlite3_session *pHead; - sqlite3_session **pp; +SQLITE_API void tdsqlite3session_delete(tdsqlite3_session *pSession){ + tdsqlite3 *db = pSession->db; + tdsqlite3_session *pHead; + tdsqlite3_session **pp; /* Unlink the session from the linked list of sessions attached to the ** database handle. Hold the db mutex while doing so. */ - sqlite3_mutex_enter(sqlite3_db_mutex(db)); - pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0); + tdsqlite3_mutex_enter(tdsqlite3_db_mutex(db)); + pHead = (tdsqlite3_session*)tdsqlite3_preupdate_hook(db, 0, 0); for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){ if( (*pp)==pSession ){ *pp = (*pp)->pNext; - if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead); + if( pHead ) tdsqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead); break; } } - sqlite3_mutex_leave(sqlite3_db_mutex(db)); + tdsqlite3_mutex_leave(tdsqlite3_db_mutex(db)); + tdsqlite3ValueFree(pSession->pZeroBlob); /* Delete all attached table objects. And the contents of their ** associated hash-tables. */ sessionDeleteTable(pSession->pTable); /* Free the session object itself. */ - sqlite3_free(pSession); + tdsqlite3_free(pSession); } /* ** Set a table filter on a Session Object. */ -SQLITE_API void sqlite3session_table_filter( - sqlite3_session *pSession, +SQLITE_API void tdsqlite3session_table_filter( + tdsqlite3_session *pSession, int(*xFilter)(void*, const char*), void *pCtx /* First argument passed to xFilter */ ){ @@ -176515,12 +205801,12 @@ SQLITE_API void sqlite3session_table_filter( ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) ** or not. */ -SQLITE_API int sqlite3session_attach( - sqlite3_session *pSession, /* Session object */ +SQLITE_API int tdsqlite3session_attach( + tdsqlite3_session *pSession, /* Session object */ const char *zName /* Table name */ ){ int rc = SQLITE_OK; - sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_enter(tdsqlite3_db_mutex(pSession->db)); if( !zName ){ pSession->bAutoAttach = 1; @@ -176530,14 +205816,14 @@ SQLITE_API int sqlite3session_attach( /* First search for an existing entry. If one is found, this call is ** a no-op. Return early. */ - nName = sqlite3Strlen30(zName); + nName = tdsqlite3Strlen30(zName); for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){ - if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break; + if( 0==tdsqlite3_strnicmp(pTab->zName, zName, nName+1) ) break; } if( !pTab ){ /* Allocate new SessionTable object. */ - pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1); + pTab = (SessionTable *)tdsqlite3_malloc64(sizeof(SessionTable) + nName + 1); if( !pTab ){ rc = SQLITE_NOMEM; }else{ @@ -176556,26 +205842,26 @@ SQLITE_API int sqlite3session_attach( } } - sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_leave(tdsqlite3_db_mutex(pSession->db)); return rc; } /* ** Ensure that there is room in the buffer to append nByte bytes of data. -** If not, use sqlite3_realloc() to grow the buffer so that there is. +** If not, use tdsqlite3_realloc() to grow the buffer so that there is. ** ** If successful, return zero. Otherwise, if an OOM condition is encountered, ** set *pRc to SQLITE_NOMEM and return non-zero. */ -static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){ - if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){ +static int sessionBufferGrow(SessionBuffer *p, size_t nByte, int *pRc){ + if( *pRc==SQLITE_OK && (size_t)(p->nAlloc-p->nBuf)<nByte ){ u8 *aNew; - int nNew = p->nAlloc ? p->nAlloc : 128; + i64 nNew = p->nAlloc ? p->nAlloc : 128; do { nNew = nNew*2; - }while( nNew<(p->nBuf+nByte) ); + }while( (size_t)(nNew-p->nBuf)<nByte ); - aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew); + aNew = (u8 *)tdsqlite3_realloc64(p->aBuf, nNew); if( 0==aNew ){ *pRc = SQLITE_NOMEM; }else{ @@ -176594,10 +205880,10 @@ static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){ ** Otherwise, if an error occurs, *pRc is set to an SQLite error code ** before returning. */ -static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){ +static void sessionAppendValue(SessionBuffer *p, tdsqlite3_value *pVal, int *pRc){ int rc = *pRc; if( rc==SQLITE_OK ){ - int nByte = 0; + tdsqlite3_int64 nByte = 0; rc = sessionSerializeValue(0, pVal, &nByte); sessionBufferGrow(p, nByte, &rc); if( rc==SQLITE_OK ){ @@ -176648,7 +205934,7 @@ static void sessionAppendBlob( int nBlob, int *pRc ){ - if( 0==sessionBufferGrow(p, nBlob, pRc) ){ + if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){ memcpy(&p->aBuf[p->nBuf], aBlob, nBlob); p->nBuf += nBlob; } @@ -176667,7 +205953,7 @@ static void sessionAppendStr( const char *zStr, int *pRc ){ - int nStr = sqlite3Strlen30(zStr); + int nStr = tdsqlite3Strlen30(zStr); if( 0==sessionBufferGrow(p, nStr, pRc) ){ memcpy(&p->aBuf[p->nBuf], zStr, nStr); p->nBuf += nStr; @@ -176688,7 +205974,7 @@ static void sessionAppendInteger( int *pRc /* IN/OUT: Error code */ ){ char aBuf[24]; - sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal); + tdsqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal); sessionAppendStr(p, aBuf, pRc); } @@ -176706,7 +205992,7 @@ static void sessionAppendIdent( const char *zStr, /* String to quote, escape and append */ int *pRc /* IN/OUT: Error code */ ){ - int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1; + int nStr = tdsqlite3Strlen30(zStr)*2 + 2 + 1; if( 0==sessionBufferGrow(p, nStr, pRc) ){ char *zOut = (char *)&p->aBuf[p->nBuf]; const char *zIn = zStr; @@ -176728,20 +206014,20 @@ static void sessionAppendIdent( */ static void sessionAppendCol( SessionBuffer *p, /* Buffer to append to */ - sqlite3_stmt *pStmt, /* Handle pointing to row containing value */ + tdsqlite3_stmt *pStmt, /* Handle pointing to row containing value */ int iCol, /* Column to read value from */ int *pRc /* IN/OUT: Error code */ ){ if( *pRc==SQLITE_OK ){ - int eType = sqlite3_column_type(pStmt, iCol); + int eType = tdsqlite3_column_type(pStmt, iCol); sessionAppendByte(p, (u8)eType, pRc); if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ - sqlite3_int64 i; + tdsqlite3_int64 i; u8 aBuf[8]; if( eType==SQLITE_INTEGER ){ - i = sqlite3_column_int64(pStmt, iCol); + i = tdsqlite3_column_int64(pStmt, iCol); }else{ - double r = sqlite3_column_double(pStmt, iCol); + double r = tdsqlite3_column_double(pStmt, iCol); memcpy(&i, &r, 8); } sessionPutI64(aBuf, i); @@ -176751,11 +206037,11 @@ static void sessionAppendCol( u8 *z; int nByte; if( eType==SQLITE_BLOB ){ - z = (u8 *)sqlite3_column_blob(pStmt, iCol); + z = (u8 *)tdsqlite3_column_blob(pStmt, iCol); }else{ - z = (u8 *)sqlite3_column_text(pStmt, iCol); + z = (u8 *)tdsqlite3_column_text(pStmt, iCol); } - nByte = sqlite3_column_bytes(pStmt, iCol); + nByte = tdsqlite3_column_bytes(pStmt, iCol); if( z || (eType==SQLITE_BLOB && nByte==0) ){ sessionAppendVarint(p, nByte, pRc); sessionAppendBlob(p, z, nByte, pRc); @@ -176791,7 +206077,7 @@ static void sessionAppendCol( static int sessionAppendUpdate( SessionBuffer *pBuf, /* Buffer to append to */ int bPatchset, /* True for "patchset", 0 for "changeset" */ - sqlite3_stmt *pStmt, /* Statement handle pointing at new row */ + tdsqlite3_stmt *pStmt, /* Statement handle pointing at new row */ SessionChange *p, /* Object containing old values */ u8 *abPK /* Boolean array - true for PK columns */ ){ @@ -176804,14 +206090,14 @@ static int sessionAppendUpdate( sessionAppendByte(pBuf, SQLITE_UPDATE, &rc); sessionAppendByte(pBuf, p->bIndirect, &rc); - for(i=0; i<sqlite3_column_count(pStmt); i++){ + for(i=0; i<tdsqlite3_column_count(pStmt); i++){ int bChanged = 0; int nAdvance; int eType = *pCsr; switch( eType ){ case SQLITE_NULL: nAdvance = 1; - if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){ + if( tdsqlite3_column_type(pStmt, i)!=SQLITE_NULL ){ bChanged = 1; } break; @@ -176819,14 +206105,14 @@ static int sessionAppendUpdate( case SQLITE_FLOAT: case SQLITE_INTEGER: { nAdvance = 9; - if( eType==sqlite3_column_type(pStmt, i) ){ - sqlite3_int64 iVal = sessionGetI64(&pCsr[1]); + if( eType==tdsqlite3_column_type(pStmt, i) ){ + tdsqlite3_int64 iVal = sessionGetI64(&pCsr[1]); if( eType==SQLITE_INTEGER ){ - if( iVal==sqlite3_column_int64(pStmt, i) ) break; + if( iVal==tdsqlite3_column_int64(pStmt, i) ) break; }else{ double dVal; memcpy(&dVal, &iVal, 8); - if( dVal==sqlite3_column_double(pStmt, i) ) break; + if( dVal==tdsqlite3_column_double(pStmt, i) ) break; } } bChanged = 1; @@ -176834,13 +206120,13 @@ static int sessionAppendUpdate( } default: { - int nByte; - int nHdr = 1 + sessionVarintGet(&pCsr[1], &nByte); + int n; + int nHdr = 1 + sessionVarintGet(&pCsr[1], &n); assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); - nAdvance = nHdr + nByte; - if( eType==sqlite3_column_type(pStmt, i) - && nByte==sqlite3_column_bytes(pStmt, i) - && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte) + nAdvance = nHdr + n; + if( eType==tdsqlite3_column_type(pStmt, i) + && n==tdsqlite3_column_bytes(pStmt, i) + && (n==0 || 0==memcmp(&pCsr[nHdr], tdsqlite3_column_blob(pStmt, i), n)) ){ break; } @@ -176877,7 +206163,7 @@ static int sessionAppendUpdate( }else{ sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc); } - sqlite3_free(buf2.aBuf); + tdsqlite3_free(buf2.aBuf); return rc; } @@ -176943,37 +206229,51 @@ static int sessionAppendDelete( ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ... */ static int sessionSelectStmt( - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ const char *zDb, /* Database name */ const char *zTab, /* Table name */ int nCol, /* Number of columns in table */ const char **azCol, /* Names of table columns */ u8 *abPK, /* PRIMARY KEY array */ - sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */ + tdsqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */ ){ int rc = SQLITE_OK; - int i; - const char *zSep = ""; - SessionBuffer buf = {0, 0, 0}; + char *zSql = 0; + int nSql = -1; - sessionAppendStr(&buf, "SELECT * FROM ", &rc); - sessionAppendIdent(&buf, zDb, &rc); - sessionAppendStr(&buf, ".", &rc); - sessionAppendIdent(&buf, zTab, &rc); - sessionAppendStr(&buf, " WHERE ", &rc); - for(i=0; i<nCol; i++){ - if( abPK[i] ){ - sessionAppendStr(&buf, zSep, &rc); - sessionAppendIdent(&buf, azCol[i], &rc); - sessionAppendStr(&buf, " = ?", &rc); - sessionAppendInteger(&buf, i+1, &rc); - zSep = " AND "; + if( 0==tdsqlite3_stricmp("sqlite_stat1", zTab) ){ + zSql = tdsqlite3_mprintf( + "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND " + "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb + ); + if( zSql==0 ) rc = SQLITE_NOMEM; + }else{ + int i; + const char *zSep = ""; + SessionBuffer buf = {0, 0, 0}; + + sessionAppendStr(&buf, "SELECT * FROM ", &rc); + sessionAppendIdent(&buf, zDb, &rc); + sessionAppendStr(&buf, ".", &rc); + sessionAppendIdent(&buf, zTab, &rc); + sessionAppendStr(&buf, " WHERE ", &rc); + for(i=0; i<nCol; i++){ + if( abPK[i] ){ + sessionAppendStr(&buf, zSep, &rc); + sessionAppendIdent(&buf, azCol[i], &rc); + sessionAppendStr(&buf, " IS ?", &rc); + sessionAppendInteger(&buf, i+1, &rc); + zSep = " AND "; + } } + zSql = (char*)buf.aBuf; + nSql = buf.nBuf; } + if( rc==SQLITE_OK ){ - rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0); + rc = tdsqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0); } - sqlite3_free(buf.aBuf); + tdsqlite3_free(zSql); return rc; } @@ -176986,7 +206286,7 @@ static int sessionSelectStmt( ** error code (e.g. SQLITE_NOMEM) otherwise. */ static int sessionSelectBind( - sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */ + tdsqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */ int nCol, /* Number of columns in table */ u8 *abPK, /* PRIMARY KEY array */ SessionChange *pChange /* Change structure */ @@ -177007,7 +206307,7 @@ static int sessionSelectBind( case SQLITE_INTEGER: { if( abPK[i] ){ i64 iVal = sessionGetI64(a); - rc = sqlite3_bind_int64(pSelect, i+1, iVal); + rc = tdsqlite3_bind_int64(pSelect, i+1, iVal); } a += 8; break; @@ -177018,7 +206318,7 @@ static int sessionSelectBind( double rVal; i64 iVal = sessionGetI64(a); memcpy(&rVal, &iVal, 8); - rc = sqlite3_bind_double(pSelect, i+1, rVal); + rc = tdsqlite3_bind_double(pSelect, i+1, rVal); } a += 8; break; @@ -177028,7 +206328,7 @@ static int sessionSelectBind( int n; a += sessionVarintGet(a, &n); if( abPK[i] ){ - rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT); + rc = tdsqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT); } a += n; break; @@ -177039,7 +206339,7 @@ static int sessionSelectBind( assert( eType==SQLITE_BLOB ); a += sessionVarintGet(a, &n); if( abPK[i] ){ - rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT); + rc = tdsqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT); } a += n; break; @@ -177080,14 +206380,14 @@ static void sessionAppendTableHdr( ** to 0. */ static int sessionGenerateChangeset( - sqlite3_session *pSession, /* Session object */ + tdsqlite3_session *pSession, /* Session object */ int bPatchset, /* True for patchset, false for changeset */ int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut, /* First argument for xOutput */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ){ - sqlite3 *db = pSession->db; /* Source database handle */ + tdsqlite3 *db = pSession->db; /* Source database handle */ SessionTable *pTab; /* Used to iterate through attached tables */ SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */ int rc; /* Return code */ @@ -177095,7 +206395,7 @@ static int sessionGenerateChangeset( assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) ); /* Zero the output variables in case an error occurs. If this session - ** object is already in the error state (sqlite3_session.rc != SQLITE_OK), + ** object is already in the error state (tdsqlite3_session.rc != SQLITE_OK), ** this call will be a no-op. */ if( xOutput==0 ){ *pnChangeset = 0; @@ -177103,10 +206403,10 @@ static int sessionGenerateChangeset( } if( pSession->rc ) return pSession->rc; - rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0); + rc = tdsqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0); if( rc!=SQLITE_OK ) return rc; - sqlite3_mutex_enter(sqlite3_db_mutex(db)); + tdsqlite3_mutex_enter(tdsqlite3_db_mutex(db)); for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){ if( pTab->nEntry ){ @@ -177115,7 +206415,7 @@ static int sessionGenerateChangeset( u8 *abPK; /* Primary key array */ const char **azCol = 0; /* Table columns */ int i; /* Used to iterate through hash buckets */ - sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */ + tdsqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */ int nRewind = buf.nBuf; /* Initial size of write buffer */ int nNoop; /* Size of buffer after writing tbl header */ @@ -177141,7 +206441,7 @@ static int sessionGenerateChangeset( for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){ rc = sessionSelectBind(pSel, nCol, abPK, p); if( rc!=SQLITE_OK ) continue; - if( sqlite3_step(pSel)==SQLITE_ROW ){ + if( tdsqlite3_step(pSel)==SQLITE_ROW ){ if( p->op==SQLITE_INSERT ){ int iCol; sessionAppendByte(&buf, SQLITE_INSERT, &rc); @@ -177156,15 +206456,15 @@ static int sessionGenerateChangeset( rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK); } if( rc==SQLITE_OK ){ - rc = sqlite3_reset(pSel); + rc = tdsqlite3_reset(pSel); } - /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass + /* If the buffer is now larger than sessions_strm_chunk_size, pass ** its contents to the xOutput() callback. */ if( xOutput && rc==SQLITE_OK && buf.nBuf>nNoop - && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE + && buf.nBuf>sessions_strm_chunk_size ){ rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf); nNoop = -1; @@ -177174,11 +206474,11 @@ static int sessionGenerateChangeset( } } - sqlite3_finalize(pSel); + tdsqlite3_finalize(pSel); if( buf.nBuf==nNoop ){ buf.nBuf = nRewind; } - sqlite3_free((char*)azCol); /* cast works around VC++ bug */ + tdsqlite3_free((char*)azCol); /* cast works around VC++ bug */ } } @@ -177192,9 +206492,9 @@ static int sessionGenerateChangeset( } } - sqlite3_free(buf.aBuf); - sqlite3_exec(db, "RELEASE changeset", 0, 0, 0); - sqlite3_mutex_leave(sqlite3_db_mutex(db)); + tdsqlite3_free(buf.aBuf); + tdsqlite3_exec(db, "RELEASE changeset", 0, 0, 0); + tdsqlite3_mutex_leave(tdsqlite3_db_mutex(db)); return rc; } @@ -177203,10 +206503,10 @@ static int sessionGenerateChangeset( ** session object passed as the first argument. ** ** It is the responsibility of the caller to eventually free the buffer -** using sqlite3_free(). +** using tdsqlite3_free(). */ -SQLITE_API int sqlite3session_changeset( - sqlite3_session *pSession, /* Session object */ +SQLITE_API int tdsqlite3session_changeset( + tdsqlite3_session *pSession, /* Session object */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ){ @@ -177214,10 +206514,10 @@ SQLITE_API int sqlite3session_changeset( } /* -** Streaming version of sqlite3session_changeset(). +** Streaming version of tdsqlite3session_changeset(). */ -SQLITE_API int sqlite3session_changeset_strm( - sqlite3_session *pSession, +SQLITE_API int tdsqlite3session_changeset_strm( + tdsqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ){ @@ -177225,10 +206525,10 @@ SQLITE_API int sqlite3session_changeset_strm( } /* -** Streaming version of sqlite3session_patchset(). +** Streaming version of tdsqlite3session_patchset(). */ -SQLITE_API int sqlite3session_patchset_strm( - sqlite3_session *pSession, +SQLITE_API int tdsqlite3session_patchset_strm( + tdsqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ){ @@ -177240,10 +206540,10 @@ SQLITE_API int sqlite3session_patchset_strm( ** session object passed as the first argument. ** ** It is the responsibility of the caller to eventually free the buffer -** using sqlite3_free(). +** using tdsqlite3_free(). */ -SQLITE_API int sqlite3session_patchset( - sqlite3_session *pSession, /* Session object */ +SQLITE_API int tdsqlite3session_patchset( + tdsqlite3_session *pSession, /* Session object */ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ void **ppPatchset /* OUT: Buffer containing changeset */ ){ @@ -177253,28 +206553,28 @@ SQLITE_API int sqlite3session_patchset( /* ** Enable or disable the session object passed as the first argument. */ -SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){ +SQLITE_API int tdsqlite3session_enable(tdsqlite3_session *pSession, int bEnable){ int ret; - sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_enter(tdsqlite3_db_mutex(pSession->db)); if( bEnable>=0 ){ pSession->bEnable = bEnable; } ret = pSession->bEnable; - sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_leave(tdsqlite3_db_mutex(pSession->db)); return ret; } /* ** Enable or disable the session object passed as the first argument. */ -SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){ +SQLITE_API int tdsqlite3session_indirect(tdsqlite3_session *pSession, int bIndirect){ int ret; - sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_enter(tdsqlite3_db_mutex(pSession->db)); if( bIndirect>=0 ){ pSession->bIndirect = bIndirect; } ret = pSession->bIndirect; - sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_leave(tdsqlite3_db_mutex(pSession->db)); return ret; } @@ -177282,30 +206582,31 @@ SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect) ** Return true if there have been no changes to monitored tables recorded ** by the session object passed as the only argument. */ -SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){ +SQLITE_API int tdsqlite3session_isempty(tdsqlite3_session *pSession){ int ret = 0; SessionTable *pTab; - sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_enter(tdsqlite3_db_mutex(pSession->db)); for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){ ret = (pTab->nEntry>0); } - sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db)); + tdsqlite3_mutex_leave(tdsqlite3_db_mutex(pSession->db)); return (ret==0); } /* -** Do the work for either sqlite3changeset_start() or start_strm(). +** Do the work for either tdsqlite3changeset_start() or start_strm(). */ static int sessionChangesetStart( - sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ + tdsqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int nChangeset, /* Size of buffer pChangeset in bytes */ - void *pChangeset /* Pointer to buffer containing changeset */ + void *pChangeset, /* Pointer to buffer containing changeset */ + int bInvert /* True to invert changeset */ ){ - sqlite3_changeset_iter *pRet; /* Iterator to return */ + tdsqlite3_changeset_iter *pRet; /* Iterator to return */ int nByte; /* Number of bytes to allocate for iterator */ assert( xInput==0 || (pChangeset==0 && nChangeset==0) ); @@ -177314,15 +206615,16 @@ static int sessionChangesetStart( *pp = 0; /* Allocate and initialize the iterator structure. */ - nByte = sizeof(sqlite3_changeset_iter); - pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte); + nByte = sizeof(tdsqlite3_changeset_iter); + pRet = (tdsqlite3_changeset_iter *)tdsqlite3_malloc(nByte); if( !pRet ) return SQLITE_NOMEM; - memset(pRet, 0, sizeof(sqlite3_changeset_iter)); + memset(pRet, 0, sizeof(tdsqlite3_changeset_iter)); pRet->in.aData = (u8 *)pChangeset; pRet->in.nData = nChangeset; pRet->in.xInput = xInput; pRet->in.pIn = pIn; pRet->in.bEof = (xInput ? 0 : 1); + pRet->bInvert = bInvert; /* Populate the output variable and return success. */ *pp = pRet; @@ -177332,23 +206634,41 @@ static int sessionChangesetStart( /* ** Create an iterator used to iterate through the contents of a changeset. */ -SQLITE_API int sqlite3changeset_start( - sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ +SQLITE_API int tdsqlite3changeset_start( + tdsqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ int nChangeset, /* Size of buffer pChangeset in bytes */ void *pChangeset /* Pointer to buffer containing changeset */ ){ - return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset); + return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0); +} +SQLITE_API int tdsqlite3changeset_start_v2( + tdsqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ + int nChangeset, /* Size of buffer pChangeset in bytes */ + void *pChangeset, /* Pointer to buffer containing changeset */ + int flags +){ + int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT); + return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert); } /* -** Streaming version of sqlite3changeset_start(). +** Streaming version of tdsqlite3changeset_start(). */ -SQLITE_API int sqlite3changeset_start_strm( - sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ +SQLITE_API int tdsqlite3changeset_start_strm( + tdsqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ){ - return sessionChangesetStart(pp, xInput, pIn, 0, 0); + return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0); +} +SQLITE_API int tdsqlite3changeset_start_v2_strm( + tdsqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int flags +){ + int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT); + return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert); } /* @@ -177356,7 +206676,7 @@ SQLITE_API int sqlite3changeset_start_strm( ** object and the buffer is full, discard some data to free up space. */ static void sessionDiscardData(SessionInput *pIn){ - if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){ + if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){ int nMove = pIn->buf.nBuf - pIn->iNext; assert( nMove>=0 ); if( nMove>0 ){ @@ -177379,7 +206699,7 @@ static int sessionInputBuffer(SessionInput *pIn, int nByte){ int rc = SQLITE_OK; if( pIn->xInput ){ while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){ - int nNew = SESSIONS_STRM_CHUNK_SIZE; + int nNew = sessions_strm_chunk_size; if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn); if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){ @@ -177424,25 +206744,25 @@ static void sessionSkipRecord( } /* -** This function sets the value of the sqlite3_value object passed as the +** This function sets the value of the tdsqlite3_value object passed as the ** first argument to a copy of the string or blob held in the aData[] ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM ** error occurs. */ static int sessionValueSetStr( - sqlite3_value *pVal, /* Set the value of this object */ + tdsqlite3_value *pVal, /* Set the value of this object */ u8 *aData, /* Buffer containing string or blob data */ int nData, /* Size of buffer aData[] in bytes */ u8 enc /* String encoding (0 for blobs) */ ){ /* In theory this code could just pass SQLITE_TRANSIENT as the final - ** argument to sqlite3ValueSetStr() and have the copy created + ** argument to tdsqlite3ValueSetStr() and have the copy created ** automatically. But doing so makes it difficult to detect any OOM ** error. Hence the code to create the copy externally. */ - u8 *aCopy = sqlite3_malloc(nData+1); + u8 *aCopy = tdsqlite3_malloc64((tdsqlite3_int64)nData+1); if( aCopy==0 ) return SQLITE_NOMEM; memcpy(aCopy, aData, nData); - sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free); + tdsqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, tdsqlite3_free); return SQLITE_OK; } @@ -177458,14 +206778,14 @@ static int sessionValueSetStr( ** (in other words, it is a patchset DELETE record). ** ** If successful, each element of the apOut[] array (allocated by the caller) -** is set to point to an sqlite3_value object containing the value read +** is set to point to an tdsqlite3_value object containing the value read ** from the corresponding position in the record. If that value is not ** included in the record (i.e. because the record is part of an UPDATE change ** and the field was not modified), the corresponding element of apOut[] is ** set to NULL. ** ** It is the responsibility of the caller to free all sqlite_value structures -** using sqlite3_free(). +** using tdsqlite3_free(). ** ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. ** The apOut[] array may have been partially populated in this case. @@ -177474,7 +206794,7 @@ static int sessionReadRecord( SessionInput *pIn, /* Input data */ int nCol, /* Number of values in record */ u8 *abPK, /* Array of primary key flags, or NULL */ - sqlite3_value **apOut /* Write values to this array */ + tdsqlite3_value **apOut /* Write values to this array */ ){ int i; /* Used to iterate through columns */ int rc = SQLITE_OK; @@ -177484,13 +206804,16 @@ static int sessionReadRecord( if( abPK && abPK[i]==0 ) continue; rc = sessionInputBuffer(pIn, 9); if( rc==SQLITE_OK ){ - eType = pIn->aData[pIn->iNext++]; - } - - assert( apOut[i]==0 ); - if( eType ){ - apOut[i] = sqlite3ValueNew(0); - if( !apOut[i] ) rc = SQLITE_NOMEM; + if( pIn->iNext>=pIn->nData ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + eType = pIn->aData[pIn->iNext++]; + assert( apOut[i]==0 ); + if( eType ){ + apOut[i] = tdsqlite3ValueNew(0); + if( !apOut[i] ) rc = SQLITE_NOMEM; + } + } } if( rc==SQLITE_OK ){ @@ -177500,19 +206823,23 @@ static int sessionReadRecord( pIn->iNext += sessionVarintGet(aVal, &nByte); rc = sessionInputBuffer(pIn, nByte); if( rc==SQLITE_OK ){ - u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0); - rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc); + if( nByte<0 || nByte>pIn->nData-pIn->iNext ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0); + rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc); + pIn->iNext += nByte; + } } - pIn->iNext += nByte; } if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ - sqlite3_int64 v = sessionGetI64(aVal); + tdsqlite3_int64 v = sessionGetI64(aVal); if( eType==SQLITE_INTEGER ){ - sqlite3VdbeMemSetInt64(apOut[i], v); + tdsqlite3VdbeMemSetInt64(apOut[i], v); }else{ double d; memcpy(&d, &v, 8); - sqlite3VdbeMemSetDouble(apOut[i], d); + tdsqlite3VdbeMemSetDouble(apOut[i], d); } pIn->iNext += 8; } @@ -177543,8 +206870,19 @@ static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){ rc = sessionInputBuffer(pIn, 9); if( rc==SQLITE_OK ){ nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol); - rc = sessionInputBuffer(pIn, nRead+nCol+100); - nRead += nCol; + /* The hard upper limit for the number of columns in an SQLite + ** database table is, according to sqliteLimit.h, 32676. So + ** consider any table-header that purports to have more than 65536 + ** columns to be corrupt. This is convenient because otherwise, + ** if the (nCol>65536) condition below were omitted, a sufficiently + ** large value for nCol may cause nRead to wrap around and become + ** negative. Leading to a crash. */ + if( nCol<0 || nCol>65536 ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = sessionInputBuffer(pIn, nRead+nCol+100); + nRead += nCol; + } } while( rc==SQLITE_OK ){ @@ -177611,7 +206949,7 @@ static int sessionChangesetBufferRecord( ** is returned and the final values of the various fields enumerated above ** are undefined. */ -static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){ +static int sessionChangesetReadTblhdr(tdsqlite3_changeset_iter *p){ int rc; int nCopy; assert( p->rc==SQLITE_OK ); @@ -177621,21 +206959,25 @@ static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){ int nByte; int nVarint; nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol); - nCopy -= nVarint; - p->in.iNext += nVarint; - nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy; - p->tblhdr.nBuf = 0; - sessionBufferGrow(&p->tblhdr, nByte, &rc); + if( p->nCol>0 ){ + nCopy -= nVarint; + p->in.iNext += nVarint; + nByte = p->nCol * sizeof(tdsqlite3_value*) * 2 + nCopy; + p->tblhdr.nBuf = 0; + sessionBufferGrow(&p->tblhdr, nByte, &rc); + }else{ + rc = SQLITE_CORRUPT_BKPT; + } } if( rc==SQLITE_OK ){ - int iPK = sizeof(sqlite3_value*)*p->nCol*2; + size_t iPK = sizeof(tdsqlite3_value*)*p->nCol*2; memset(p->tblhdr.aBuf, 0, iPK); memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy); p->in.iNext += nCopy; } - p->apValue = (sqlite3_value**)p->tblhdr.aBuf; + p->apValue = (tdsqlite3_value**)p->tblhdr.aBuf; p->abPK = (u8*)&p->apValue[p->nCol*2]; p->zTab = (char*)&p->abPK[p->nCol]; return (p->rc = rc); @@ -177645,8 +206987,8 @@ static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){ ** Advance the changeset iterator to the next change. ** ** If both paRec and pnRec are NULL, then this function works like the public -** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the -** sqlite3changeset_new() and old() APIs may be used to query for values. +** API tdsqlite3changeset_next(). If SQLITE_ROW is returned, then the +** tdsqlite3changeset_new() and old() APIs may be used to query for values. ** ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change ** record is written to *paRec before returning and the number of bytes in @@ -177658,9 +207000,10 @@ static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){ ** changes in the changeset. */ static int sessionChangesetNext( - sqlite3_changeset_iter *p, /* Changeset iterator */ + tdsqlite3_changeset_iter *p, /* Changeset iterator */ u8 **paRec, /* If non-NULL, store record pointer here */ - int *pnRec /* If non-NULL, store size of record here */ + int *pnRec, /* If non-NULL, store size of record here */ + int *pbNew /* If non-NULL, true if new table */ ){ int i; u8 op; @@ -177673,9 +207016,9 @@ static int sessionChangesetNext( /* Free the current contents of p->apValue[], if any. */ if( p->apValue ){ for(i=0; i<p->nCol*2; i++){ - sqlite3ValueFree(p->apValue[i]); + tdsqlite3ValueFree(p->apValue[i]); } - memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2); + memset(p->apValue, 0, sizeof(tdsqlite3_value*)*p->nCol*2); } /* Make sure the buffer contains at least 10 bytes of input data, or all @@ -177694,14 +207037,23 @@ static int sessionChangesetNext( p->in.iCurrent = p->in.iNext; op = p->in.aData[p->in.iNext++]; - if( op=='T' || op=='P' ){ + while( op=='T' || op=='P' ){ + if( pbNew ) *pbNew = 1; p->bPatchset = (op=='P'); if( sessionChangesetReadTblhdr(p) ) return p->rc; if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc; p->in.iCurrent = p->in.iNext; + if( p->in.iNext>=p->in.nData ) return SQLITE_DONE; op = p->in.aData[p->in.iNext++]; } + if( p->zTab==0 || (p->bPatchset && p->bInvert) ){ + /* The first record in the changeset is not a table header. Must be a + ** corrupt changeset. */ + assert( p->in.iNext==1 || p->zTab ); + return (p->rc = SQLITE_CORRUPT_BKPT); + } + p->op = op; p->bIndirect = p->in.aData[p->in.iNext++]; if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){ @@ -177723,33 +207075,39 @@ static int sessionChangesetNext( *paRec = &p->in.aData[p->in.iNext]; p->in.iNext += *pnRec; }else{ + tdsqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue); + tdsqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]); /* If this is an UPDATE or DELETE, read the old.* record. */ if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){ u8 *abPK = p->bPatchset ? p->abPK : 0; - p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue); + p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld); if( p->rc!=SQLITE_OK ) return p->rc; } /* If this is an INSERT or UPDATE, read the new.* record. */ if( p->op!=SQLITE_DELETE ){ - p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]); + p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew); if( p->rc!=SQLITE_OK ) return p->rc; } - if( p->bPatchset && p->op==SQLITE_UPDATE ){ + if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){ /* If this is an UPDATE that is part of a patchset, then all PK and ** modified fields are present in the new.* record. The old.* record ** is currently completely empty. This block shifts the PK fields from ** new.* to old.*, to accommodate the code that reads these arrays. */ for(i=0; i<p->nCol; i++){ - assert( p->apValue[i]==0 ); - assert( p->abPK[i]==0 || p->apValue[i+p->nCol] ); + assert( p->bPatchset==0 || p->apValue[i]==0 ); if( p->abPK[i] ){ + assert( p->apValue[i]==0 ); p->apValue[i] = p->apValue[i+p->nCol]; + if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT); p->apValue[i+p->nCol] = 0; } } + }else if( p->bInvert ){ + if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE; + else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT; } } @@ -177757,15 +207115,15 @@ static int sessionChangesetNext( } /* -** Advance an iterator created by sqlite3changeset_start() to the next +** Advance an iterator created by tdsqlite3changeset_start() to the next ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE ** or SQLITE_CORRUPT. ** ** This function may not be called on iterators passed to a conflict handler ** callback by changeset_apply(). */ -SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){ - return sessionChangesetNext(p, 0, 0); +SQLITE_API int tdsqlite3changeset_next(tdsqlite3_changeset_iter *p){ + return sessionChangesetNext(p, 0, 0, 0); } /* @@ -177773,8 +207131,8 @@ SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){ ** from a changeset iterator. It may only be called after changeset_next() ** has returned SQLITE_ROW. */ -SQLITE_API int sqlite3changeset_op( - sqlite3_changeset_iter *pIter, /* Iterator handle */ +SQLITE_API int tdsqlite3changeset_op( + tdsqlite3_changeset_iter *pIter, /* Iterator handle */ const char **pzTab, /* OUT: Pointer to table name */ int *pnCol, /* OUT: Number of columns in table */ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ @@ -177793,8 +207151,8 @@ SQLITE_API int sqlite3changeset_op( ** to. This function may only be called after changeset_next() returns ** SQLITE_ROW. */ -SQLITE_API int sqlite3changeset_pk( - sqlite3_changeset_iter *pIter, /* Iterator object */ +SQLITE_API int tdsqlite3changeset_pk( + tdsqlite3_changeset_iter *pIter, /* Iterator object */ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ int *pnCol /* OUT: Number of entries in output array */ ){ @@ -177805,10 +207163,10 @@ SQLITE_API int sqlite3changeset_pk( /* ** This function may only be called while the iterator is pointing to an -** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()). +** SQLITE_UPDATE or SQLITE_DELETE change (see tdsqlite3changeset_op()). ** Otherwise, SQLITE_MISUSE is returned. ** -** It sets *ppValue to point to an sqlite3_value structure containing the +** It sets *ppValue to point to an tdsqlite3_value structure containing the ** iVal'th value in the old.* record. Or, if that particular value is not ** included in the record (because the change is an UPDATE and the field ** was not modified and is not a PK column), set *ppValue to NULL. @@ -177816,10 +207174,10 @@ SQLITE_API int sqlite3changeset_pk( ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is ** not modified. Otherwise, SQLITE_OK. */ -SQLITE_API int sqlite3changeset_old( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_old( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Index of old.* value to retrieve */ - sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ + tdsqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ ){ if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){ return SQLITE_MISUSE; @@ -177833,10 +207191,10 @@ SQLITE_API int sqlite3changeset_old( /* ** This function may only be called while the iterator is pointing to an -** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()). +** SQLITE_UPDATE or SQLITE_INSERT change (see tdsqlite3changeset_op()). ** Otherwise, SQLITE_MISUSE is returned. ** -** It sets *ppValue to point to an sqlite3_value structure containing the +** It sets *ppValue to point to an tdsqlite3_value structure containing the ** iVal'th value in the new.* record. Or, if that particular value is not ** included in the record (because the change is an UPDATE and the field ** was not modified), set *ppValue to NULL. @@ -177844,10 +207202,10 @@ SQLITE_API int sqlite3changeset_old( ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is ** not modified. Otherwise, SQLITE_OK. */ -SQLITE_API int sqlite3changeset_new( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_new( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Index of new.* value to retrieve */ - sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ + tdsqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ ){ if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){ return SQLITE_MISUSE; @@ -177861,7 +207219,7 @@ SQLITE_API int sqlite3changeset_new( /* ** The following two macros are used internally. They are similar to the -** sqlite3changeset_new() and sqlite3changeset_old() functions, except that +** tdsqlite3changeset_new() and tdsqlite3changeset_old() functions, except that ** they omit all error checking and return a pointer to the requested value. */ #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)] @@ -177872,24 +207230,24 @@ SQLITE_API int sqlite3changeset_new( ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned. ** -** If successful, *ppValue is set to point to an sqlite3_value structure +** If successful, *ppValue is set to point to an tdsqlite3_value structure ** containing the iVal'th value of the conflicting record. ** ** If value iVal is out-of-range or some other error occurs, an SQLite error ** code is returned. Otherwise, SQLITE_OK. */ -SQLITE_API int sqlite3changeset_conflict( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_conflict( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Index of conflict record value to fetch */ - sqlite3_value **ppValue /* OUT: Value from conflicting row */ + tdsqlite3_value **ppValue /* OUT: Value from conflicting row */ ){ if( !pIter->pConflict ){ return SQLITE_MISUSE; } - if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){ + if( iVal<0 || iVal>=pIter->nCol ){ return SQLITE_RANGE; } - *ppValue = sqlite3_column_value(pIter->pConflict, iVal); + *ppValue = tdsqlite3_column_value(pIter->pConflict, iVal); return SQLITE_OK; } @@ -177901,8 +207259,8 @@ SQLITE_API int sqlite3changeset_conflict( ** ** In all other cases this function returns SQLITE_MISUSE. */ -SQLITE_API int sqlite3changeset_fk_conflicts( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_fk_conflicts( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int *pnOut /* OUT: Number of FK violations */ ){ if( pIter->pConflict || pIter->apValue ){ @@ -177914,22 +207272,22 @@ SQLITE_API int sqlite3changeset_fk_conflicts( /* -** Finalize an iterator allocated with sqlite3changeset_start(). +** Finalize an iterator allocated with tdsqlite3changeset_start(). ** ** This function may not be called on iterators passed to a conflict handler ** callback by changeset_apply(). */ -SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){ +SQLITE_API int tdsqlite3changeset_finalize(tdsqlite3_changeset_iter *p){ int rc = SQLITE_OK; if( p ){ int i; /* Used to iterate through p->apValue[] */ rc = p->rc; if( p->apValue ){ - for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]); + for(i=0; i<p->nCol*2; i++) tdsqlite3ValueFree(p->apValue[i]); } - sqlite3_free(p->tblhdr.aBuf); - sqlite3_free(p->in.buf.aBuf); - sqlite3_free(p); + tdsqlite3_free(p->tblhdr.aBuf); + tdsqlite3_free(p->in.buf.aBuf); + tdsqlite3_free(p); } return rc; } @@ -177945,7 +207303,7 @@ static int sessionChangesetInvert( SessionBuffer sOut; /* Output buffer */ int nCol = 0; /* Number of cols in current table */ u8 *abPK = 0; /* PK array for current table */ - sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */ + tdsqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */ SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */ /* Initialize the output buffer */ @@ -177988,7 +207346,7 @@ static int sessionChangesetInvert( if( rc ) goto finished_invert; pInput->iNext += nByte; - sqlite3_free(apVal); + tdsqlite3_free(apVal); apVal = 0; abPK = sPK.aBuf; break; @@ -178014,7 +207372,7 @@ static int sessionChangesetInvert( int iCol; if( 0==apVal ){ - apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2); + apVal = (tdsqlite3_value **)tdsqlite3_malloc64(sizeof(apVal[0])*nCol*2); if( 0==apVal ){ rc = SQLITE_NOMEM; goto finished_invert; @@ -178037,7 +207395,7 @@ static int sessionChangesetInvert( ** original old.* record, and the other values from the original ** new.* record. */ for(iCol=0; iCol<nCol; iCol++){ - sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)]; + tdsqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)]; sessionAppendValue(&sOut, pVal, &rc); } @@ -178045,12 +207403,12 @@ static int sessionChangesetInvert( ** from the original old.* record, except for the PK columns, which ** are set to "undefined". */ for(iCol=0; iCol<nCol; iCol++){ - sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]); + tdsqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]); sessionAppendValue(&sOut, pVal, &rc); } for(iCol=0; iCol<nCol*2; iCol++){ - sqlite3ValueFree(apVal[iCol]); + tdsqlite3ValueFree(apVal[iCol]); } memset(apVal, 0, sizeof(apVal[0])*nCol*2); if( rc!=SQLITE_OK ){ @@ -178066,7 +207424,7 @@ static int sessionChangesetInvert( } assert( rc==SQLITE_OK ); - if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){ + if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){ rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); sOut.nBuf = 0; if( rc!=SQLITE_OK ) goto finished_invert; @@ -178083,9 +207441,9 @@ static int sessionChangesetInvert( } finished_invert: - sqlite3_free(sOut.aBuf); - sqlite3_free(apVal); - sqlite3_free(sPK.aBuf); + tdsqlite3_free(sOut.aBuf); + tdsqlite3_free(apVal); + tdsqlite3_free(sPK.aBuf); return rc; } @@ -178093,7 +207451,7 @@ static int sessionChangesetInvert( /* ** Invert a changeset object. */ -SQLITE_API int sqlite3changeset_invert( +SQLITE_API int tdsqlite3changeset_invert( int nChangeset, /* Number of bytes in input */ const void *pChangeset, /* Input changeset */ int *pnInverted, /* OUT: Number of bytes in output changeset */ @@ -178110,9 +207468,9 @@ SQLITE_API int sqlite3changeset_invert( } /* -** Streaming version of sqlite3changeset_invert(). +** Streaming version of tdsqlite3changeset_invert(). */ -SQLITE_API int sqlite3changeset_invert_strm( +SQLITE_API int tdsqlite3changeset_invert_strm( int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), @@ -178127,23 +207485,26 @@ SQLITE_API int sqlite3changeset_invert_strm( sInput.pIn = pIn; rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0); - sqlite3_free(sInput.buf.aBuf); + tdsqlite3_free(sInput.buf.aBuf); return rc; } typedef struct SessionApplyCtx SessionApplyCtx; struct SessionApplyCtx { - sqlite3 *db; - sqlite3_stmt *pDelete; /* DELETE statement */ - sqlite3_stmt *pUpdate; /* UPDATE statement */ - sqlite3_stmt *pInsert; /* INSERT statement */ - sqlite3_stmt *pSelect; /* SELECT statement */ + tdsqlite3 *db; + tdsqlite3_stmt *pDelete; /* DELETE statement */ + tdsqlite3_stmt *pUpdate; /* UPDATE statement */ + tdsqlite3_stmt *pInsert; /* INSERT statement */ + tdsqlite3_stmt *pSelect; /* SELECT statement */ int nCol; /* Size of azCol[] and abPK[] arrays */ const char **azCol; /* Array of column names */ u8 *abPK; /* Boolean array - true if column is in PK */ - + int bStat1; /* True if table is sqlite_stat1 */ int bDeferConstraints; /* True to defer constraints */ SessionBuffer constraints; /* Deferred constraints are stored here */ + SessionBuffer rebase; /* Rebase information (if any) here */ + u8 bRebaseStarted; /* If table header is already in rebase */ + u8 bRebase; /* True to collect rebase information */ }; /* @@ -178164,7 +207525,7 @@ struct SessionApplyCtx { ** pointing to the prepared version of the SQL statement. */ static int sessionDeleteRow( - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ const char *zTab, /* Table name */ SessionApplyCtx *p /* Session changeset-apply context */ ){ @@ -178208,9 +207569,9 @@ static int sessionDeleteRow( } if( rc==SQLITE_OK ){ - rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0); + rc = tdsqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0); } - sqlite3_free(buf.aBuf); + tdsqlite3_free(buf.aBuf); return rc; } @@ -178247,7 +207608,7 @@ static int sessionDeleteRow( ** pointing to the prepared version of the SQL statement. */ static int sessionUpdateRow( - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ const char *zTab, /* Table name */ SessionApplyCtx *p /* Session changeset-apply context */ ){ @@ -178304,13 +207665,14 @@ static int sessionUpdateRow( sessionAppendStr(&buf, ")", &rc); if( rc==SQLITE_OK ){ - rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0); + rc = tdsqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0); } - sqlite3_free(buf.aBuf); + tdsqlite3_free(buf.aBuf); return rc; } + /* ** Formulate and prepare an SQL statement to query table zTab by primary ** key. Assuming the following table structure: @@ -178325,7 +207687,7 @@ static int sessionUpdateRow( ** pointing to the prepared version of the SQL statement. */ static int sessionSelectRow( - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ const char *zTab, /* Table name */ SessionApplyCtx *p /* Session changeset-apply context */ ){ @@ -178343,7 +207705,7 @@ static int sessionSelectRow( ** pointing to the prepared version of the SQL statement. */ static int sessionInsertRow( - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ const char *zTab, /* Table name */ SessionApplyCtx *p /* Session changeset-apply context */ ){ @@ -178353,40 +207715,86 @@ static int sessionInsertRow( sessionAppendStr(&buf, "INSERT INTO main.", &rc); sessionAppendIdent(&buf, zTab, &rc); - sessionAppendStr(&buf, " VALUES(?", &rc); + sessionAppendStr(&buf, "(", &rc); + for(i=0; i<p->nCol; i++){ + if( i!=0 ) sessionAppendStr(&buf, ", ", &rc); + sessionAppendIdent(&buf, p->azCol[i], &rc); + } + + sessionAppendStr(&buf, ") VALUES(?", &rc); for(i=1; i<p->nCol; i++){ sessionAppendStr(&buf, ", ?", &rc); } sessionAppendStr(&buf, ")", &rc); if( rc==SQLITE_OK ){ - rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0); + rc = tdsqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0); + } + tdsqlite3_free(buf.aBuf); + return rc; +} + +static int sessionPrepare(tdsqlite3 *db, tdsqlite3_stmt **pp, const char *zSql){ + return tdsqlite3_prepare_v2(db, zSql, -1, pp, 0); +} + +/* +** Prepare statements for applying changes to the sqlite_stat1 table. +** These are similar to those created by sessionSelectRow(), +** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for +** other tables. +*/ +static int sessionStat1Sql(tdsqlite3 *db, SessionApplyCtx *p){ + int rc = sessionSelectRow(db, "sqlite_stat1", p); + if( rc==SQLITE_OK ){ + rc = sessionPrepare(db, &p->pInsert, + "INSERT INTO main.sqlite_stat1 VALUES(?1, " + "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, " + "?3)" + ); + } + if( rc==SQLITE_OK ){ + rc = sessionPrepare(db, &p->pUpdate, + "UPDATE main.sqlite_stat1 SET " + "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, " + "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, " + "stat = CASE WHEN ?8 THEN ?9 ELSE stat END " + "WHERE tbl=?1 AND idx IS " + "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END " + "AND (?10 OR ?8=0 OR stat IS ?7)" + ); + } + if( rc==SQLITE_OK ){ + rc = sessionPrepare(db, &p->pDelete, + "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS " + "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END " + "AND (?4 OR stat IS ?3)" + ); } - sqlite3_free(buf.aBuf); return rc; } /* -** A wrapper around sqlite3_bind_value() that detects an extra problem. +** A wrapper around tdsqlite3_bind_value() that detects an extra problem. ** See comments in the body of this function for details. */ static int sessionBindValue( - sqlite3_stmt *pStmt, /* Statement to bind value to */ + tdsqlite3_stmt *pStmt, /* Statement to bind value to */ int i, /* Parameter number to bind to */ - sqlite3_value *pVal /* Value to bind */ + tdsqlite3_value *pVal /* Value to bind */ ){ - int eType = sqlite3_value_type(pVal); + int eType = tdsqlite3_value_type(pVal); /* COVERAGE: The (pVal->z==0) branch is never true using current versions - ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either + ** of SQLite. If a malloc fails in an tdsqlite3_value_xxx() function, either ** the (pVal->z) variable remains as it was or the type of the value is ** set to SQLITE_NULL. */ if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){ /* This condition occurs when an earlier OOM in a call to - ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within + ** tdsqlite3_value_text() or tdsqlite3_value_blob() (perhaps from within ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */ return SQLITE_NOMEM; } - return sqlite3_bind_value(pStmt, i, pVal); + return tdsqlite3_bind_value(pStmt, i, pVal); } /* @@ -178404,26 +207812,32 @@ static int sessionBindValue( ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK. */ static int sessionBindRow( - sqlite3_changeset_iter *pIter, /* Iterator to read values from */ - int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **), + tdsqlite3_changeset_iter *pIter, /* Iterator to read values from */ + int(*xValue)(tdsqlite3_changeset_iter *, int, tdsqlite3_value **), int nCol, /* Number of columns */ u8 *abPK, /* If not NULL, bind only if true */ - sqlite3_stmt *pStmt /* Bind values to this statement */ + tdsqlite3_stmt *pStmt /* Bind values to this statement */ ){ int i; int rc = SQLITE_OK; - /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the + /* Neither tdsqlite3changeset_old or tdsqlite3changeset_new can fail if the ** argument iterator points to a suitable entry. Make sure that xValue ** is one of these to guarantee that it is safe to ignore the return ** in the code below. */ - assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new ); + assert( xValue==tdsqlite3changeset_old || xValue==tdsqlite3changeset_new ); for(i=0; rc==SQLITE_OK && i<nCol; i++){ if( !abPK || abPK[i] ){ - sqlite3_value *pVal; + tdsqlite3_value *pVal; (void)xValue(pIter, i, &pVal); - rc = sessionBindValue(pStmt, i+1, pVal); + if( pVal==0 ){ + /* The value in the changeset was "undefined". This indicates a + ** corrupt changeset blob. */ + rc = SQLITE_CORRUPT_BKPT; + }else{ + rc = sessionBindValue(pStmt, i+1, pVal); + } } } return rc; @@ -178447,31 +207861,80 @@ static int sessionBindRow( ** UPDATE, bind values from the old.* record. */ static int sessionSeekToRow( - sqlite3 *db, /* Database handle */ - sqlite3_changeset_iter *pIter, /* Changeset iterator */ + tdsqlite3 *db, /* Database handle */ + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ u8 *abPK, /* Primary key flags array */ - sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */ + tdsqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */ ){ int rc; /* Return code */ int nCol; /* Number of columns in table */ int op; /* Changset operation (SQLITE_UPDATE etc.) */ const char *zDummy; /* Unused */ - sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); + tdsqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); rc = sessionBindRow(pIter, - op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old, + op==SQLITE_INSERT ? tdsqlite3changeset_new : tdsqlite3changeset_old, nCol, abPK, pSelect ); if( rc==SQLITE_OK ){ - rc = sqlite3_step(pSelect); - if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect); + rc = tdsqlite3_step(pSelect); + if( rc!=SQLITE_ROW ) rc = tdsqlite3_reset(pSelect); } return rc; } /* +** This function is called from within tdsqlite3changeset_apply_v2() when +** a conflict is encountered and resolved using conflict resolution +** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE).. +** It adds a conflict resolution record to the buffer in +** SessionApplyCtx.rebase, which will eventually be returned to the caller +** of apply_v2() as the "rebase" buffer. +** +** Return SQLITE_OK if successful, or an SQLite error code otherwise. +*/ +static int sessionRebaseAdd( + SessionApplyCtx *p, /* Apply context */ + int eType, /* Conflict resolution (OMIT or REPLACE) */ + tdsqlite3_changeset_iter *pIter /* Iterator pointing at current change */ +){ + int rc = SQLITE_OK; + if( p->bRebase ){ + int i; + int eOp = pIter->op; + if( p->bRebaseStarted==0 ){ + /* Append a table-header to the rebase buffer */ + const char *zTab = pIter->zTab; + sessionAppendByte(&p->rebase, 'T', &rc); + sessionAppendVarint(&p->rebase, p->nCol, &rc); + sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc); + sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc); + p->bRebaseStarted = 1; + } + + assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT ); + assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE ); + + sessionAppendByte(&p->rebase, + (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc + ); + sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc); + for(i=0; i<p->nCol; i++){ + tdsqlite3_value *pVal = 0; + if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){ + tdsqlite3changeset_old(pIter, i, &pVal); + }else{ + tdsqlite3changeset_new(pIter, i, &pVal); + } + sessionAppendValue(&p->rebase, pVal, &rc); + } + } + return rc; +} + +/* ** Invoke the conflict handler for the change that the changeset iterator ** currently points to. ** @@ -178509,8 +207972,8 @@ static int sessionSeekToRow( static int sessionConflictHandler( int eType, /* Either CHANGESET_DATA or CONFLICT */ SessionApplyCtx *p, /* changeset_apply() context */ - sqlite3_changeset_iter *pIter, /* Changeset iterator */ - int(*xConflict)(void *, int, sqlite3_changeset_iter*), + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ + int(*xConflict)(void *, int, tdsqlite3_changeset_iter*), void *pCtx, /* First argument for conflict handler */ int *pbReplace /* OUT: Set to true if PK row is found */ ){ @@ -178520,7 +207983,7 @@ static int sessionConflictHandler( int op; const char *zDummy; - sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); + tdsqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA ); assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT ); @@ -178538,7 +208001,7 @@ static int sessionConflictHandler( pIter->pConflict = p->pSelect; res = xConflict(pCtx, eType, pIter); pIter->pConflict = 0; - rc = sqlite3_reset(p->pSelect); + rc = tdsqlite3_reset(p->pSelect); }else if( rc==SQLITE_OK ){ if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){ /* Instead of invoking the conflict handler, append the change blob @@ -178546,7 +208009,7 @@ static int sessionConflictHandler( u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent]; int nBlob = pIter->in.iNext - pIter->in.iCurrent; sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc); - res = SQLITE_CHANGESET_OMIT; + return SQLITE_OK; }else{ /* No other row with the new.* primary key. */ res = xConflict(pCtx, eType+1, pIter); @@ -178572,6 +208035,9 @@ static int sessionConflictHandler( rc = SQLITE_MISUSE; break; } + if( rc==SQLITE_OK ){ + rc = sessionRebaseAdd(p, res, pIter); + } } return rc; @@ -178602,9 +208068,9 @@ static int sessionConflictHandler( ** returned. */ static int sessionApplyOneOp( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ SessionApplyCtx *p, /* changeset_apply() context */ - int(*xConflict)(void *, int, sqlite3_changeset_iter *), + int(*xConflict)(void *, int, tdsqlite3_changeset_iter *), void *pCtx, /* First argument for the conflict handler */ int *pbReplace, /* OUT: True to remove PK row and retry */ int *pbRetry /* OUT: True to retry. */ @@ -178618,7 +208084,7 @@ static int sessionApplyOneOp( assert( p->azCol && p->abPK ); assert( !pbReplace || *pbReplace==0 ); - sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); + tdsqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0); if( op==SQLITE_DELETE ){ @@ -178634,15 +208100,15 @@ static int sessionApplyOneOp( ** no (nCol+1) variable to bind to). */ u8 *abPK = (pIter->bPatchset ? p->abPK : 0); - rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete); - if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){ - rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK)); + rc = sessionBindRow(pIter, tdsqlite3changeset_old, nCol, abPK, p->pDelete); + if( rc==SQLITE_OK && tdsqlite3_bind_parameter_count(p->pDelete)>nCol ){ + rc = tdsqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK)); } if( rc!=SQLITE_OK ) return rc; - sqlite3_step(p->pDelete); - rc = sqlite3_reset(p->pDelete); - if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){ + tdsqlite3_step(p->pDelete); + rc = tdsqlite3_reset(p->pDelete); + if( rc==SQLITE_OK && tdsqlite3_changes(p->db)==0 ){ rc = sessionConflictHandler( SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry ); @@ -178657,10 +208123,10 @@ static int sessionApplyOneOp( /* Bind values to the UPDATE statement. */ for(i=0; rc==SQLITE_OK && i<nCol; i++){ - sqlite3_value *pOld = sessionChangesetOld(pIter, i); - sqlite3_value *pNew = sessionChangesetNew(pIter, i); + tdsqlite3_value *pOld = sessionChangesetOld(pIter, i); + tdsqlite3_value *pNew = sessionChangesetNew(pIter, i); - sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew); + tdsqlite3_bind_int(p->pUpdate, i*3+2, !!pNew); if( pOld ){ rc = sessionBindValue(p->pUpdate, i*3+1, pOld); } @@ -178669,16 +208135,16 @@ static int sessionApplyOneOp( } } if( rc==SQLITE_OK ){ - sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset); + tdsqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset); } if( rc!=SQLITE_OK ) return rc; /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict, ** the result will be SQLITE_OK with 0 rows modified. */ - sqlite3_step(p->pUpdate); - rc = sqlite3_reset(p->pUpdate); + tdsqlite3_step(p->pUpdate); + rc = tdsqlite3_reset(p->pUpdate); - if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){ + if( rc==SQLITE_OK && tdsqlite3_changes(p->db)==0 ){ /* A NOTFOUND or DATA error. Search the table to see if it contains ** a row with a matching primary key. If so, this is a DATA conflict. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */ @@ -178696,11 +208162,25 @@ static int sessionApplyOneOp( }else{ assert( op==SQLITE_INSERT ); - rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert); - if( rc!=SQLITE_OK ) return rc; + if( p->bStat1 ){ + /* Check if there is a conflicting row. For sqlite_stat1, this needs + ** to be done using a SELECT, as there is no PRIMARY KEY in the + ** database schema to throw an exception if a duplicate is inserted. */ + rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect); + if( rc==SQLITE_ROW ){ + rc = SQLITE_CONSTRAINT; + tdsqlite3_reset(p->pSelect); + } + } + + if( rc==SQLITE_OK ){ + rc = sessionBindRow(pIter, tdsqlite3changeset_new, nCol, 0, p->pInsert); + if( rc!=SQLITE_OK ) return rc; + + tdsqlite3_step(p->pInsert); + rc = tdsqlite3_reset(p->pInsert); + } - sqlite3_step(p->pInsert); - rc = sqlite3_reset(p->pInsert); if( (rc&0xff)==SQLITE_CONSTRAINT ){ rc = sessionConflictHandler( SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace @@ -178722,10 +208202,10 @@ static int sessionApplyOneOp( ** retried in some manner. */ static int sessionApplyOneWithRetry( - sqlite3 *db, /* Apply change to "main" db of this handle */ - sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */ + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + tdsqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */ SessionApplyCtx *pApply, /* Apply context */ - int(*xConflict)(void*, int, sqlite3_changeset_iter*), + int(*xConflict)(void*, int, tdsqlite3_changeset_iter*), void *pCtx /* First argument passed to xConflict */ ){ int bReplace = 0; @@ -178733,42 +208213,42 @@ static int sessionApplyOneWithRetry( int rc; rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry); - assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) ); - - /* If the bRetry flag is set, the change has not been applied due to an - ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and - ** a row with the correct PK is present in the db, but one or more other - ** fields do not contain the expected values) and the conflict handler - ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation, - ** but pass NULL as the final argument so that sessionApplyOneOp() ignores - ** the SQLITE_CHANGESET_DATA problem. */ - if( bRetry ){ - assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE ); - rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0); - } - - /* If the bReplace flag is set, the change is an INSERT that has not - ** been performed because the database already contains a row with the - ** specified primary key and the conflict handler returned - ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row - ** before reattempting the INSERT. */ - else if( bReplace ){ - assert( pIter->op==SQLITE_INSERT ); - rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0); - if( rc==SQLITE_OK ){ - rc = sessionBindRow(pIter, - sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete); - sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1); - } - if( rc==SQLITE_OK ){ - sqlite3_step(pApply->pDelete); - rc = sqlite3_reset(pApply->pDelete); - } - if( rc==SQLITE_OK ){ + if( rc==SQLITE_OK ){ + /* If the bRetry flag is set, the change has not been applied due to an + ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and + ** a row with the correct PK is present in the db, but one or more other + ** fields do not contain the expected values) and the conflict handler + ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation, + ** but pass NULL as the final argument so that sessionApplyOneOp() ignores + ** the SQLITE_CHANGESET_DATA problem. */ + if( bRetry ){ + assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE ); rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0); } - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0); + + /* If the bReplace flag is set, the change is an INSERT that has not + ** been performed because the database already contains a row with the + ** specified primary key and the conflict handler returned + ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row + ** before reattempting the INSERT. */ + else if( bReplace ){ + assert( pIter->op==SQLITE_INSERT ); + rc = tdsqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0); + if( rc==SQLITE_OK ){ + rc = sessionBindRow(pIter, + tdsqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete); + tdsqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1); + } + if( rc==SQLITE_OK ){ + tdsqlite3_step(pApply->pDelete); + rc = tdsqlite3_reset(pApply->pDelete); + } + if( rc==SQLITE_OK ){ + rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0); + } + if( rc==SQLITE_OK ){ + rc = tdsqlite3_exec(db, "RELEASE replace_op", 0, 0, 0); + } } } @@ -178779,42 +208259,42 @@ static int sessionApplyOneWithRetry( ** Retry the changes accumulated in the pApply->constraints buffer. */ static int sessionRetryConstraints( - sqlite3 *db, + tdsqlite3 *db, int bPatchset, const char *zTab, SessionApplyCtx *pApply, - int(*xConflict)(void*, int, sqlite3_changeset_iter*), + int(*xConflict)(void*, int, tdsqlite3_changeset_iter*), void *pCtx /* First argument passed to xConflict */ ){ int rc = SQLITE_OK; while( pApply->constraints.nBuf ){ - sqlite3_changeset_iter *pIter2 = 0; + tdsqlite3_changeset_iter *pIter2 = 0; SessionBuffer cons = pApply->constraints; memset(&pApply->constraints, 0, sizeof(SessionBuffer)); - rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf); + rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, 0); if( rc==SQLITE_OK ){ - int nByte = 2*pApply->nCol*sizeof(sqlite3_value*); + size_t nByte = 2*pApply->nCol*sizeof(tdsqlite3_value*); int rc2; pIter2->bPatchset = bPatchset; pIter2->zTab = (char*)zTab; pIter2->nCol = pApply->nCol; pIter2->abPK = pApply->abPK; sessionBufferGrow(&pIter2->tblhdr, nByte, &rc); - pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf; + pIter2->apValue = (tdsqlite3_value**)pIter2->tblhdr.aBuf; if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){ + while( rc==SQLITE_OK && SQLITE_ROW==tdsqlite3changeset_next(pIter2) ){ rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx); } - rc2 = sqlite3changeset_finalize(pIter2); + rc2 = tdsqlite3changeset_finalize(pIter2); if( rc==SQLITE_OK ) rc = rc2; } assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 ); - sqlite3_free(cons.aBuf); + tdsqlite3_free(cons.aBuf); if( rc!=SQLITE_OK ) break; if( pApply->constraints.nBuf>=cons.nBuf ){ /* No progress was made on the last round. */ @@ -178827,14 +208307,14 @@ static int sessionRetryConstraints( /* ** Argument pIter is a changeset iterator that has been initialized, but -** not yet passed to sqlite3changeset_next(). This function applies the +** not yet passed to tdsqlite3changeset_next(). This function applies the ** changeset to the main database attached to handle "db". The supplied ** conflict handler callback is invoked to resolve any conflicts encountered ** while applying the change. */ static int sessionChangesetApply( - sqlite3 *db, /* Apply change to "main" db of this handle */ - sqlite3_changeset_iter *pIter, /* Changeset to apply */ + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + tdsqlite3_changeset_iter *pIter, /* Changeset to apply */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ @@ -178842,14 +208322,16 @@ static int sessionChangesetApply( int(*xConflict)( void *pCtx, /* Copy of fifth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ ), - void *pCtx /* First argument passed to xConflict */ + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, /* OUT: Rebase information */ + int flags /* SESSION_APPLY_XXX flags */ ){ int schemaMismatch = 0; - int rc; /* Return code */ + int rc = SQLITE_OK; /* Return code */ const char *zTab = 0; /* Name of current table */ - int nTab = 0; /* Result of sqlite3Strlen30(zTab) */ + int nTab = 0; /* Result of tdsqlite3Strlen30(zTab) */ SessionApplyCtx sApply; /* changeset_apply() context object */ int bPatchset; @@ -178857,19 +208339,22 @@ static int sessionChangesetApply( pIter->in.bNoDiscard = 1; memset(&sApply, 0, sizeof(sApply)); - sqlite3_mutex_enter(sqlite3_db_mutex(db)); - rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0); + sApply.bRebase = (ppRebase && pnRebase); + tdsqlite3_mutex_enter(tdsqlite3_db_mutex(db)); + if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){ + rc = tdsqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0); + } if( rc==SQLITE_OK ){ - rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0); + rc = tdsqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0); } - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){ + while( rc==SQLITE_OK && SQLITE_ROW==tdsqlite3changeset_next(pIter) ){ int nCol; int op; const char *zNew; - sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0); + tdsqlite3changeset_op(pIter, &zNew, &nCol, &op, 0); - if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){ + if( zTab==0 || tdsqlite3_strnicmp(zNew, zTab, nTab+1) ){ u8 *abPK; rc = sessionRetryConstraints( @@ -178877,21 +208362,30 @@ static int sessionChangesetApply( ); if( rc!=SQLITE_OK ) break; - sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ - sqlite3_finalize(sApply.pDelete); - sqlite3_finalize(sApply.pUpdate); - sqlite3_finalize(sApply.pInsert); - sqlite3_finalize(sApply.pSelect); - memset(&sApply, 0, sizeof(sApply)); + tdsqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ + tdsqlite3_finalize(sApply.pDelete); + tdsqlite3_finalize(sApply.pUpdate); + tdsqlite3_finalize(sApply.pInsert); + tdsqlite3_finalize(sApply.pSelect); sApply.db = db; + sApply.pDelete = 0; + sApply.pUpdate = 0; + sApply.pInsert = 0; + sApply.pSelect = 0; + sApply.nCol = 0; + sApply.azCol = 0; + sApply.abPK = 0; + sApply.bStat1 = 0; sApply.bDeferConstraints = 1; + sApply.bRebaseStarted = 0; + memset(&sApply.constraints, 0, sizeof(SessionBuffer)); /* If an xFilter() callback was specified, invoke it now. If the ** xFilter callback returns zero, skip this table. If it returns ** non-zero, proceed. */ schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew))); if( schemaMismatch ){ - zTab = sqlite3_mprintf("%s", zNew); + zTab = tdsqlite3_mprintf("%s", zNew); if( zTab==0 ){ rc = SQLITE_NOMEM; break; @@ -178899,40 +208393,57 @@ static int sessionChangesetApply( nTab = (int)strlen(zTab); sApply.azCol = (const char **)zTab; }else{ - sqlite3changeset_pk(pIter, &abPK, 0); + int nMinCol = 0; + int i; + + tdsqlite3changeset_pk(pIter, &abPK, 0); rc = sessionTableInfo( db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK ); if( rc!=SQLITE_OK ) break; + for(i=0; i<sApply.nCol; i++){ + if( sApply.abPK[i] ) nMinCol = i+1; + } if( sApply.nCol==0 ){ schemaMismatch = 1; - sqlite3_log(SQLITE_SCHEMA, - "sqlite3changeset_apply(): no such table: %s", zTab + tdsqlite3_log(SQLITE_SCHEMA, + "tdsqlite3changeset_apply(): no such table: %s", zTab ); } - else if( sApply.nCol!=nCol ){ + else if( sApply.nCol<nCol ){ schemaMismatch = 1; - sqlite3_log(SQLITE_SCHEMA, - "sqlite3changeset_apply(): table %s has %d columns, expected %d", + tdsqlite3_log(SQLITE_SCHEMA, + "tdsqlite3changeset_apply(): table %s has %d columns, " + "expected %d or more", zTab, sApply.nCol, nCol ); } - else if( memcmp(sApply.abPK, abPK, nCol)!=0 ){ + else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){ schemaMismatch = 1; - sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): " + tdsqlite3_log(SQLITE_SCHEMA, "tdsqlite3changeset_apply(): " "primary key mismatch for table %s", zTab ); } - else if( - (rc = sessionSelectRow(db, zTab, &sApply)) - || (rc = sessionUpdateRow(db, zTab, &sApply)) - || (rc = sessionDeleteRow(db, zTab, &sApply)) - || (rc = sessionInsertRow(db, zTab, &sApply)) - ){ - break; + else{ + sApply.nCol = nCol; + if( 0==tdsqlite3_stricmp(zTab, "sqlite_stat1") ){ + if( (rc = sessionStat1Sql(db, &sApply) ) ){ + break; + } + sApply.bStat1 = 1; + }else{ + if((rc = sessionSelectRow(db, zTab, &sApply)) + || (rc = sessionUpdateRow(db, zTab, &sApply)) + || (rc = sessionDeleteRow(db, zTab, &sApply)) + || (rc = sessionInsertRow(db, zTab, &sApply)) + ){ + break; + } + sApply.bStat1 = 0; + } } - nTab = sqlite3Strlen30(zTab); + nTab = tdsqlite3Strlen30(zTab); } } @@ -178945,9 +208456,9 @@ static int sessionChangesetApply( bPatchset = pIter->bPatchset; if( rc==SQLITE_OK ){ - rc = sqlite3changeset_finalize(pIter); + rc = tdsqlite3changeset_finalize(pIter); }else{ - sqlite3changeset_finalize(pIter); + tdsqlite3changeset_finalize(pIter); } if( rc==SQLITE_OK ){ @@ -178956,10 +208467,10 @@ static int sessionChangesetApply( if( rc==SQLITE_OK ){ int nFk, notUsed; - sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, ¬Used, 0); + tdsqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, ¬Used, 0); if( nFk!=0 ){ int res = SQLITE_CHANGESET_ABORT; - sqlite3_changeset_iter sIter; + tdsqlite3_changeset_iter sIter; memset(&sIter, 0, sizeof(sIter)); sIter.nCol = nFk; res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter); @@ -178968,22 +208479,63 @@ static int sessionChangesetApply( } } } - sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0); + tdsqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); - }else{ - sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0); - sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); + if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){ + if( rc==SQLITE_OK ){ + rc = tdsqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); + }else{ + tdsqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0); + tdsqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); + } } - sqlite3_finalize(sApply.pInsert); - sqlite3_finalize(sApply.pDelete); - sqlite3_finalize(sApply.pUpdate); - sqlite3_finalize(sApply.pSelect); - sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ - sqlite3_free((char*)sApply.constraints.aBuf); - sqlite3_mutex_leave(sqlite3_db_mutex(db)); + assert( sApply.bRebase || sApply.rebase.nBuf==0 ); + if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){ + *ppRebase = (void*)sApply.rebase.aBuf; + *pnRebase = sApply.rebase.nBuf; + sApply.rebase.aBuf = 0; + } + tdsqlite3_finalize(sApply.pInsert); + tdsqlite3_finalize(sApply.pDelete); + tdsqlite3_finalize(sApply.pUpdate); + tdsqlite3_finalize(sApply.pSelect); + tdsqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */ + tdsqlite3_free((char*)sApply.constraints.aBuf); + tdsqlite3_free((char*)sApply.rebase.aBuf); + tdsqlite3_mutex_leave(tdsqlite3_db_mutex(db)); + return rc; +} + +/* +** Apply the changeset passed via pChangeset/nChangeset to the main +** database attached to handle "db". +*/ +SQLITE_API int tdsqlite3changeset_apply_v2( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +){ + tdsqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ + int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); + int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse); + if( rc==SQLITE_OK ){ + rc = sessionChangesetApply( + db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags + ); + } return rc; } @@ -178992,8 +208544,8 @@ static int sessionChangesetApply( ** attached to handle "db". Invoke the supplied conflict handler callback ** to resolve any conflicts encountered while applying the change. */ -SQLITE_API int sqlite3changeset_apply( - sqlite3 *db, /* Apply change to "main" db of this handle */ +SQLITE_API int tdsqlite3changeset_apply( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ int(*xFilter)( @@ -179003,16 +208555,13 @@ SQLITE_API int sqlite3changeset_apply( int(*xConflict)( void *pCtx, /* Copy of fifth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ){ - sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ - int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset); - if( rc==SQLITE_OK ){ - rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx); - } - return rc; + return tdsqlite3changeset_apply_v2( + db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0 + ); } /* @@ -179020,8 +208569,8 @@ SQLITE_API int sqlite3changeset_apply( ** attached to handle "db". Invoke the supplied conflict handler callback ** to resolve any conflicts encountered while applying the change. */ -SQLITE_API int sqlite3changeset_apply_strm( - sqlite3 *db, /* Apply change to "main" db of this handle */ +SQLITE_API int tdsqlite3changeset_apply_v2_strm( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ void *pIn, /* First arg for xInput */ int(*xFilter)( @@ -179031,22 +208580,46 @@ SQLITE_API int sqlite3changeset_apply_strm( int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ ), - void *pCtx /* First argument passed to xConflict */ + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags ){ - sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ - int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn); + tdsqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ + int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); + int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse); if( rc==SQLITE_OK ){ - rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx); + rc = sessionChangesetApply( + db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags + ); } return rc; } +SQLITE_API int tdsqlite3changeset_apply_strm( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx /* First argument passed to xConflict */ +){ + return tdsqlite3changeset_apply_v2_strm( + db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0 + ); +} /* -** sqlite3_changegroup handle. +** tdsqlite3_changegroup handle. */ -struct sqlite3_changegroup { +struct tdsqlite3_changegroup { int rc; /* Error code */ int bPatch; /* True to accumulate patchsets */ SessionTable *pList; /* List of tables in current patch */ @@ -179054,11 +208627,12 @@ struct sqlite3_changegroup { /* ** This function is called to merge two changes to the same row together as -** part of an sqlite3changeset_concat() operation. A new change object is +** part of an tdsqlite3changeset_concat() operation. A new change object is ** allocated and a pointer to it stored in *ppNew. */ static int sessionChangeMerge( SessionTable *pTab, /* Table structure */ + int bRebase, /* True for a rebase hash-table */ int bPatchset, /* True for patchsets */ SessionChange *pExist, /* Existing change */ int op2, /* Second change operation */ @@ -179068,18 +208642,76 @@ static int sessionChangeMerge( SessionChange **ppNew /* OUT: Merged change */ ){ SessionChange *pNew = 0; + int rc = SQLITE_OK; if( !pExist ){ - pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec); + pNew = (SessionChange *)tdsqlite3_malloc64(sizeof(SessionChange) + nRec); if( !pNew ){ return SQLITE_NOMEM; } memset(pNew, 0, sizeof(SessionChange)); pNew->op = op2; pNew->bIndirect = bIndirect; - pNew->nRecord = nRec; pNew->aRecord = (u8*)&pNew[1]; - memcpy(pNew->aRecord, aRec, nRec); + if( bIndirect==0 || bRebase==0 ){ + pNew->nRecord = nRec; + memcpy(pNew->aRecord, aRec, nRec); + }else{ + int i; + u8 *pIn = aRec; + u8 *pOut = pNew->aRecord; + for(i=0; i<pTab->nCol; i++){ + int nIn = sessionSerialLen(pIn); + if( *pIn==0 ){ + *pOut++ = 0; + }else if( pTab->abPK[i]==0 ){ + *pOut++ = 0xFF; + }else{ + memcpy(pOut, pIn, nIn); + pOut += nIn; + } + pIn += nIn; + } + pNew->nRecord = pOut - pNew->aRecord; + } + }else if( bRebase ){ + if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){ + *ppNew = pExist; + }else{ + tdsqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange); + pNew = (SessionChange*)tdsqlite3_malloc64(nByte); + if( pNew==0 ){ + rc = SQLITE_NOMEM; + }else{ + int i; + u8 *a1 = pExist->aRecord; + u8 *a2 = aRec; + u8 *pOut; + + memset(pNew, 0, nByte); + pNew->bIndirect = bIndirect || pExist->bIndirect; + pNew->op = op2; + pOut = pNew->aRecord = (u8*)&pNew[1]; + + for(i=0; i<pTab->nCol; i++){ + int n1 = sessionSerialLen(a1); + int n2 = sessionSerialLen(a2); + if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){ + *pOut++ = 0xFF; + }else if( *a2==0 ){ + memcpy(pOut, a1, n1); + pOut += n1; + }else{ + memcpy(pOut, a2, n2); + pOut += n2; + } + a1 += n1; + a2 += n2; + } + pNew->nRecord = pOut - pNew->aRecord; + } + tdsqlite3_free(pExist); + } }else{ int op1 = pExist->op; @@ -179103,20 +208735,20 @@ static int sessionChangeMerge( ){ pNew = pExist; }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){ - sqlite3_free(pExist); + tdsqlite3_free(pExist); assert( pNew==0 ); }else{ u8 *aExist = pExist->aRecord; - int nByte; + tdsqlite3_int64 nByte; u8 *aCsr; /* Allocate a new SessionChange object. Ensure that the aRecord[] ** buffer of the new object is large enough to hold any record that ** may be generated by combining the input records. */ nByte = sizeof(SessionChange) + pExist->nRecord + nRec; - pNew = (SessionChange *)sqlite3_malloc(nByte); + pNew = (SessionChange *)tdsqlite3_malloc64(nByte); if( !pNew ){ - sqlite3_free(pExist); + tdsqlite3_free(pExist); return SQLITE_NOMEM; } memset(pNew, 0, sizeof(SessionChange)); @@ -179137,7 +208769,7 @@ static int sessionChangeMerge( aCsr += nRec; }else{ if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){ - sqlite3_free(pNew); + tdsqlite3_free(pNew); pNew = 0; } } @@ -179151,7 +208783,7 @@ static int sessionChangeMerge( } pNew->op = SQLITE_UPDATE; if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){ - sqlite3_free(pNew); + tdsqlite3_free(pNew); pNew = 0; } }else{ /* UPDATE + DELETE */ @@ -179168,12 +208800,12 @@ static int sessionChangeMerge( if( pNew ){ pNew->nRecord = (int)(aCsr - pNew->aRecord); } - sqlite3_free(pExist); + tdsqlite3_free(pExist); } } *ppNew = pNew; - return SQLITE_OK; + return rc; } /* @@ -179181,16 +208813,16 @@ static int sessionChangeMerge( ** the first argument to the changegroup hash tables. */ static int sessionChangesetToHash( - sqlite3_changeset_iter *pIter, /* Iterator to read from */ - sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */ + tdsqlite3_changeset_iter *pIter, /* Iterator to read from */ + tdsqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */ + int bRebase /* True if hash table is for rebasing */ ){ u8 *aRec; int nRec; int rc = SQLITE_OK; SessionTable *pTab = 0; - - while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){ + while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){ const char *zNew; int nCol; int op; @@ -179207,20 +208839,20 @@ static int sessionChangesetToHash( break; } - sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect); - if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){ + tdsqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect); + if( !pTab || tdsqlite3_stricmp(zNew, pTab->zName) ){ /* Search the list for a matching table */ int nNew = (int)strlen(zNew); u8 *abPK; - sqlite3changeset_pk(pIter, &abPK, 0); + tdsqlite3changeset_pk(pIter, &abPK, 0); for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){ - if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break; + if( 0==tdsqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break; } if( !pTab ){ SessionTable **ppTab; - pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1); + pTab = tdsqlite3_malloc64(sizeof(SessionTable) + nCol + nNew+1); if( !pTab ){ rc = SQLITE_NOMEM; break; @@ -179234,7 +208866,7 @@ static int sessionChangesetToHash( /* The new object must be linked on to the end of the list, not ** simply added to the start of it. This is to ensure that the - ** tables within the output of sqlite3changegroup_output() are in + ** tables within the output of tdsqlite3changegroup_output() are in ** the right order. */ for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext); *ppTab = pTab; @@ -179270,7 +208902,7 @@ static int sessionChangesetToHash( } } - rc = sessionChangeMerge(pTab, + rc = sessionChangeMerge(pTab, bRebase, pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange ); if( rc ) break; @@ -179297,14 +208929,14 @@ static int sessionChangesetToHash( ** buffer containing the output changeset before this function returns. In ** this case (*pnOut) is set to the size of the output buffer in bytes. It ** is the responsibility of the caller to free the output buffer using -** sqlite3_free() when it is no longer required. +** tdsqlite3_free() when it is no longer required. ** ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut) ** are both set to 0 before returning. */ static int sessionChangegroupOutput( - sqlite3_changegroup *pGrp, + tdsqlite3_changegroup *pGrp, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut, int *pnOut, @@ -179329,13 +208961,12 @@ static int sessionChangegroupOutput( sessionAppendByte(&buf, p->op, &rc); sessionAppendByte(&buf, p->bIndirect, &rc); sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc); + if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){ + rc = xOutput(pOut, buf.aBuf, buf.nBuf); + buf.nBuf = 0; + } } } - - if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){ - rc = xOutput(pOut, buf.aBuf, buf.nBuf); - buf.nBuf = 0; - } } if( rc==SQLITE_OK ){ @@ -179347,22 +208978,22 @@ static int sessionChangegroupOutput( buf.aBuf = 0; } } - sqlite3_free(buf.aBuf); + tdsqlite3_free(buf.aBuf); return rc; } /* -** Allocate a new, empty, sqlite3_changegroup. +** Allocate a new, empty, tdsqlite3_changegroup. */ -SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){ +SQLITE_API int tdsqlite3changegroup_new(tdsqlite3_changegroup **pp){ int rc = SQLITE_OK; /* Return code */ - sqlite3_changegroup *p; /* New object */ - p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup)); + tdsqlite3_changegroup *p; /* New object */ + p = (tdsqlite3_changegroup*)tdsqlite3_malloc(sizeof(tdsqlite3_changegroup)); if( p==0 ){ rc = SQLITE_NOMEM; }else{ - memset(p, 0, sizeof(sqlite3_changegroup)); + memset(p, 0, sizeof(tdsqlite3_changegroup)); } *pp = p; return rc; @@ -179372,15 +209003,15 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){ ** Add the changeset currently stored in buffer pData, size nData bytes, ** to changeset-group p. */ -SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){ - sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ +SQLITE_API int tdsqlite3changegroup_add(tdsqlite3_changegroup *pGrp, int nData, void *pData){ + tdsqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ int rc; /* Return code */ - rc = sqlite3changeset_start(&pIter, nData, pData); + rc = tdsqlite3changeset_start(&pIter, nData, pData); if( rc==SQLITE_OK ){ - rc = sessionChangesetToHash(pIter, pGrp); + rc = sessionChangesetToHash(pIter, pGrp, 0); } - sqlite3changeset_finalize(pIter); + tdsqlite3changeset_finalize(pIter); return rc; } @@ -179388,8 +209019,8 @@ SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void ** Obtain a buffer containing a changeset representing the concatenation ** of all changesets added to the group so far. */ -SQLITE_API int sqlite3changegroup_output( - sqlite3_changegroup *pGrp, +SQLITE_API int tdsqlite3changegroup_output( + tdsqlite3_changegroup *pGrp, int *pnData, void **ppData ){ @@ -179399,27 +209030,27 @@ SQLITE_API int sqlite3changegroup_output( /* ** Streaming versions of changegroup_add(). */ -SQLITE_API int sqlite3changegroup_add_strm( - sqlite3_changegroup *pGrp, +SQLITE_API int tdsqlite3changegroup_add_strm( + tdsqlite3_changegroup *pGrp, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ){ - sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ + tdsqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */ int rc; /* Return code */ - rc = sqlite3changeset_start_strm(&pIter, xInput, pIn); + rc = tdsqlite3changeset_start_strm(&pIter, xInput, pIn); if( rc==SQLITE_OK ){ - rc = sessionChangesetToHash(pIter, pGrp); + rc = sessionChangesetToHash(pIter, pGrp, 0); } - sqlite3changeset_finalize(pIter); + tdsqlite3changeset_finalize(pIter); return rc; } /* ** Streaming versions of changegroup_output(). */ -SQLITE_API int sqlite3changegroup_output_strm( - sqlite3_changegroup *pGrp, +SQLITE_API int tdsqlite3changegroup_output_strm( + tdsqlite3_changegroup *pGrp, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ){ @@ -179429,17 +209060,17 @@ SQLITE_API int sqlite3changegroup_output_strm( /* ** Delete a changegroup object. */ -SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){ +SQLITE_API void tdsqlite3changegroup_delete(tdsqlite3_changegroup *pGrp){ if( pGrp ){ sessionDeleteTable(pGrp->pList); - sqlite3_free(pGrp); + tdsqlite3_free(pGrp); } } /* ** Combine two changesets together. */ -SQLITE_API int sqlite3changeset_concat( +SQLITE_API int tdsqlite3changeset_concat( int nLeft, /* Number of bytes in lhs input */ void *pLeft, /* Lhs input changeset */ int nRight /* Number of bytes in rhs input */, @@ -179447,28 +209078,28 @@ SQLITE_API int sqlite3changeset_concat( int *pnOut, /* OUT: Number of bytes in output changeset */ void **ppOut /* OUT: changeset (left <concat> right) */ ){ - sqlite3_changegroup *pGrp; + tdsqlite3_changegroup *pGrp; int rc; - rc = sqlite3changegroup_new(&pGrp); + rc = tdsqlite3changegroup_new(&pGrp); if( rc==SQLITE_OK ){ - rc = sqlite3changegroup_add(pGrp, nLeft, pLeft); + rc = tdsqlite3changegroup_add(pGrp, nLeft, pLeft); } if( rc==SQLITE_OK ){ - rc = sqlite3changegroup_add(pGrp, nRight, pRight); + rc = tdsqlite3changegroup_add(pGrp, nRight, pRight); } if( rc==SQLITE_OK ){ - rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); + rc = tdsqlite3changegroup_output(pGrp, pnOut, ppOut); } - sqlite3changegroup_delete(pGrp); + tdsqlite3changegroup_delete(pGrp); return rc; } /* -** Streaming version of sqlite3changeset_concat(). +** Streaming version of tdsqlite3changeset_concat(). */ -SQLITE_API int sqlite3changeset_concat_strm( +SQLITE_API int tdsqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, int (*xInputB)(void *pIn, void *pData, int *pnData), @@ -179476,2259 +209107,391 @@ SQLITE_API int sqlite3changeset_concat_strm( int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ){ - sqlite3_changegroup *pGrp; + tdsqlite3_changegroup *pGrp; int rc; - rc = sqlite3changegroup_new(&pGrp); + rc = tdsqlite3changegroup_new(&pGrp); if( rc==SQLITE_OK ){ - rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA); + rc = tdsqlite3changegroup_add_strm(pGrp, xInputA, pInA); } if( rc==SQLITE_OK ){ - rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB); + rc = tdsqlite3changegroup_add_strm(pGrp, xInputB, pInB); } if( rc==SQLITE_OK ){ - rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut); + rc = tdsqlite3changegroup_output_strm(pGrp, xOutput, pOut); } - sqlite3changegroup_delete(pGrp); + tdsqlite3changegroup_delete(pGrp); return rc; } -#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */ - -/************** End of sqlite3session.c **************************************/ -/************** Begin file json1.c *******************************************/ -/* -** 2015-08-12 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This SQLite extension implements JSON functions. The interface is -** modeled after MySQL JSON functions: -** -** https://dev.mysql.com/doc/refman/5.7/en/json.html -** -** For the time being, all JSON is stored as pure text. (We might add -** a JSONB type in the future which stores a binary encoding of JSON in -** a BLOB, but there is no support for JSONB in the current implementation. -** This implementation parses JSON text at 250 MB/s, so it is hard to see -** how JSONB might improve on that.) -*/ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) -#if !defined(_SQLITEINT_H_) -/* #include "sqlite3ext.h" */ -#endif -SQLITE_EXTENSION_INIT1 -/* #include <assert.h> */ -/* #include <string.h> */ -/* #include <stdlib.h> */ -/* #include <stdarg.h> */ - -/* Mark a function parameter as unused, to suppress nuisance compiler -** warnings. */ -#ifndef UNUSED_PARAM -# define UNUSED_PARAM(X) (void)(X) -#endif - -#ifndef LARGEST_INT64 -# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) -# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) -#endif - -/* -** Versions of isspace(), isalnum() and isdigit() to which it is safe -** to pass signed char values. -*/ -#ifdef sqlite3Isdigit - /* Use the SQLite core versions if this routine is part of the - ** SQLite amalgamation */ -# define safe_isdigit(x) sqlite3Isdigit(x) -# define safe_isalnum(x) sqlite3Isalnum(x) -# define safe_isxdigit(x) sqlite3Isxdigit(x) -#else - /* Use the standard library for separate compilation */ -#include <ctype.h> /* amalgamator: keep */ -# define safe_isdigit(x) isdigit((unsigned char)(x)) -# define safe_isalnum(x) isalnum((unsigned char)(x)) -# define safe_isxdigit(x) isxdigit((unsigned char)(x)) -#endif - -/* -** Growing our own isspace() routine this way is twice as fast as -** the library isspace() function, resulting in a 7% overall performance -** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os). -*/ -static const char jsonIsSpace[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -}; -#define safe_isspace(x) (jsonIsSpace[(unsigned char)x]) - -#ifndef SQLITE_AMALGAMATION - /* Unsigned integer types. These are already defined in the sqliteInt.h, - ** but the definitions need to be repeated for separate compilation. */ - typedef sqlite3_uint64 u64; - typedef unsigned int u32; - typedef unsigned char u8; -#endif - -/* Objects */ -typedef struct JsonString JsonString; -typedef struct JsonNode JsonNode; -typedef struct JsonParse JsonParse; - -/* An instance of this object represents a JSON string -** under construction. Really, this is a generic string accumulator -** that can be and is used to create strings other than JSON. -*/ -struct JsonString { - sqlite3_context *pCtx; /* Function context - put error messages here */ - char *zBuf; /* Append JSON content here */ - u64 nAlloc; /* Bytes of storage available in zBuf[] */ - u64 nUsed; /* Bytes of zBuf[] currently used */ - u8 bStatic; /* True if zBuf is static space */ - u8 bErr; /* True if an error has been encountered */ - char zSpace[100]; /* Initial static space */ -}; - -/* JSON type values -*/ -#define JSON_NULL 0 -#define JSON_TRUE 1 -#define JSON_FALSE 2 -#define JSON_INT 3 -#define JSON_REAL 4 -#define JSON_STRING 5 -#define JSON_ARRAY 6 -#define JSON_OBJECT 7 - -/* The "subtype" set for JSON values */ -#define JSON_SUBTYPE 74 /* Ascii for "J" */ - /* -** Names of the various JSON types: -*/ -static const char * const jsonType[] = { - "null", "true", "false", "integer", "real", "text", "array", "object" -}; - -/* Bit values for the JsonNode.jnFlag field -*/ -#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */ -#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */ -#define JNODE_REMOVE 0x04 /* Do not output */ -#define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */ -#define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */ -#define JNODE_LABEL 0x20 /* Is a label of an object */ - - -/* A single node of parsed JSON +** Changeset rebaser handle. */ -struct JsonNode { - u8 eType; /* One of the JSON_ type values */ - u8 jnFlags; /* JNODE flags */ - u8 iVal; /* Replacement value when JNODE_REPLACE */ - u32 n; /* Bytes of content, or number of sub-nodes */ - union { - const char *zJContent; /* Content for INT, REAL, and STRING */ - u32 iAppend; /* More terms for ARRAY and OBJECT */ - u32 iKey; /* Key for ARRAY objects in json_tree() */ - } u; -}; - -/* A completely parsed JSON string -*/ -struct JsonParse { - u32 nNode; /* Number of slots of aNode[] used */ - u32 nAlloc; /* Number of slots of aNode[] allocated */ - JsonNode *aNode; /* Array of nodes containing the parse */ - const char *zJson; /* Original JSON string */ - u32 *aUp; /* Index of parent of each node */ - u8 oom; /* Set to true if out of memory */ - u8 nErr; /* Number of errors seen */ +struct tdsqlite3_rebaser { + tdsqlite3_changegroup grp; /* Hash table */ }; -/************************************************************************** -** Utility routines for dealing with JsonString objects -**************************************************************************/ - -/* Set the JsonString object to an empty string -*/ -static void jsonZero(JsonString *p){ - p->zBuf = p->zSpace; - p->nAlloc = sizeof(p->zSpace); - p->nUsed = 0; - p->bStatic = 1; -} - -/* Initialize the JsonString object -*/ -static void jsonInit(JsonString *p, sqlite3_context *pCtx){ - p->pCtx = pCtx; - p->bErr = 0; - jsonZero(p); -} - - -/* Free all allocated memory and reset the JsonString object back to its -** initial state. -*/ -static void jsonReset(JsonString *p){ - if( !p->bStatic ) sqlite3_free(p->zBuf); - jsonZero(p); -} - - -/* Report an out-of-memory (OOM) condition -*/ -static void jsonOom(JsonString *p){ - p->bErr = 1; - sqlite3_result_error_nomem(p->pCtx); - jsonReset(p); -} - -/* Enlarge pJson->zBuf so that it can hold at least N more bytes. -** Return zero on success. Return non-zero on an OOM error -*/ -static int jsonGrow(JsonString *p, u32 N){ - u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10; - char *zNew; - if( p->bStatic ){ - if( p->bErr ) return 1; - zNew = sqlite3_malloc64(nTotal); - if( zNew==0 ){ - jsonOom(p); - return SQLITE_NOMEM; - } - memcpy(zNew, p->zBuf, (size_t)p->nUsed); - p->zBuf = zNew; - p->bStatic = 0; - }else{ - zNew = sqlite3_realloc64(p->zBuf, nTotal); - if( zNew==0 ){ - jsonOom(p); - return SQLITE_NOMEM; - } - p->zBuf = zNew; - } - p->nAlloc = nTotal; - return SQLITE_OK; -} - -/* Append N bytes from zIn onto the end of the JsonString string. -*/ -static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){ - if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return; - memcpy(p->zBuf+p->nUsed, zIn, N); - p->nUsed += N; -} - -/* Append formatted text (not to exceed N bytes) to the JsonString. -*/ -static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){ - va_list ap; - if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return; - va_start(ap, zFormat); - sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap); - va_end(ap); - p->nUsed += (int)strlen(p->zBuf+p->nUsed); -} - -/* Append a single character -*/ -static void jsonAppendChar(JsonString *p, char c){ - if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return; - p->zBuf[p->nUsed++] = c; -} - -/* Append a comma separator to the output buffer, if the previous -** character is not '[' or '{'. -*/ -static void jsonAppendSeparator(JsonString *p){ - char c; - if( p->nUsed==0 ) return; - c = p->zBuf[p->nUsed-1]; - if( c!='[' && c!='{' ) jsonAppendChar(p, ','); -} - -/* Append the N-byte string in zIn to the end of the JsonString string -** under construction. Enclose the string in "..." and escape -** any double-quotes or backslash characters contained within the -** string. -*/ -static void jsonAppendString(JsonString *p, const char *zIn, u32 N){ - u32 i; - if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return; - p->zBuf[p->nUsed++] = '"'; - for(i=0; i<N; i++){ - unsigned char c = ((unsigned const char*)zIn)[i]; - if( c=='"' || c=='\\' ){ - json_simple_escape: - if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return; - p->zBuf[p->nUsed++] = '\\'; - }else if( c<=0x1f ){ - static const char aSpecial[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - assert( sizeof(aSpecial)==32 ); - assert( aSpecial['\b']=='b' ); - assert( aSpecial['\f']=='f' ); - assert( aSpecial['\n']=='n' ); - assert( aSpecial['\r']=='r' ); - assert( aSpecial['\t']=='t' ); - if( aSpecial[c] ){ - c = aSpecial[c]; - goto json_simple_escape; - } - if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return; - p->zBuf[p->nUsed++] = '\\'; - p->zBuf[p->nUsed++] = 'u'; - p->zBuf[p->nUsed++] = '0'; - p->zBuf[p->nUsed++] = '0'; - p->zBuf[p->nUsed++] = '0' + (c>>4); - c = "0123456789abcdef"[c&0xf]; - } - p->zBuf[p->nUsed++] = c; - } - p->zBuf[p->nUsed++] = '"'; - assert( p->nUsed<p->nAlloc ); -} - /* -** Append a function parameter value to the JSON string under -** construction. +** Buffers a1 and a2 must both contain a sessions module record nCol +** fields in size. This function appends an nCol sessions module +** record to buffer pBuf that is a copy of a1, except that for +** each field that is undefined in a1[], swap in the field from a2[]. */ -static void jsonAppendValue( - JsonString *p, /* Append to this JSON string */ - sqlite3_value *pValue /* Value to append */ +static void sessionAppendRecordMerge( + SessionBuffer *pBuf, /* Buffer to append to */ + int nCol, /* Number of columns in each record */ + u8 *a1, int n1, /* Record 1 */ + u8 *a2, int n2, /* Record 2 */ + int *pRc /* IN/OUT: error code */ ){ - switch( sqlite3_value_type(pValue) ){ - case SQLITE_NULL: { - jsonAppendRaw(p, "null", 4); - break; - } - case SQLITE_INTEGER: - case SQLITE_FLOAT: { - const char *z = (const char*)sqlite3_value_text(pValue); - u32 n = (u32)sqlite3_value_bytes(pValue); - jsonAppendRaw(p, z, n); - break; - } - case SQLITE_TEXT: { - const char *z = (const char*)sqlite3_value_text(pValue); - u32 n = (u32)sqlite3_value_bytes(pValue); - if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){ - jsonAppendRaw(p, z, n); + sessionBufferGrow(pBuf, n1+n2, pRc); + if( *pRc==SQLITE_OK ){ + int i; + u8 *pOut = &pBuf->aBuf[pBuf->nBuf]; + for(i=0; i<nCol; i++){ + int nn1 = sessionSerialLen(a1); + int nn2 = sessionSerialLen(a2); + if( *a1==0 || *a1==0xFF ){ + memcpy(pOut, a2, nn2); + pOut += nn2; }else{ - jsonAppendString(p, z, n); - } - break; - } - default: { - if( p->bErr==0 ){ - sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1); - p->bErr = 2; - jsonReset(p); + memcpy(pOut, a1, nn1); + pOut += nn1; } - break; + a1 += nn1; + a2 += nn2; } - } -} - -/* Make the JSON in p the result of the SQL function. -*/ -static void jsonResult(JsonString *p){ - if( p->bErr==0 ){ - sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, - p->bStatic ? SQLITE_TRANSIENT : sqlite3_free, - SQLITE_UTF8); - jsonZero(p); + pBuf->nBuf = pOut-pBuf->aBuf; + assert( pBuf->nBuf<=pBuf->nAlloc ); } - assert( p->bStatic ); } -/************************************************************************** -** Utility routines for dealing with JsonNode and JsonParse objects -**************************************************************************/ - /* -** Return the number of consecutive JsonNode slots need to represent -** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and -** OBJECT types, the number might be larger. +** This function is called when rebasing a local UPDATE change against one +** or more remote UPDATE changes. The aRec/nRec buffer contains the current +** old.* and new.* records for the change. The rebase buffer (a single +** record) is in aChange/nChange. The rebased change is appended to buffer +** pBuf. ** -** Appended elements are not counted. The value returned is the number -** by which the JsonNode counter should increment in order to go to the -** next peer value. -*/ -static u32 jsonNodeSize(JsonNode *pNode){ - return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1; -} - -/* -** Reclaim all memory allocated by a JsonParse object. But do not -** delete the JsonParse object itself. -*/ -static void jsonParseReset(JsonParse *pParse){ - sqlite3_free(pParse->aNode); - pParse->aNode = 0; - pParse->nNode = 0; - pParse->nAlloc = 0; - sqlite3_free(pParse->aUp); - pParse->aUp = 0; -} - -/* -** Convert the JsonNode pNode into a pure JSON string and -** append to pOut. Subsubstructure is also included. Return -** the number of JsonNode objects that are encoded. -*/ -static void jsonRenderNode( - JsonNode *pNode, /* The node to render */ - JsonString *pOut, /* Write JSON here */ - sqlite3_value **aReplace /* Replacement values */ -){ - switch( pNode->eType ){ - default: { - assert( pNode->eType==JSON_NULL ); - jsonAppendRaw(pOut, "null", 4); - break; - } - case JSON_TRUE: { - jsonAppendRaw(pOut, "true", 4); - break; - } - case JSON_FALSE: { - jsonAppendRaw(pOut, "false", 5); - break; - } - case JSON_STRING: { - if( pNode->jnFlags & JNODE_RAW ){ - jsonAppendString(pOut, pNode->u.zJContent, pNode->n); - break; - } - /* Fall through into the next case */ - } - case JSON_REAL: - case JSON_INT: { - jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n); - break; - } - case JSON_ARRAY: { - u32 j = 1; - jsonAppendChar(pOut, '['); - for(;;){ - while( j<=pNode->n ){ - if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){ - if( pNode[j].jnFlags & JNODE_REPLACE ){ - jsonAppendSeparator(pOut); - jsonAppendValue(pOut, aReplace[pNode[j].iVal]); - } - }else{ - jsonAppendSeparator(pOut); - jsonRenderNode(&pNode[j], pOut, aReplace); - } - j += jsonNodeSize(&pNode[j]); - } - if( (pNode->jnFlags & JNODE_APPEND)==0 ) break; - pNode = &pNode[pNode->u.iAppend]; - j = 1; - } - jsonAppendChar(pOut, ']'); - break; - } - case JSON_OBJECT: { - u32 j = 1; - jsonAppendChar(pOut, '{'); - for(;;){ - while( j<=pNode->n ){ - if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){ - jsonAppendSeparator(pOut); - jsonRenderNode(&pNode[j], pOut, aReplace); - jsonAppendChar(pOut, ':'); - if( pNode[j+1].jnFlags & JNODE_REPLACE ){ - jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]); - }else{ - jsonRenderNode(&pNode[j+1], pOut, aReplace); - } - } - j += 1 + jsonNodeSize(&pNode[j+1]); - } - if( (pNode->jnFlags & JNODE_APPEND)==0 ) break; - pNode = &pNode[pNode->u.iAppend]; - j = 1; - } - jsonAppendChar(pOut, '}'); - break; - } - } -} - -/* -** Return a JsonNode and all its descendents as a JSON string. +** Rebasing the UPDATE involves: +** +** * Removing any changes to fields for which the corresponding field +** in the rebase buffer is set to "replaced" (type 0xFF). If this +** means the UPDATE change updates no fields, nothing is appended +** to the output buffer. +** +** * For each field modified by the local change for which the +** corresponding field in the rebase buffer is not "undefined" (0x00) +** or "replaced" (0xFF), the old.* value is replaced by the value +** in the rebase buffer. */ -static void jsonReturnJson( - JsonNode *pNode, /* Node to return */ - sqlite3_context *pCtx, /* Return value for this function */ - sqlite3_value **aReplace /* Array of replacement values */ +static void sessionAppendPartialUpdate( + SessionBuffer *pBuf, /* Append record here */ + tdsqlite3_changeset_iter *pIter, /* Iterator pointed at local change */ + u8 *aRec, int nRec, /* Local change */ + u8 *aChange, int nChange, /* Record to rebase against */ + int *pRc /* IN/OUT: Return Code */ ){ - JsonString s; - jsonInit(&s, pCtx); - jsonRenderNode(pNode, &s, aReplace); - jsonResult(&s); - sqlite3_result_subtype(pCtx, JSON_SUBTYPE); -} + sessionBufferGrow(pBuf, 2+nRec+nChange, pRc); + if( *pRc==SQLITE_OK ){ + int bData = 0; + u8 *pOut = &pBuf->aBuf[pBuf->nBuf]; + int i; + u8 *a1 = aRec; + u8 *a2 = aChange; -/* -** Make the JsonNode the return value of the function. -*/ -static void jsonReturn( - JsonNode *pNode, /* Node to return */ - sqlite3_context *pCtx, /* Return value for this function */ - sqlite3_value **aReplace /* Array of replacement values */ -){ - switch( pNode->eType ){ - default: { - assert( pNode->eType==JSON_NULL ); - sqlite3_result_null(pCtx); - break; - } - case JSON_TRUE: { - sqlite3_result_int(pCtx, 1); - break; - } - case JSON_FALSE: { - sqlite3_result_int(pCtx, 0); - break; - } - case JSON_INT: { - sqlite3_int64 i = 0; - const char *z = pNode->u.zJContent; - if( z[0]=='-' ){ z++; } - while( z[0]>='0' && z[0]<='9' ){ - unsigned v = *(z++) - '0'; - if( i>=LARGEST_INT64/10 ){ - if( i>LARGEST_INT64/10 ) goto int_as_real; - if( z[0]>='0' && z[0]<='9' ) goto int_as_real; - if( v==9 ) goto int_as_real; - if( v==8 ){ - if( pNode->u.zJContent[0]=='-' ){ - sqlite3_result_int64(pCtx, SMALLEST_INT64); - goto int_done; - }else{ - goto int_as_real; - } - } - } - i = i*10 + v; - } - if( pNode->u.zJContent[0]=='-' ){ i = -i; } - sqlite3_result_int64(pCtx, i); - int_done: - break; - int_as_real: /* fall through to real */; - } - case JSON_REAL: { - double r; -#ifdef SQLITE_AMALGAMATION - const char *z = pNode->u.zJContent; - sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8); -#else - r = strtod(pNode->u.zJContent, 0); -#endif - sqlite3_result_double(pCtx, r); - break; - } - case JSON_STRING: { -#if 0 /* Never happens because JNODE_RAW is only set by json_set(), - ** json_insert() and json_replace() and those routines do not - ** call jsonReturn() */ - if( pNode->jnFlags & JNODE_RAW ){ - sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n, - SQLITE_TRANSIENT); - }else -#endif - assert( (pNode->jnFlags & JNODE_RAW)==0 ); - if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){ - /* JSON formatted without any backslash-escapes */ - sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2, - SQLITE_TRANSIENT); + *pOut++ = SQLITE_UPDATE; + *pOut++ = pIter->bIndirect; + for(i=0; i<pIter->nCol; i++){ + int n1 = sessionSerialLen(a1); + int n2 = sessionSerialLen(a2); + if( pIter->abPK[i] || a2[0]==0 ){ + if( !pIter->abPK[i] ) bData = 1; + memcpy(pOut, a1, n1); + pOut += n1; + }else if( a2[0]!=0xFF ){ + bData = 1; + memcpy(pOut, a2, n2); + pOut += n2; }else{ - /* Translate JSON formatted string into raw text */ - u32 i; - u32 n = pNode->n; - const char *z = pNode->u.zJContent; - char *zOut; - u32 j; - zOut = sqlite3_malloc( n+1 ); - if( zOut==0 ){ - sqlite3_result_error_nomem(pCtx); - break; - } - for(i=1, j=0; i<n-1; i++){ - char c = z[i]; - if( c!='\\' ){ - zOut[j++] = c; - }else{ - c = z[++i]; - if( c=='u' ){ - u32 v = 0, k; - for(k=0; k<4 && i<n-2; i++, k++){ - c = z[i+1]; - if( c>='0' && c<='9' ) v = v*16 + c - '0'; - else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10; - else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10; - else break; - } - if( v==0 ) break; - if( v<=0x7f ){ - zOut[j++] = (char)v; - }else if( v<=0x7ff ){ - zOut[j++] = (char)(0xc0 | (v>>6)); - zOut[j++] = 0x80 | (v&0x3f); - }else{ - zOut[j++] = (char)(0xe0 | (v>>12)); - zOut[j++] = 0x80 | ((v>>6)&0x3f); - zOut[j++] = 0x80 | (v&0x3f); - } - }else{ - if( c=='b' ){ - c = '\b'; - }else if( c=='f' ){ - c = '\f'; - }else if( c=='n' ){ - c = '\n'; - }else if( c=='r' ){ - c = '\r'; - }else if( c=='t' ){ - c = '\t'; - } - zOut[j++] = c; - } - } - } - zOut[j] = 0; - sqlite3_result_text(pCtx, zOut, j, sqlite3_free); + *pOut++ = '\0'; } - break; - } - case JSON_ARRAY: - case JSON_OBJECT: { - jsonReturnJson(pNode, pCtx, aReplace); - break; - } - } -} - -/* Forward reference */ -static int jsonParseAddNode(JsonParse*,u32,u32,const char*); - -/* -** A macro to hint to the compiler that a function should not be -** inlined. -*/ -#if defined(__GNUC__) -# define JSON_NOINLINE __attribute__((noinline)) -#elif defined(_MSC_VER) && _MSC_VER>=1310 -# define JSON_NOINLINE __declspec(noinline) -#else -# define JSON_NOINLINE -#endif - - -static JSON_NOINLINE int jsonParseAddNodeExpand( - JsonParse *pParse, /* Append the node to this object */ - u32 eType, /* Node type */ - u32 n, /* Content size or sub-node count */ - const char *zContent /* Content */ -){ - u32 nNew; - JsonNode *pNew; - assert( pParse->nNode>=pParse->nAlloc ); - if( pParse->oom ) return -1; - nNew = pParse->nAlloc*2 + 10; - pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew); - if( pNew==0 ){ - pParse->oom = 1; - return -1; - } - pParse->nAlloc = nNew; - pParse->aNode = pNew; - assert( pParse->nNode<pParse->nAlloc ); - return jsonParseAddNode(pParse, eType, n, zContent); -} - -/* -** Create a new JsonNode instance based on the arguments and append that -** instance to the JsonParse. Return the index in pParse->aNode[] of the -** new node, or -1 if a memory allocation fails. -*/ -static int jsonParseAddNode( - JsonParse *pParse, /* Append the node to this object */ - u32 eType, /* Node type */ - u32 n, /* Content size or sub-node count */ - const char *zContent /* Content */ -){ - JsonNode *p; - if( pParse->nNode>=pParse->nAlloc ){ - return jsonParseAddNodeExpand(pParse, eType, n, zContent); - } - p = &pParse->aNode[pParse->nNode]; - p->eType = (u8)eType; - p->jnFlags = 0; - p->iVal = 0; - p->n = n; - p->u.zJContent = zContent; - return pParse->nNode++; -} - -/* -** Return true if z[] begins with 4 (or more) hexadecimal digits -*/ -static int jsonIs4Hex(const char *z){ - int i; - for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0; - return 1; -} - -/* -** Parse a single JSON value which begins at pParse->zJson[i]. Return the -** index of the first character past the end of the value parsed. -** -** Return negative for a syntax error. Special cases: return -2 if the -** first non-whitespace character is '}' and return -3 if the first -** non-whitespace character is ']'. -*/ -static int jsonParseValue(JsonParse *pParse, u32 i){ - char c; - u32 j; - int iThis; - int x; - JsonNode *pNode; - while( safe_isspace(pParse->zJson[i]) ){ i++; } - if( (c = pParse->zJson[i])=='{' ){ - /* Parse object */ - iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0); - if( iThis<0 ) return -1; - for(j=i+1;;j++){ - while( safe_isspace(pParse->zJson[j]) ){ j++; } - x = jsonParseValue(pParse, j); - if( x<0 ){ - if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1; - return -1; - } - if( pParse->oom ) return -1; - pNode = &pParse->aNode[pParse->nNode-1]; - if( pNode->eType!=JSON_STRING ) return -1; - pNode->jnFlags |= JNODE_LABEL; - j = x; - while( safe_isspace(pParse->zJson[j]) ){ j++; } - if( pParse->zJson[j]!=':' ) return -1; - j++; - x = jsonParseValue(pParse, j); - if( x<0 ) return -1; - j = x; - while( safe_isspace(pParse->zJson[j]) ){ j++; } - c = pParse->zJson[j]; - if( c==',' ) continue; - if( c!='}' ) return -1; - break; - } - pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1; - return j+1; - }else if( c=='[' ){ - /* Parse array */ - iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0); - if( iThis<0 ) return -1; - for(j=i+1;;j++){ - while( safe_isspace(pParse->zJson[j]) ){ j++; } - x = jsonParseValue(pParse, j); - if( x<0 ){ - if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1; - return -1; - } - j = x; - while( safe_isspace(pParse->zJson[j]) ){ j++; } - c = pParse->zJson[j]; - if( c==',' ) continue; - if( c!=']' ) return -1; - break; + a1 += n1; + a2 += n2; } - pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1; - return j+1; - }else if( c=='"' ){ - /* Parse string */ - u8 jnFlags = 0; - j = i+1; - for(;;){ - c = pParse->zJson[j]; - if( c==0 ) return -1; - if( c=='\\' ){ - c = pParse->zJson[++j]; - if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f' - || c=='n' || c=='r' || c=='t' - || (c=='u' && jsonIs4Hex(pParse->zJson+j+1)) ){ - jnFlags = JNODE_ESCAPE; + if( bData ){ + a2 = aChange; + for(i=0; i<pIter->nCol; i++){ + int n1 = sessionSerialLen(a1); + int n2 = sessionSerialLen(a2); + if( pIter->abPK[i] || a2[0]!=0xFF ){ + memcpy(pOut, a1, n1); + pOut += n1; }else{ - return -1; - } - }else if( c=='"' ){ - break; - } - j++; - } - jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]); - if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags; - return j+1; - }else if( c=='n' - && strncmp(pParse->zJson+i,"null",4)==0 - && !safe_isalnum(pParse->zJson[i+4]) ){ - jsonParseAddNode(pParse, JSON_NULL, 0, 0); - return i+4; - }else if( c=='t' - && strncmp(pParse->zJson+i,"true",4)==0 - && !safe_isalnum(pParse->zJson[i+4]) ){ - jsonParseAddNode(pParse, JSON_TRUE, 0, 0); - return i+4; - }else if( c=='f' - && strncmp(pParse->zJson+i,"false",5)==0 - && !safe_isalnum(pParse->zJson[i+5]) ){ - jsonParseAddNode(pParse, JSON_FALSE, 0, 0); - return i+5; - }else if( c=='-' || (c>='0' && c<='9') ){ - /* Parse number */ - u8 seenDP = 0; - u8 seenE = 0; - j = i+1; - for(;; j++){ - c = pParse->zJson[j]; - if( c>='0' && c<='9' ) continue; - if( c=='.' ){ - if( pParse->zJson[j-1]=='-' ) return -1; - if( seenDP ) return -1; - seenDP = 1; - continue; - } - if( c=='e' || c=='E' ){ - if( pParse->zJson[j-1]<'0' ) return -1; - if( seenE ) return -1; - seenDP = seenE = 1; - c = pParse->zJson[j+1]; - if( c=='+' || c=='-' ){ - j++; - c = pParse->zJson[j+1]; + *pOut++ = '\0'; } - if( c<'0' || c>'9' ) return -1; - continue; + a1 += n1; + a2 += n2; } - break; + pBuf->nBuf = (pOut - pBuf->aBuf); } - if( pParse->zJson[j-1]<'0' ) return -1; - jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT, - j - i, &pParse->zJson[i]); - return j; - }else if( c=='}' ){ - return -2; /* End of {...} */ - }else if( c==']' ){ - return -3; /* End of [...] */ - }else if( c==0 ){ - return 0; /* End of file */ - }else{ - return -1; /* Syntax error */ } } /* -** Parse a complete JSON string. Return 0 on success or non-zero if there -** are any errors. If an error occurs, free all memory associated with -** pParse. +** pIter is configured to iterate through a changeset. This function rebases +** that changeset according to the current configuration of the rebaser +** object passed as the first argument. If no error occurs and argument xOutput +** is not NULL, then the changeset is returned to the caller by invoking +** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL, +** then (*ppOut) is set to point to a buffer containing the rebased changeset +** before this function returns. In this case (*pnOut) is set to the size of +** the buffer in bytes. It is the responsibility of the caller to eventually +** free the (*ppOut) buffer using tdsqlite3_free(). ** -** pParse is uninitialized when this routine is called. +** If an error occurs, an SQLite error code is returned. If ppOut and +** pnOut are not NULL, then the two output parameters are set to 0 before +** returning. */ -static int jsonParse( - JsonParse *pParse, /* Initialize and fill this JsonParse object */ - sqlite3_context *pCtx, /* Report errors here */ - const char *zJson /* Input JSON text to be parsed */ +static int sessionRebase( + tdsqlite3_rebaser *p, /* Rebaser hash table */ + tdsqlite3_changeset_iter *pIter, /* Input data */ + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut, /* Context for xOutput callback */ + int *pnOut, /* OUT: Number of bytes in output changeset */ + void **ppOut /* OUT: Inverse of pChangeset */ ){ - int i; - memset(pParse, 0, sizeof(*pParse)); - if( zJson==0 ) return 1; - pParse->zJson = zJson; - i = jsonParseValue(pParse, 0); - if( pParse->oom ) i = -1; - if( i>0 ){ - while( safe_isspace(zJson[i]) ) i++; - if( zJson[i] ) i = -1; - } - if( i<=0 ){ - if( pCtx!=0 ){ - if( pParse->oom ){ - sqlite3_result_error_nomem(pCtx); - }else{ - sqlite3_result_error(pCtx, "malformed JSON", -1); - } - } - jsonParseReset(pParse); - return 1; - } - return 0; -} + int rc = SQLITE_OK; + u8 *aRec = 0; + int nRec = 0; + int bNew = 0; + SessionTable *pTab = 0; + SessionBuffer sOut = {0,0,0}; -/* Mark node i of pParse as being a child of iParent. Call recursively -** to fill in all the descendants of node i. -*/ -static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){ - JsonNode *pNode = &pParse->aNode[i]; - u32 j; - pParse->aUp[i] = iParent; - switch( pNode->eType ){ - case JSON_ARRAY: { - for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){ - jsonParseFillInParentage(pParse, i+j, i); - } - break; - } - case JSON_OBJECT: { - for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){ - pParse->aUp[i+j] = i; - jsonParseFillInParentage(pParse, i+j+1, i); + while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){ + SessionChange *pChange = 0; + int bDone = 0; + + if( bNew ){ + const char *zTab = pIter->zTab; + for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){ + if( 0==tdsqlite3_stricmp(pTab->zName, zTab) ) break; } - break; - } - default: { - break; - } - } -} + bNew = 0; -/* -** Compute the parentage of all nodes in a completed parse. -*/ -static int jsonParseFindParents(JsonParse *pParse){ - u32 *aUp; - assert( pParse->aUp==0 ); - aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode ); - if( aUp==0 ){ - pParse->oom = 1; - return SQLITE_NOMEM; - } - jsonParseFillInParentage(pParse, 0, 0); - return SQLITE_OK; -} + /* A patchset may not be rebased */ + if( pIter->bPatchset ){ + rc = SQLITE_ERROR; + } -/* -** Compare the OBJECT label at pNode against zKey,nKey. Return true on -** a match. -*/ -static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){ - if( pNode->jnFlags & JNODE_RAW ){ - if( pNode->n!=nKey ) return 0; - return strncmp(pNode->u.zJContent, zKey, nKey)==0; - }else{ - if( pNode->n!=nKey+2 ) return 0; - return strncmp(pNode->u.zJContent+1, zKey, nKey)==0; - } -} + /* Append a table header to the output for this new table */ + sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc); + sessionAppendVarint(&sOut, pIter->nCol, &rc); + sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc); + sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc); + } -/* forward declaration */ -static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**); + if( pTab && rc==SQLITE_OK ){ + int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange); -/* -** Search along zPath to find the node specified. Return a pointer -** to that node, or NULL if zPath is malformed or if there is no such -** node. -** -** If pApnd!=0, then try to append new nodes to complete zPath if it is -** possible to do so and if no existing node corresponds to zPath. If -** new nodes are appended *pApnd is set to 1. -*/ -static JsonNode *jsonLookupStep( - JsonParse *pParse, /* The JSON to search */ - u32 iRoot, /* Begin the search at this node */ - const char *zPath, /* The path to search */ - int *pApnd, /* Append nodes to complete path if not NULL */ - const char **pzErr /* Make *pzErr point to any syntax error in zPath */ -){ - u32 i, j, nKey; - const char *zKey; - JsonNode *pRoot = &pParse->aNode[iRoot]; - if( zPath[0]==0 ) return pRoot; - if( zPath[0]=='.' ){ - if( pRoot->eType!=JSON_OBJECT ) return 0; - zPath++; - if( zPath[0]=='"' ){ - zKey = zPath + 1; - for(i=1; zPath[i] && zPath[i]!='"'; i++){} - nKey = i-1; - if( zPath[i] ){ - i++; - }else{ - *pzErr = zPath; - return 0; - } - }else{ - zKey = zPath; - for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){} - nKey = i; - } - if( nKey==0 ){ - *pzErr = zPath; - return 0; - } - j = 1; - for(;;){ - while( j<=pRoot->n ){ - if( jsonLabelCompare(pRoot+j, zKey, nKey) ){ - return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr); + for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){ + if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){ + break; } - j++; - j += jsonNodeSize(&pRoot[j]); - } - if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break; - iRoot += pRoot->u.iAppend; - pRoot = &pParse->aNode[iRoot]; - j = 1; - } - if( pApnd ){ - u32 iStart, iLabel; - JsonNode *pNode; - iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0); - iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath); - zPath += i; - pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr); - if( pParse->oom ) return 0; - if( pNode ){ - pRoot = &pParse->aNode[iRoot]; - pRoot->u.iAppend = iStart - iRoot; - pRoot->jnFlags |= JNODE_APPEND; - pParse->aNode[iLabel].jnFlags |= JNODE_RAW; - } - return pNode; - } - }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){ - if( pRoot->eType!=JSON_ARRAY ) return 0; - i = 0; - j = 1; - while( safe_isdigit(zPath[j]) ){ - i = i*10 + zPath[j] - '0'; - j++; - } - if( zPath[j]!=']' ){ - *pzErr = zPath; - return 0; - } - zPath += j + 1; - j = 1; - for(;;){ - while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){ - if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--; - j += jsonNodeSize(&pRoot[j]); - } - if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break; - iRoot += pRoot->u.iAppend; - pRoot = &pParse->aNode[iRoot]; - j = 1; - } - if( j<=pRoot->n ){ - return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr); - } - if( i==0 && pApnd ){ - u32 iStart; - JsonNode *pNode; - iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0); - pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr); - if( pParse->oom ) return 0; - if( pNode ){ - pRoot = &pParse->aNode[iRoot]; - pRoot->u.iAppend = iStart - iRoot; - pRoot->jnFlags |= JNODE_APPEND; } - return pNode; - } - }else{ - *pzErr = zPath; - } - return 0; -} - -/* -** Append content to pParse that will complete zPath. Return a pointer -** to the inserted node, or return NULL if the append fails. -*/ -static JsonNode *jsonLookupAppend( - JsonParse *pParse, /* Append content to the JSON parse */ - const char *zPath, /* Description of content to append */ - int *pApnd, /* Set this flag to 1 */ - const char **pzErr /* Make this point to any syntax error */ -){ - *pApnd = 1; - if( zPath[0]==0 ){ - jsonParseAddNode(pParse, JSON_NULL, 0, 0); - return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1]; - } - if( zPath[0]=='.' ){ - jsonParseAddNode(pParse, JSON_OBJECT, 0, 0); - }else if( strncmp(zPath,"[0]",3)==0 ){ - jsonParseAddNode(pParse, JSON_ARRAY, 0, 0); - }else{ - return 0; - } - if( pParse->oom ) return 0; - return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr); -} - -/* -** Return the text of a syntax error message on a JSON path. Space is -** obtained from sqlite3_malloc(). -*/ -static char *jsonPathSyntaxError(const char *zErr){ - return sqlite3_mprintf("JSON path error near '%q'", zErr); -} - -/* -** Do a node lookup using zPath. Return a pointer to the node on success. -** Return NULL if not found or if there is an error. -** -** On an error, write an error message into pCtx and increment the -** pParse->nErr counter. -** -** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if -** nodes are appended. -*/ -static JsonNode *jsonLookup( - JsonParse *pParse, /* The JSON to search */ - const char *zPath, /* The path to search */ - int *pApnd, /* Append nodes to complete path if not NULL */ - sqlite3_context *pCtx /* Report errors here, if not NULL */ -){ - const char *zErr = 0; - JsonNode *pNode = 0; - char *zMsg; - - if( zPath==0 ) return 0; - if( zPath[0]!='$' ){ - zErr = zPath; - goto lookup_err; - } - zPath++; - pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr); - if( zErr==0 ) return pNode; - -lookup_err: - pParse->nErr++; - assert( zErr!=0 && pCtx!=0 ); - zMsg = jsonPathSyntaxError(zErr); - if( zMsg ){ - sqlite3_result_error(pCtx, zMsg, -1); - sqlite3_free(zMsg); - }else{ - sqlite3_result_error_nomem(pCtx); - } - return 0; -} - - -/* -** Report the wrong number of arguments for json_insert(), json_replace() -** or json_set(). -*/ -static void jsonWrongNumArgs( - sqlite3_context *pCtx, - const char *zFuncName -){ - char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments", - zFuncName); - sqlite3_result_error(pCtx, zMsg, -1); - sqlite3_free(zMsg); -} - - -/**************************************************************************** -** SQL functions used for testing and debugging -****************************************************************************/ - -#ifdef SQLITE_DEBUG -/* -** The json_parse(JSON) function returns a string which describes -** a parse of the JSON provided. Or it returns NULL if JSON is not -** well-formed. -*/ -static void jsonParseFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonString s; /* Output string - not real JSON */ - JsonParse x; /* The parse */ - u32 i; - - assert( argc==1 ); - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - jsonParseFindParents(&x); - jsonInit(&s, ctx); - for(i=0; i<x.nNode; i++){ - const char *zType; - if( x.aNode[i].jnFlags & JNODE_LABEL ){ - assert( x.aNode[i].eType==JSON_STRING ); - zType = "label"; - }else{ - zType = jsonType[x.aNode[i].eType]; } - jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d", - i, zType, x.aNode[i].n, x.aUp[i]); - if( x.aNode[i].u.zJContent!=0 ){ - jsonAppendRaw(&s, " ", 1); - jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n); - } - jsonAppendRaw(&s, "\n", 1); - } - jsonParseReset(&x); - jsonResult(&s); -} -/* -** The json_test1(JSON) function return true (1) if the input is JSON -** text generated by another json function. It returns (0) if the input -** is not known to be JSON. -*/ -static void jsonTest1Func( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - UNUSED_PARAM(argc); - sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE); -} -#endif /* SQLITE_DEBUG */ - -/**************************************************************************** -** Scalar SQL function implementations -****************************************************************************/ - -/* -** Implementation of the json_QUOTE(VALUE) function. Return a JSON value -** corresponding to the SQL value input. Mostly this means putting -** double-quotes around strings and returning the unquoted string "null" -** when given a NULL input. -*/ -static void jsonQuoteFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonString jx; - UNUSED_PARAM(argc); - - jsonInit(&jx, ctx); - jsonAppendValue(&jx, argv[0]); - jsonResult(&jx); - sqlite3_result_subtype(ctx, JSON_SUBTYPE); -} - -/* -** Implementation of the json_array(VALUE,...) function. Return a JSON -** array that contains all values given in arguments. Or if any argument -** is a BLOB, throw an error. -*/ -static void jsonArrayFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - int i; - JsonString jx; - - jsonInit(&jx, ctx); - jsonAppendChar(&jx, '['); - for(i=0; i<argc; i++){ - jsonAppendSeparator(&jx); - jsonAppendValue(&jx, argv[i]); - } - jsonAppendChar(&jx, ']'); - jsonResult(&jx); - sqlite3_result_subtype(ctx, JSON_SUBTYPE); -} - - -/* -** json_array_length(JSON) -** json_array_length(JSON, PATH) -** -** Return the number of elements in the top-level JSON array. -** Return 0 if the input is not a well-formed JSON array. -*/ -static void jsonArrayLengthFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse x; /* The parse */ - sqlite3_int64 n = 0; - u32 i; - JsonNode *pNode; - - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - assert( x.nNode ); - if( argc==2 ){ - const char *zPath = (const char*)sqlite3_value_text(argv[1]); - pNode = jsonLookup(&x, zPath, 0, ctx); - }else{ - pNode = x.aNode; - } - if( pNode==0 ){ - x.nErr = 1; - }else if( pNode->eType==JSON_ARRAY ){ - assert( (pNode->jnFlags & JNODE_APPEND)==0 ); - for(i=1; i<=pNode->n; n++){ - i += jsonNodeSize(&pNode[i]); - } - } - if( x.nErr==0 ) sqlite3_result_int64(ctx, n); - jsonParseReset(&x); -} + if( pChange ){ + assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT ); + switch( pIter->op ){ + case SQLITE_INSERT: + if( pChange->op==SQLITE_INSERT ){ + bDone = 1; + if( pChange->bIndirect==0 ){ + sessionAppendByte(&sOut, SQLITE_UPDATE, &rc); + sessionAppendByte(&sOut, pIter->bIndirect, &rc); + sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc); + sessionAppendBlob(&sOut, aRec, nRec, &rc); + } + } + break; -/* -** json_extract(JSON, PATH, ...) -** -** Return the element described by PATH. Return NULL if there is no -** PATH element. If there are multiple PATHs, then return a JSON array -** with the result from each path. Throw an error if the JSON or any PATH -** is malformed. -*/ -static void jsonExtractFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse x; /* The parse */ - JsonNode *pNode; - const char *zPath; - JsonString jx; - int i; + case SQLITE_UPDATE: + bDone = 1; + if( pChange->op==SQLITE_DELETE ){ + if( pChange->bIndirect==0 ){ + u8 *pCsr = aRec; + sessionSkipRecord(&pCsr, pIter->nCol); + sessionAppendByte(&sOut, SQLITE_INSERT, &rc); + sessionAppendByte(&sOut, pIter->bIndirect, &rc); + sessionAppendRecordMerge(&sOut, pIter->nCol, + pCsr, nRec-(pCsr-aRec), + pChange->aRecord, pChange->nRecord, &rc + ); + } + }else{ + sessionAppendPartialUpdate(&sOut, pIter, + aRec, nRec, pChange->aRecord, pChange->nRecord, &rc + ); + } + break; - if( argc<2 ) return; - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - jsonInit(&jx, ctx); - jsonAppendChar(&jx, '['); - for(i=1; i<argc; i++){ - zPath = (const char*)sqlite3_value_text(argv[i]); - pNode = jsonLookup(&x, zPath, 0, ctx); - if( x.nErr ) break; - if( argc>2 ){ - jsonAppendSeparator(&jx); - if( pNode ){ - jsonRenderNode(pNode, &jx, 0); - }else{ - jsonAppendRaw(&jx, "null", 4); + default: + assert( pIter->op==SQLITE_DELETE ); + bDone = 1; + if( pChange->op==SQLITE_INSERT ){ + sessionAppendByte(&sOut, SQLITE_DELETE, &rc); + sessionAppendByte(&sOut, pIter->bIndirect, &rc); + sessionAppendRecordMerge(&sOut, pIter->nCol, + pChange->aRecord, pChange->nRecord, aRec, nRec, &rc + ); + } + break; } - }else if( pNode ){ - jsonReturn(pNode, ctx, 0); } - } - if( argc>2 && i==argc ){ - jsonAppendChar(&jx, ']'); - jsonResult(&jx); - sqlite3_result_subtype(ctx, JSON_SUBTYPE); - } - jsonReset(&jx); - jsonParseReset(&x); -} -/* -** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON -** object that contains all name/value given in arguments. Or if any name -** is not a string or if any value is a BLOB, throw an error. -*/ -static void jsonObjectFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - int i; - JsonString jx; - const char *z; - u32 n; - - if( argc&1 ){ - sqlite3_result_error(ctx, "json_object() requires an even number " - "of arguments", -1); - return; - } - jsonInit(&jx, ctx); - jsonAppendChar(&jx, '{'); - for(i=0; i<argc; i+=2){ - if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){ - sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1); - jsonReset(&jx); - return; + if( bDone==0 ){ + sessionAppendByte(&sOut, pIter->op, &rc); + sessionAppendByte(&sOut, pIter->bIndirect, &rc); + sessionAppendBlob(&sOut, aRec, nRec, &rc); } - jsonAppendSeparator(&jx); - z = (const char*)sqlite3_value_text(argv[i]); - n = (u32)sqlite3_value_bytes(argv[i]); - jsonAppendString(&jx, z, n); - jsonAppendChar(&jx, ':'); - jsonAppendValue(&jx, argv[i+1]); + if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){ + rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); + sOut.nBuf = 0; + } + if( rc ) break; } - jsonAppendChar(&jx, '}'); - jsonResult(&jx); - sqlite3_result_subtype(ctx, JSON_SUBTYPE); -} - - -/* -** json_remove(JSON, PATH, ...) -** -** Remove the named elements from JSON and return the result. malformed -** JSON or PATH arguments result in an error. -*/ -static void jsonRemoveFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse x; /* The parse */ - JsonNode *pNode; - const char *zPath; - u32 i; - if( argc<1 ) return; - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - assert( x.nNode ); - for(i=1; i<(u32)argc; i++){ - zPath = (const char*)sqlite3_value_text(argv[i]); - if( zPath==0 ) goto remove_done; - pNode = jsonLookup(&x, zPath, 0, ctx); - if( x.nErr ) goto remove_done; - if( pNode ) pNode->jnFlags |= JNODE_REMOVE; - } - if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){ - jsonReturnJson(x.aNode, ctx, 0); + if( rc!=SQLITE_OK ){ + tdsqlite3_free(sOut.aBuf); + memset(&sOut, 0, sizeof(sOut)); } -remove_done: - jsonParseReset(&x); -} -/* -** json_replace(JSON, PATH, VALUE, ...) -** -** Replace the value at PATH with VALUE. If PATH does not already exist, -** this routine is a no-op. If JSON or PATH is malformed, throw an error. -*/ -static void jsonReplaceFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse x; /* The parse */ - JsonNode *pNode; - const char *zPath; - u32 i; - - if( argc<1 ) return; - if( (argc&1)==0 ) { - jsonWrongNumArgs(ctx, "replace"); - return; - } - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - assert( x.nNode ); - for(i=1; i<(u32)argc; i+=2){ - zPath = (const char*)sqlite3_value_text(argv[i]); - pNode = jsonLookup(&x, zPath, 0, ctx); - if( x.nErr ) goto replace_err; - if( pNode ){ - pNode->jnFlags |= (u8)JNODE_REPLACE; - pNode->iVal = (u8)(i+1); + if( rc==SQLITE_OK ){ + if( xOutput ){ + if( sOut.nBuf>0 ){ + rc = xOutput(pOut, sOut.aBuf, sOut.nBuf); + } + }else{ + *ppOut = (void*)sOut.aBuf; + *pnOut = sOut.nBuf; + sOut.aBuf = 0; } } - if( x.aNode[0].jnFlags & JNODE_REPLACE ){ - sqlite3_result_value(ctx, argv[x.aNode[0].iVal]); - }else{ - jsonReturnJson(x.aNode, ctx, argv); - } -replace_err: - jsonParseReset(&x); + tdsqlite3_free(sOut.aBuf); + return rc; } -/* -** json_set(JSON, PATH, VALUE, ...) -** -** Set the value at PATH to VALUE. Create the PATH if it does not already -** exist. Overwrite existing values that do exist. -** If JSON or PATH is malformed, throw an error. -** -** json_insert(JSON, PATH, VALUE, ...) -** -** Create PATH and initialize it to VALUE. If PATH already exists, this -** routine is a no-op. If JSON or PATH is malformed, throw an error. +/* +** Create a new rebaser object. */ -static void jsonSetFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse x; /* The parse */ - JsonNode *pNode; - const char *zPath; - u32 i; - int bApnd; - int bIsSet = *(int*)sqlite3_user_data(ctx); +SQLITE_API int tdsqlite3rebaser_create(tdsqlite3_rebaser **ppNew){ + int rc = SQLITE_OK; + tdsqlite3_rebaser *pNew; - if( argc<1 ) return; - if( (argc&1)==0 ) { - jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert"); - return; - } - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - assert( x.nNode ); - for(i=1; i<(u32)argc; i+=2){ - zPath = (const char*)sqlite3_value_text(argv[i]); - bApnd = 0; - pNode = jsonLookup(&x, zPath, &bApnd, ctx); - if( x.oom ){ - sqlite3_result_error_nomem(ctx); - goto jsonSetDone; - }else if( x.nErr ){ - goto jsonSetDone; - }else if( pNode && (bApnd || bIsSet) ){ - pNode->jnFlags |= (u8)JNODE_REPLACE; - pNode->iVal = (u8)(i+1); - } - } - if( x.aNode[0].jnFlags & JNODE_REPLACE ){ - sqlite3_result_value(ctx, argv[x.aNode[0].iVal]); + pNew = tdsqlite3_malloc(sizeof(tdsqlite3_rebaser)); + if( pNew==0 ){ + rc = SQLITE_NOMEM; }else{ - jsonReturnJson(x.aNode, ctx, argv); + memset(pNew, 0, sizeof(tdsqlite3_rebaser)); } -jsonSetDone: - jsonParseReset(&x); + *ppNew = pNew; + return rc; } -/* -** json_type(JSON) -** json_type(JSON, PATH) -** -** Return the top-level "type" of a JSON string. Throw an error if -** either the JSON or PATH inputs are not well-formed. +/* +** Call this one or more times to configure a rebaser. */ -static void jsonTypeFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv +SQLITE_API int tdsqlite3rebaser_configure( + tdsqlite3_rebaser *p, + int nRebase, const void *pRebase ){ - JsonParse x; /* The parse */ - const char *zPath; - JsonNode *pNode; - - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - assert( x.nNode ); - if( argc==2 ){ - zPath = (const char*)sqlite3_value_text(argv[1]); - pNode = jsonLookup(&x, zPath, 0, ctx); - }else{ - pNode = x.aNode; - } - if( pNode ){ - sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC); + tdsqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */ + int rc; /* Return code */ + rc = tdsqlite3changeset_start(&pIter, nRebase, (void*)pRebase); + if( rc==SQLITE_OK ){ + rc = sessionChangesetToHash(pIter, &p->grp, 1); } - jsonParseReset(&x); + tdsqlite3changeset_finalize(pIter); + return rc; } -/* -** json_valid(JSON) -** -** Return 1 if JSON is a well-formed JSON string according to RFC-7159. -** Return 0 otherwise. +/* +** Rebase a changeset according to current rebaser configuration */ -static void jsonValidFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv +SQLITE_API int tdsqlite3rebaser_rebase( + tdsqlite3_rebaser *p, + int nIn, const void *pIn, + int *pnOut, void **ppOut ){ - JsonParse x; /* The parse */ - int rc = 0; + tdsqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */ + int rc = tdsqlite3changeset_start(&pIter, nIn, (void*)pIn); - UNUSED_PARAM(argc); - if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){ - rc = 1; + if( rc==SQLITE_OK ){ + rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut); + tdsqlite3changeset_finalize(pIter); } - jsonParseReset(&x); - sqlite3_result_int(ctx, rc); -} - -/**************************************************************************** -** Aggregate SQL function implementations -****************************************************************************/ -/* -** json_group_array(VALUE) -** -** Return a JSON array composed of all values in the aggregate. -*/ -static void jsonArrayStep( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonString *pStr; - UNUSED_PARAM(argc); - pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr)); - if( pStr ){ - if( pStr->zBuf==0 ){ - jsonInit(pStr, ctx); - jsonAppendChar(pStr, '['); - }else{ - jsonAppendChar(pStr, ','); - pStr->pCtx = ctx; - } - jsonAppendValue(pStr, argv[0]); - } -} -static void jsonArrayFinal(sqlite3_context *ctx){ - JsonString *pStr; - pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); - if( pStr ){ - pStr->pCtx = ctx; - jsonAppendChar(pStr, ']'); - if( pStr->bErr ){ - if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx); - assert( pStr->bStatic ); - }else{ - sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed, - pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free); - pStr->bStatic = 1; - } - }else{ - sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC); - } - sqlite3_result_subtype(ctx, JSON_SUBTYPE); + return rc; } -/* -** json_group_obj(NAME,VALUE) -** -** Return a JSON object composed of all names and values in the aggregate. +/* +** Rebase a changeset according to current rebaser configuration */ -static void jsonObjectStep( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonString *pStr; - const char *z; - u32 n; - UNUSED_PARAM(argc); - pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr)); - if( pStr ){ - if( pStr->zBuf==0 ){ - jsonInit(pStr, ctx); - jsonAppendChar(pStr, '{'); - }else{ - jsonAppendChar(pStr, ','); - pStr->pCtx = ctx; - } - z = (const char*)sqlite3_value_text(argv[0]); - n = (u32)sqlite3_value_bytes(argv[0]); - jsonAppendString(pStr, z, n); - jsonAppendChar(pStr, ':'); - jsonAppendValue(pStr, argv[1]); - } -} -static void jsonObjectFinal(sqlite3_context *ctx){ - JsonString *pStr; - pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); - if( pStr ){ - jsonAppendChar(pStr, '}'); - if( pStr->bErr ){ - if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx); - assert( pStr->bStatic ); - }else{ - sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed, - pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free); - pStr->bStatic = 1; - } - }else{ - sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC); - } - sqlite3_result_subtype(ctx, JSON_SUBTYPE); -} - - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/**************************************************************************** -** The json_each virtual table -****************************************************************************/ -typedef struct JsonEachCursor JsonEachCursor; -struct JsonEachCursor { - sqlite3_vtab_cursor base; /* Base class - must be first */ - u32 iRowid; /* The rowid */ - u32 iBegin; /* The first node of the scan */ - u32 i; /* Index in sParse.aNode[] of current row */ - u32 iEnd; /* EOF when i equals or exceeds this value */ - u8 eType; /* Type of top-level element */ - u8 bRecursive; /* True for json_tree(). False for json_each() */ - char *zJson; /* Input JSON */ - char *zRoot; /* Path by which to filter zJson */ - JsonParse sParse; /* Parse of the input JSON */ -}; - -/* Constructor for the json_each virtual table */ -static int jsonEachConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr +SQLITE_API int tdsqlite3rebaser_rebase_strm( + tdsqlite3_rebaser *p, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut ){ - sqlite3_vtab *pNew; - int rc; - -/* Column numbers */ -#define JEACH_KEY 0 -#define JEACH_VALUE 1 -#define JEACH_TYPE 2 -#define JEACH_ATOM 3 -#define JEACH_ID 4 -#define JEACH_PARENT 5 -#define JEACH_FULLKEY 6 -#define JEACH_PATH 7 -#define JEACH_JSON 8 -#define JEACH_ROOT 9 + tdsqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */ + int rc = tdsqlite3changeset_start_strm(&pIter, xInput, pIn); - UNUSED_PARAM(pzErr); - UNUSED_PARAM(argv); - UNUSED_PARAM(argc); - UNUSED_PARAM(pAux); - rc = sqlite3_declare_vtab(db, - "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path," - "json HIDDEN,root HIDDEN)"); if( rc==SQLITE_OK ){ - pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) ); - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(*pNew)); + rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0); + tdsqlite3changeset_finalize(pIter); } - return rc; -} - -/* destructor for json_each virtual table */ -static int jsonEachDisconnect(sqlite3_vtab *pVtab){ - sqlite3_free(pVtab); - return SQLITE_OK; -} - -/* constructor for a JsonEachCursor object for json_each(). */ -static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - JsonEachCursor *pCur; - UNUSED_PARAM(p); - pCur = sqlite3_malloc( sizeof(*pCur) ); - if( pCur==0 ) return SQLITE_NOMEM; - memset(pCur, 0, sizeof(*pCur)); - *ppCursor = &pCur->base; - return SQLITE_OK; -} - -/* constructor for a JsonEachCursor object for json_tree(). */ -static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - int rc = jsonEachOpenEach(p, ppCursor); - if( rc==SQLITE_OK ){ - JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor; - pCur->bRecursive = 1; - } return rc; } -/* Reset a JsonEachCursor back to its original state. Free any memory -** held. */ -static void jsonEachCursorReset(JsonEachCursor *p){ - sqlite3_free(p->zJson); - sqlite3_free(p->zRoot); - jsonParseReset(&p->sParse); - p->iRowid = 0; - p->i = 0; - p->iEnd = 0; - p->eType = 0; - p->zJson = 0; - p->zRoot = 0; -} - -/* Destructor for a jsonEachCursor object */ -static int jsonEachClose(sqlite3_vtab_cursor *cur){ - JsonEachCursor *p = (JsonEachCursor*)cur; - jsonEachCursorReset(p); - sqlite3_free(cur); - return SQLITE_OK; -} - -/* Return TRUE if the jsonEachCursor object has been advanced off the end -** of the JSON object */ -static int jsonEachEof(sqlite3_vtab_cursor *cur){ - JsonEachCursor *p = (JsonEachCursor*)cur; - return p->i >= p->iEnd; -} - -/* Advance the cursor to the next element for json_tree() */ -static int jsonEachNext(sqlite3_vtab_cursor *cur){ - JsonEachCursor *p = (JsonEachCursor*)cur; - if( p->bRecursive ){ - if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++; - p->i++; - p->iRowid++; - if( p->i<p->iEnd ){ - u32 iUp = p->sParse.aUp[p->i]; - JsonNode *pUp = &p->sParse.aNode[iUp]; - p->eType = pUp->eType; - if( pUp->eType==JSON_ARRAY ){ - if( iUp==p->i-1 ){ - pUp->u.iKey = 0; - }else{ - pUp->u.iKey++; - } - } - } - }else{ - switch( p->eType ){ - case JSON_ARRAY: { - p->i += jsonNodeSize(&p->sParse.aNode[p->i]); - p->iRowid++; - break; - } - case JSON_OBJECT: { - p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]); - p->iRowid++; - break; - } - default: { - p->i = p->iEnd; - break; - } - } - } - return SQLITE_OK; -} - -/* Append the name of the path for element i to pStr +/* +** Destroy a rebaser object */ -static void jsonEachComputePath( - JsonEachCursor *p, /* The cursor */ - JsonString *pStr, /* Write the path here */ - u32 i /* Path to this element */ -){ - JsonNode *pNode, *pUp; - u32 iUp; - if( i==0 ){ - jsonAppendChar(pStr, '$'); - return; - } - iUp = p->sParse.aUp[i]; - jsonEachComputePath(p, pStr, iUp); - pNode = &p->sParse.aNode[i]; - pUp = &p->sParse.aNode[iUp]; - if( pUp->eType==JSON_ARRAY ){ - jsonPrintf(30, pStr, "[%d]", pUp->u.iKey); - }else{ - assert( pUp->eType==JSON_OBJECT ); - if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--; - assert( pNode->eType==JSON_STRING ); - assert( pNode->jnFlags & JNODE_LABEL ); - jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1); +SQLITE_API void tdsqlite3rebaser_delete(tdsqlite3_rebaser *p){ + if( p ){ + sessionDeleteTable(p->grp.pList); + tdsqlite3_free(p); } } -/* Return the value of a column */ -static int jsonEachColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - JsonEachCursor *p = (JsonEachCursor*)cur; - JsonNode *pThis = &p->sParse.aNode[p->i]; - switch( i ){ - case JEACH_KEY: { - if( p->i==0 ) break; - if( p->eType==JSON_OBJECT ){ - jsonReturn(pThis, ctx, 0); - }else if( p->eType==JSON_ARRAY ){ - u32 iKey; - if( p->bRecursive ){ - if( p->iRowid==0 ) break; - iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey; - }else{ - iKey = p->iRowid; - } - sqlite3_result_int64(ctx, (sqlite3_int64)iKey); - } - break; - } - case JEACH_VALUE: { - if( pThis->jnFlags & JNODE_LABEL ) pThis++; - jsonReturn(pThis, ctx, 0); - break; - } - case JEACH_TYPE: { - if( pThis->jnFlags & JNODE_LABEL ) pThis++; - sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC); - break; - } - case JEACH_ATOM: { - if( pThis->jnFlags & JNODE_LABEL ) pThis++; - if( pThis->eType>=JSON_ARRAY ) break; - jsonReturn(pThis, ctx, 0); - break; - } - case JEACH_ID: { - sqlite3_result_int64(ctx, - (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0)); - break; - } - case JEACH_PARENT: { - if( p->i>p->iBegin && p->bRecursive ){ - sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]); - } - break; - } - case JEACH_FULLKEY: { - JsonString x; - jsonInit(&x, ctx); - if( p->bRecursive ){ - jsonEachComputePath(p, &x, p->i); - }else{ - if( p->zRoot ){ - jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot)); - }else{ - jsonAppendChar(&x, '$'); - } - if( p->eType==JSON_ARRAY ){ - jsonPrintf(30, &x, "[%d]", p->iRowid); - }else{ - jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1); - } - } - jsonResult(&x); - break; - } - case JEACH_PATH: { - if( p->bRecursive ){ - JsonString x; - jsonInit(&x, ctx); - jsonEachComputePath(p, &x, p->sParse.aUp[p->i]); - jsonResult(&x); - break; +/* +** Global configuration +*/ +SQLITE_API int tdsqlite3session_config(int op, void *pArg){ + int rc = SQLITE_OK; + switch( op ){ + case SQLITE_SESSION_CONFIG_STRMSIZE: { + int *pInt = (int*)pArg; + if( *pInt>0 ){ + sessions_strm_chunk_size = *pInt; } - /* For json_each() path and root are the same so fall through - ** into the root case */ - } - default: { - const char *zRoot = p->zRoot; - if( zRoot==0 ) zRoot = "$"; - sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC); + *pInt = sessions_strm_chunk_size; break; } - case JEACH_JSON: { - assert( i==JEACH_JSON ); - sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC); + default: + rc = SQLITE_MISUSE; break; - } } - return SQLITE_OK; -} - -/* Return the current rowid value */ -static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - JsonEachCursor *p = (JsonEachCursor*)cur; - *pRowid = p->iRowid; - return SQLITE_OK; -} - -/* The query strategy is to look for an equality constraint on the json -** column. Without such a constraint, the table cannot operate. idxNum is -** 1 if the constraint is found, 3 if the constraint and zRoot are found, -** and 0 otherwise. -*/ -static int jsonEachBestIndex( - sqlite3_vtab *tab, - sqlite3_index_info *pIdxInfo -){ - int i; - int jsonIdx = -1; - int rootIdx = -1; - const struct sqlite3_index_constraint *pConstraint; - - UNUSED_PARAM(tab); - pConstraint = pIdxInfo->aConstraint; - for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ - if( pConstraint->usable==0 ) continue; - if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; - switch( pConstraint->iColumn ){ - case JEACH_JSON: jsonIdx = i; break; - case JEACH_ROOT: rootIdx = i; break; - default: /* no-op */ break; - } - } - if( jsonIdx<0 ){ - pIdxInfo->idxNum = 0; - pIdxInfo->estimatedCost = 1e99; - }else{ - pIdxInfo->estimatedCost = 1.0; - pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1; - pIdxInfo->aConstraintUsage[jsonIdx].omit = 1; - if( rootIdx<0 ){ - pIdxInfo->idxNum = 1; - }else{ - pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2; - pIdxInfo->aConstraintUsage[rootIdx].omit = 1; - pIdxInfo->idxNum = 3; - } - } - return SQLITE_OK; -} - -/* Start a search on a new JSON string */ -static int jsonEachFilter( - sqlite3_vtab_cursor *cur, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - JsonEachCursor *p = (JsonEachCursor*)cur; - const char *z; - const char *zRoot = 0; - sqlite3_int64 n; - - UNUSED_PARAM(idxStr); - UNUSED_PARAM(argc); - jsonEachCursorReset(p); - if( idxNum==0 ) return SQLITE_OK; - z = (const char*)sqlite3_value_text(argv[0]); - if( z==0 ) return SQLITE_OK; - n = sqlite3_value_bytes(argv[0]); - p->zJson = sqlite3_malloc64( n+1 ); - if( p->zJson==0 ) return SQLITE_NOMEM; - memcpy(p->zJson, z, (size_t)n+1); - if( jsonParse(&p->sParse, 0, p->zJson) ){ - int rc = SQLITE_NOMEM; - if( p->sParse.oom==0 ){ - sqlite3_free(cur->pVtab->zErrMsg); - cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON"); - if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR; - } - jsonEachCursorReset(p); - return rc; - }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){ - jsonEachCursorReset(p); - return SQLITE_NOMEM; - }else{ - JsonNode *pNode = 0; - if( idxNum==3 ){ - const char *zErr = 0; - zRoot = (const char*)sqlite3_value_text(argv[1]); - if( zRoot==0 ) return SQLITE_OK; - n = sqlite3_value_bytes(argv[1]); - p->zRoot = sqlite3_malloc64( n+1 ); - if( p->zRoot==0 ) return SQLITE_NOMEM; - memcpy(p->zRoot, zRoot, (size_t)n+1); - if( zRoot[0]!='$' ){ - zErr = zRoot; - }else{ - pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr); - } - if( zErr ){ - sqlite3_free(cur->pVtab->zErrMsg); - cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr); - jsonEachCursorReset(p); - return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; - }else if( pNode==0 ){ - return SQLITE_OK; - } - }else{ - pNode = p->sParse.aNode; - } - p->iBegin = p->i = (int)(pNode - p->sParse.aNode); - p->eType = pNode->eType; - if( p->eType>=JSON_ARRAY ){ - pNode->u.iKey = 0; - p->iEnd = p->i + pNode->n + 1; - if( p->bRecursive ){ - p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType; - if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){ - p->i--; - } - }else{ - p->i++; - } - }else{ - p->iEnd = p->i+1; - } - } - return SQLITE_OK; -} - -/* The methods of the json_each virtual table */ -static sqlite3_module jsonEachModule = { - 0, /* iVersion */ - 0, /* xCreate */ - jsonEachConnect, /* xConnect */ - jsonEachBestIndex, /* xBestIndex */ - jsonEachDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - jsonEachOpenEach, /* xOpen - open a cursor */ - jsonEachClose, /* xClose - close a cursor */ - jsonEachFilter, /* xFilter - configure scan constraints */ - jsonEachNext, /* xNext - advance a cursor */ - jsonEachEof, /* xEof - check for end of scan */ - jsonEachColumn, /* xColumn - read data */ - jsonEachRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0 /* xRollbackTo */ -}; - -/* The methods of the json_tree virtual table. */ -static sqlite3_module jsonTreeModule = { - 0, /* iVersion */ - 0, /* xCreate */ - jsonEachConnect, /* xConnect */ - jsonEachBestIndex, /* xBestIndex */ - jsonEachDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - jsonEachOpenTree, /* xOpen - open a cursor */ - jsonEachClose, /* xClose - close a cursor */ - jsonEachFilter, /* xFilter - configure scan constraints */ - jsonEachNext, /* xNext - advance a cursor */ - jsonEachEof, /* xEof - check for end of scan */ - jsonEachColumn, /* xColumn - read data */ - jsonEachRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0 /* xRollbackTo */ -}; -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -/**************************************************************************** -** The following routines are the only publically visible identifiers in this -** file. Call the following routines in order to register the various SQL -** functions and the virtual table implemented by this file. -****************************************************************************/ - -SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){ - int rc = SQLITE_OK; - unsigned int i; - static const struct { - const char *zName; - int nArg; - int flag; - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); - } aFunc[] = { - { "json", 1, 0, jsonRemoveFunc }, - { "json_array", -1, 0, jsonArrayFunc }, - { "json_array_length", 1, 0, jsonArrayLengthFunc }, - { "json_array_length", 2, 0, jsonArrayLengthFunc }, - { "json_extract", -1, 0, jsonExtractFunc }, - { "json_insert", -1, 0, jsonSetFunc }, - { "json_object", -1, 0, jsonObjectFunc }, - { "json_quote", 1, 0, jsonQuoteFunc }, - { "json_remove", -1, 0, jsonRemoveFunc }, - { "json_replace", -1, 0, jsonReplaceFunc }, - { "json_set", -1, 1, jsonSetFunc }, - { "json_type", 1, 0, jsonTypeFunc }, - { "json_type", 2, 0, jsonTypeFunc }, - { "json_valid", 1, 0, jsonValidFunc }, - -#if SQLITE_DEBUG - /* DEBUG and TESTING functions */ - { "json_parse", 1, 0, jsonParseFunc }, - { "json_test1", 1, 0, jsonTest1Func }, -#endif - }; - static const struct { - const char *zName; - int nArg; - void (*xStep)(sqlite3_context*,int,sqlite3_value**); - void (*xFinal)(sqlite3_context*); - } aAgg[] = { - { "json_group_array", 1, jsonArrayStep, jsonArrayFinal }, - { "json_group_object", 2, jsonObjectStep, jsonObjectFinal }, - }; -#ifndef SQLITE_OMIT_VIRTUALTABLE - static const struct { - const char *zName; - sqlite3_module *pModule; - } aMod[] = { - { "json_each", &jsonEachModule }, - { "json_tree", &jsonTreeModule }, - }; -#endif - for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){ - rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, - SQLITE_UTF8 | SQLITE_DETERMINISTIC, - (void*)&aFunc[i].flag, - aFunc[i].xFunc, 0, 0); - } - for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){ - rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg, - SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0, - 0, aAgg[i].xStep, aAgg[i].xFinal); - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){ - rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0); - } -#endif return rc; } +#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */ -#ifndef SQLITE_CORE -#ifdef _WIN32 -__declspec(dllexport) -#endif -SQLITE_API int sqlite3_json_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - return sqlite3Json1Init(db); -} -#endif -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */ - -/************** End of json1.c ***********************************************/ +/************** End of tdsqlite3session.c **************************************/ /************** Begin file fts5.c ********************************************/ @@ -181774,7 +209537,7 @@ extern "C" { ** CUSTOM AUXILIARY FUNCTIONS ** ** Virtual table implementations may overload SQL functions by implementing -** the sqlite3_module.xFindFunction() method. +** the tdsqlite3_module.xFindFunction() method. */ typedef struct Fts5ExtensionApi Fts5ExtensionApi; @@ -181784,9 +209547,9 @@ typedef struct Fts5PhraseIter Fts5PhraseIter; typedef void (*fts5_extension_function)( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ - sqlite3_context *pCtx, /* Context for returning result/error */ + tdsqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ - sqlite3_value **apVal /* Array of trailing arguments */ + tdsqlite3_value **apVal /* Array of trailing arguments */ ); struct Fts5PhraseIter { @@ -181863,12 +209626,8 @@ struct Fts5PhraseIter { ** ** Usually, output parameter *piPhrase is set to the phrase number, *piCol ** to the column in which it occurs and *piOff the token offset of the -** first token of the phrase. The exception is if the table was created -** with the offsets=0 option specified. In this case *piOff is always -** set to -1. -** -** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) -** if an error occurs. +** first token of the phrase. Returns SQLITE_OK if successful, or an error +** code (i.e. SQLITE_NOMEM) if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. @@ -181906,10 +209665,10 @@ struct Fts5PhraseIter { ** ** xSetAuxdata(pFts5, pAux, xDelete) ** -** Save the pointer passed as the second argument as the extension functions +** Save the pointer passed as the second argument as the extension function's ** "auxiliary data". The pointer may then be retrieved by the current or any ** future invocation of the same fts5 extension function made as part of -** of the same MATCH query using the xGetAuxdata() API. +** the same MATCH query using the xGetAuxdata() API. ** ** Each extension function is allocated a single auxiliary data slot for ** each FTS query (MATCH expression). If the extension function is invoked @@ -181924,7 +209683,7 @@ struct Fts5PhraseIter { ** The xDelete callback, if one is specified, is also invoked on the ** auxiliary data pointer after the FTS5 query has finished. ** -** If an error (e.g. an OOM condition) occurs within this function, an +** If an error (e.g. an OOM condition) occurs within this function, ** the auxiliary data is set to NULL and an error code returned. If the ** xDelete parameter was not NULL, it is invoked on the auxiliary data ** pointer before returning. @@ -182015,8 +209774,8 @@ struct Fts5ExtensionApi { void *(*xUserData)(Fts5Context*); int (*xColumnCount)(Fts5Context*); - int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); - int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); + int (*xRowCount)(Fts5Context*, tdsqlite3_int64 *pnRow); + int (*xColumnTotalSize)(Fts5Context*, int iCol, tdsqlite3_int64 *pnToken); int (*xTokenize)(Fts5Context*, const char *pText, int nText, /* Text to tokenize */ @@ -182030,7 +209789,7 @@ struct Fts5ExtensionApi { int (*xInstCount)(Fts5Context*, int *pnInst); int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); - sqlite3_int64 (*xRowid)(Fts5Context*); + tdsqlite3_int64 (*xRowid)(Fts5Context*); int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); @@ -182148,8 +209907,8 @@ struct Fts5ExtensionApi { ** ** There are several ways to approach this in FTS5: ** -** <ol><li> By mapping all synonyms to a single token. In this case, the -** In the above example, this means that the tokenizer returns the +** <ol><li> By mapping all synonyms to a single token. In this case, using +** the above example, this means that the tokenizer returns the ** same token for inputs "first" and "1st". Say that token is in ** fact "first", so that when the user inserts the document "I won ** 1st place" entries are added to the index for tokens "i", "won", @@ -182157,11 +209916,11 @@ struct Fts5ExtensionApi { ** the tokenizer substitutes "first" for "1st" and the query works ** as expected. ** -** <li> By adding multiple synonyms for a single term to the FTS index. -** In this case, when tokenizing query text, the tokenizer may -** provide multiple synonyms for a single term within the document. -** FTS5 then queries the index for each synonym individually. For -** example, faced with the query: +** <li> By querying the index for all synonyms of each query term +** separately. In this case, when tokenizing query text, the +** tokenizer may provide multiple synonyms for a single term +** within the document. FTS5 then queries the index for each +** synonym individually. For example, faced with the query: ** ** <codeblock> ** ... MATCH 'first place'</codeblock> @@ -182185,9 +209944,9 @@ struct Fts5ExtensionApi { ** "place". ** ** This way, even if the tokenizer does not provide synonyms -** when tokenizing query text (it should not - to do would be +** when tokenizing query text (it should not - to do so would be ** inefficient), it doesn't matter if the user queries for -** 'first + place' or '1st + place', as there are entires in the +** 'first + place' or '1st + place', as there are entries in the ** FTS index corresponding to both forms of the first token. ** </ol> ** @@ -182215,7 +209974,7 @@ struct Fts5ExtensionApi { ** extra data to the FTS index or require FTS5 to query for multiple terms, ** so it is efficient in terms of disk space and query speed. However, it ** does not support prefix queries very well. If, as suggested above, the -** token "first" is subsituted for "1st" by the tokenizer, then the query: +** token "first" is substituted for "1st" by the tokenizer, then the query: ** ** <codeblock> ** ... MATCH '1s*'</codeblock> @@ -182338,7 +210097,7 @@ struct fts5_api { #define _FTS5INT_H /* #include "fts5.h" */ -/* #include "sqlite3ext.h" */ +/* #include "tdsqlite3ext.h" */ SQLITE_EXTENSION_INIT1 /* #include <string.h> */ @@ -182350,10 +210109,12 @@ typedef unsigned char u8; typedef unsigned int u32; typedef unsigned short u16; typedef short i16; -typedef sqlite3_int64 i64; -typedef sqlite3_uint64 u64; +typedef tdsqlite3_int64 i64; +typedef tdsqlite3_uint64 u64; -#define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0]))) +#ifndef ArraySize +# define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0]))) +#endif #define testcase(x) #define ALWAYS(x) 1 @@ -182382,6 +210143,11 @@ typedef sqlite3_uint64 u64; */ #define FTS5_MAX_PREFIX_INDEXES 31 +/* +** Maximum segments permitted in a single index +*/ +#define FTS5_MAX_SEGMENT 2000 + #define FTS5_DEFAULT_NEARDIST 10 #define FTS5_DEFAULT_RANK "bm25" @@ -182390,8 +210156,8 @@ typedef sqlite3_uint64 u64; #define FTS5_ROWID_NAME "rowid" #ifdef SQLITE_DEBUG -# define FTS5_CORRUPT sqlite3Fts5Corrupt() -static int sqlite3Fts5Corrupt(void); +# define FTS5_CORRUPT tdsqlite3Fts5Corrupt() +static int tdsqlite3Fts5Corrupt(void); #else # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB #endif @@ -182402,12 +210168,18 @@ static int sqlite3Fts5Corrupt(void); ** guranteed that the database is not corrupt. */ #ifdef SQLITE_DEBUG -SQLITE_API extern int sqlite3_fts5_may_be_corrupt; -# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x)) +SQLITE_API extern int tdsqlite3_fts5_may_be_corrupt; +# define assert_nc(x) assert(tdsqlite3_fts5_may_be_corrupt || (x)) #else # define assert_nc(x) assert(x) #endif +/* +** A version of memcmp() that does not cause asan errors if one of the pointer +** parameters is NULL and the number of bytes to compare is zero. +*/ +#define fts5Memcmp(s1, s2, n) ((n)==0 ? 0 : memcmp((s1), (s2), (n))) + /* Mark a function parameter as unused, to suppress nuisance compiler ** warnings. */ #ifndef UNUSED_PARAM @@ -182477,7 +210249,7 @@ typedef struct Fts5Config Fts5Config; ** */ struct Fts5Config { - sqlite3 *db; /* Database handle */ + tdsqlite3 *db; /* Database handle */ char *zDb; /* Database holding FTS index (e.g. "main") */ char *zName; /* Name of FTS index */ int nCol; /* Number of columns */ @@ -182493,6 +210265,7 @@ struct Fts5Config { char *zContentExprlist; Fts5Tokenizer *pTok; fts5_tokenizer *pTokApi; + int bLock; /* True when table is preparing statement */ /* Values loaded from the %_config table */ int iCookie; /* Incremented when %_config is modified */ @@ -182504,7 +210277,7 @@ struct Fts5Config { char *zRank; /* Name of rank function */ char *zRankArgs; /* Arguments to rank function */ - /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */ + /* If non-NULL, points to tdsqlite3_vtab.base.zErrmsg. Often NULL. */ char **pzErrmsg; #ifdef SQLITE_DEBUG @@ -182525,14 +210298,14 @@ struct Fts5Config { -static int sqlite3Fts5ConfigParse( - Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char** +static int tdsqlite3Fts5ConfigParse( + Fts5Global*, tdsqlite3*, int, const char **, Fts5Config**, char** ); -static void sqlite3Fts5ConfigFree(Fts5Config*); +static void tdsqlite3Fts5ConfigFree(Fts5Config*); -static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig); +static int tdsqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig); -static int sqlite3Fts5Tokenize( +static int tdsqlite3Fts5Tokenize( Fts5Config *pConfig, /* FTS5 Configuration object */ int flags, /* FTS5_TOKENIZE_* flags */ const char *pText, int nText, /* Text to tokenize */ @@ -182540,15 +210313,15 @@ static int sqlite3Fts5Tokenize( int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ ); -static void sqlite3Fts5Dequote(char *z); +static void tdsqlite3Fts5Dequote(char *z); /* Load the contents of the %_config table */ -static int sqlite3Fts5ConfigLoad(Fts5Config*, int); +static int tdsqlite3Fts5ConfigLoad(Fts5Config*, int); /* Set the value of a single config attribute */ -static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*); +static int tdsqlite3Fts5ConfigSetValue(Fts5Config*, const char*, tdsqlite3_value*, int*); -static int sqlite3Fts5ConfigParseRank(const char*, char**, char**); +static int tdsqlite3Fts5ConfigParseRank(const char*, char**, char**); /* ** End of interface to code in fts5_config.c. @@ -182568,38 +210341,38 @@ struct Fts5Buffer { int nSpace; }; -static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32); -static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64); -static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*); -static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*); -static void sqlite3Fts5BufferFree(Fts5Buffer*); -static void sqlite3Fts5BufferZero(Fts5Buffer*); -static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*); -static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...); +static int tdsqlite3Fts5BufferSize(int*, Fts5Buffer*, u32); +static void tdsqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64); +static void tdsqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*); +static void tdsqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*); +static void tdsqlite3Fts5BufferFree(Fts5Buffer*); +static void tdsqlite3Fts5BufferZero(Fts5Buffer*); +static void tdsqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*); +static void tdsqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...); -static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...); +static char *tdsqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...); -#define fts5BufferZero(x) sqlite3Fts5BufferZero(x) -#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c) -#define fts5BufferFree(a) sqlite3Fts5BufferFree(a) -#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d) -#define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d) +#define fts5BufferZero(x) tdsqlite3Fts5BufferZero(x) +#define fts5BufferAppendVarint(a,b,c) tdsqlite3Fts5BufferAppendVarint(a,b,c) +#define fts5BufferFree(a) tdsqlite3Fts5BufferFree(a) +#define fts5BufferAppendBlob(a,b,c,d) tdsqlite3Fts5BufferAppendBlob(a,b,c,d) +#define fts5BufferSet(a,b,c,d) tdsqlite3Fts5BufferSet(a,b,c,d) #define fts5BufferGrow(pRc,pBuf,nn) ( \ (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \ - sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \ + tdsqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \ ) /* Write and decode big-endian 32-bit integer values */ -static void sqlite3Fts5Put32(u8*, int); -static int sqlite3Fts5Get32(const u8*); +static void tdsqlite3Fts5Put32(u8*, int); +static int tdsqlite3Fts5Get32(const u8*); #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32) -#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF) +#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0x7FFFFFFF) typedef struct Fts5PoslistReader Fts5PoslistReader; struct Fts5PoslistReader { - /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */ + /* Variables used only by tdsqlite3Fts5PoslistIterXXX() functions. */ const u8 *a; /* Position list to iterate through */ int n; /* Size of buffer at a[] in bytes */ int i; /* Current offset in a[] */ @@ -182610,38 +210383,38 @@ struct Fts5PoslistReader { u8 bEof; /* Set to true at EOF */ i64 iPos; /* (iCol<<32) + iPos */ }; -static int sqlite3Fts5PoslistReaderInit( +static int tdsqlite3Fts5PoslistReaderInit( const u8 *a, int n, /* Poslist buffer to iterate through */ Fts5PoslistReader *pIter /* Iterator object to initialize */ ); -static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*); +static int tdsqlite3Fts5PoslistReaderNext(Fts5PoslistReader*); typedef struct Fts5PoslistWriter Fts5PoslistWriter; struct Fts5PoslistWriter { i64 iPrev; }; -static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64); -static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64); +static int tdsqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64); +static void tdsqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64); -static int sqlite3Fts5PoslistNext64( +static int tdsqlite3Fts5PoslistNext64( const u8 *a, int n, /* Buffer containing poslist */ int *pi, /* IN/OUT: Offset within a[] */ i64 *piOff /* IN/OUT: Current offset */ ); /* Malloc utility */ -static void *sqlite3Fts5MallocZero(int *pRc, int nByte); -static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn); +static void *tdsqlite3Fts5MallocZero(int *pRc, tdsqlite3_int64 nByte); +static char *tdsqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn); /* Character set tests (like isspace(), isalpha() etc.) */ -static int sqlite3Fts5IsBareword(char t); +static int tdsqlite3Fts5IsBareword(char t); /* Bucket of terms object used by the integrity-check in offsets=0 mode. */ typedef struct Fts5Termset Fts5Termset; -static int sqlite3Fts5TermsetNew(Fts5Termset**); -static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent); -static void sqlite3Fts5TermsetFree(Fts5Termset*); +static int tdsqlite3Fts5TermsetNew(Fts5Termset**); +static int tdsqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent); +static void tdsqlite3Fts5TermsetFree(Fts5Termset*); /* ** End of interface to code in fts5_buffer.c. @@ -182662,7 +210435,7 @@ struct Fts5IndexIter { u8 bEof; }; -#define sqlite3Fts5IterEof(x) ((x)->bEof) +#define tdsqlite3Fts5IterEof(x) ((x)->bEof) /* ** Values used as part of the flags argument passed to IndexQuery(). @@ -182681,13 +210454,13 @@ struct Fts5IndexIter { /* ** Create/destroy an Fts5Index object. */ -static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**); -static int sqlite3Fts5IndexClose(Fts5Index *p); +static int tdsqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**); +static int tdsqlite3Fts5IndexClose(Fts5Index *p); /* ** Return a simple checksum value based on the arguments. */ -static u64 sqlite3Fts5IndexEntryCksum( +static u64 tdsqlite3Fts5IndexEntryCksum( i64 iRowid, int iCol, int iPos, @@ -182701,7 +210474,7 @@ static u64 sqlite3Fts5IndexEntryCksum( ** size. Return the number of bytes in the nChar character prefix of the ** buffer, or 0 if there are less than nChar characters in total. */ -static int sqlite3Fts5IndexCharlenToBytelen( +static int tdsqlite3Fts5IndexCharlenToBytelen( const char *p, int nByte, int nChar @@ -182711,7 +210484,7 @@ static int sqlite3Fts5IndexCharlenToBytelen( ** Open a new iterator to iterate though all rowids that match the ** specified token or token prefix. */ -static int sqlite3Fts5IndexQuery( +static int tdsqlite3Fts5IndexQuery( Fts5Index *p, /* FTS index to query */ const char *pToken, int nToken, /* Token (or prefix) to query for */ int flags, /* Mask of FTS5INDEX_QUERY_X flags */ @@ -182721,21 +210494,26 @@ static int sqlite3Fts5IndexQuery( /* ** The various operations on open token or token prefix iterators opened -** using sqlite3Fts5IndexQuery(). +** using tdsqlite3Fts5IndexQuery(). +*/ +static int tdsqlite3Fts5IterNext(Fts5IndexIter*); +static int tdsqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch); + +/* +** Close an iterator opened by tdsqlite3Fts5IndexQuery(). */ -static int sqlite3Fts5IterNext(Fts5IndexIter*); -static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch); +static void tdsqlite3Fts5IterClose(Fts5IndexIter*); /* -** Close an iterator opened by sqlite3Fts5IndexQuery(). +** Close the reader blob handle, if it is open. */ -static void sqlite3Fts5IterClose(Fts5IndexIter*); +static void tdsqlite3Fts5IndexCloseReader(Fts5Index*); /* ** This interface is used by the fts5vocab module. */ -static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*); -static int sqlite3Fts5IterNextScan(Fts5IndexIter*); +static const char *tdsqlite3Fts5IterTerm(Fts5IndexIter*, int*); +static int tdsqlite3Fts5IterNextScan(Fts5IndexIter*); /* @@ -182748,7 +210526,7 @@ static int sqlite3Fts5IterNextScan(Fts5IndexIter*); ** unique token in the document with an iCol value less than zero. The iPos ** argument is ignored for a delete. */ -static int sqlite3Fts5IndexWrite( +static int tdsqlite3Fts5IndexWrite( Fts5Index *p, /* Index to write to */ int iCol, /* Column token appears in (-ve -> delete) */ int iPos, /* Position of token within column */ @@ -182756,10 +210534,10 @@ static int sqlite3Fts5IndexWrite( ); /* -** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to +** Indicate that subsequent calls to tdsqlite3Fts5IndexWrite() pertain to ** document iDocid. */ -static int sqlite3Fts5IndexBeginWrite( +static int tdsqlite3Fts5IndexBeginWrite( Fts5Index *p, /* Index to write to */ int bDelete, /* True if current operation is a delete */ i64 iDocid /* Docid to add or remove data from */ @@ -182767,9 +210545,9 @@ static int sqlite3Fts5IndexBeginWrite( /* ** Flush any data stored in the in-memory hash tables to the database. -** If the bCommit flag is true, also close any open blob handles. +** Also close any open blob handles. */ -static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit); +static int tdsqlite3Fts5IndexSync(Fts5Index *p); /* ** Discard any data stored in the in-memory hash tables. Do not write it @@ -182777,39 +210555,39 @@ static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit); ** table may have changed on disk. So any in-memory caches of %_data ** records must be invalidated. */ -static int sqlite3Fts5IndexRollback(Fts5Index *p); +static int tdsqlite3Fts5IndexRollback(Fts5Index *p); /* ** Get or set the "averages" values. */ -static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize); -static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int); +static int tdsqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize); +static int tdsqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int); /* ** Functions called by the storage module as part of integrity-check. */ -static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum); +static int tdsqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum); /* ** Called during virtual module initialization to register UDF ** fts5_decode() with SQLite */ -static int sqlite3Fts5IndexInit(sqlite3*); +static int tdsqlite3Fts5IndexInit(tdsqlite3*); -static int sqlite3Fts5IndexSetCookie(Fts5Index*, int); +static int tdsqlite3Fts5IndexSetCookie(Fts5Index*, int); /* ** Return the total number of entries read from the %_data table by ** this connection since it was created. */ -static int sqlite3Fts5IndexReads(Fts5Index *p); +static int tdsqlite3Fts5IndexReads(Fts5Index *p); -static int sqlite3Fts5IndexReinit(Fts5Index *p); -static int sqlite3Fts5IndexOptimize(Fts5Index *p); -static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge); -static int sqlite3Fts5IndexReset(Fts5Index *p); +static int tdsqlite3Fts5IndexReinit(Fts5Index *p); +static int tdsqlite3Fts5IndexOptimize(Fts5Index *p); +static int tdsqlite3Fts5IndexMerge(Fts5Index *p, int nMerge); +static int tdsqlite3Fts5IndexReset(Fts5Index *p); -static int sqlite3Fts5IndexLoadConfig(Fts5Index *p); +static int tdsqlite3Fts5IndexLoadConfig(Fts5Index *p); /* ** End of interface to code in fts5_index.c. @@ -182818,13 +210596,13 @@ static int sqlite3Fts5IndexLoadConfig(Fts5Index *p); /************************************************************************** ** Interface to code in fts5_varint.c. */ -static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v); -static int sqlite3Fts5GetVarintLen(u32 iVal); -static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*); -static int sqlite3Fts5PutVarint(unsigned char *p, u64 v); +static int tdsqlite3Fts5GetVarint32(const unsigned char *p, u32 *v); +static int tdsqlite3Fts5GetVarintLen(u32 iVal); +static u8 tdsqlite3Fts5GetVarint(const unsigned char*, u64*); +static int tdsqlite3Fts5PutVarint(unsigned char *p, u64 v); -#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b) -#define fts5GetVarint sqlite3Fts5GetVarint +#define fts5GetVarint32(a,b) tdsqlite3Fts5GetVarint32(a,(u32*)&b) +#define fts5GetVarint tdsqlite3Fts5GetVarint #define fts5FastGetVarint32(a, iOff, nVal) { \ nVal = (a)[iOff++]; \ @@ -182841,10 +210619,20 @@ static int sqlite3Fts5PutVarint(unsigned char *p, u64 v); /************************************************************************** -** Interface to code in fts5.c. +** Interface to code in fts5_main.c. */ -static int sqlite3Fts5GetTokenizer( +/* +** Virtual-table object. +*/ +typedef struct Fts5Table Fts5Table; +struct Fts5Table { + tdsqlite3_vtab base; /* Base class used by SQLite core */ + Fts5Config *pConfig; /* Virtual table configuration */ + Fts5Index *pIndex; /* Full-text index */ +}; + +static int tdsqlite3Fts5GetTokenizer( Fts5Global*, const char **azArg, int nArg, @@ -182853,7 +210641,9 @@ static int sqlite3Fts5GetTokenizer( char **pzErr ); -static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **); +static Fts5Table *tdsqlite3Fts5TableFromCsrid(Fts5Global*, i64); + +static int tdsqlite3Fts5FlushToDisk(Fts5Table*); /* ** End of interface to code in fts5.c. @@ -182867,10 +210657,10 @@ typedef struct Fts5Hash Fts5Hash; /* ** Create a hash table, free a hash table. */ -static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize); -static void sqlite3Fts5HashFree(Fts5Hash*); +static int tdsqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize); +static void tdsqlite3Fts5HashFree(Fts5Hash*); -static int sqlite3Fts5HashWrite( +static int tdsqlite3Fts5HashWrite( Fts5Hash*, i64 iRowid, /* Rowid for this entry */ int iCol, /* Column token appears in (-ve -> delete) */ @@ -182882,22 +210672,23 @@ static int sqlite3Fts5HashWrite( /* ** Empty (but do not delete) a hash table. */ -static void sqlite3Fts5HashClear(Fts5Hash*); +static void tdsqlite3Fts5HashClear(Fts5Hash*); -static int sqlite3Fts5HashQuery( +static int tdsqlite3Fts5HashQuery( Fts5Hash*, /* Hash table to query */ + int nPre, const char *pTerm, int nTerm, /* Query term */ - const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */ + void **ppObj, /* OUT: Pointer to doclist for pTerm */ int *pnDoclist /* OUT: Size of doclist in bytes */ ); -static int sqlite3Fts5HashScanInit( +static int tdsqlite3Fts5HashScanInit( Fts5Hash*, /* Hash table to query */ const char *pTerm, int nTerm /* Query prefix */ ); -static void sqlite3Fts5HashScanNext(Fts5Hash*); -static int sqlite3Fts5HashScanEof(Fts5Hash*); -static void sqlite3Fts5HashScanEntry(Fts5Hash *, +static void tdsqlite3Fts5HashScanNext(Fts5Hash*); +static int tdsqlite3Fts5HashScanEof(Fts5Hash*); +static void tdsqlite3Fts5HashScanEntry(Fts5Hash *, const char **pzTerm, /* OUT: term (nul-terminated) */ const u8 **ppDoclist, /* OUT: pointer to doclist */ int *pnDoclist /* OUT: size of doclist in bytes */ @@ -182919,38 +210710,38 @@ static void sqlite3Fts5HashScanEntry(Fts5Hash *, typedef struct Fts5Storage Fts5Storage; -static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**); -static int sqlite3Fts5StorageClose(Fts5Storage *p); -static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName); +static int tdsqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**); +static int tdsqlite3Fts5StorageClose(Fts5Storage *p); +static int tdsqlite3Fts5StorageRename(Fts5Storage*, const char *zName); -static int sqlite3Fts5DropAll(Fts5Config*); -static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **); +static int tdsqlite3Fts5DropAll(Fts5Config*); +static int tdsqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **); -static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**); -static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*); -static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64); +static int tdsqlite3Fts5StorageDelete(Fts5Storage *p, i64, tdsqlite3_value**); +static int tdsqlite3Fts5StorageContentInsert(Fts5Storage *p, tdsqlite3_value**, i64*); +static int tdsqlite3Fts5StorageIndexInsert(Fts5Storage *p, tdsqlite3_value**, i64); -static int sqlite3Fts5StorageIntegrity(Fts5Storage *p); +static int tdsqlite3Fts5StorageIntegrity(Fts5Storage *p); -static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**); -static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*); +static int tdsqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, tdsqlite3_stmt**, char**); +static void tdsqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, tdsqlite3_stmt*); -static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol); -static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg); -static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow); +static int tdsqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol); +static int tdsqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg); +static int tdsqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow); -static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit); -static int sqlite3Fts5StorageRollback(Fts5Storage *p); +static int tdsqlite3Fts5StorageSync(Fts5Storage *p); +static int tdsqlite3Fts5StorageRollback(Fts5Storage *p); -static int sqlite3Fts5StorageConfigValue( - Fts5Storage *p, const char*, sqlite3_value*, int +static int tdsqlite3Fts5StorageConfigValue( + Fts5Storage *p, const char*, tdsqlite3_value*, int ); -static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p); -static int sqlite3Fts5StorageRebuild(Fts5Storage *p); -static int sqlite3Fts5StorageOptimize(Fts5Storage *p); -static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge); -static int sqlite3Fts5StorageReset(Fts5Storage *p); +static int tdsqlite3Fts5StorageDeleteAll(Fts5Storage *p); +static int tdsqlite3Fts5StorageRebuild(Fts5Storage *p); +static int tdsqlite3Fts5StorageOptimize(Fts5Storage *p); +static int tdsqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge); +static int tdsqlite3Fts5StorageReset(Fts5Storage *p); /* ** End of interface to code in fts5_storage.c. @@ -182973,55 +210764,57 @@ struct Fts5Token { }; /* Parse a MATCH expression. */ -static int sqlite3Fts5ExprNew( +static int tdsqlite3Fts5ExprNew( Fts5Config *pConfig, + int iCol, /* Column on LHS of MATCH operator */ const char *zExpr, Fts5Expr **ppNew, char **pzErr ); /* -** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc); -** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr); -** rc = sqlite3Fts5ExprNext(pExpr) +** for(rc = tdsqlite3Fts5ExprFirst(pExpr, pIdx, bDesc); +** rc==SQLITE_OK && 0==tdsqlite3Fts5ExprEof(pExpr); +** rc = tdsqlite3Fts5ExprNext(pExpr) ** ){ ** // The document with rowid iRowid matches the expression! -** i64 iRowid = sqlite3Fts5ExprRowid(pExpr); +** i64 iRowid = tdsqlite3Fts5ExprRowid(pExpr); ** } */ -static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc); -static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax); -static int sqlite3Fts5ExprEof(Fts5Expr*); -static i64 sqlite3Fts5ExprRowid(Fts5Expr*); +static int tdsqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc); +static int tdsqlite3Fts5ExprNext(Fts5Expr*, i64 iMax); +static int tdsqlite3Fts5ExprEof(Fts5Expr*); +static i64 tdsqlite3Fts5ExprRowid(Fts5Expr*); -static void sqlite3Fts5ExprFree(Fts5Expr*); +static void tdsqlite3Fts5ExprFree(Fts5Expr*); +static int tdsqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2); /* Called during startup to register a UDF with SQLite */ -static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*); +static int tdsqlite3Fts5ExprInit(Fts5Global*, tdsqlite3*); -static int sqlite3Fts5ExprPhraseCount(Fts5Expr*); -static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase); -static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **); +static int tdsqlite3Fts5ExprPhraseCount(Fts5Expr*); +static int tdsqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase); +static int tdsqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **); typedef struct Fts5PoslistPopulator Fts5PoslistPopulator; -static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int); -static int sqlite3Fts5ExprPopulatePoslists( +static Fts5PoslistPopulator *tdsqlite3Fts5ExprClearPoslists(Fts5Expr*, int); +static int tdsqlite3Fts5ExprPopulatePoslists( Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int ); -static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64); +static void tdsqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64); -static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**); +static int tdsqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**); -static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *); +static int tdsqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *); /******************************************* ** The fts5_expr.c API above this point is used by the other hand-written ** C code in this module. The interfaces below this point are called by ** the parser code in fts5parse.y. */ -static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...); +static void tdsqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...); -static Fts5ExprNode *sqlite3Fts5ParseNode( +static Fts5ExprNode *tdsqlite3Fts5ParseNode( Fts5Parse *pParse, int eType, Fts5ExprNode *pLeft, @@ -183029,40 +210822,42 @@ static Fts5ExprNode *sqlite3Fts5ParseNode( Fts5ExprNearset *pNear ); -static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd( +static Fts5ExprNode *tdsqlite3Fts5ParseImplicitAnd( Fts5Parse *pParse, Fts5ExprNode *pLeft, Fts5ExprNode *pRight ); -static Fts5ExprPhrase *sqlite3Fts5ParseTerm( +static Fts5ExprPhrase *tdsqlite3Fts5ParseTerm( Fts5Parse *pParse, Fts5ExprPhrase *pPhrase, Fts5Token *pToken, int bPrefix ); -static Fts5ExprNearset *sqlite3Fts5ParseNearset( +static void tdsqlite3Fts5ParseSetCaret(Fts5ExprPhrase*); + +static Fts5ExprNearset *tdsqlite3Fts5ParseNearset( Fts5Parse*, Fts5ExprNearset*, Fts5ExprPhrase* ); -static Fts5Colset *sqlite3Fts5ParseColset( +static Fts5Colset *tdsqlite3Fts5ParseColset( Fts5Parse*, Fts5Colset*, Fts5Token * ); -static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*); -static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*); -static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*); +static void tdsqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*); +static void tdsqlite3Fts5ParseNearsetFree(Fts5ExprNearset*); +static void tdsqlite3Fts5ParseNodeFree(Fts5ExprNode*); -static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*); -static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*); -static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*); -static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p); -static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*); +static void tdsqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*); +static void tdsqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*); +static Fts5Colset *tdsqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*); +static void tdsqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p); +static void tdsqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*); /* ** End of interface to code in fts5_expr.c. @@ -183074,7 +210869,7 @@ static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*); ** Interface to code in fts5_aux.c. */ -static int sqlite3Fts5AuxInit(fts5_api*); +static int tdsqlite3Fts5AuxInit(fts5_api*); /* ** End of interface to code in fts5_aux.c. **************************************************************************/ @@ -183083,7 +210878,7 @@ static int sqlite3Fts5AuxInit(fts5_api*); ** Interface to code in fts5_tokenizer.c. */ -static int sqlite3Fts5TokenizerInit(fts5_api*); +static int tdsqlite3Fts5TokenizerInit(fts5_api*); /* ** End of interface to code in fts5_tokenizer.c. **************************************************************************/ @@ -183092,7 +210887,7 @@ static int sqlite3Fts5TokenizerInit(fts5_api*); ** Interface to code in fts5_vocab.c. */ -static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*); +static int tdsqlite3Fts5VocabInit(Fts5Global*, tdsqlite3*); /* ** End of interface to code in fts5_vocab.c. @@ -183102,9 +210897,12 @@ static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*); /************************************************************************** ** Interface to automatically generated code in fts5_unicode2.c. */ -static int sqlite3Fts5UnicodeIsalnum(int c); -static int sqlite3Fts5UnicodeIsdiacritic(int c); -static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic); +static int tdsqlite3Fts5UnicodeIsdiacritic(int c); +static int tdsqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic); + +static int tdsqlite3Fts5UnicodeCatParse(const char*, u8*); +static int tdsqlite3Fts5UnicodeCategory(u32 iCode); +static void tdsqlite3Fts5UnicodeAscii(u8*, u8*); /* ** End of interface to code in fts5_unicode2.c. **************************************************************************/ @@ -183116,15 +210914,16 @@ static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic); #define FTS5_NOT 3 #define FTS5_TERM 4 #define FTS5_COLON 5 -#define FTS5_LP 6 -#define FTS5_RP 7 -#define FTS5_MINUS 8 -#define FTS5_LCP 9 -#define FTS5_RCP 10 -#define FTS5_STRING 11 -#define FTS5_COMMA 12 -#define FTS5_PLUS 13 -#define FTS5_STAR 14 +#define FTS5_MINUS 6 +#define FTS5_LCP 7 +#define FTS5_RCP 8 +#define FTS5_STRING 9 +#define FTS5_LP 10 +#define FTS5_RP 11 +#define FTS5_CARET 12 +#define FTS5_COMMA 13 +#define FTS5_PLUS 14 +#define FTS5_STAR 15 /* ** 2000-05-29 @@ -183151,6 +210950,7 @@ static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic); ** input grammar file: */ /* #include <stdio.h> */ +/* #include <assert.h> */ /************ Begin %include sections from the grammar ************************/ /* #include "fts5Int.h" */ @@ -183168,14 +210968,14 @@ static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic); #define fts5yytestcase(X) testcase(X) /* -** Indicate that sqlite3ParserFree() will never be called with a null +** Indicate that tdsqlite3ParserFree() will never be called with a null ** pointer. */ #define fts5YYPARSEFREENOTNULL 1 /* ** Alternative datatype for the argument to the malloc() routine passed -** into sqlite3ParserAlloc(). The default is size_t. +** into tdsqlite3ParserAlloc(). The default is size_t. */ #define fts5YYMALLOCARGTYPE u64 @@ -183202,7 +211002,7 @@ static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic); ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers ** that indicate what to do in response to the next ** token. -** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal +** tdsqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal ** symbols. Background: A "minor type" is a semantic ** value associated with a terminal or non-terminal ** symbols. For example, for an "ID" terminal symbol, @@ -183213,37 +211013,41 @@ static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic); ** symbols. ** fts5YYMINORTYPE is the data type used for all minor types. ** This is typically a union of many types, one of -** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union +** which is tdsqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union ** for terminal symbols is called "fts5yy0". ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If ** zero the stack is dynamically sized using realloc() -** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument -** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument -** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser -** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser +** tdsqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument +** tdsqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument +** tdsqlite3Fts5ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter +** tdsqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser +** tdsqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser +** tdsqlite3Fts5ParserCTX_* As tdsqlite3Fts5ParserARG_ except for %extra_context ** fts5YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. ** fts5YYNSTATE the combined number of states. ** fts5YYNRULE the number of rules in the grammar +** fts5YYNFTS5TOKEN Number of terminal symbols ** fts5YY_MAX_SHIFT Maximum value for shift actions ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions -** fts5YY_MIN_REDUCE Maximum value for reduce actions ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op +** fts5YY_MIN_REDUCE Minimum value for reduce actions +** fts5YY_MAX_REDUCE Maximum value for reduce actions */ #ifndef INTERFACE # define INTERFACE 1 #endif /************* Begin control #defines *****************************************/ #define fts5YYCODETYPE unsigned char -#define fts5YYNOCODE 28 +#define fts5YYNOCODE 27 #define fts5YYACTIONTYPE unsigned char -#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token +#define tdsqlite3Fts5ParserFTS5TOKENTYPE Fts5Token typedef union { int fts5yyinit; - sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0; + tdsqlite3Fts5ParserFTS5TOKENTYPE fts5yy0; int fts5yy4; Fts5Colset* fts5yy11; Fts5ExprNode* fts5yy24; @@ -183253,21 +211057,30 @@ typedef union { #ifndef fts5YYSTACKDEPTH #define fts5YYSTACKDEPTH 100 #endif -#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse; -#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse -#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse -#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse -#define fts5YYNSTATE 29 -#define fts5YYNRULE 26 -#define fts5YY_MAX_SHIFT 28 -#define fts5YY_MIN_SHIFTREDUCE 45 -#define fts5YY_MAX_SHIFTREDUCE 70 -#define fts5YY_MIN_REDUCE 71 -#define fts5YY_MAX_REDUCE 96 -#define fts5YY_ERROR_ACTION 97 -#define fts5YY_ACCEPT_ACTION 98 -#define fts5YY_NO_ACTION 99 +#define tdsqlite3Fts5ParserARG_SDECL Fts5Parse *pParse; +#define tdsqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse +#define tdsqlite3Fts5ParserARG_PARAM ,pParse +#define tdsqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse; +#define tdsqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse; +#define tdsqlite3Fts5ParserCTX_SDECL +#define tdsqlite3Fts5ParserCTX_PDECL +#define tdsqlite3Fts5ParserCTX_PARAM +#define tdsqlite3Fts5ParserCTX_FETCH +#define tdsqlite3Fts5ParserCTX_STORE +#define fts5YYNSTATE 35 +#define fts5YYNRULE 28 +#define fts5YYNRULE_WITH_ACTION 28 +#define fts5YYNFTS5TOKEN 16 +#define fts5YY_MAX_SHIFT 34 +#define fts5YY_MIN_SHIFTREDUCE 52 +#define fts5YY_MAX_SHIFTREDUCE 79 +#define fts5YY_ERROR_ACTION 80 +#define fts5YY_ACCEPT_ACTION 81 +#define fts5YY_NO_ACTION 82 +#define fts5YY_MIN_REDUCE 83 +#define fts5YY_MAX_REDUCE 110 /************* End control #defines *******************************************/ +#define fts5YY_NLOOKAHEAD ((int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0]))) /* Define the fts5yytestcase() macro to be a no-op if is not already defined ** otherwise. @@ -183296,9 +211109,6 @@ typedef union { ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE. ** -** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE -** and fts5YY_MAX_REDUCE -** ** N == fts5YY_ERROR_ACTION A syntax error has occurred. ** ** N == fts5YY_ACCEPT_ACTION The parser accepts its input. @@ -183306,25 +211116,22 @@ typedef union { ** N == fts5YY_NO_ACTION No such action. Denotes unused ** slots in the fts5yy_action[] table. ** +** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE +** and fts5YY_MAX_REDUCE +** ** The action table is constructed as a single large table named fts5yy_action[]. ** Given state S and lookahead X, the action is computed as either: ** ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ] ** (B) N = fts5yy_default[S] ** -** The (A) formula is preferred. The B formula is used instead if: -** (1) The fts5yy_shift_ofst[S]+X value is out of range, or -** (2) fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or -** (3) fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT. -** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that -** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X. -** Hence only tests (1) and (2) need to be evaluated.) +** The (A) formula is preferred. The B formula is used instead if +** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X. ** ** The formulas above are for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of -** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of -** fts5YY_SHIFT_USE_DFLT. +** the fts5yy_shift_ofst[] array. ** ** The following are the tables generated in this section: ** @@ -183338,50 +211145,56 @@ typedef union { ** fts5yy_default[] Default action for each state. ** *********** Begin parsing tables **********************************************/ -#define fts5YY_ACTTAB_COUNT (85) +#define fts5YY_ACTTAB_COUNT (105) static const fts5YYACTIONTYPE fts5yy_action[] = { - /* 0 */ 98, 16, 51, 5, 53, 27, 83, 7, 26, 15, - /* 10 */ 51, 5, 53, 27, 13, 69, 26, 48, 51, 5, - /* 20 */ 53, 27, 19, 11, 26, 9, 20, 51, 5, 53, - /* 30 */ 27, 13, 22, 26, 28, 51, 5, 53, 27, 68, - /* 40 */ 1, 26, 19, 11, 17, 9, 52, 10, 53, 27, - /* 50 */ 23, 24, 26, 54, 3, 4, 2, 26, 6, 21, - /* 60 */ 49, 71, 3, 4, 2, 7, 56, 59, 55, 59, - /* 70 */ 4, 2, 12, 69, 58, 60, 18, 67, 62, 69, - /* 80 */ 25, 66, 8, 14, 2, + /* 0 */ 81, 20, 96, 6, 28, 99, 98, 26, 26, 18, + /* 10 */ 96, 6, 28, 17, 98, 56, 26, 19, 96, 6, + /* 20 */ 28, 14, 98, 14, 26, 31, 92, 96, 6, 28, + /* 30 */ 108, 98, 25, 26, 21, 96, 6, 28, 78, 98, + /* 40 */ 58, 26, 29, 96, 6, 28, 107, 98, 22, 26, + /* 50 */ 24, 16, 12, 11, 1, 13, 13, 24, 16, 23, + /* 60 */ 11, 33, 34, 13, 97, 8, 27, 32, 98, 7, + /* 70 */ 26, 3, 4, 5, 3, 4, 5, 3, 83, 4, + /* 80 */ 5, 3, 63, 5, 3, 62, 12, 2, 86, 13, + /* 90 */ 9, 30, 10, 10, 54, 57, 75, 78, 78, 53, + /* 100 */ 57, 15, 82, 82, 71, }; static const fts5YYCODETYPE fts5yy_lookahead[] = { - /* 0 */ 16, 17, 18, 19, 20, 21, 5, 6, 24, 17, - /* 10 */ 18, 19, 20, 21, 11, 14, 24, 17, 18, 19, - /* 20 */ 20, 21, 8, 9, 24, 11, 17, 18, 19, 20, - /* 30 */ 21, 11, 12, 24, 17, 18, 19, 20, 21, 26, - /* 40 */ 6, 24, 8, 9, 22, 11, 18, 11, 20, 21, - /* 50 */ 24, 25, 24, 20, 1, 2, 3, 24, 23, 24, - /* 60 */ 7, 0, 1, 2, 3, 6, 10, 11, 10, 11, - /* 70 */ 2, 3, 9, 14, 11, 11, 22, 26, 7, 14, - /* 80 */ 13, 11, 5, 11, 3, + /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17, + /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19, + /* 20 */ 20, 9, 22, 9, 24, 13, 17, 18, 19, 20, + /* 30 */ 26, 22, 24, 24, 17, 18, 19, 20, 15, 22, + /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24, + /* 50 */ 6, 7, 9, 9, 10, 12, 12, 6, 7, 21, + /* 60 */ 9, 24, 25, 12, 18, 5, 20, 14, 22, 5, + /* 70 */ 24, 3, 1, 2, 3, 1, 2, 3, 0, 1, + /* 80 */ 2, 3, 11, 2, 3, 11, 9, 10, 5, 12, + /* 90 */ 23, 24, 10, 10, 8, 9, 9, 15, 15, 8, + /* 100 */ 9, 9, 27, 27, 11, 27, 27, 27, 27, 27, + /* 110 */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, + /* 120 */ 27, }; -#define fts5YY_SHIFT_USE_DFLT (85) -#define fts5YY_SHIFT_COUNT (28) +#define fts5YY_SHIFT_COUNT (34) #define fts5YY_SHIFT_MIN (0) -#define fts5YY_SHIFT_MAX (81) +#define fts5YY_SHIFT_MAX (93) static const unsigned char fts5yy_shift_ofst[] = { - /* 0 */ 34, 34, 34, 34, 34, 14, 20, 3, 36, 1, - /* 10 */ 59, 64, 64, 65, 65, 53, 61, 56, 58, 63, - /* 20 */ 68, 67, 70, 67, 71, 72, 67, 77, 81, + /* 0 */ 44, 44, 44, 44, 44, 44, 51, 77, 43, 12, + /* 10 */ 14, 83, 82, 14, 23, 23, 31, 31, 71, 74, + /* 20 */ 78, 81, 86, 91, 6, 53, 53, 60, 64, 68, + /* 30 */ 53, 87, 92, 53, 93, }; -#define fts5YY_REDUCE_USE_DFLT (-17) -#define fts5YY_REDUCE_COUNT (14) -#define fts5YY_REDUCE_MIN (-16) -#define fts5YY_REDUCE_MAX (54) +#define fts5YY_REDUCE_COUNT (17) +#define fts5YY_REDUCE_MIN (-17) +#define fts5YY_REDUCE_MAX (67) static const signed char fts5yy_reduce_ofst[] = { - /* 0 */ -16, -8, 0, 9, 17, 28, 26, 35, 33, 13, - /* 10 */ 13, 22, 54, 13, 51, + /* 0 */ -16, -8, 0, 9, 17, 25, 46, -17, -17, 37, + /* 10 */ 67, 4, 4, 8, 4, 20, 27, 38, }; static const fts5YYACTIONTYPE fts5yy_default[] = { - /* 0 */ 97, 97, 97, 97, 97, 76, 91, 97, 97, 96, - /* 10 */ 96, 97, 97, 96, 96, 97, 97, 97, 97, 97, - /* 20 */ 73, 89, 97, 90, 97, 97, 87, 97, 72, + /* 0 */ 80, 80, 80, 80, 80, 80, 95, 80, 80, 105, + /* 10 */ 80, 110, 110, 80, 110, 110, 80, 80, 80, 80, + /* 20 */ 80, 91, 80, 80, 80, 101, 100, 80, 80, 90, + /* 30 */ 103, 80, 80, 104, 80, }; /********** End of lemon-generated parsing tables *****************************/ @@ -183439,13 +211252,15 @@ struct fts5yyParser { #ifndef fts5YYNOERRORRECOVERY int fts5yyerrcnt; /* Shifts left before out of the error */ #endif - sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */ + tdsqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */ + tdsqlite3Fts5ParserCTX_SDECL /* A place to hold %extra_context */ #if fts5YYSTACKDEPTH<=0 int fts5yystksz; /* Current side of the stack */ fts5yyStackEntry *fts5yystack; /* The parser's stack */ fts5yyStackEntry fts5yystk0; /* First stack entry */ #else fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */ + fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */ #endif }; typedef struct fts5yyParser fts5yyParser; @@ -183474,7 +211289,7 @@ static char *fts5yyTracePrompt = 0; ** Outputs: ** None. */ -static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){ +static void tdsqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){ fts5yyTraceFILE = TraceFILE; fts5yyTracePrompt = zTracePrompt; if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0; @@ -183482,50 +211297,72 @@ static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){ } #endif /* NDEBUG */ -#ifndef NDEBUG +#if defined(fts5YYCOVERAGE) || !defined(NDEBUG) /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *const fts5yyTokenName[] = { - "$", "OR", "AND", "NOT", - "TERM", "COLON", "LP", "RP", - "MINUS", "LCP", "RCP", "STRING", - "COMMA", "PLUS", "STAR", "error", - "input", "expr", "cnearset", "exprlist", - "nearset", "colset", "colsetlist", "nearphrases", - "phrase", "neardist_opt", "star_opt", + /* 0 */ "$", + /* 1 */ "OR", + /* 2 */ "AND", + /* 3 */ "NOT", + /* 4 */ "TERM", + /* 5 */ "COLON", + /* 6 */ "MINUS", + /* 7 */ "LCP", + /* 8 */ "RCP", + /* 9 */ "STRING", + /* 10 */ "LP", + /* 11 */ "RP", + /* 12 */ "CARET", + /* 13 */ "COMMA", + /* 14 */ "PLUS", + /* 15 */ "STAR", + /* 16 */ "input", + /* 17 */ "expr", + /* 18 */ "cnearset", + /* 19 */ "exprlist", + /* 20 */ "colset", + /* 21 */ "colsetlist", + /* 22 */ "nearset", + /* 23 */ "nearphrases", + /* 24 */ "phrase", + /* 25 */ "neardist_opt", + /* 26 */ "star_opt", }; -#endif /* NDEBUG */ +#endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *const fts5yyRuleName[] = { /* 0 */ "input ::= expr", - /* 1 */ "expr ::= expr AND expr", - /* 2 */ "expr ::= expr OR expr", - /* 3 */ "expr ::= expr NOT expr", - /* 4 */ "expr ::= LP expr RP", - /* 5 */ "expr ::= exprlist", - /* 6 */ "exprlist ::= cnearset", - /* 7 */ "exprlist ::= exprlist cnearset", - /* 8 */ "cnearset ::= nearset", - /* 9 */ "cnearset ::= colset COLON nearset", - /* 10 */ "colset ::= MINUS LCP colsetlist RCP", - /* 11 */ "colset ::= LCP colsetlist RCP", - /* 12 */ "colset ::= STRING", - /* 13 */ "colset ::= MINUS STRING", - /* 14 */ "colsetlist ::= colsetlist STRING", - /* 15 */ "colsetlist ::= STRING", - /* 16 */ "nearset ::= phrase", - /* 17 */ "nearset ::= STRING LP nearphrases neardist_opt RP", - /* 18 */ "nearphrases ::= phrase", - /* 19 */ "nearphrases ::= nearphrases phrase", - /* 20 */ "neardist_opt ::=", - /* 21 */ "neardist_opt ::= COMMA STRING", - /* 22 */ "phrase ::= phrase PLUS STRING star_opt", - /* 23 */ "phrase ::= STRING star_opt", - /* 24 */ "star_opt ::= STAR", - /* 25 */ "star_opt ::=", + /* 1 */ "colset ::= MINUS LCP colsetlist RCP", + /* 2 */ "colset ::= LCP colsetlist RCP", + /* 3 */ "colset ::= STRING", + /* 4 */ "colset ::= MINUS STRING", + /* 5 */ "colsetlist ::= colsetlist STRING", + /* 6 */ "colsetlist ::= STRING", + /* 7 */ "expr ::= expr AND expr", + /* 8 */ "expr ::= expr OR expr", + /* 9 */ "expr ::= expr NOT expr", + /* 10 */ "expr ::= colset COLON LP expr RP", + /* 11 */ "expr ::= LP expr RP", + /* 12 */ "expr ::= exprlist", + /* 13 */ "exprlist ::= cnearset", + /* 14 */ "exprlist ::= exprlist cnearset", + /* 15 */ "cnearset ::= nearset", + /* 16 */ "cnearset ::= colset COLON nearset", + /* 17 */ "nearset ::= phrase", + /* 18 */ "nearset ::= CARET phrase", + /* 19 */ "nearset ::= STRING LP nearphrases neardist_opt RP", + /* 20 */ "nearphrases ::= phrase", + /* 21 */ "nearphrases ::= nearphrases phrase", + /* 22 */ "neardist_opt ::=", + /* 23 */ "neardist_opt ::= COMMA STRING", + /* 24 */ "phrase ::= phrase PLUS STRING star_opt", + /* 25 */ "phrase ::= STRING star_opt", + /* 26 */ "star_opt ::= STAR", + /* 27 */ "star_opt ::=", }; #endif /* NDEBUG */ @@ -183564,7 +211401,7 @@ static int fts5yyGrowStack(fts5yyParser *p){ #endif /* Datatype of the argument to the memory allocated passed as the -** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by +** second argument to tdsqlite3Fts5ParserAlloc() below. This can be changed by ** putting an appropriate #define in the %include section of the input ** grammar. */ @@ -183572,6 +211409,35 @@ static int fts5yyGrowStack(fts5yyParser *p){ # define fts5YYMALLOCARGTYPE size_t #endif +/* Initialize a new parser that has already been allocated. +*/ +static void tdsqlite3Fts5ParserInit(void *fts5yypRawParser tdsqlite3Fts5ParserCTX_PDECL){ + fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser; + tdsqlite3Fts5ParserCTX_STORE +#ifdef fts5YYTRACKMAXSTACKDEPTH + fts5yypParser->fts5yyhwm = 0; +#endif +#if fts5YYSTACKDEPTH<=0 + fts5yypParser->fts5yytos = NULL; + fts5yypParser->fts5yystack = NULL; + fts5yypParser->fts5yystksz = 0; + if( fts5yyGrowStack(fts5yypParser) ){ + fts5yypParser->fts5yystack = &fts5yypParser->fts5yystk0; + fts5yypParser->fts5yystksz = 1; + } +#endif +#ifndef fts5YYNOERRORRECOVERY + fts5yypParser->fts5yyerrcnt = -1; +#endif + fts5yypParser->fts5yytos = fts5yypParser->fts5yystack; + fts5yypParser->fts5yystack[0].stateno = 0; + fts5yypParser->fts5yystack[0].major = 0; +#if fts5YYSTACKDEPTH>0 + fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1]; +#endif +} + +#ifndef tdsqlite3Fts5Parser_ENGINEALWAYSONSTACK /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like @@ -183582,33 +211448,19 @@ static int fts5yyGrowStack(fts5yyParser *p){ ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls -** to sqlite3Fts5Parser and sqlite3Fts5ParserFree. +** to tdsqlite3Fts5Parser and tdsqlite3Fts5ParserFree. */ -static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){ - fts5yyParser *pParser; - pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) ); - if( pParser ){ -#ifdef fts5YYTRACKMAXSTACKDEPTH - pParser->fts5yyhwm = 0; -#endif -#if fts5YYSTACKDEPTH<=0 - pParser->fts5yytos = NULL; - pParser->fts5yystack = NULL; - pParser->fts5yystksz = 0; - if( fts5yyGrowStack(pParser) ){ - pParser->fts5yystack = &pParser->fts5yystk0; - pParser->fts5yystksz = 1; - } -#endif -#ifndef fts5YYNOERRORRECOVERY - pParser->fts5yyerrcnt = -1; -#endif - pParser->fts5yytos = pParser->fts5yystack; - pParser->fts5yystack[0].stateno = 0; - pParser->fts5yystack[0].major = 0; +static void *tdsqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) tdsqlite3Fts5ParserCTX_PDECL){ + fts5yyParser *fts5yypParser; + fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) ); + if( fts5yypParser ){ + tdsqlite3Fts5ParserCTX_STORE + tdsqlite3Fts5ParserInit(fts5yypParser tdsqlite3Fts5ParserCTX_PARAM); } - return pParser; + return (void*)fts5yypParser; } +#endif /* tdsqlite3Fts5Parser_ENGINEALWAYSONSTACK */ + /* The following function deletes the "minor type" or semantic value ** associated with a symbol. The symbol can be either a terminal @@ -183622,7 +211474,8 @@ static void fts5yy_destructor( fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */ fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */ ){ - sqlite3Fts5ParserARG_FETCH; + tdsqlite3Fts5ParserARG_FETCH + tdsqlite3Fts5ParserCTX_FETCH switch( fts5yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen @@ -183644,24 +211497,24 @@ static void fts5yy_destructor( case 18: /* cnearset */ case 19: /* exprlist */ { - sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24)); + tdsqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24)); } break; - case 20: /* nearset */ - case 23: /* nearphrases */ + case 20: /* colset */ + case 21: /* colsetlist */ { - sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46)); + tdsqlite3_free((fts5yypminor->fts5yy11)); } break; - case 21: /* colset */ - case 22: /* colsetlist */ + case 22: /* nearset */ + case 23: /* nearphrases */ { - sqlite3_free((fts5yypminor->fts5yy11)); + tdsqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46)); } break; case 24: /* phrase */ { - sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53)); + tdsqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53)); } break; /********* End destructor definitions *****************************************/ @@ -183690,6 +211543,18 @@ static void fts5yy_pop_parser_stack(fts5yyParser *pParser){ fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor); } +/* +** Clear all secondary memory allocations from the parser +*/ +static void tdsqlite3Fts5ParserFinalize(void *p){ + fts5yyParser *pParser = (fts5yyParser*)p; + while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser); +#if fts5YYSTACKDEPTH<=0 + if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack); +#endif +} + +#ifndef tdsqlite3Fts5Parser_ENGINEALWAYSONSTACK /* ** Deallocate and destroy a parser. Destructors are called for ** all stack elements before shutting the parser down. @@ -183698,53 +211563,95 @@ static void fts5yy_pop_parser_stack(fts5yyParser *pParser){ ** is defined in a %include section of the input grammar) then it is ** assumed that the input pointer is never NULL. */ -static void sqlite3Fts5ParserFree( +static void tdsqlite3Fts5ParserFree( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ - fts5yyParser *pParser = (fts5yyParser*)p; #ifndef fts5YYPARSEFREENEVERNULL - if( pParser==0 ) return; -#endif - while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser); -#if fts5YYSTACKDEPTH<=0 - if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack); + if( p==0 ) return; #endif - (*freeProc)((void*)pParser); + tdsqlite3Fts5ParserFinalize(p); + (*freeProc)(p); } +#endif /* tdsqlite3Fts5Parser_ENGINEALWAYSONSTACK */ /* ** Return the peak depth of the stack for a parser. */ #ifdef fts5YYTRACKMAXSTACKDEPTH -static int sqlite3Fts5ParserStackPeak(void *p){ +static int tdsqlite3Fts5ParserStackPeak(void *p){ fts5yyParser *pParser = (fts5yyParser*)p; return pParser->fts5yyhwm; } #endif +/* This array of booleans keeps track of the parser statement +** coverage. The element fts5yycoverage[X][Y] is set when the parser +** is in state X and has a lookahead token Y. In a well-tested +** systems, every element of this matrix should end up being set. +*/ +#if defined(fts5YYCOVERAGE) +static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN]; +#endif + +/* +** Write into out a description of every state/lookahead combination that +** +** (1) has not been used by the parser, and +** (2) is not a syntax error. +** +** Return the number of missed state/lookahead combinations. +*/ +#if defined(fts5YYCOVERAGE) +static int tdsqlite3Fts5ParserCoverage(FILE *out){ + int stateno, iLookAhead, i; + int nMissed = 0; + for(stateno=0; stateno<fts5YYNSTATE; stateno++){ + i = fts5yy_shift_ofst[stateno]; + for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){ + if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue; + if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++; + if( out ){ + fprintf(out,"State %d lookahead %s %s\n", stateno, + fts5yyTokenName[iLookAhead], + fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed"); + } + } + } + return nMissed; +} +#endif + /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. */ -static unsigned int fts5yy_find_shift_action( - fts5yyParser *pParser, /* The parser */ - fts5YYCODETYPE iLookAhead /* The look-ahead token */ +static fts5YYACTIONTYPE fts5yy_find_shift_action( + fts5YYCODETYPE iLookAhead, /* The look-ahead token */ + fts5YYACTIONTYPE stateno /* Current state number */ ){ int i; - int stateno = pParser->fts5yytos->stateno; - - if( stateno>=fts5YY_MIN_REDUCE ) return stateno; + + if( stateno>fts5YY_MAX_SHIFT ) return stateno; assert( stateno <= fts5YY_SHIFT_COUNT ); +#if defined(fts5YYCOVERAGE) + fts5yycoverage[stateno][iLookAhead] = 1; +#endif do{ i = fts5yy_shift_ofst[stateno]; + assert( i>=0 ); + assert( i<=fts5YY_ACTTAB_COUNT ); + assert( i+fts5YYNFTS5TOKEN<=(int)fts5YY_NLOOKAHEAD ); assert( iLookAhead!=fts5YYNOCODE ); + assert( iLookAhead < fts5YYNFTS5TOKEN ); i += iLookAhead; - if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){ + assert( i<(int)fts5YY_NLOOKAHEAD ); + if( fts5yy_lookahead[i]!=iLookAhead ){ #ifdef fts5YYFALLBACK fts5YYCODETYPE iFallback; /* Fallback token */ - if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0]) - && (iFallback = fts5yyFallback[iLookAhead])!=0 ){ + assert( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0]) ); + iFallback = fts5yyFallback[iLookAhead]; + if( iFallback!=0 ){ #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n", @@ -183759,15 +211666,8 @@ static unsigned int fts5yy_find_shift_action( #ifdef fts5YYWILDCARD { int j = i - iLookAhead + fts5YYWILDCARD; - if( -#if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0 - j>=0 && -#endif -#if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT - j<fts5YY_ACTTAB_COUNT && -#endif - fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0 - ){ + assert( j<(int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])) ); + if( fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0 ){ #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n", @@ -183781,6 +211681,7 @@ static unsigned int fts5yy_find_shift_action( #endif /* fts5YYWILDCARD */ return fts5yy_default[stateno]; }else{ + assert( i>=0 && i<sizeof(fts5yy_action)/sizeof(fts5yy_action[0]) ); return fts5yy_action[i]; } }while(1); @@ -183790,8 +211691,8 @@ static unsigned int fts5yy_find_shift_action( ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. */ -static int fts5yy_find_reduce_action( - int stateno, /* Current state number */ +static fts5YYACTIONTYPE fts5yy_find_reduce_action( + fts5YYACTIONTYPE stateno, /* Current state number */ fts5YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; @@ -183803,7 +211704,6 @@ static int fts5yy_find_reduce_action( assert( stateno<=fts5YY_REDUCE_COUNT ); #endif i = fts5yy_reduce_ofst[stateno]; - assert( i!=fts5YY_REDUCE_USE_DFLT ); assert( iLookAhead!=fts5YYNOCODE ); i += iLookAhead; #ifdef fts5YYERRORSYMBOL @@ -183821,8 +211721,8 @@ static int fts5yy_find_reduce_action( ** The following routine is called if the stack overflows. */ static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){ - sqlite3Fts5ParserARG_FETCH; - fts5yypParser->fts5yytos--; + tdsqlite3Fts5ParserARG_FETCH + tdsqlite3Fts5ParserCTX_FETCH #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt); @@ -183833,29 +211733,31 @@ static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){ ** stack every overflows */ /******** Begin %stack_overflow code ******************************************/ - sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow"); + tdsqlite3Fts5ParseError(pParse, "fts5: parser stack overflow"); /******** End %stack_overflow code ********************************************/ - sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */ + tdsqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */ + tdsqlite3Fts5ParserCTX_STORE } /* ** Print tracing information for a SHIFT action */ #ifndef NDEBUG -static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){ +static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){ if( fts5yyTraceFILE ){ if( fts5yyNewState<fts5YYNSTATE ){ - fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n", - fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major], + fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n", + fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major], fts5yyNewState); }else{ - fprintf(fts5yyTraceFILE,"%sShift '%s'\n", - fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]); + fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n", + fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major], + fts5yyNewState - fts5YY_MIN_REDUCE); } } } #else -# define fts5yyTraceShift(X,Y) +# define fts5yyTraceShift(X,Y,Z) #endif /* @@ -183863,9 +211765,9 @@ static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){ */ static void fts5yy_shift( fts5yyParser *fts5yypParser, /* The parser to be shifted */ - int fts5yyNewState, /* The new state to shift in */ - int fts5yyMajor, /* The major token to shift in */ - sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */ + fts5YYACTIONTYPE fts5yyNewState, /* The new state to shift in */ + fts5YYCODETYPE fts5yyMajor, /* The major token to shift in */ + tdsqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */ ){ fts5yyStackEntry *fts5yytos; fts5yypParser->fts5yytos++; @@ -183876,13 +211778,15 @@ static void fts5yy_shift( } #endif #if fts5YYSTACKDEPTH>0 - if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){ + if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){ + fts5yypParser->fts5yytos--; fts5yyStackOverflow(fts5yypParser); return; } #else if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){ if( fts5yyGrowStack(fts5yypParser) ){ + fts5yypParser->fts5yytos--; fts5yyStackOverflow(fts5yypParser); return; } @@ -183892,45 +211796,76 @@ static void fts5yy_shift( fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE; } fts5yytos = fts5yypParser->fts5yytos; - fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState; - fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor; + fts5yytos->stateno = fts5yyNewState; + fts5yytos->major = fts5yyMajor; fts5yytos->minor.fts5yy0 = fts5yyMinor; - fts5yyTraceShift(fts5yypParser, fts5yyNewState); -} + fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift"); +} + +/* For rule J, fts5yyRuleInfoLhs[J] contains the symbol on the left-hand side +** of that rule */ +static const fts5YYCODETYPE fts5yyRuleInfoLhs[] = { + 16, /* (0) input ::= expr */ + 20, /* (1) colset ::= MINUS LCP colsetlist RCP */ + 20, /* (2) colset ::= LCP colsetlist RCP */ + 20, /* (3) colset ::= STRING */ + 20, /* (4) colset ::= MINUS STRING */ + 21, /* (5) colsetlist ::= colsetlist STRING */ + 21, /* (6) colsetlist ::= STRING */ + 17, /* (7) expr ::= expr AND expr */ + 17, /* (8) expr ::= expr OR expr */ + 17, /* (9) expr ::= expr NOT expr */ + 17, /* (10) expr ::= colset COLON LP expr RP */ + 17, /* (11) expr ::= LP expr RP */ + 17, /* (12) expr ::= exprlist */ + 19, /* (13) exprlist ::= cnearset */ + 19, /* (14) exprlist ::= exprlist cnearset */ + 18, /* (15) cnearset ::= nearset */ + 18, /* (16) cnearset ::= colset COLON nearset */ + 22, /* (17) nearset ::= phrase */ + 22, /* (18) nearset ::= CARET phrase */ + 22, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */ + 23, /* (20) nearphrases ::= phrase */ + 23, /* (21) nearphrases ::= nearphrases phrase */ + 25, /* (22) neardist_opt ::= */ + 25, /* (23) neardist_opt ::= COMMA STRING */ + 24, /* (24) phrase ::= phrase PLUS STRING star_opt */ + 24, /* (25) phrase ::= STRING star_opt */ + 26, /* (26) star_opt ::= STAR */ + 26, /* (27) star_opt ::= */ +}; -/* The following table contains information about every rule that -** is used during the reduce. -*/ -static const struct { - fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ - unsigned char nrhs; /* Number of right-hand side symbols in the rule */ -} fts5yyRuleInfo[] = { - { 16, 1 }, - { 17, 3 }, - { 17, 3 }, - { 17, 3 }, - { 17, 3 }, - { 17, 1 }, - { 19, 1 }, - { 19, 2 }, - { 18, 1 }, - { 18, 3 }, - { 21, 4 }, - { 21, 3 }, - { 21, 1 }, - { 21, 2 }, - { 22, 2 }, - { 22, 1 }, - { 20, 1 }, - { 20, 5 }, - { 23, 1 }, - { 23, 2 }, - { 25, 0 }, - { 25, 2 }, - { 24, 4 }, - { 24, 2 }, - { 26, 1 }, - { 26, 0 }, +/* For rule J, fts5yyRuleInfoNRhs[J] contains the negative of the number +** of symbols on the right-hand side of that rule. */ +static const signed char fts5yyRuleInfoNRhs[] = { + -1, /* (0) input ::= expr */ + -4, /* (1) colset ::= MINUS LCP colsetlist RCP */ + -3, /* (2) colset ::= LCP colsetlist RCP */ + -1, /* (3) colset ::= STRING */ + -2, /* (4) colset ::= MINUS STRING */ + -2, /* (5) colsetlist ::= colsetlist STRING */ + -1, /* (6) colsetlist ::= STRING */ + -3, /* (7) expr ::= expr AND expr */ + -3, /* (8) expr ::= expr OR expr */ + -3, /* (9) expr ::= expr NOT expr */ + -5, /* (10) expr ::= colset COLON LP expr RP */ + -3, /* (11) expr ::= LP expr RP */ + -1, /* (12) expr ::= exprlist */ + -1, /* (13) exprlist ::= cnearset */ + -2, /* (14) exprlist ::= exprlist cnearset */ + -1, /* (15) cnearset ::= nearset */ + -3, /* (16) cnearset ::= colset COLON nearset */ + -1, /* (17) nearset ::= phrase */ + -2, /* (18) nearset ::= CARET phrase */ + -5, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */ + -1, /* (20) nearphrases ::= phrase */ + -2, /* (21) nearphrases ::= nearphrases phrase */ + 0, /* (22) neardist_opt ::= */ + -2, /* (23) neardist_opt ::= COMMA STRING */ + -4, /* (24) phrase ::= phrase PLUS STRING star_opt */ + -2, /* (25) phrase ::= STRING star_opt */ + -1, /* (26) star_opt ::= STAR */ + 0, /* (27) star_opt ::= */ }; static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */ @@ -183938,29 +211873,49 @@ static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. +** +** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions +** access to the lookahead token (if any). The fts5yyLookahead will be fts5YYNOCODE +** if the lookahead token has already been consumed. As this procedure is +** only called from one place, optimizing compilers will in-line it, which +** means that the extra parameters have no performance impact. */ -static void fts5yy_reduce( +static fts5YYACTIONTYPE fts5yy_reduce( fts5yyParser *fts5yypParser, /* The parser */ - unsigned int fts5yyruleno /* Number of the rule by which to reduce */ + unsigned int fts5yyruleno, /* Number of the rule by which to reduce */ + int fts5yyLookahead, /* Lookahead token, or fts5YYNOCODE if none */ + tdsqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken /* Value of the lookahead token */ + tdsqlite3Fts5ParserCTX_PDECL /* %extra_context */ ){ int fts5yygoto; /* The next state */ - int fts5yyact; /* The next action */ + fts5YYACTIONTYPE fts5yyact; /* The next action */ fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */ int fts5yysize; /* Amount to pop the stack */ - sqlite3Fts5ParserARG_FETCH; + tdsqlite3Fts5ParserARG_FETCH + (void)fts5yyLookahead; + (void)fts5yyLookaheadToken; fts5yymsp = fts5yypParser->fts5yytos; #ifndef NDEBUG if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){ - fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs; - fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt, - fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno); + fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno]; + if( fts5yysize ){ + fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n", + fts5yyTracePrompt, + fts5yyruleno, fts5yyRuleName[fts5yyruleno], + fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action", + fts5yymsp[fts5yysize].stateno); + }else{ + fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s.\n", + fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno], + fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action"); + } } #endif /* NDEBUG */ /* Check that the stack is large enough to grow by a single entry ** if the RHS of the rule is empty. This ensures that there is room ** enough on the stack to push the LHS value */ - if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){ + if( fts5yyRuleInfoNRhs[fts5yyruleno]==0 ){ #ifdef fts5YYTRACKMAXSTACKDEPTH if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){ fts5yypParser->fts5yyhwm++; @@ -183968,15 +211923,21 @@ static void fts5yy_reduce( } #endif #if fts5YYSTACKDEPTH>0 - if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){ + if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){ fts5yyStackOverflow(fts5yypParser); - return; + /* The call to fts5yyStackOverflow() above pops the stack until it is + ** empty, causing the main parser loop to exit. So the return value + ** is never used and does not matter. */ + return 0; } #else if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){ if( fts5yyGrowStack(fts5yypParser) ){ fts5yyStackOverflow(fts5yypParser); - return; + /* The call to fts5yyStackOverflow() above pops the stack until it is + ** empty, causing the main parser loop to exit. So the return value + ** is never used and does not matter. */ + return 0; } fts5yymsp = fts5yypParser->fts5yytos; } @@ -183995,154 +211956,167 @@ static void fts5yy_reduce( /********** Begin reduce actions **********************************************/ fts5YYMINORTYPE fts5yylhsminor; case 0: /* input ::= expr */ -{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); } +{ tdsqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); } + break; + case 1: /* colset ::= MINUS LCP colsetlist RCP */ +{ + fts5yymsp[-3].minor.fts5yy11 = tdsqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11); +} + break; + case 2: /* colset ::= LCP colsetlist RCP */ +{ fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; } + break; + case 3: /* colset ::= STRING */ +{ + fts5yylhsminor.fts5yy11 = tdsqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); +} + fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11; + break; + case 4: /* colset ::= MINUS STRING */ +{ + fts5yymsp[-1].minor.fts5yy11 = tdsqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); + fts5yymsp[-1].minor.fts5yy11 = tdsqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11); +} + break; + case 5: /* colsetlist ::= colsetlist STRING */ +{ + fts5yylhsminor.fts5yy11 = tdsqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); } + fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11; + break; + case 6: /* colsetlist ::= STRING */ +{ + fts5yylhsminor.fts5yy11 = tdsqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); +} + fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11; break; - case 1: /* expr ::= expr AND expr */ + case 7: /* expr ::= expr AND expr */ { - fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0); + fts5yylhsminor.fts5yy24 = tdsqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0); } fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; - case 2: /* expr ::= expr OR expr */ + case 8: /* expr ::= expr OR expr */ { - fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0); + fts5yylhsminor.fts5yy24 = tdsqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0); } fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; - case 3: /* expr ::= expr NOT expr */ + case 9: /* expr ::= expr NOT expr */ { - fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0); + fts5yylhsminor.fts5yy24 = tdsqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0); } fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; - case 4: /* expr ::= LP expr RP */ + case 10: /* expr ::= colset COLON LP expr RP */ +{ + tdsqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11); + fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24; +} + fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24; + break; + case 11: /* expr ::= LP expr RP */ {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;} break; - case 5: /* expr ::= exprlist */ - case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6); + case 12: /* expr ::= exprlist */ + case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13); {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;} fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; - case 7: /* exprlist ::= exprlist cnearset */ + case 14: /* exprlist ::= exprlist cnearset */ { - fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24); + fts5yylhsminor.fts5yy24 = tdsqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24); } fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; - case 8: /* cnearset ::= nearset */ + case 15: /* cnearset ::= nearset */ { - fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); + fts5yylhsminor.fts5yy24 = tdsqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); } fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; - case 9: /* cnearset ::= colset COLON nearset */ + case 16: /* cnearset ::= colset COLON nearset */ { - sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy46, fts5yymsp[-2].minor.fts5yy11); - fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); + fts5yylhsminor.fts5yy24 = tdsqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); + tdsqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11); } fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24; break; - case 10: /* colset ::= MINUS LCP colsetlist RCP */ -{ - fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11); -} - break; - case 11: /* colset ::= LCP colsetlist RCP */ -{ fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; } - break; - case 12: /* colset ::= STRING */ -{ - fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); -} - fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11; - break; - case 13: /* colset ::= MINUS STRING */ -{ - fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); - fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11); -} - break; - case 14: /* colsetlist ::= colsetlist STRING */ -{ - fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); } - fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11; + case 17: /* nearset ::= phrase */ +{ fts5yylhsminor.fts5yy46 = tdsqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); } + fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46; break; - case 15: /* colsetlist ::= STRING */ + case 18: /* nearset ::= CARET phrase */ { - fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); + tdsqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53); + fts5yymsp[-1].minor.fts5yy46 = tdsqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); } - fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11; - break; - case 16: /* nearset ::= phrase */ -{ fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); } - fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46; break; - case 17: /* nearset ::= STRING LP nearphrases neardist_opt RP */ + case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */ { - sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0); - sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0); + tdsqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0); + tdsqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0); fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46; } fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46; break; - case 18: /* nearphrases ::= phrase */ + case 20: /* nearphrases ::= phrase */ { - fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); + fts5yylhsminor.fts5yy46 = tdsqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); } fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46; break; - case 19: /* nearphrases ::= nearphrases phrase */ + case 21: /* nearphrases ::= nearphrases phrase */ { - fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53); + fts5yylhsminor.fts5yy46 = tdsqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53); } fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46; break; - case 20: /* neardist_opt ::= */ + case 22: /* neardist_opt ::= */ { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; } break; - case 21: /* neardist_opt ::= COMMA STRING */ + case 23: /* neardist_opt ::= COMMA STRING */ { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; } break; - case 22: /* phrase ::= phrase PLUS STRING star_opt */ + case 24: /* phrase ::= phrase PLUS STRING star_opt */ { - fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4); + fts5yylhsminor.fts5yy53 = tdsqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4); } fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53; break; - case 23: /* phrase ::= STRING star_opt */ + case 25: /* phrase ::= STRING star_opt */ { - fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4); + fts5yylhsminor.fts5yy53 = tdsqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4); } fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53; break; - case 24: /* star_opt ::= STAR */ + case 26: /* star_opt ::= STAR */ { fts5yymsp[0].minor.fts5yy4 = 1; } break; - case 25: /* star_opt ::= */ + case 27: /* star_opt ::= */ { fts5yymsp[1].minor.fts5yy4 = 0; } break; default: break; /********** End reduce actions ************************************************/ }; - assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) ); - fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs; - fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs; - fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto); - if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){ - if( fts5yyact>fts5YY_MAX_SHIFT ){ - fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE; - } - fts5yymsp -= fts5yysize-1; - fts5yypParser->fts5yytos = fts5yymsp; - fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact; - fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto; - fts5yyTraceShift(fts5yypParser, fts5yyact); - }else{ - assert( fts5yyact == fts5YY_ACCEPT_ACTION ); - fts5yypParser->fts5yytos -= fts5yysize; - fts5yy_accept(fts5yypParser); - } + assert( fts5yyruleno<sizeof(fts5yyRuleInfoLhs)/sizeof(fts5yyRuleInfoLhs[0]) ); + fts5yygoto = fts5yyRuleInfoLhs[fts5yyruleno]; + fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno]; + fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto); + + /* There are no SHIFTREDUCE actions on nonterminals because the table + ** generator has simplified them to pure REDUCE actions. */ + assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) ); + + /* It is not possible for a REDUCE to be followed by an error */ + assert( fts5yyact!=fts5YY_ERROR_ACTION ); + + fts5yymsp += fts5yysize+1; + fts5yypParser->fts5yytos = fts5yymsp; + fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact; + fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto; + fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift"); + return fts5yyact; } /* @@ -184152,7 +212126,8 @@ static void fts5yy_reduce( static void fts5yy_parse_failed( fts5yyParser *fts5yypParser /* The parser */ ){ - sqlite3Fts5ParserARG_FETCH; + tdsqlite3Fts5ParserARG_FETCH + tdsqlite3Fts5ParserCTX_FETCH #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt); @@ -184163,7 +212138,8 @@ static void fts5yy_parse_failed( ** parser fails */ /************ Begin %parse_failure code ***************************************/ /************ End %parse_failure code *****************************************/ - sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ + tdsqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */ + tdsqlite3Fts5ParserCTX_STORE } #endif /* fts5YYNOERRORRECOVERY */ @@ -184173,18 +212149,20 @@ static void fts5yy_parse_failed( static void fts5yy_syntax_error( fts5yyParser *fts5yypParser, /* The parser */ int fts5yymajor, /* The major type of the error token */ - sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */ + tdsqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */ ){ - sqlite3Fts5ParserARG_FETCH; + tdsqlite3Fts5ParserARG_FETCH + tdsqlite3Fts5ParserCTX_FETCH #define FTS5TOKEN fts5yyminor /************ Begin %syntax_error code ****************************************/ UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */ - sqlite3Fts5ParseError( + tdsqlite3Fts5ParseError( pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p ); /************ End %syntax_error code ******************************************/ - sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ + tdsqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */ + tdsqlite3Fts5ParserCTX_STORE } /* @@ -184193,7 +212171,8 @@ static void fts5yy_syntax_error( static void fts5yy_accept( fts5yyParser *fts5yypParser /* The parser */ ){ - sqlite3Fts5ParserARG_FETCH; + tdsqlite3Fts5ParserARG_FETCH + tdsqlite3Fts5ParserCTX_FETCH #ifndef NDEBUG if( fts5yyTraceFILE ){ fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt); @@ -184207,12 +212186,13 @@ static void fts5yy_accept( ** parser accepts */ /*********** Begin %parse_accept code *****************************************/ /*********** End %parse_accept code *******************************************/ - sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ + tdsqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */ + tdsqlite3Fts5ParserCTX_STORE } /* The main parser program. ** The first argument is a pointer to a structure obtained from -** "sqlite3Fts5ParserAlloc" which describes the current state of the parser. +** "tdsqlite3Fts5ParserAlloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for @@ -184229,45 +212209,58 @@ static void fts5yy_accept( ** Outputs: ** None. */ -static void sqlite3Fts5Parser( +static void tdsqlite3Fts5Parser( void *fts5yyp, /* The parser */ int fts5yymajor, /* The major token code number */ - sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */ - sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */ + tdsqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */ + tdsqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */ ){ fts5YYMINORTYPE fts5yyminorunion; - unsigned int fts5yyact; /* The parser action. */ + fts5YYACTIONTYPE fts5yyact; /* The parser action. */ #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY) int fts5yyendofinput; /* True if we are at the end of input */ #endif #ifdef fts5YYERRORSYMBOL int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */ #endif - fts5yyParser *fts5yypParser; /* The parser */ + fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp; /* The parser */ + tdsqlite3Fts5ParserCTX_FETCH + tdsqlite3Fts5ParserARG_STORE - fts5yypParser = (fts5yyParser*)fts5yyp; assert( fts5yypParser->fts5yytos!=0 ); #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY) fts5yyendofinput = (fts5yymajor==0); #endif - sqlite3Fts5ParserARG_STORE; + fts5yyact = fts5yypParser->fts5yytos->stateno; #ifndef NDEBUG if( fts5yyTraceFILE ){ - fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]); + if( fts5yyact < fts5YY_MIN_REDUCE ){ + fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n", + fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact); + }else{ + fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n", + fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE); + } } #endif do{ - fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor); - if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){ - fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor); + assert( fts5yyact==fts5yypParser->fts5yytos->stateno ); + fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact); + if( fts5yyact >= fts5YY_MIN_REDUCE ){ + fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor, + fts5yyminor tdsqlite3Fts5ParserCTX_PARAM); + }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){ + fts5yy_shift(fts5yypParser,fts5yyact,(fts5YYCODETYPE)fts5yymajor,fts5yyminor); #ifndef fts5YYNOERRORRECOVERY fts5yypParser->fts5yyerrcnt--; #endif - fts5yymajor = fts5YYNOCODE; - }else if( fts5yyact <= fts5YY_MAX_REDUCE ){ - fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE); + break; + }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){ + fts5yypParser->fts5yytos--; + fts5yy_accept(fts5yypParser); + return; }else{ assert( fts5yyact == fts5YY_ERROR_ACTION ); fts5yyminorunion.fts5yy0 = fts5yyminor; @@ -184314,10 +212307,9 @@ static void sqlite3Fts5Parser( fts5yymajor = fts5YYNOCODE; }else{ while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack - && fts5yymx != fts5YYERRORSYMBOL && (fts5yyact = fts5yy_find_reduce_action( fts5yypParser->fts5yytos->stateno, - fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE + fts5YYERRORSYMBOL)) > fts5YY_MAX_SHIFTREDUCE ){ fts5yy_pop_parser_stack(fts5yypParser); } @@ -184334,6 +212326,8 @@ static void sqlite3Fts5Parser( } fts5yypParser->fts5yyerrcnt = 3; fts5yyerrorhit = 1; + if( fts5yymajor==fts5YYNOCODE ) break; + fts5yyact = fts5yypParser->fts5yytos->stateno; #elif defined(fts5YYNOERRORRECOVERY) /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to ** do any kind of error recovery. Instead, simply invoke the syntax @@ -184344,8 +212338,7 @@ static void sqlite3Fts5Parser( */ fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor); fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion); - fts5yymajor = fts5YYNOCODE; - + break; #else /* fts5YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** @@ -184367,10 +212360,10 @@ static void sqlite3Fts5Parser( fts5yypParser->fts5yyerrcnt = -1; #endif } - fts5yymajor = fts5YYNOCODE; + break; #endif } - }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ); + }while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ); #ifndef NDEBUG if( fts5yyTraceFILE ){ fts5yyStackEntry *i; @@ -184387,6 +212380,20 @@ static void sqlite3Fts5Parser( } /* +** Return the fallback token corresponding to canonical token iToken, or +** 0 if iToken has no fallback. +*/ +static int tdsqlite3Fts5ParserFallback(int iToken){ +#ifdef fts5YYFALLBACK + assert( iToken<(int)(sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])) ); + return fts5yyFallback[iToken]; +#else + (void)iToken; + return 0; +#endif +} + +/* ** 2014 May 31 ** ** The author disclaims copyright to this source code. In place of @@ -184524,9 +212531,9 @@ static void fts5HighlightAppend( HighlightContext *p, const char *z, int n ){ - if( *pRc==SQLITE_OK ){ + if( *pRc==SQLITE_OK && z ){ if( n<0 ) n = (int)strlen(z); - p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z); + p->zOut = tdsqlite3_mprintf("%z%.*s", p->zOut, n, z); if( p->zOut==0 ) *pRc = SQLITE_NOMEM; } } @@ -184591,9 +212598,9 @@ static int fts5HighlightCb( static void fts5HighlightFunction( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ - sqlite3_context *pCtx, /* Context for returning result/error */ + tdsqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ - sqlite3_value **apVal /* Array of trailing arguments */ + tdsqlite3_value **apVal /* Array of trailing arguments */ ){ HighlightContext ctx; int rc; @@ -184601,14 +212608,14 @@ static void fts5HighlightFunction( if( nVal!=3 ){ const char *zErr = "wrong number of arguments to function highlight()"; - sqlite3_result_error(pCtx, zErr, -1); + tdsqlite3_result_error(pCtx, zErr, -1); return; } - iCol = sqlite3_value_int(apVal[0]); + iCol = tdsqlite3_value_int(apVal[0]); memset(&ctx, 0, sizeof(HighlightContext)); - ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]); - ctx.zClose = (const char*)sqlite3_value_text(apVal[2]); + ctx.zOpen = (const char*)tdsqlite3_value_text(apVal[1]); + ctx.zClose = (const char*)tdsqlite3_value_text(apVal[2]); rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn); if( ctx.zIn ){ @@ -184622,12 +212629,12 @@ static void fts5HighlightFunction( fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff); if( rc==SQLITE_OK ){ - sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT); + tdsqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT); } - sqlite3_free(ctx.zOut); + tdsqlite3_free(ctx.zOut); } if( rc!=SQLITE_OK ){ - sqlite3_result_error_code(pCtx, rc); + tdsqlite3_result_error_code(pCtx, rc); } } /* @@ -184656,7 +212663,7 @@ static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){ int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64; int *aNew; - aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int)); + aNew = (int*)tdsqlite3_realloc64(p->aFirst, nNew*sizeof(int)); if( aNew==0 ) return SQLITE_NOMEM; p->aFirst = aNew; p->nFirstAlloc = nNew; @@ -184723,11 +212730,12 @@ static int fts5SnippetScore( int nInst; int nScore = 0; int iLast = 0; + tdsqlite3_int64 iEnd = (tdsqlite3_int64)iPos + nToken; rc = pApi->xInstCount(pFts, &nInst); for(i=0; i<nInst && rc==SQLITE_OK; i++){ rc = pApi->xInst(pFts, i, &ip, &ic, &iOff); - if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){ + if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<iEnd ){ nScore += (aSeen[ip] ? 1 : 1000); aSeen[ip] = 1; if( iFirst<0 ) iFirst = iOff; @@ -184737,24 +212745,34 @@ static int fts5SnippetScore( *pnScore = nScore; if( piPos ){ - int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2; + tdsqlite3_int64 iAdj = iFirst - (nToken - (iLast-iFirst)) / 2; if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken; if( iAdj<0 ) iAdj = 0; - *piPos = iAdj; + *piPos = (int)iAdj; } return rc; } /* +** Return the value in pVal interpreted as utf-8 text. Except, if pVal +** contains a NULL value, return a pointer to a static string zero +** bytes in length instead of a NULL pointer. +*/ +static const char *fts5ValueToText(tdsqlite3_value *pVal){ + const char *zRet = (const char*)tdsqlite3_value_text(pVal); + return zRet ? zRet : ""; +} + +/* ** Implementation of snippet() function. */ static void fts5SnippetFunction( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ - sqlite3_context *pCtx, /* Context for returning result/error */ + tdsqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ - sqlite3_value **apVal /* Array of trailing arguments */ + tdsqlite3_value **apVal /* Array of trailing arguments */ ){ HighlightContext ctx; int rc = SQLITE_OK; /* Return code */ @@ -184774,21 +212792,21 @@ static void fts5SnippetFunction( if( nVal!=5 ){ const char *zErr = "wrong number of arguments to function snippet()"; - sqlite3_result_error(pCtx, zErr, -1); + tdsqlite3_result_error(pCtx, zErr, -1); return; } nCol = pApi->xColumnCount(pFts); memset(&ctx, 0, sizeof(HighlightContext)); - iCol = sqlite3_value_int(apVal[0]); - ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]); - ctx.zClose = (const char*)sqlite3_value_text(apVal[2]); - zEllips = (const char*)sqlite3_value_text(apVal[3]); - nToken = sqlite3_value_int(apVal[4]); + iCol = tdsqlite3_value_int(apVal[0]); + ctx.zOpen = fts5ValueToText(apVal[1]); + ctx.zClose = fts5ValueToText(apVal[2]); + zEllips = fts5ValueToText(apVal[3]); + nToken = tdsqlite3_value_int(apVal[4]); iBestCol = (iCol>=0 ? iCol : 0); nPhrase = pApi->xPhraseCount(pFts); - aSeen = sqlite3_malloc(nPhrase); + aSeen = tdsqlite3_malloc(nPhrase); if( aSeen==0 ){ rc = SQLITE_NOMEM; } @@ -184820,7 +212838,9 @@ static void fts5SnippetFunction( int jj; rc = pApi->xInst(pFts, ii, &ip, &ic, &io); - if( ic!=i || rc!=SQLITE_OK ) continue; + if( ic!=i ) continue; + if( io>nDocsize ) rc = FTS5_CORRUPT; + if( rc!=SQLITE_OK ) continue; memset(aSeen, 0, nPhrase); rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i, io, nToken, &nScore, &iAdj @@ -184890,13 +212910,13 @@ static void fts5SnippetFunction( } } if( rc==SQLITE_OK ){ - sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT); + tdsqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT); }else{ - sqlite3_result_error_code(pCtx, rc); + tdsqlite3_result_error_code(pCtx, rc); } - sqlite3_free(ctx.zOut); - sqlite3_free(aSeen); - sqlite3_free(sFinder.aFirst); + tdsqlite3_free(ctx.zOut); + tdsqlite3_free(aSeen); + tdsqlite3_free(sFinder.aFirst); } /************************************************************************/ @@ -184920,9 +212940,9 @@ struct Fts5Bm25Data { static int fts5CountCb( const Fts5ExtensionApi *pApi, Fts5Context *pFts, - void *pUserData /* Pointer to sqlite3_int64 variable */ + void *pUserData /* Pointer to tdsqlite3_int64 variable */ ){ - sqlite3_int64 *pn = (sqlite3_int64*)pUserData; + tdsqlite3_int64 *pn = (tdsqlite3_int64*)pUserData; UNUSED_PARAM2(pApi, pFts); (*pn)++; return SQLITE_OK; @@ -184944,19 +212964,19 @@ static int fts5Bm25GetData( p = pApi->xGetAuxdata(pFts, 0); if( p==0 ){ int nPhrase; /* Number of phrases in query */ - sqlite3_int64 nRow = 0; /* Number of rows in table */ - sqlite3_int64 nToken = 0; /* Number of tokens in table */ - int nByte; /* Bytes of space to allocate */ + tdsqlite3_int64 nRow = 0; /* Number of rows in table */ + tdsqlite3_int64 nToken = 0; /* Number of tokens in table */ + tdsqlite3_int64 nByte; /* Bytes of space to allocate */ int i; /* Allocate the Fts5Bm25Data object */ nPhrase = pApi->xPhraseCount(pFts); nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double); - p = (Fts5Bm25Data*)sqlite3_malloc(nByte); + p = (Fts5Bm25Data*)tdsqlite3_malloc64(nByte); if( p==0 ){ rc = SQLITE_NOMEM; }else{ - memset(p, 0, nByte); + memset(p, 0, (size_t)nByte); p->nPhrase = nPhrase; p->aIDF = (double*)&p[1]; p->aFreq = &p->aIDF[nPhrase]; @@ -184964,12 +212984,13 @@ static int fts5Bm25GetData( /* Calculate the average document length for this FTS5 table */ if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow); + assert( rc!=SQLITE_OK || nRow>0 ); if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken); if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow; /* Calculate an IDF for each phrase in the query */ for(i=0; rc==SQLITE_OK && i<nPhrase; i++){ - sqlite3_int64 nHit = 0; + tdsqlite3_int64 nHit = 0; rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb); if( rc==SQLITE_OK ){ /* Calculate the IDF (Inverse Document Frequency) for phrase i. @@ -184992,9 +213013,9 @@ static int fts5Bm25GetData( } if( rc!=SQLITE_OK ){ - sqlite3_free(p); + tdsqlite3_free(p); }else{ - rc = pApi->xSetAuxdata(pFts, p, sqlite3_free); + rc = pApi->xSetAuxdata(pFts, p, tdsqlite3_free); } if( rc!=SQLITE_OK ) p = 0; } @@ -185008,9 +213029,9 @@ static int fts5Bm25GetData( static void fts5Bm25Function( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ - sqlite3_context *pCtx, /* Context for returning result/error */ + tdsqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ - sqlite3_value **apVal /* Array of trailing arguments */ + tdsqlite3_value **apVal /* Array of trailing arguments */ ){ const double k1 = 1.2; /* Constant "k1" from BM25 formula */ const double b = 0.75; /* Constant "b" from BM25 formula */ @@ -185034,7 +213055,7 @@ static void fts5Bm25Function( int ip; int ic; int io; rc = pApi->xInst(pFts, i, &ip, &ic, &io); if( rc==SQLITE_OK ){ - double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0; + double w = (nVal > ic) ? tdsqlite3_value_double(apVal[ic]) : 1.0; aFreq[ip] += w; } } @@ -185057,13 +213078,13 @@ static void fts5Bm25Function( /* If no error has occurred, return the calculated score. Otherwise, ** throw an SQL exception. */ if( rc==SQLITE_OK ){ - sqlite3_result_double(pCtx, -1.0 * score); + tdsqlite3_result_double(pCtx, -1.0 * score); }else{ - sqlite3_result_error_code(pCtx, rc); + tdsqlite3_result_error_code(pCtx, rc); } } -static int sqlite3Fts5AuxInit(fts5_api *pApi){ +static int tdsqlite3Fts5AuxInit(fts5_api *pApi){ struct Builtin { const char *zFunc; /* Function name (nul-terminated) */ void *pUserData; /* User-data pointer */ @@ -185089,8 +213110,6 @@ static int sqlite3Fts5AuxInit(fts5_api *pApi){ return rc; } - - /* ** 2014 May 31 ** @@ -185108,19 +213127,19 @@ static int sqlite3Fts5AuxInit(fts5_api *pApi){ /* #include "fts5Int.h" */ -static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){ +static int tdsqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){ if( (u32)pBuf->nSpace<nByte ){ - u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64; + u64 nNew = pBuf->nSpace ? pBuf->nSpace : 64; u8 *pNew; while( nNew<nByte ){ nNew = nNew * 2; } - pNew = sqlite3_realloc(pBuf->p, nNew); + pNew = tdsqlite3_realloc64(pBuf->p, nNew); if( pNew==0 ){ *pRc = SQLITE_NOMEM; return 1; }else{ - pBuf->nSpace = nNew; + pBuf->nSpace = (int)nNew; pBuf->p = pNew; } } @@ -185132,20 +213151,20 @@ static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){ ** Encode value iVal as an SQLite varint and append it to the buffer object ** pBuf. If an OOM error occurs, set the error code in p. */ -static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){ +static void tdsqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){ if( fts5BufferGrow(pRc, pBuf, 9) ) return; - pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal); + pBuf->n += tdsqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal); } -static void sqlite3Fts5Put32(u8 *aBuf, int iVal){ +static void tdsqlite3Fts5Put32(u8 *aBuf, int iVal){ aBuf[0] = (iVal>>24) & 0x00FF; aBuf[1] = (iVal>>16) & 0x00FF; aBuf[2] = (iVal>> 8) & 0x00FF; aBuf[3] = (iVal>> 0) & 0x00FF; } -static int sqlite3Fts5Get32(const u8 *aBuf){ - return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3]; +static int tdsqlite3Fts5Get32(const u8 *aBuf){ + return (int)((((u32)aBuf[0])<<24) + (aBuf[1]<<16) + (aBuf[2]<<8) + aBuf[3]); } /* @@ -185153,16 +213172,18 @@ static int sqlite3Fts5Get32(const u8 *aBuf){ ** the error code in p. If an error has already occurred when this function ** is called, it is a no-op. */ -static void sqlite3Fts5BufferAppendBlob( +static void tdsqlite3Fts5BufferAppendBlob( int *pRc, Fts5Buffer *pBuf, u32 nData, const u8 *pData ){ assert_nc( *pRc || nData>=0 ); - if( fts5BufferGrow(pRc, pBuf, nData) ) return; - memcpy(&pBuf->p[pBuf->n], pData, nData); - pBuf->n += nData; + if( nData ){ + if( fts5BufferGrow(pRc, pBuf, nData) ) return; + memcpy(&pBuf->p[pBuf->n], pData, nData); + pBuf->n += nData; + } } /* @@ -185170,13 +213191,13 @@ static void sqlite3Fts5BufferAppendBlob( ** ensures that the byte following the buffer data is set to 0x00, even ** though this byte is not included in the pBuf->n count. */ -static void sqlite3Fts5BufferAppendString( +static void tdsqlite3Fts5BufferAppendString( int *pRc, Fts5Buffer *pBuf, const char *zStr ){ int nStr = (int)strlen(zStr); - sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr); + tdsqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr); pBuf->n--; } @@ -185184,11 +213205,11 @@ static void sqlite3Fts5BufferAppendString( ** Argument zFmt is a printf() style format string. This function performs ** the printf() style processing, then appends the results to buffer pBuf. ** -** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte +** Like tdsqlite3Fts5BufferAppendString(), this function ensures that the byte ** following the buffer data is set to 0x00, even though this byte is not ** included in the pBuf->n count. */ -static void sqlite3Fts5BufferAppendPrintf( +static void tdsqlite3Fts5BufferAppendPrintf( int *pRc, Fts5Buffer *pBuf, char *zFmt, ... @@ -185197,24 +213218,24 @@ static void sqlite3Fts5BufferAppendPrintf( char *zTmp; va_list ap; va_start(ap, zFmt); - zTmp = sqlite3_vmprintf(zFmt, ap); + zTmp = tdsqlite3_vmprintf(zFmt, ap); va_end(ap); if( zTmp==0 ){ *pRc = SQLITE_NOMEM; }else{ - sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp); - sqlite3_free(zTmp); + tdsqlite3Fts5BufferAppendString(pRc, pBuf, zTmp); + tdsqlite3_free(zTmp); } } } -static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){ +static char *tdsqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){ char *zRet = 0; if( *pRc==SQLITE_OK ){ va_list ap; va_start(ap, zFmt); - zRet = sqlite3_vmprintf(zFmt, ap); + zRet = tdsqlite3_vmprintf(zFmt, ap); va_end(ap); if( zRet==0 ){ *pRc = SQLITE_NOMEM; @@ -185227,8 +213248,8 @@ static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){ /* ** Free any buffer allocated by pBuf. Zero the structure before returning. */ -static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){ - sqlite3_free(pBuf->p); +static void tdsqlite3Fts5BufferFree(Fts5Buffer *pBuf){ + tdsqlite3_free(pBuf->p); memset(pBuf, 0, sizeof(Fts5Buffer)); } @@ -185236,7 +213257,7 @@ static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){ ** Zero the contents of the buffer object. But do not free the associated ** memory allocation. */ -static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){ +static void tdsqlite3Fts5BufferZero(Fts5Buffer *pBuf){ pBuf->n = 0; } @@ -185245,17 +213266,17 @@ static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){ ** the error code in p. If an error has already occurred when this function ** is called, it is a no-op. */ -static void sqlite3Fts5BufferSet( +static void tdsqlite3Fts5BufferSet( int *pRc, Fts5Buffer *pBuf, int nData, const u8 *pData ){ pBuf->n = 0; - sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData); + tdsqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData); } -static int sqlite3Fts5PoslistNext64( +static int tdsqlite3Fts5PoslistNext64( const u8 *a, int n, /* Buffer containing poslist */ int *pi, /* IN/OUT: Offset within a[] */ i64 *piOff /* IN/OUT: Current offset */ @@ -185269,12 +213290,21 @@ static int sqlite3Fts5PoslistNext64( i64 iOff = *piOff; int iVal; fts5FastGetVarint32(a, i, iVal); - if( iVal==1 ){ + if( iVal<=1 ){ + if( iVal==0 ){ + *pi = i; + return 0; + } fts5FastGetVarint32(a, i, iVal); iOff = ((i64)iVal) << 32; fts5FastGetVarint32(a, i, iVal); + if( iVal<2 ){ + /* This is a corrupt record. So stop parsing it here. */ + *piOff = -1; + return 1; + } } - *piOff = iOff + (iVal-2); + *piOff = iOff + ((iVal-2) & 0x7FFFFFFF); *pi = i; return 0; } @@ -185285,21 +213315,21 @@ static int sqlite3Fts5PoslistNext64( ** Advance the iterator object passed as the only argument. Return true ** if the iterator reaches EOF, or false otherwise. */ -static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){ - if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){ +static int tdsqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){ + if( tdsqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){ pIter->bEof = 1; } return pIter->bEof; } -static int sqlite3Fts5PoslistReaderInit( +static int tdsqlite3Fts5PoslistReaderInit( const u8 *a, int n, /* Poslist buffer to iterate through */ Fts5PoslistReader *pIter /* Iterator object to initialize */ ){ memset(pIter, 0, sizeof(*pIter)); pIter->a = a; pIter->n = n; - sqlite3Fts5PoslistReaderNext(pIter); + tdsqlite3Fts5PoslistReaderNext(pIter); return pIter->bEof; } @@ -185309,7 +213339,7 @@ static int sqlite3Fts5PoslistReaderInit( ** The previous position written to this list is *piPrev. *piPrev is set ** to iPos before returning. */ -static void sqlite3Fts5PoslistSafeAppend( +static void tdsqlite3Fts5PoslistSafeAppend( Fts5Buffer *pBuf, i64 *piPrev, i64 iPos @@ -185317,32 +213347,32 @@ static void sqlite3Fts5PoslistSafeAppend( static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32; if( (iPos & colmask) != (*piPrev & colmask) ){ pBuf->p[pBuf->n++] = 1; - pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32)); + pBuf->n += tdsqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32)); *piPrev = (iPos & colmask); } - pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2); + pBuf->n += tdsqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2); *piPrev = iPos; } -static int sqlite3Fts5PoslistWriterAppend( +static int tdsqlite3Fts5PoslistWriterAppend( Fts5Buffer *pBuf, Fts5PoslistWriter *pWriter, i64 iPos ){ int rc = 0; /* Initialized only to suppress erroneous warning from Clang */ if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc; - sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos); + tdsqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos); return SQLITE_OK; } -static void *sqlite3Fts5MallocZero(int *pRc, int nByte){ +static void *tdsqlite3Fts5MallocZero(int *pRc, tdsqlite3_int64 nByte){ void *pRet = 0; if( *pRc==SQLITE_OK ){ - pRet = sqlite3_malloc(nByte); - if( pRet==0 && nByte>0 ){ - *pRc = SQLITE_NOMEM; + pRet = tdsqlite3_malloc64(nByte); + if( pRet==0 ){ + if( nByte>0 ) *pRc = SQLITE_NOMEM; }else{ - memset(pRet, 0, nByte); + memset(pRet, 0, (size_t)nByte); } } return pRet; @@ -185354,15 +213384,15 @@ static void *sqlite3Fts5MallocZero(int *pRc, int nByte){ ** the length of the string is determined using strlen(). ** ** It is the responsibility of the caller to eventually free the returned -** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned. +** buffer using tdsqlite3_free(). If an OOM error occurs, NULL is returned. */ -static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){ +static char *tdsqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){ char *zRet = 0; if( *pRc==SQLITE_OK ){ if( nIn<0 ){ nIn = (int)strlen(pIn); } - zRet = (char*)sqlite3_malloc(nIn+1); + zRet = (char*)tdsqlite3_malloc(nIn+1); if( zRet ){ memcpy(zRet, pIn, nIn); zRet[nIn] = '\0'; @@ -185384,7 +213414,7 @@ static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){ ** * The underscore character "_" (0x5F). ** * The unicode "subsitute" character (0x1A). */ -static int sqlite3Fts5IsBareword(char t){ +static int tdsqlite3Fts5IsBareword(char t){ u8 aBareword[128] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */ @@ -185414,13 +213444,13 @@ struct Fts5Termset { Fts5TermsetEntry *apHash[512]; }; -static int sqlite3Fts5TermsetNew(Fts5Termset **pp){ +static int tdsqlite3Fts5TermsetNew(Fts5Termset **pp){ int rc = SQLITE_OK; - *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset)); + *pp = tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset)); return rc; } -static int sqlite3Fts5TermsetAdd( +static int tdsqlite3Fts5TermsetAdd( Fts5Termset *p, int iIdx, const char *pTerm, int nTerm, @@ -185454,7 +213484,7 @@ static int sqlite3Fts5TermsetAdd( } if( pEntry==0 ){ - pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm); + pEntry = tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm); if( pEntry ){ pEntry->pTerm = (char*)&pEntry[1]; pEntry->nTerm = nTerm; @@ -185469,7 +213499,7 @@ static int sqlite3Fts5TermsetAdd( return rc; } -static void sqlite3Fts5TermsetFree(Fts5Termset *p){ +static void tdsqlite3Fts5TermsetFree(Fts5Termset *p){ if( p ){ u32 i; for(i=0; i<ArraySize(p->apHash); i++){ @@ -185477,10 +213507,10 @@ static void sqlite3Fts5TermsetFree(Fts5Termset *p){ while( pEntry ){ Fts5TermsetEntry *pDel = pEntry; pEntry = pEntry->pNext; - sqlite3_free(pDel); + tdsqlite3_free(pDel); } } - sqlite3_free(p); + tdsqlite3_free(p); } } @@ -185509,7 +213539,7 @@ static void sqlite3Fts5TermsetFree(Fts5Termset *p){ #define FTS5_DEFAULT_HASHSIZE (1024*1024) /* Maximum allowed page size */ -#define FTS5_MAX_PAGE_SIZE (128*1024) +#define FTS5_MAX_PAGE_SIZE (64*1024) static int fts5_iswhitespace(char x){ return (x==' '); @@ -185539,7 +213569,7 @@ static const char *fts5ConfigSkipWhitespace(const char *pIn){ */ static const char *fts5ConfigSkipBareword(const char *pIn){ const char *p = pIn; - while ( sqlite3Fts5IsBareword(*p) ) p++; + while ( tdsqlite3Fts5IsBareword(*p) ) p++; if( p==pIn ) p = 0; return p; } @@ -185554,7 +213584,7 @@ static const char *fts5ConfigSkipLiteral(const char *pIn){ const char *p = pIn; switch( *p ){ case 'n': case 'N': - if( sqlite3_strnicmp("null", p, 4)==0 ){ + if( tdsqlite3_strnicmp("null", p, 4)==0 ){ p = &p[4]; }else{ p = 0; @@ -185636,7 +213666,7 @@ static int fts5Dequote(char *z){ assert( q=='[' || q=='\'' || q=='"' || q=='`' ); if( q=='[' ) q = ']'; - while( ALWAYS(z[iIn]) ){ + while( z[iIn] ){ if( z[iIn]==q ){ if( z[iIn+1]!=q ){ /* Character iIn was the close quote. */ @@ -185671,7 +213701,7 @@ static int fts5Dequote(char *z){ ** [pqr] becomes pqr ** `mno` becomes mno */ -static void sqlite3Fts5Dequote(char *z){ +static void tdsqlite3Fts5Dequote(char *z){ char quote; /* Quote character (if any ) */ assert( 0==fts5_iswhitespace(z[0]) ); @@ -185698,7 +213728,7 @@ static int fts5ConfigSetEnum( int iVal = -1; for(i=0; aEnum[i].zName; i++){ - if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){ + if( tdsqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){ if( iVal>=0 ) return SQLITE_ERROR; iVal = aEnum[i].eVal; } @@ -185715,7 +213745,7 @@ static int fts5ConfigSetEnum( ** If successful, object pConfig is updated and SQLITE_OK returned. If ** an error occurs, an SQLite error code is returned and an error message ** may be left in *pzErr. It is the responsibility of the caller to -** eventually free any such error message using sqlite3_free(). +** eventually free any such error message using tdsqlite3_free(). */ static int fts5ConfigParseSpecial( Fts5Global *pGlobal, @@ -185726,12 +213756,12 @@ static int fts5ConfigParseSpecial( ){ int rc = SQLITE_OK; int nCmd = (int)strlen(zCmd); - if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){ + if( tdsqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){ const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES; const char *p; int bFirst = 1; if( pConfig->aPrefix==0 ){ - pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte); + pConfig->aPrefix = tdsqlite3Fts5MallocZero(&rc, nByte); if( rc ) return rc; } @@ -185747,13 +213777,13 @@ static int fts5ConfigParseSpecial( break; } if( p[0]<'0' || p[0]>'9' ){ - *pzErr = sqlite3_mprintf("malformed prefix=... directive"); + *pzErr = tdsqlite3_mprintf("malformed prefix=... directive"); rc = SQLITE_ERROR; break; } if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){ - *pzErr = sqlite3_mprintf( + *pzErr = tdsqlite3_mprintf( "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES ); rc = SQLITE_ERROR; @@ -185766,7 +213796,7 @@ static int fts5ConfigParseSpecial( } if( nPre<=0 || nPre>=1000 ){ - *pzErr = sqlite3_mprintf("prefix length out of range (max 999)"); + *pzErr = tdsqlite3_mprintf("prefix length out of range (max 999)"); rc = SQLITE_ERROR; break; } @@ -185779,16 +213809,16 @@ static int fts5ConfigParseSpecial( return rc; } - if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){ + if( tdsqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){ const char *p = (const char*)zArg; - int nArg = (int)strlen(zArg) + 1; - char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg); - char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2); + tdsqlite3_int64 nArg = strlen(zArg) + 1; + char **azArg = tdsqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg); + char *pDel = tdsqlite3Fts5MallocZero(&rc, nArg * 2); char *pSpace = pDel; if( azArg && pSpace ){ if( pConfig->pTok ){ - *pzErr = sqlite3_mprintf("multiple tokenize=... directives"); + *pzErr = tdsqlite3_mprintf("multiple tokenize=... directives"); rc = SQLITE_ERROR; }else{ for(nArg=0; p && *p; nArg++){ @@ -185801,36 +213831,36 @@ static int fts5ConfigParseSpecial( if( p ){ memcpy(pSpace, p2, p-p2); azArg[nArg] = pSpace; - sqlite3Fts5Dequote(pSpace); + tdsqlite3Fts5Dequote(pSpace); pSpace += (p - p2) + 1; p = fts5ConfigSkipWhitespace(p); } } if( p==0 ){ - *pzErr = sqlite3_mprintf("parse error in tokenize directive"); + *pzErr = tdsqlite3_mprintf("parse error in tokenize directive"); rc = SQLITE_ERROR; }else{ - rc = sqlite3Fts5GetTokenizer(pGlobal, - (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi, + rc = tdsqlite3Fts5GetTokenizer(pGlobal, + (const char**)azArg, (int)nArg, &pConfig->pTok, &pConfig->pTokApi, pzErr ); } } } - sqlite3_free(azArg); - sqlite3_free(pDel); + tdsqlite3_free(azArg); + tdsqlite3_free(pDel); return rc; } - if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){ + if( tdsqlite3_strnicmp("content", zCmd, nCmd)==0 ){ if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){ - *pzErr = sqlite3_mprintf("multiple content=... directives"); + *pzErr = tdsqlite3_mprintf("multiple content=... directives"); rc = SQLITE_ERROR; }else{ if( zArg[0] ){ pConfig->eContent = FTS5_CONTENT_EXTERNAL; - pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg); + pConfig->zContent = tdsqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg); }else{ pConfig->eContent = FTS5_CONTENT_NONE; } @@ -185838,19 +213868,19 @@ static int fts5ConfigParseSpecial( return rc; } - if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){ + if( tdsqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){ if( pConfig->zContentRowid ){ - *pzErr = sqlite3_mprintf("multiple content_rowid=... directives"); + *pzErr = tdsqlite3_mprintf("multiple content_rowid=... directives"); rc = SQLITE_ERROR; }else{ - pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1); + pConfig->zContentRowid = tdsqlite3Fts5Strndup(&rc, zArg, -1); } return rc; } - if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){ + if( tdsqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){ if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){ - *pzErr = sqlite3_mprintf("malformed columnsize=... directive"); + *pzErr = tdsqlite3_mprintf("malformed columnsize=... directive"); rc = SQLITE_ERROR; }else{ pConfig->bColumnsize = (zArg[0]=='1'); @@ -185858,7 +213888,7 @@ static int fts5ConfigParseSpecial( return rc; } - if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){ + if( tdsqlite3_strnicmp("detail", zCmd, nCmd)==0 ){ const Fts5Enum aDetail[] = { { "none", FTS5_DETAIL_NONE }, { "full", FTS5_DETAIL_FULL }, @@ -185867,12 +213897,12 @@ static int fts5ConfigParseSpecial( }; if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){ - *pzErr = sqlite3_mprintf("malformed detail=... directive"); + *pzErr = tdsqlite3_mprintf("malformed detail=... directive"); } return rc; } - *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd); + *pzErr = tdsqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd); return SQLITE_ERROR; } @@ -185883,7 +213913,7 @@ static int fts5ConfigParseSpecial( */ static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){ assert( pConfig->pTok==0 && pConfig->pTokApi==0 ); - return sqlite3Fts5GetTokenizer( + return tdsqlite3Fts5GetTokenizer( pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0 ); } @@ -185911,8 +213941,8 @@ static const char *fts5ConfigGobbleWord( ){ const char *zRet = 0; - int nIn = (int)strlen(zIn); - char *zOut = sqlite3_malloc(nIn+1); + tdsqlite3_int64 nIn = strlen(zIn); + char *zOut = tdsqlite3_malloc64(nIn+1); assert( *pRc==SQLITE_OK ); *pbQuoted = 0; @@ -185921,7 +213951,7 @@ static const char *fts5ConfigGobbleWord( if( zOut==0 ){ *pRc = SQLITE_NOMEM; }else{ - memcpy(zOut, zIn, nIn+1); + memcpy(zOut, zIn, (size_t)(nIn+1)); if( fts5_isopenquote(zOut[0]) ){ int ii = fts5Dequote(zOut); zRet = &zIn[ii]; @@ -185935,7 +213965,7 @@ static const char *fts5ConfigGobbleWord( } if( zRet==0 ){ - sqlite3_free(zOut); + tdsqlite3_free(zOut); }else{ *pzOut = zOut; } @@ -185950,16 +213980,16 @@ static int fts5ConfigParseColumn( char **pzErr ){ int rc = SQLITE_OK; - if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME) - || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME) + if( 0==tdsqlite3_stricmp(zCol, FTS5_RANK_NAME) + || 0==tdsqlite3_stricmp(zCol, FTS5_ROWID_NAME) ){ - *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol); + *pzErr = tdsqlite3_mprintf("reserved fts5 column name: %s", zCol); rc = SQLITE_ERROR; }else if( zArg ){ - if( 0==sqlite3_stricmp(zArg, "unindexed") ){ + if( 0==tdsqlite3_stricmp(zArg, "unindexed") ){ p->abUnindexed[p->nCol] = 1; }else{ - *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg); + *pzErr = tdsqlite3_mprintf("unrecognized column option: %s", zArg); rc = SQLITE_ERROR; } } @@ -185976,13 +214006,13 @@ static int fts5ConfigMakeExprlist(Fts5Config *p){ int rc = SQLITE_OK; Fts5Buffer buf = {0, 0, 0}; - sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid); + tdsqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid); if( p->eContent!=FTS5_CONTENT_NONE ){ for(i=0; i<p->nCol; i++){ if( p->eContent==FTS5_CONTENT_EXTERNAL ){ - sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]); + tdsqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]); }else{ - sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i); + tdsqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i); } } } @@ -186002,11 +214032,11 @@ static int fts5ConfigMakeExprlist(Fts5Config *p){ ** new Fts5Config object. If an error occurs, an SQLite error code is ** returned, *ppOut is set to NULL and an error message may be left in ** *pzErr. It is the responsibility of the caller to eventually free any -** such error message using sqlite3_free(). +** such error message using tdsqlite3_free(). */ -static int sqlite3Fts5ConfigParse( +static int tdsqlite3Fts5ConfigParse( Fts5Global *pGlobal, - sqlite3 *db, + tdsqlite3 *db, int nArg, /* Number of arguments */ const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */ Fts5Config **ppOut, /* OUT: Results of parse */ @@ -186015,26 +214045,26 @@ static int sqlite3Fts5ConfigParse( int rc = SQLITE_OK; /* Return code */ Fts5Config *pRet; /* New object to return */ int i; - int nByte; + tdsqlite3_int64 nByte; - *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config)); + *ppOut = pRet = (Fts5Config*)tdsqlite3_malloc(sizeof(Fts5Config)); if( pRet==0 ) return SQLITE_NOMEM; memset(pRet, 0, sizeof(Fts5Config)); pRet->db = db; pRet->iCookie = -1; nByte = nArg * (sizeof(char*) + sizeof(u8)); - pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte); + pRet->azCol = (char**)tdsqlite3Fts5MallocZero(&rc, nByte); pRet->abUnindexed = (u8*)&pRet->azCol[nArg]; - pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1); - pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1); + pRet->zDb = tdsqlite3Fts5Strndup(&rc, azArg[1], -1); + pRet->zName = tdsqlite3Fts5Strndup(&rc, azArg[2], -1); pRet->bColumnsize = 1; pRet->eDetail = FTS5_DETAIL_FULL; #ifdef SQLITE_DEBUG pRet->bPrefixIndex = 1; #endif - if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){ - *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName); + if( rc==SQLITE_OK && tdsqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){ + *pzErr = tdsqlite3_mprintf("reserved fts5 table name: %s", pRet->zName); rc = SQLITE_ERROR; } @@ -186062,7 +214092,7 @@ static int sqlite3Fts5ConfigParse( if( rc==SQLITE_OK ){ if( z==0 ){ - *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig); + *pzErr = tdsqlite3_mprintf("parse error in \"%s\"", zOrig); rc = SQLITE_ERROR; }else{ if( bOption ){ @@ -186074,8 +214104,8 @@ static int sqlite3Fts5ConfigParse( } } - sqlite3_free(zOne); - sqlite3_free(zTwo); + tdsqlite3_free(zOne); + tdsqlite3_free(zTwo); } /* If a tokenizer= option was successfully parsed, the tokenizer has @@ -186098,14 +214128,14 @@ static int sqlite3Fts5ConfigParse( } if( zTail ){ - pRet->zContent = sqlite3Fts5Mprintf( + pRet->zContent = tdsqlite3Fts5Mprintf( &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail ); } } if( rc==SQLITE_OK && pRet->zContentRowid==0 ){ - pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1); + pRet->zContentRowid = tdsqlite3Fts5Strndup(&rc, "rowid", -1); } /* Formulate the zContentExprlist text */ @@ -186114,7 +214144,7 @@ static int sqlite3Fts5ConfigParse( } if( rc!=SQLITE_OK ){ - sqlite3Fts5ConfigFree(pRet); + tdsqlite3Fts5ConfigFree(pRet); *ppOut = 0; } return rc; @@ -186123,53 +214153,53 @@ static int sqlite3Fts5ConfigParse( /* ** Free the configuration object passed as the only argument. */ -static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){ +static void tdsqlite3Fts5ConfigFree(Fts5Config *pConfig){ if( pConfig ){ int i; if( pConfig->pTok ){ pConfig->pTokApi->xDelete(pConfig->pTok); } - sqlite3_free(pConfig->zDb); - sqlite3_free(pConfig->zName); + tdsqlite3_free(pConfig->zDb); + tdsqlite3_free(pConfig->zName); for(i=0; i<pConfig->nCol; i++){ - sqlite3_free(pConfig->azCol[i]); + tdsqlite3_free(pConfig->azCol[i]); } - sqlite3_free(pConfig->azCol); - sqlite3_free(pConfig->aPrefix); - sqlite3_free(pConfig->zRank); - sqlite3_free(pConfig->zRankArgs); - sqlite3_free(pConfig->zContent); - sqlite3_free(pConfig->zContentRowid); - sqlite3_free(pConfig->zContentExprlist); - sqlite3_free(pConfig); + tdsqlite3_free(pConfig->azCol); + tdsqlite3_free(pConfig->aPrefix); + tdsqlite3_free(pConfig->zRank); + tdsqlite3_free(pConfig->zRankArgs); + tdsqlite3_free(pConfig->zContent); + tdsqlite3_free(pConfig->zContentRowid); + tdsqlite3_free(pConfig->zContentExprlist); + tdsqlite3_free(pConfig); } } /* -** Call sqlite3_declare_vtab() based on the contents of the configuration +** Call tdsqlite3_declare_vtab() based on the contents of the configuration ** object passed as the only argument. Return SQLITE_OK if successful, or ** an SQLite error code if an error occurs. */ -static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){ +static int tdsqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){ int i; int rc = SQLITE_OK; char *zSql; - zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x("); + zSql = tdsqlite3Fts5Mprintf(&rc, "CREATE TABLE x("); for(i=0; zSql && i<pConfig->nCol; i++){ const char *zSep = (i==0?"":", "); - zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]); + zSql = tdsqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]); } - zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)", + zSql = tdsqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)", zSql, pConfig->zName, FTS5_RANK_NAME ); assert( zSql || rc==SQLITE_NOMEM ); if( zSql ){ - rc = sqlite3_declare_vtab(pConfig->db, zSql); - sqlite3_free(zSql); + rc = tdsqlite3_declare_vtab(pConfig->db, zSql); + tdsqlite3_free(zSql); } - + return rc; } @@ -186179,7 +214209,7 @@ static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){ ** The callback is invoked once for each token in the input text. The ** arguments passed to it are, in order: ** -** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize() +** void *pCtx // Copy of 4th argument to tdsqlite3Fts5Tokenize() ** const char *pToken // Pointer to buffer containing token ** int nToken // Size of token in bytes ** int iStart // Byte offset of start of token within input text @@ -186196,7 +214226,7 @@ static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){ ** because the callback returned another non-zero value, it is assumed ** to be an SQLite error code and returned to the caller. */ -static int sqlite3Fts5Tokenize( +static int tdsqlite3Fts5Tokenize( Fts5Config *pConfig, /* FTS5 Configuration object */ int flags, /* FTS5_TOKENIZE_* flags */ const char *pText, int nText, /* Text to tokenize */ @@ -186242,7 +214272,7 @@ static const char *fts5ConfigSkipArgs(const char *pIn){ ** + Zero or more SQL literals in a comma separated list ** + Close parenthesis - ")" */ -static int sqlite3Fts5ConfigParseRank( +static int tdsqlite3Fts5ConfigParseRank( const char *zIn, /* Input string */ char **pzRank, /* OUT: Rank function name */ char **pzRankArgs /* OUT: Rank function arguments */ @@ -186264,7 +214294,7 @@ static int sqlite3Fts5ConfigParseRank( p = fts5ConfigSkipBareword(p); if( p ){ - zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank); + zRank = tdsqlite3Fts5MallocZero(&rc, 1 + p - pRank); if( zRank ) memcpy(zRank, pRank, p-pRank); }else{ rc = SQLITE_ERROR; @@ -186284,7 +214314,7 @@ static int sqlite3Fts5ConfigParseRank( if( p==0 ){ rc = SQLITE_ERROR; }else{ - zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs); + zRankArgs = tdsqlite3Fts5MallocZero(&rc, 1 + p - pArgs); if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs); } } @@ -186292,7 +214322,7 @@ static int sqlite3Fts5ConfigParseRank( } if( rc!=SQLITE_OK ){ - sqlite3_free(zRank); + tdsqlite3_free(zRank); assert( zRankArgs==0 ); }else{ *pzRank = zRank; @@ -186301,30 +214331,30 @@ static int sqlite3Fts5ConfigParseRank( return rc; } -static int sqlite3Fts5ConfigSetValue( +static int tdsqlite3Fts5ConfigSetValue( Fts5Config *pConfig, const char *zKey, - sqlite3_value *pVal, + tdsqlite3_value *pVal, int *pbBadkey ){ int rc = SQLITE_OK; - if( 0==sqlite3_stricmp(zKey, "pgsz") ){ + if( 0==tdsqlite3_stricmp(zKey, "pgsz") ){ int pgsz = 0; - if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ - pgsz = sqlite3_value_int(pVal); + if( SQLITE_INTEGER==tdsqlite3_value_numeric_type(pVal) ){ + pgsz = tdsqlite3_value_int(pVal); } - if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){ + if( pgsz<32 || pgsz>FTS5_MAX_PAGE_SIZE ){ *pbBadkey = 1; }else{ pConfig->pgsz = pgsz; } } - else if( 0==sqlite3_stricmp(zKey, "hashsize") ){ + else if( 0==tdsqlite3_stricmp(zKey, "hashsize") ){ int nHashSize = -1; - if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ - nHashSize = sqlite3_value_int(pVal); + if( SQLITE_INTEGER==tdsqlite3_value_numeric_type(pVal) ){ + nHashSize = tdsqlite3_value_int(pVal); } if( nHashSize<=0 ){ *pbBadkey = 1; @@ -186333,10 +214363,10 @@ static int sqlite3Fts5ConfigSetValue( } } - else if( 0==sqlite3_stricmp(zKey, "automerge") ){ + else if( 0==tdsqlite3_stricmp(zKey, "automerge") ){ int nAutomerge = -1; - if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ - nAutomerge = sqlite3_value_int(pVal); + if( SQLITE_INTEGER==tdsqlite3_value_numeric_type(pVal) ){ + nAutomerge = tdsqlite3_value_int(pVal); } if( nAutomerge<0 || nAutomerge>64 ){ *pbBadkey = 1; @@ -186346,10 +214376,10 @@ static int sqlite3Fts5ConfigSetValue( } } - else if( 0==sqlite3_stricmp(zKey, "usermerge") ){ + else if( 0==tdsqlite3_stricmp(zKey, "usermerge") ){ int nUsermerge = -1; - if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ - nUsermerge = sqlite3_value_int(pVal); + if( SQLITE_INTEGER==tdsqlite3_value_numeric_type(pVal) ){ + nUsermerge = tdsqlite3_value_int(pVal); } if( nUsermerge<2 || nUsermerge>16 ){ *pbBadkey = 1; @@ -186358,27 +214388,28 @@ static int sqlite3Fts5ConfigSetValue( } } - else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){ + else if( 0==tdsqlite3_stricmp(zKey, "crisismerge") ){ int nCrisisMerge = -1; - if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ - nCrisisMerge = sqlite3_value_int(pVal); + if( SQLITE_INTEGER==tdsqlite3_value_numeric_type(pVal) ){ + nCrisisMerge = tdsqlite3_value_int(pVal); } if( nCrisisMerge<0 ){ *pbBadkey = 1; }else{ if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE; + if( nCrisisMerge>=FTS5_MAX_SEGMENT ) nCrisisMerge = FTS5_MAX_SEGMENT-1; pConfig->nCrisisMerge = nCrisisMerge; } } - else if( 0==sqlite3_stricmp(zKey, "rank") ){ - const char *zIn = (const char*)sqlite3_value_text(pVal); + else if( 0==tdsqlite3_stricmp(zKey, "rank") ){ + const char *zIn = (const char*)tdsqlite3_value_text(pVal); char *zRank; char *zRankArgs; - rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs); + rc = tdsqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs); if( rc==SQLITE_OK ){ - sqlite3_free(pConfig->zRank); - sqlite3_free(pConfig->zRankArgs); + tdsqlite3_free(pConfig->zRank); + tdsqlite3_free(pConfig->zRankArgs); pConfig->zRank = zRank; pConfig->zRankArgs = zRankArgs; }else if( rc==SQLITE_ERROR ){ @@ -186394,10 +214425,10 @@ static int sqlite3Fts5ConfigSetValue( /* ** Load the contents of the %_config table into memory. */ -static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){ +static int tdsqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){ const char *zSelect = "SELECT k, v FROM %Q.'%q_config'"; char *zSql; - sqlite3_stmt *p = 0; + tdsqlite3_stmt *p = 0; int rc = SQLITE_OK; int iVersion = 0; @@ -186408,32 +214439,32 @@ static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){ pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE; pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE; - zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName); + zSql = tdsqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName); if( zSql ){ - rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0); - sqlite3_free(zSql); + rc = tdsqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0); + tdsqlite3_free(zSql); } assert( rc==SQLITE_OK || p==0 ); if( rc==SQLITE_OK ){ - while( SQLITE_ROW==sqlite3_step(p) ){ - const char *zK = (const char*)sqlite3_column_text(p, 0); - sqlite3_value *pVal = sqlite3_column_value(p, 1); - if( 0==sqlite3_stricmp(zK, "version") ){ - iVersion = sqlite3_value_int(pVal); + while( SQLITE_ROW==tdsqlite3_step(p) ){ + const char *zK = (const char*)tdsqlite3_column_text(p, 0); + tdsqlite3_value *pVal = tdsqlite3_column_value(p, 1); + if( 0==tdsqlite3_stricmp(zK, "version") ){ + iVersion = tdsqlite3_value_int(pVal); }else{ int bDummy = 0; - sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy); + tdsqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy); } } - rc = sqlite3_finalize(p); + rc = tdsqlite3_finalize(p); } if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){ rc = SQLITE_ERROR; if( pConfig->pzErrmsg ){ assert( 0==*pConfig->pzErrmsg ); - *pConfig->pzErrmsg = sqlite3_mprintf( + *pConfig->pzErrmsg = tdsqlite3_mprintf( "invalid fts5 file format (found %d, expected %d) - run 'rebuild'", iVersion, FTS5_CURRENT_VERSION ); @@ -186477,13 +214508,14 @@ typedef struct Fts5ExprTerm Fts5ExprTerm; /* ** Functions generated by lemon from fts5parse.y. */ -static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64)); -static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*)); -static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*); +static void *tdsqlite3Fts5ParserAlloc(void *(*mallocProc)(u64)); +static void tdsqlite3Fts5ParserFree(void*, void (*freeProc)(void*)); +static void tdsqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*); #ifndef NDEBUG /* #include <stdio.h> */ -static void sqlite3Fts5ParserTrace(FILE*, char*); +static void tdsqlite3Fts5ParserTrace(FILE*, char*); #endif +static int tdsqlite3Fts5ParserFallback(int); struct Fts5Expr { @@ -186535,7 +214567,8 @@ struct Fts5ExprNode { ** or term prefix. */ struct Fts5ExprTerm { - int bPrefix; /* True for a prefix term */ + u8 bPrefix; /* True for a prefix term */ + u8 bFirst; /* True if token must be first in column */ char *zTerm; /* nul-terminated term */ Fts5IndexIter *pIter; /* Iterator for this term */ Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */ @@ -186576,11 +214609,11 @@ struct Fts5Parse { Fts5ExprNode *pExpr; /* Result of a successful parse */ }; -static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){ +static void tdsqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); if( pParse->rc==SQLITE_OK ){ - pParse->zErr = sqlite3_vmprintf(zFmt, ap); + pParse->zErr = tdsqlite3_vmprintf(zFmt, ap); pParse->rc = SQLITE_ERROR; } va_end(ap); @@ -186616,6 +214649,7 @@ static int fts5ExprGetToken( case '+': tok = FTS5_PLUS; break; case '*': tok = FTS5_STAR; break; case '-': tok = FTS5_MINUS; break; + case '^': tok = FTS5_CARET; break; case '\0': tok = FTS5_EOF; break; case '"': { @@ -186628,7 +214662,7 @@ static int fts5ExprGetToken( if( z2[0]!='"' ) break; } if( z2[0]=='\0' ){ - sqlite3Fts5ParseError(pParse, "unterminated string"); + tdsqlite3Fts5ParseError(pParse, "unterminated string"); return FTS5_EOF; } } @@ -186638,12 +214672,12 @@ static int fts5ExprGetToken( default: { const char *z2; - if( sqlite3Fts5IsBareword(z[0])==0 ){ - sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z); + if( tdsqlite3Fts5IsBareword(z[0])==0 ){ + tdsqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z); return FTS5_EOF; } tok = FTS5_STRING; - for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++); + for(z2=&z[1]; tdsqlite3Fts5IsBareword(*z2); z2++); pToken->n = (z2 - z); if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR; if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT; @@ -186656,11 +214690,12 @@ static int fts5ExprGetToken( return tok; } -static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); } -static void fts5ParseFree(void *p){ sqlite3_free(p); } +static void *fts5ParseAlloc(u64 t){ return tdsqlite3_malloc64((tdsqlite3_int64)t);} +static void fts5ParseFree(void *p){ tdsqlite3_free(p); } -static int sqlite3Fts5ExprNew( +static int tdsqlite3Fts5ExprNew( Fts5Config *pConfig, /* FTS5 Configuration */ + int iCol, const char *zExpr, /* Expression text */ Fts5Expr **ppNew, char **pzErr @@ -186675,26 +214710,38 @@ static int sqlite3Fts5ExprNew( *ppNew = 0; *pzErr = 0; memset(&sParse, 0, sizeof(sParse)); - pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc); + pEngine = tdsqlite3Fts5ParserAlloc(fts5ParseAlloc); if( pEngine==0 ){ return SQLITE_NOMEM; } sParse.pConfig = pConfig; do { t = fts5ExprGetToken(&sParse, &z, &token); - sqlite3Fts5Parser(pEngine, t, token, &sParse); + tdsqlite3Fts5Parser(pEngine, t, token, &sParse); }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF ); - sqlite3Fts5ParserFree(pEngine, fts5ParseFree); + tdsqlite3Fts5ParserFree(pEngine, fts5ParseFree); + + /* If the LHS of the MATCH expression was a user column, apply the + ** implicit column-filter. */ + if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){ + int n = sizeof(Fts5Colset); + Fts5Colset *pColset = (Fts5Colset*)tdsqlite3Fts5MallocZero(&sParse.rc, n); + if( pColset ){ + pColset->nCol = 1; + pColset->aiCol[0] = iCol; + tdsqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset); + } + } assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 ); if( sParse.rc==SQLITE_OK ){ - *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr)); + *ppNew = pNew = tdsqlite3_malloc(sizeof(Fts5Expr)); if( pNew==0 ){ sParse.rc = SQLITE_NOMEM; - sqlite3Fts5ParseNodeFree(sParse.pExpr); + tdsqlite3Fts5ParseNodeFree(sParse.pExpr); }else{ if( !sParse.pExpr ){ const int nByte = sizeof(Fts5ExprNode); - pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte); + pNew->pRoot = (Fts5ExprNode*)tdsqlite3Fts5MallocZero(&sParse.rc, nByte); if( pNew->pRoot ){ pNew->pRoot->bEof = 1; } @@ -186708,10 +214755,10 @@ static int sqlite3Fts5ExprNew( sParse.apPhrase = 0; } }else{ - sqlite3Fts5ParseNodeFree(sParse.pExpr); + tdsqlite3Fts5ParseNodeFree(sParse.pExpr); } - sqlite3_free(sParse.apPhrase); + tdsqlite3_free(sParse.apPhrase); *pzErr = sParse.zErr; return sParse.rc; } @@ -186719,26 +214766,62 @@ static int sqlite3Fts5ExprNew( /* ** Free the expression node object passed as the only argument. */ -static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){ +static void tdsqlite3Fts5ParseNodeFree(Fts5ExprNode *p){ if( p ){ int i; for(i=0; i<p->nChild; i++){ - sqlite3Fts5ParseNodeFree(p->apChild[i]); + tdsqlite3Fts5ParseNodeFree(p->apChild[i]); } - sqlite3Fts5ParseNearsetFree(p->pNear); - sqlite3_free(p); + tdsqlite3Fts5ParseNearsetFree(p->pNear); + tdsqlite3_free(p); } } /* ** Free the expression object passed as the only argument. */ -static void sqlite3Fts5ExprFree(Fts5Expr *p){ +static void tdsqlite3Fts5ExprFree(Fts5Expr *p){ if( p ){ - sqlite3Fts5ParseNodeFree(p->pRoot); - sqlite3_free(p->apExprPhrase); - sqlite3_free(p); + tdsqlite3Fts5ParseNodeFree(p->pRoot); + tdsqlite3_free(p->apExprPhrase); + tdsqlite3_free(p); + } +} + +static int tdsqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2){ + Fts5Parse sParse; + memset(&sParse, 0, sizeof(sParse)); + + if( *pp1 ){ + Fts5Expr *p1 = *pp1; + int nPhrase = p1->nPhrase + p2->nPhrase; + + p1->pRoot = tdsqlite3Fts5ParseNode(&sParse, FTS5_AND, p1->pRoot, p2->pRoot,0); + p2->pRoot = 0; + + if( sParse.rc==SQLITE_OK ){ + Fts5ExprPhrase **ap = (Fts5ExprPhrase**)tdsqlite3_realloc( + p1->apExprPhrase, nPhrase * sizeof(Fts5ExprPhrase*) + ); + if( ap==0 ){ + sParse.rc = SQLITE_NOMEM; + }else{ + int i; + memmove(&ap[p2->nPhrase], ap, p1->nPhrase*sizeof(Fts5ExprPhrase*)); + for(i=0; i<p2->nPhrase; i++){ + ap[i] = p2->apExprPhrase[i]; + } + p1->nPhrase = nPhrase; + p1->apExprPhrase = ap; + } + } + tdsqlite3_free(p2->apExprPhrase); + tdsqlite3_free(p2); + }else{ + *pp1 = p2; } + + return sParse.rc; } /* @@ -186753,7 +214836,7 @@ static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){ assert( pTerm->pSynonym ); assert( bDesc==0 || bDesc==1 ); for(p=pTerm; p; p=p->pSynonym){ - if( 0==sqlite3Fts5IterEof(p->pIter) ){ + if( 0==tdsqlite3Fts5IterEof(p->pIter) ){ i64 iRowid = p->pIter->iRowid; if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){ iRet = iRowid; @@ -186785,21 +214868,21 @@ static int fts5ExprSynonymList( assert( pTerm->pSynonym ); for(p=pTerm; p; p=p->pSynonym){ Fts5IndexIter *pIter = p->pIter; - if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){ + if( tdsqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){ if( pIter->nData==0 ) continue; if( nIter==nAlloc ){ - int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2; - Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte); + tdsqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nAlloc * 2; + Fts5PoslistReader *aNew = (Fts5PoslistReader*)tdsqlite3_malloc64(nByte); if( aNew==0 ){ rc = SQLITE_NOMEM; goto synonym_poslist_out; } memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter); nAlloc = nAlloc*2; - if( aIter!=aStatic ) sqlite3_free(aIter); + if( aIter!=aStatic ) tdsqlite3_free(aIter); aIter = aNew; } - sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]); + tdsqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]); assert( aIter[nIter].bEof==0 ); nIter++; } @@ -186818,7 +214901,7 @@ static int fts5ExprSynonymList( for(i=0; i<nIter; i++){ if( aIter[i].bEof==0 ){ if( aIter[i].iPos==iPrev ){ - if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue; + if( tdsqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue; } if( aIter[i].iPos<iMin ){ iMin = aIter[i].iPos; @@ -186826,7 +214909,7 @@ static int fts5ExprSynonymList( } } if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break; - rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin); + rc = tdsqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin); iPrev = iMin; } if( rc==SQLITE_OK ){ @@ -186836,7 +214919,7 @@ static int fts5ExprSynonymList( } synonym_poslist_out: - if( aIter!=aStatic ) sqlite3_free(aIter); + if( aIter!=aStatic ) tdsqlite3_free(aIter); return rc; } @@ -186862,14 +214945,15 @@ static int fts5ExprPhraseIsMatch( Fts5PoslistReader *aIter = aStatic; int i; int rc = SQLITE_OK; + int bFirst = pPhrase->aTerm[0].bFirst; fts5BufferZero(&pPhrase->poslist); /* If the aStatic[] array is not large enough, allocate a large array - ** using sqlite3_malloc(). This approach could be improved upon. */ + ** using tdsqlite3_malloc(). This approach could be improved upon. */ if( pPhrase->nTerm>ArraySize(aStatic) ){ - int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm; - aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte); + tdsqlite3_int64 nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm; + aIter = (Fts5PoslistReader*)tdsqlite3_malloc64(nByte); if( !aIter ) return SQLITE_NOMEM; } memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm); @@ -186884,7 +214968,7 @@ static int fts5ExprPhraseIsMatch( Fts5Buffer buf = {0, 0, 0}; rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n); if( rc ){ - sqlite3_free(a); + tdsqlite3_free(a); goto ismatch_out; } if( a==buf.p ) bFlag = 1; @@ -186892,7 +214976,7 @@ static int fts5ExprPhraseIsMatch( a = (u8*)pTerm->pIter->pData; n = pTerm->pIter->nData; } - sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]); + tdsqlite3Fts5PoslistReaderInit(a, n, &aIter[i]); aIter[i].bFlag = (u8)bFlag; if( aIter[i].bEof ) goto ismatch_out; } @@ -186908,7 +214992,7 @@ static int fts5ExprPhraseIsMatch( if( pPos->iPos!=iAdj ){ bMatch = 0; while( pPos->iPos<iAdj ){ - if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out; + if( tdsqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out; } if( pPos->iPos>iAdj ) iPos = pPos->iPos-i; } @@ -186916,20 +215000,22 @@ static int fts5ExprPhraseIsMatch( }while( bMatch==0 ); /* Append position iPos to the output */ - rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos); - if( rc!=SQLITE_OK ) goto ismatch_out; + if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){ + rc = tdsqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos); + if( rc!=SQLITE_OK ) goto ismatch_out; + } for(i=0; i<pPhrase->nTerm; i++){ - if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out; + if( tdsqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out; } } ismatch_out: *pbMatch = (pPhrase->poslist.n>0); for(i=0; i<pPhrase->nTerm; i++){ - if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a); + if( aIter[i].bFlag ) tdsqlite3_free((u8*)aIter[i].a); } - if( aIter!=aStatic ) sqlite3_free(aIter); + if( aIter!=aStatic ) tdsqlite3_free(aIter); return rc; } @@ -186946,7 +215032,7 @@ struct Fts5LookaheadReader { static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){ p->iPos = p->iLookahead; - if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){ + if( tdsqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){ p->iLookahead = FTS5_LOOKAHEAD_EOF; } return (p->iPos==FTS5_LOOKAHEAD_EOF); @@ -186999,10 +215085,10 @@ static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){ assert( pNear->nPhrase>1 ); /* If the aStatic[] array is not large enough, allocate a large array - ** using sqlite3_malloc(). This approach could be improved upon. */ + ** using tdsqlite3_malloc(). This approach could be improved upon. */ if( pNear->nPhrase>ArraySize(aStatic) ){ - int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase; - a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte); + tdsqlite3_int64 nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase; + a = (Fts5NearTrimmer*)tdsqlite3Fts5MallocZero(&rc, nByte); }else{ memset(aStatic, 0, sizeof(aStatic)); } @@ -187054,7 +215140,7 @@ static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){ i64 iPos = a[i].reader.iPos; Fts5PoslistWriter *pWriter = &a[i].writer; if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){ - sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos); + tdsqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos); } } @@ -187072,7 +215158,7 @@ static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){ ismatch_out: { int bRet = a[0].pOut->n>0; *pRc = rc; - if( a!=aStatic ) sqlite3_free(a); + if( a!=aStatic ) tdsqlite3_free(a); return bRet; } } @@ -187098,8 +215184,8 @@ static int fts5ExprAdvanceto( iRowid = pIter->iRowid; if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){ - int rc = sqlite3Fts5IterNextFrom(pIter, iLast); - if( rc || sqlite3Fts5IterEof(pIter) ){ + int rc = tdsqlite3Fts5IterNextFrom(pIter, iLast); + if( rc || tdsqlite3Fts5IterEof(pIter) ){ *pRc = rc; *pbEof = 1; return 1; @@ -187124,10 +215210,10 @@ static int fts5ExprSynonymAdvanceto( int bEof = 0; for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){ - if( sqlite3Fts5IterEof(p->pIter)==0 ){ + if( tdsqlite3Fts5IterEof(p->pIter)==0 ){ i64 iRowid = p->pIter->iRowid; if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){ - rc = sqlite3Fts5IterNextFrom(p->pIter, iLast); + rc = tdsqlite3Fts5IterNextFrom(p->pIter, iLast); } } } @@ -187156,7 +215242,7 @@ static int fts5ExprNearTest( pPhrase->poslist.n = 0; for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){ Fts5IndexIter *pIter = pTerm->pIter; - if( sqlite3Fts5IterEof(pIter)==0 ){ + if( tdsqlite3Fts5IterEof(pIter)==0 ){ if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){ pPhrase->poslist.n = 1; } @@ -187171,7 +215257,9 @@ static int fts5ExprNearTest( ** phrase is not a match, break out of the loop early. */ for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i]; - if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){ + if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym + || pNear->pColset || pPhrase->aTerm[0].bFirst + ){ int bMatch = 0; rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch); if( bMatch==0 ) break; @@ -187194,48 +215282,61 @@ static int fts5ExprNearTest( ** Initialize all term iterators in the pNear object. If any term is found ** to match no documents at all, return immediately without initializing any ** further iterators. +** +** If an error occurs, return an SQLite error code. Otherwise, return +** SQLITE_OK. It is not considered an error if some term matches zero +** documents. */ static int fts5ExprNearInitAll( Fts5Expr *pExpr, Fts5ExprNode *pNode ){ Fts5ExprNearset *pNear = pNode->pNear; - int i, j; - int rc = SQLITE_OK; - int bEof = 1; + int i; assert( pNode->bNomatch==0 ); - for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){ + for(i=0; i<pNear->nPhrase; i++){ Fts5ExprPhrase *pPhrase = pNear->apPhrase[i]; - for(j=0; j<pPhrase->nTerm; j++){ - Fts5ExprTerm *pTerm = &pPhrase->aTerm[j]; - Fts5ExprTerm *p; + if( pPhrase->nTerm==0 ){ + pNode->bEof = 1; + return SQLITE_OK; + }else{ + int j; + for(j=0; j<pPhrase->nTerm; j++){ + Fts5ExprTerm *pTerm = &pPhrase->aTerm[j]; + Fts5ExprTerm *p; + int bHit = 0; + + for(p=pTerm; p; p=p->pSynonym){ + int rc; + if( p->pIter ){ + tdsqlite3Fts5IterClose(p->pIter); + p->pIter = 0; + } + rc = tdsqlite3Fts5IndexQuery( + pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm), + (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) | + (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0), + pNear->pColset, + &p->pIter + ); + assert( (rc==SQLITE_OK)==(p->pIter!=0) ); + if( rc!=SQLITE_OK ) return rc; + if( 0==tdsqlite3Fts5IterEof(p->pIter) ){ + bHit = 1; + } + } - for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){ - if( p->pIter ){ - sqlite3Fts5IterClose(p->pIter); - p->pIter = 0; - } - rc = sqlite3Fts5IndexQuery( - pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm), - (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) | - (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0), - pNear->pColset, - &p->pIter - ); - assert( rc==SQLITE_OK || p->pIter==0 ); - if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){ - bEof = 0; + if( bHit==0 ){ + pNode->bEof = 1; + return SQLITE_OK; } } - - if( bEof ) break; } - if( bEof ) break; } - pNode->bEof = bEof; - return rc; + pNode->bEof = 0; + return SQLITE_OK; } /* @@ -187339,6 +215440,7 @@ static int fts5ExprNodeTest_STRING( assert( pNear->nPhrase>1 || pNear->apPhrase[0]->nTerm>1 || pNear->apPhrase[0]->aTerm[0].pSynonym + || pNear->apPhrase[0]->aTerm[0].bFirst ); /* Initialize iLast, the "lastest" rowid any iterator points to. If the @@ -187412,18 +215514,18 @@ static int fts5ExprNodeNext_STRING( /* Advance each iterator that currently points to iRowid. Or, if iFrom ** is valid - each iterator that points to a rowid before iFrom. */ for(p=pTerm; p; p=p->pSynonym){ - if( sqlite3Fts5IterEof(p->pIter)==0 ){ + if( tdsqlite3Fts5IterEof(p->pIter)==0 ){ i64 ii = p->pIter->iRowid; if( ii==iRowid || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc) ){ if( bFromValid ){ - rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom); + rc = tdsqlite3Fts5IterNextFrom(p->pIter, iFrom); }else{ - rc = sqlite3Fts5IterNext(p->pIter); + rc = tdsqlite3Fts5IterNext(p->pIter); } if( rc!=SQLITE_OK ) break; - if( sqlite3Fts5IterEof(p->pIter)==0 ){ + if( tdsqlite3Fts5IterEof(p->pIter)==0 ){ bEof = 0; } }else{ @@ -187440,12 +215542,12 @@ static int fts5ExprNodeNext_STRING( assert( Fts5NodeIsString(pNode) ); if( bFromValid ){ - rc = sqlite3Fts5IterNextFrom(pIter, iFrom); + rc = tdsqlite3Fts5IterNextFrom(pIter, iFrom); }else{ - rc = sqlite3Fts5IterNext(pIter); + rc = tdsqlite3Fts5IterNext(pIter); } - pNode->bEof = (rc || sqlite3Fts5IterEof(pIter)); + pNode->bEof = (rc || tdsqlite3Fts5IterEof(pIter)); } if( pNode->bEof==0 ){ @@ -187496,11 +215598,11 @@ static int fts5ExprNodeNext_TERM( assert( pNode->bEof==0 ); if( bFromValid ){ - rc = sqlite3Fts5IterNextFrom(pIter, iFrom); + rc = tdsqlite3Fts5IterNextFrom(pIter, iFrom); }else{ - rc = sqlite3Fts5IterNext(pIter); + rc = tdsqlite3Fts5IterNext(pIter); } - if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){ + if( rc==SQLITE_OK && tdsqlite3Fts5IterEof(pIter)==0 ){ rc = fts5ExprNodeTest_TERM(pExpr, pNode); }else{ pNode->bEof = 1; @@ -187545,7 +215647,10 @@ static int fts5ExprNodeNext_OR( || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0) ){ int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom); - if( rc!=SQLITE_OK ) return rc; + if( rc!=SQLITE_OK ){ + pNode->bNomatch = 0; + return rc; + } } } } @@ -187576,7 +215681,10 @@ static int fts5ExprNodeTest_AND( if( cmp>0 ){ /* Advance pChild until it points to iLast or laster */ rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast); - if( rc!=SQLITE_OK ) return rc; + if( rc!=SQLITE_OK ){ + pAnd->bNomatch = 0; + return rc; + } } /* If the child node is now at EOF, so is the parent AND node. Otherwise, @@ -187615,6 +215723,8 @@ static int fts5ExprNodeNext_AND( int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom); if( rc==SQLITE_OK ){ rc = fts5ExprNodeTest_AND(pExpr, pNode); + }else{ + pNode->bNomatch = 0; } return rc; } @@ -187657,6 +215767,9 @@ static int fts5ExprNodeNext_NOT( if( rc==SQLITE_OK ){ rc = fts5ExprNodeTest_NOT(pExpr, pNode); } + if( rc!=SQLITE_OK ){ + pNode->bNomatch = 0; + } return rc; } @@ -187769,7 +215882,7 @@ static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){ ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It ** is not considered an error if the query does not match any documents. */ -static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){ +static int tdsqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){ Fts5ExprNode *pRoot = p->pRoot; int rc; /* Return code */ @@ -187779,7 +215892,10 @@ static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bD /* If not at EOF but the current rowid occurs earlier than iFirst in ** the iteration order, move to document iFirst or later. */ - if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){ + if( rc==SQLITE_OK + && 0==pRoot->bEof + && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 + ){ rc = fts5ExprNodeNext(p, pRoot, 1, iFirst); } @@ -187797,7 +215913,7 @@ static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bD ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It ** is not considered an error if the query does not match any documents. */ -static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){ +static int tdsqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){ int rc; Fts5ExprNode *pRoot = p->pRoot; assert( pRoot->bEof==0 && pRoot->bNomatch==0 ); @@ -187811,17 +215927,17 @@ static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){ return rc; } -static int sqlite3Fts5ExprEof(Fts5Expr *p){ +static int tdsqlite3Fts5ExprEof(Fts5Expr *p){ return p->pRoot->bEof; } -static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){ +static i64 tdsqlite3Fts5ExprRowid(Fts5Expr *p){ return p->pRoot->iRowid; } static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){ int rc = SQLITE_OK; - *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n); + *pz = tdsqlite3Fts5Strndup(&rc, pToken->p, pToken->n); return rc; } @@ -187835,17 +215951,27 @@ static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){ Fts5ExprTerm *pSyn; Fts5ExprTerm *pNext; Fts5ExprTerm *pTerm = &pPhrase->aTerm[i]; - sqlite3_free(pTerm->zTerm); - sqlite3Fts5IterClose(pTerm->pIter); + tdsqlite3_free(pTerm->zTerm); + tdsqlite3Fts5IterClose(pTerm->pIter); for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){ pNext = pSyn->pSynonym; - sqlite3Fts5IterClose(pSyn->pIter); + tdsqlite3Fts5IterClose(pSyn->pIter); fts5BufferFree((Fts5Buffer*)&pSyn[1]); - sqlite3_free(pSyn); + tdsqlite3_free(pSyn); } } if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist); - sqlite3_free(pPhrase); + tdsqlite3_free(pPhrase); + } +} + +/* +** Set the "bFirst" flag on the first token of the phrase passed as the +** only argument. +*/ +static void tdsqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){ + if( pPhrase && pPhrase->nTerm ){ + pPhrase->aTerm[0].bFirst = 1; } } @@ -187857,7 +215983,7 @@ static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){ ** If an OOM error occurs, both the pNear and pPhrase objects are freed and ** NULL returned. */ -static Fts5ExprNearset *sqlite3Fts5ParseNearset( +static Fts5ExprNearset *tdsqlite3Fts5ParseNearset( Fts5Parse *pParse, /* Parse context */ Fts5ExprNearset *pNear, /* Existing nearset, or NULL */ Fts5ExprPhrase *pPhrase /* Recently parsed phrase */ @@ -187870,18 +215996,20 @@ static Fts5ExprNearset *sqlite3Fts5ParseNearset( return pNear; } if( pNear==0 ){ - int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*); - pRet = sqlite3_malloc(nByte); + tdsqlite3_int64 nByte; + nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*); + pRet = tdsqlite3_malloc64(nByte); if( pRet==0 ){ pParse->rc = SQLITE_NOMEM; }else{ - memset(pRet, 0, nByte); + memset(pRet, 0, (size_t)nByte); } }else if( (pNear->nPhrase % SZALLOC)==0 ){ int nNew = pNear->nPhrase + SZALLOC; - int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*); + tdsqlite3_int64 nByte; - pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte); + nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*); + pRet = (Fts5ExprNearset*)tdsqlite3_realloc64(pNear, nByte); if( pRet==0 ){ pParse->rc = SQLITE_NOMEM; } @@ -187892,8 +216020,8 @@ static Fts5ExprNearset *sqlite3Fts5ParseNearset( if( pRet==0 ){ assert( pParse->rc!=SQLITE_OK ); - sqlite3Fts5ParseNearsetFree(pNear); - sqlite3Fts5ParsePhraseFree(pPhrase); + tdsqlite3Fts5ParseNearsetFree(pNear); + tdsqlite3Fts5ParsePhraseFree(pPhrase); }else{ if( pRet->nPhrase>0 ){ Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1]; @@ -187945,12 +216073,12 @@ static int fts5ParseTokenize( if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){ Fts5ExprTerm *pSyn; - int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1; - pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte); + tdsqlite3_int64 nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1; + pSyn = (Fts5ExprTerm*)tdsqlite3_malloc64(nByte); if( pSyn==0 ){ rc = SQLITE_NOMEM; }else{ - memset(pSyn, 0, nByte); + memset(pSyn, 0, (size_t)nByte); pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer); memcpy(pSyn->zTerm, pToken, nToken); pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym; @@ -187962,7 +216090,7 @@ static int fts5ParseTokenize( Fts5ExprPhrase *pNew; int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0); - pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase, + pNew = (Fts5ExprPhrase*)tdsqlite3_realloc64(pPhrase, sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew ); if( pNew==0 ){ @@ -187977,7 +216105,7 @@ static int fts5ParseTokenize( if( rc==SQLITE_OK ){ pTerm = &pPhrase->aTerm[pPhrase->nTerm++]; memset(pTerm, 0, sizeof(Fts5ExprTerm)); - pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken); + pTerm->zTerm = tdsqlite3Fts5Strndup(&rc, pToken, nToken); } } @@ -187989,25 +216117,25 @@ static int fts5ParseTokenize( /* ** Free the phrase object passed as the only argument. */ -static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){ +static void tdsqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){ fts5ExprPhraseFree(pPhrase); } /* ** Free the phrase object passed as the second argument. */ -static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){ +static void tdsqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){ if( pNear ){ int i; for(i=0; i<pNear->nPhrase; i++){ fts5ExprPhraseFree(pNear->apPhrase[i]); } - sqlite3_free(pNear->pColset); - sqlite3_free(pNear); + tdsqlite3_free(pNear->pColset); + tdsqlite3_free(pNear); } } -static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){ +static void tdsqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){ assert( pParse->pExpr==0 ); pParse->pExpr = p; } @@ -188017,7 +216145,7 @@ static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){ ** string may or may not be quoted. In any case it is tokenized and a ** phrase object consisting of all tokens returned. */ -static Fts5ExprPhrase *sqlite3Fts5ParseTerm( +static Fts5ExprPhrase *tdsqlite3Fts5ParseTerm( Fts5Parse *pParse, /* Parse context */ Fts5ExprPhrase *pAppend, /* Phrase to append to */ Fts5Token *pToken, /* String to tokenize */ @@ -188033,13 +216161,13 @@ static Fts5ExprPhrase *sqlite3Fts5ParseTerm( rc = fts5ParseStringFromToken(pToken, &z); if( rc==SQLITE_OK ){ - int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0); + int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0); int n; - sqlite3Fts5Dequote(z); + tdsqlite3Fts5Dequote(z); n = (int)strlen(z); - rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize); + rc = tdsqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize); } - sqlite3_free(z); + tdsqlite3_free(z); if( rc || (rc = sCtx.rc) ){ pParse->rc = rc; fts5ExprPhraseFree(sCtx.pPhrase); @@ -188048,9 +216176,9 @@ static Fts5ExprPhrase *sqlite3Fts5ParseTerm( if( pAppend==0 ){ if( (pParse->nPhrase % 8)==0 ){ - int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8); + tdsqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8); Fts5ExprPhrase **apNew; - apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte); + apNew = (Fts5ExprPhrase**)tdsqlite3_realloc64(pParse->apPhrase, nByte); if( apNew==0 ){ pParse->rc = SQLITE_NOMEM; fts5ExprPhraseFree(sCtx.pPhrase); @@ -188064,9 +216192,9 @@ static Fts5ExprPhrase *sqlite3Fts5ParseTerm( if( sCtx.pPhrase==0 ){ /* This happens when parsing a token or quoted phrase that contains ** no token characters at all. (e.g ... MATCH '""'). */ - sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase)); + sCtx.pPhrase = tdsqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase)); }else if( sCtx.pPhrase->nTerm ){ - sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix; + sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix; } pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase; } @@ -188078,7 +216206,7 @@ static Fts5ExprPhrase *sqlite3Fts5ParseTerm( ** Create a new FTS5 expression by cloning phrase iPhrase of the ** expression passed as the second argument. */ -static int sqlite3Fts5ExprClonePhrase( +static int tdsqlite3Fts5ExprClonePhrase( Fts5Expr *pExpr, int iPhrase, Fts5Expr **ppNew @@ -188089,26 +216217,28 @@ static int sqlite3Fts5ExprClonePhrase( TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */ pOrig = pExpr->apExprPhrase[iPhrase]; - pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr)); + pNew = (Fts5Expr*)tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr)); if( rc==SQLITE_OK ){ - pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc, + pNew->apExprPhrase = (Fts5ExprPhrase**)tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase*)); } if( rc==SQLITE_OK ){ - pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, + pNew->pRoot = (Fts5ExprNode*)tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprNode)); } if( rc==SQLITE_OK ){ - pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc, + pNew->pRoot->pNear = (Fts5ExprNearset*)tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*)); } if( rc==SQLITE_OK ){ Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset; if( pColsetOrig ){ - int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int); - Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte); + tdsqlite3_int64 nByte; + Fts5Colset *pColset; + nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int); + pColset = (Fts5Colset*)tdsqlite3Fts5MallocZero(&rc, nByte); if( pColset ){ - memcpy(pColset, pColsetOrig, nByte); + memcpy(pColset, pColsetOrig, (size_t)nByte); } pNew->pRoot->pNear->pColset = pColset; } @@ -188127,12 +216257,13 @@ static int sqlite3Fts5ExprClonePhrase( } if( rc==SQLITE_OK ){ sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix; + sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst; } } }else{ /* This happens when parsing a token or quoted phrase that contains ** no token characters at all. (e.g ... MATCH '""'). */ - sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase)); + sCtx.pPhrase = tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase)); } if( rc==SQLITE_OK ){ @@ -188145,7 +216276,10 @@ static int sqlite3Fts5ExprClonePhrase( pNew->pRoot->pNear->nPhrase = 1; sCtx.pPhrase->pNode = pNew->pRoot; - if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){ + if( pOrig->nTerm==1 + && pOrig->aTerm[0].pSynonym==0 + && pOrig->aTerm[0].bFirst==0 + ){ pNew->pRoot->eType = FTS5_TERM; pNew->pRoot->xNext = fts5ExprNodeNext_TERM; }else{ @@ -188153,7 +216287,7 @@ static int sqlite3Fts5ExprClonePhrase( pNew->pRoot->xNext = fts5ExprNodeNext_STRING; } }else{ - sqlite3Fts5ExprFree(pNew); + tdsqlite3Fts5ExprFree(pNew); fts5ExprPhraseFree(sCtx.pPhrase); pNew = 0; } @@ -188168,15 +216302,15 @@ static int sqlite3Fts5ExprClonePhrase( ** is expected. If token pTok does not contain "NEAR", store an error ** in the pParse object. */ -static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){ +static void tdsqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){ if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){ - sqlite3Fts5ParseError( + tdsqlite3Fts5ParseError( pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p ); } } -static void sqlite3Fts5ParseSetDistance( +static void tdsqlite3Fts5ParseSetDistance( Fts5Parse *pParse, Fts5ExprNearset *pNear, Fts5Token *p @@ -188188,7 +216322,7 @@ static void sqlite3Fts5ParseSetDistance( for(i=0; i<p->n; i++){ char c = (char)p->p[i]; if( c<'0' || c>'9' ){ - sqlite3Fts5ParseError( + tdsqlite3Fts5ParseError( pParse, "expected integer, got \"%.*s\"", p->n, p->p ); return; @@ -188222,7 +216356,7 @@ static Fts5Colset *fts5ParseColset( assert( pParse->rc==SQLITE_OK ); assert( iCol>=0 && iCol<pParse->pConfig->nCol ); - pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol); + pNew = tdsqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol); if( pNew==0 ){ pParse->rc = SQLITE_NOMEM; }else{ @@ -188252,11 +216386,11 @@ static Fts5Colset *fts5ParseColset( ** the colset passed as the second argument. Free the colset passed ** as the second argument before returning. */ -static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){ +static Fts5Colset *tdsqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){ Fts5Colset *pRet; int nCol = pParse->pConfig->nCol; - pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc, + pRet = (Fts5Colset*)tdsqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5Colset) + sizeof(int)*nCol ); if( pRet ){ @@ -188271,11 +216405,11 @@ static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p } } - sqlite3_free(p); + tdsqlite3_free(p); return pRet; } -static Fts5Colset *sqlite3Fts5ParseColset( +static Fts5Colset *tdsqlite3Fts5ParseColset( Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */ Fts5Colset *pColset, /* Existing colset object */ Fts5Token *p @@ -188284,48 +216418,133 @@ static Fts5Colset *sqlite3Fts5ParseColset( int iCol; char *z; /* Dequoted copy of token p */ - z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n); + z = tdsqlite3Fts5Strndup(&pParse->rc, p->p, p->n); if( pParse->rc==SQLITE_OK ){ Fts5Config *pConfig = pParse->pConfig; - sqlite3Fts5Dequote(z); + tdsqlite3Fts5Dequote(z); for(iCol=0; iCol<pConfig->nCol; iCol++){ - if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break; + if( 0==tdsqlite3_stricmp(pConfig->azCol[iCol], z) ) break; } if( iCol==pConfig->nCol ){ - sqlite3Fts5ParseError(pParse, "no such column: %s", z); + tdsqlite3Fts5ParseError(pParse, "no such column: %s", z); }else{ pRet = fts5ParseColset(pParse, pColset, iCol); } - sqlite3_free(z); + tdsqlite3_free(z); } if( pRet==0 ){ assert( pParse->rc!=SQLITE_OK ); - sqlite3_free(pColset); + tdsqlite3_free(pColset); } return pRet; } -static void sqlite3Fts5ParseSetColset( +/* +** If argument pOrig is NULL, or if (*pRc) is set to anything other than +** SQLITE_OK when this function is called, NULL is returned. +** +** Otherwise, a copy of (*pOrig) is made into memory obtained from +** tdsqlite3Fts5MallocZero() and a pointer to it returned. If the allocation +** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned. +*/ +static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){ + Fts5Colset *pRet; + if( pOrig ){ + tdsqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int); + pRet = (Fts5Colset*)tdsqlite3Fts5MallocZero(pRc, nByte); + if( pRet ){ + memcpy(pRet, pOrig, (size_t)nByte); + } + }else{ + pRet = 0; + } + return pRet; +} + +/* +** Remove from colset pColset any columns that are not also in colset pMerge. +*/ +static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){ + int iIn = 0; /* Next input in pColset */ + int iMerge = 0; /* Next input in pMerge */ + int iOut = 0; /* Next output slot in pColset */ + + while( iIn<pColset->nCol && iMerge<pMerge->nCol ){ + int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge]; + if( iDiff==0 ){ + pColset->aiCol[iOut++] = pMerge->aiCol[iMerge]; + iMerge++; + iIn++; + }else if( iDiff>0 ){ + iMerge++; + }else{ + iIn++; + } + } + pColset->nCol = iOut; +} + +/* +** Recursively apply colset pColset to expression node pNode and all of +** its decendents. If (*ppFree) is not NULL, it contains a spare copy +** of pColset. This function may use the spare copy and set (*ppFree) to +** zero, or it may create copies of pColset using fts5CloneColset(). +*/ +static void fts5ParseSetColset( + Fts5Parse *pParse, + Fts5ExprNode *pNode, + Fts5Colset *pColset, + Fts5Colset **ppFree +){ + if( pParse->rc==SQLITE_OK ){ + assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING + || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR + || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF + ); + if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){ + Fts5ExprNearset *pNear = pNode->pNear; + if( pNear->pColset ){ + fts5MergeColset(pNear->pColset, pColset); + if( pNear->pColset->nCol==0 ){ + pNode->eType = FTS5_EOF; + pNode->xNext = 0; + } + }else if( *ppFree ){ + pNear->pColset = pColset; + *ppFree = 0; + }else{ + pNear->pColset = fts5CloneColset(&pParse->rc, pColset); + } + }else{ + int i; + assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 ); + for(i=0; i<pNode->nChild; i++){ + fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree); + } + } + } +} + +/* +** Apply colset pColset to expression node pExpr and all of its descendents. +*/ +static void tdsqlite3Fts5ParseSetColset( Fts5Parse *pParse, - Fts5ExprNearset *pNear, + Fts5ExprNode *pExpr, Fts5Colset *pColset ){ + Fts5Colset *pFree = pColset; if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){ pParse->rc = SQLITE_ERROR; - pParse->zErr = sqlite3_mprintf( + pParse->zErr = tdsqlite3_mprintf( "fts5: column queries are not supported (detail=none)" ); - sqlite3_free(pColset); - return; - } - - if( pNear ){ - pNear->pColset = pColset; }else{ - sqlite3_free(pColset); + fts5ParseSetColset(pParse, pExpr, pColset, &pFree); } + tdsqlite3_free(pFree); } static void fts5ExprAssignXNext(Fts5ExprNode *pNode){ @@ -188334,6 +216553,7 @@ static void fts5ExprAssignXNext(Fts5ExprNode *pNode){ Fts5ExprNearset *pNear = pNode->pNear; if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1 && pNear->apPhrase[0]->aTerm[0].pSynonym==0 + && pNear->apPhrase[0]->aTerm[0].bFirst==0 ){ pNode->eType = FTS5_TERM; pNode->xNext = fts5ExprNodeNext_TERM; @@ -188365,7 +216585,7 @@ static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){ int nByte = sizeof(Fts5ExprNode*) * pSub->nChild; memcpy(&p->apChild[p->nChild], pSub->apChild, nByte); p->nChild += pSub->nChild; - sqlite3_free(pSub); + tdsqlite3_free(pSub); }else{ p->apChild[p->nChild++] = pSub; } @@ -188375,7 +216595,7 @@ static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){ ** Allocate and return a new expression object. If anything goes wrong (i.e. ** OOM error), leave an error code in pParse and return NULL. */ -static Fts5ExprNode *sqlite3Fts5ParseNode( +static Fts5ExprNode *tdsqlite3Fts5ParseNode( Fts5Parse *pParse, /* Parse context */ int eType, /* FTS5_STRING, AND, OR or NOT */ Fts5ExprNode *pLeft, /* Left hand child expression */ @@ -188386,7 +216606,7 @@ static Fts5ExprNode *sqlite3Fts5ParseNode( if( pParse->rc==SQLITE_OK ){ int nChild = 0; /* Number of children of returned node */ - int nByte; /* Bytes of space to allocate for this node */ + tdsqlite3_int64 nByte; /* Bytes of space to allocate for this node */ assert( (eType!=FTS5_STRING && !pNear) || (eType==FTS5_STRING && !pLeft && !pRight) @@ -188404,7 +216624,7 @@ static Fts5ExprNode *sqlite3Fts5ParseNode( } nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1); - pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte); + pRet = (Fts5ExprNode*)tdsqlite3Fts5MallocZero(&pParse->rc, nByte); if( pRet ){ pRet->eType = eType; @@ -188420,20 +216640,23 @@ static Fts5ExprNode *sqlite3Fts5ParseNode( } } - if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL - && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1) - ){ - assert( pParse->rc==SQLITE_OK ); - pParse->rc = SQLITE_ERROR; - assert( pParse->zErr==0 ); - pParse->zErr = sqlite3_mprintf( - "fts5: %s queries are not supported (detail!=full)", - pNear->nPhrase==1 ? "phrase": "NEAR" - ); - sqlite3_free(pRet); - pRet = 0; + if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){ + Fts5ExprPhrase *pPhrase = pNear->apPhrase[0]; + if( pNear->nPhrase!=1 + || pPhrase->nTerm>1 + || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst) + ){ + assert( pParse->rc==SQLITE_OK ); + pParse->rc = SQLITE_ERROR; + assert( pParse->zErr==0 ); + pParse->zErr = tdsqlite3_mprintf( + "fts5: %s queries are not supported (detail!=full)", + pNear->nPhrase==1 ? "phrase": "NEAR" + ); + tdsqlite3_free(pRet); + pRet = 0; + } } - }else{ fts5ExprAddChildren(pRet, pLeft); fts5ExprAddChildren(pRet, pRight); @@ -188443,14 +216666,14 @@ static Fts5ExprNode *sqlite3Fts5ParseNode( if( pRet==0 ){ assert( pParse->rc!=SQLITE_OK ); - sqlite3Fts5ParseNodeFree(pLeft); - sqlite3Fts5ParseNodeFree(pRight); - sqlite3Fts5ParseNearsetFree(pNear); + tdsqlite3Fts5ParseNodeFree(pLeft); + tdsqlite3Fts5ParseNodeFree(pRight); + tdsqlite3Fts5ParseNearsetFree(pNear); } return pRet; } -static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd( +static Fts5ExprNode *tdsqlite3Fts5ParseImplicitAnd( Fts5Parse *pParse, /* Parse context */ Fts5ExprNode *pLeft, /* Left hand child expression */ Fts5ExprNode *pRight /* Right hand child expression */ @@ -188459,8 +216682,8 @@ static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd( Fts5ExprNode *pPrev; if( pParse->rc ){ - sqlite3Fts5ParseNodeFree(pLeft); - sqlite3Fts5ParseNodeFree(pRight); + tdsqlite3Fts5ParseNodeFree(pLeft); + tdsqlite3Fts5ParseNodeFree(pRight); }else{ assert( pLeft->eType==FTS5_STRING @@ -188485,7 +216708,7 @@ static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd( if( pRight->eType==FTS5_EOF ){ assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] ); - sqlite3Fts5ParseNodeFree(pRight); + tdsqlite3Fts5ParseNodeFree(pRight); pRet = pLeft; pParse->nPhrase--; } @@ -188504,10 +216727,10 @@ static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd( memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase); pParse->nPhrase--; - sqlite3Fts5ParseNodeFree(pPrev); + tdsqlite3Fts5ParseNodeFree(pPrev); } else{ - pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0); + pRet = tdsqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0); } } @@ -188515,7 +216738,7 @@ static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd( } static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){ - int nByte = 0; + tdsqlite3_int64 nByte = 0; Fts5ExprTerm *p; char *zQuoted; @@ -188523,7 +216746,7 @@ static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){ for(p=pTerm; p; p=p->pSynonym){ nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2; } - zQuoted = sqlite3_malloc(nByte); + zQuoted = tdsqlite3_malloc64(nByte); if( zQuoted ){ int i = 0; @@ -188550,14 +216773,14 @@ static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){ char *zNew; va_list ap; va_start(ap, zFmt); - zNew = sqlite3_vmprintf(zFmt, ap); + zNew = tdsqlite3_vmprintf(zFmt, ap); va_end(ap); if( zApp && zNew ){ - char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew); - sqlite3_free(zNew); + char *zNew2 = tdsqlite3_mprintf("%s%s", zApp, zNew); + tdsqlite3_free(zNew); zNew = zNew2; } - sqlite3_free(zApp); + tdsqlite3_free(zApp); return zNew; } @@ -188565,7 +216788,7 @@ static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){ ** Compose a tcl-readable representation of expression pExpr. Return a ** pointer to a buffer containing that representation. It is the ** responsibility of the caller to at some point free the buffer using -** sqlite3_free(). +** tdsqlite3_free(). */ static char *fts5ExprPrintTcl( Fts5Config *pConfig, @@ -188631,11 +216854,11 @@ static char *fts5ExprPrintTcl( break; } - zRet = sqlite3_mprintf("%s", zOp); + zRet = tdsqlite3_mprintf("%s", zOp); for(i=0; zRet && i<pExpr->nChild; i++){ char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]); if( !z ){ - sqlite3_free(zRet); + tdsqlite3_free(zRet); zRet = 0; }else{ zRet = fts5PrintfAppend(zRet, " [%z]", z); @@ -188649,7 +216872,7 @@ static char *fts5ExprPrintTcl( static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){ char *zRet = 0; if( pExpr->eType==0 ){ - return sqlite3_mprintf("\"\""); + return tdsqlite3_mprintf("\"\""); }else if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){ Fts5ExprNearset *pNear = pExpr->pNear; @@ -188677,10 +216900,10 @@ static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){ char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]); if( zTerm ){ zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm); - sqlite3_free(zTerm); + tdsqlite3_free(zTerm); } if( zTerm==0 || zRet==0 ){ - sqlite3_free(zRet); + tdsqlite3_free(zRet); return 0; } } @@ -188707,7 +216930,7 @@ static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){ for(i=0; i<pExpr->nChild; i++){ char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]); if( z==0 ){ - sqlite3_free(zRet); + tdsqlite3_free(zRet); zRet = 0; }else{ int e = pExpr->apChild[i]->eType; @@ -188729,13 +216952,13 @@ static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){ ** and fts5_expr_tcl() (bTcl!=0). */ static void fts5ExprFunction( - sqlite3_context *pCtx, /* Function call context */ + tdsqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ - sqlite3_value **apVal, /* Function arguments */ + tdsqlite3_value **apVal, /* Function arguments */ int bTcl ){ - Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx); - sqlite3 *db = sqlite3_context_db_handle(pCtx); + Fts5Global *pGlobal = (Fts5Global*)tdsqlite3_user_data(pCtx); + tdsqlite3 *db = tdsqlite3_context_db_handle(pCtx); const char *zExpr = 0; char *zErr = 0; Fts5Expr *pExpr = 0; @@ -188749,42 +216972,44 @@ static void fts5ExprFunction( int iArg = 1; if( nArg<1 ){ - zErr = sqlite3_mprintf("wrong number of arguments to function %s", + zErr = tdsqlite3_mprintf("wrong number of arguments to function %s", bTcl ? "fts5_expr_tcl" : "fts5_expr" ); - sqlite3_result_error(pCtx, zErr, -1); - sqlite3_free(zErr); + tdsqlite3_result_error(pCtx, zErr, -1); + tdsqlite3_free(zErr); return; } if( bTcl && nArg>1 ){ - zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]); + zNearsetCmd = (const char*)tdsqlite3_value_text(apVal[1]); iArg = 2; } nConfig = 3 + (nArg-iArg); - azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig); + azConfig = (const char**)tdsqlite3_malloc64(sizeof(char*) * nConfig); if( azConfig==0 ){ - sqlite3_result_error_nomem(pCtx); + tdsqlite3_result_error_nomem(pCtx); return; } azConfig[0] = 0; azConfig[1] = "main"; azConfig[2] = "tbl"; for(i=3; iArg<nArg; iArg++){ - azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]); + const char *z = (const char*)tdsqlite3_value_text(apVal[iArg]); + azConfig[i++] = (z ? z : ""); } - zExpr = (const char*)sqlite3_value_text(apVal[0]); + zExpr = (const char*)tdsqlite3_value_text(apVal[0]); + if( zExpr==0 ) zExpr = ""; - rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr); + rc = tdsqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr); if( rc==SQLITE_OK ){ - rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr); + rc = tdsqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr); } if( rc==SQLITE_OK ){ char *zText; if( pExpr->pRoot->xNext==0 ){ - zText = sqlite3_mprintf(""); + zText = tdsqlite3_mprintf(""); }else if( bTcl ){ zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot); }else{ @@ -188793,35 +217018,35 @@ static void fts5ExprFunction( if( zText==0 ){ rc = SQLITE_NOMEM; }else{ - sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT); - sqlite3_free(zText); + tdsqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT); + tdsqlite3_free(zText); } } if( rc!=SQLITE_OK ){ if( zErr ){ - sqlite3_result_error(pCtx, zErr, -1); - sqlite3_free(zErr); + tdsqlite3_result_error(pCtx, zErr, -1); + tdsqlite3_free(zErr); }else{ - sqlite3_result_error_code(pCtx, rc); + tdsqlite3_result_error_code(pCtx, rc); } } - sqlite3_free((void *)azConfig); - sqlite3Fts5ConfigFree(pConfig); - sqlite3Fts5ExprFree(pExpr); + tdsqlite3_free((void *)azConfig); + tdsqlite3Fts5ConfigFree(pConfig); + tdsqlite3Fts5ExprFree(pExpr); } static void fts5ExprFunctionHr( - sqlite3_context *pCtx, /* Function call context */ + tdsqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ - sqlite3_value **apVal /* Function arguments */ + tdsqlite3_value **apVal /* Function arguments */ ){ fts5ExprFunction(pCtx, nArg, apVal, 0); } static void fts5ExprFunctionTcl( - sqlite3_context *pCtx, /* Function call context */ + tdsqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ - sqlite3_value **apVal /* Function arguments */ + tdsqlite3_value **apVal /* Function arguments */ ){ fts5ExprFunction(pCtx, nArg, apVal, 1); } @@ -188832,36 +217057,41 @@ static void fts5ExprFunctionTcl( ** unicode code point, 1 is returned. Otherwise 0. */ static void fts5ExprIsAlnum( - sqlite3_context *pCtx, /* Function call context */ + tdsqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ - sqlite3_value **apVal /* Function arguments */ + tdsqlite3_value **apVal /* Function arguments */ ){ int iCode; + u8 aArr[32]; if( nArg!=1 ){ - sqlite3_result_error(pCtx, + tdsqlite3_result_error(pCtx, "wrong number of arguments to function fts5_isalnum", -1 ); return; } - iCode = sqlite3_value_int(apVal[0]); - sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode)); + memset(aArr, 0, sizeof(aArr)); + tdsqlite3Fts5UnicodeCatParse("L*", aArr); + tdsqlite3Fts5UnicodeCatParse("N*", aArr); + tdsqlite3Fts5UnicodeCatParse("Co", aArr); + iCode = tdsqlite3_value_int(apVal[0]); + tdsqlite3_result_int(pCtx, aArr[tdsqlite3Fts5UnicodeCategory((u32)iCode)]); } static void fts5ExprFold( - sqlite3_context *pCtx, /* Function call context */ + tdsqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ - sqlite3_value **apVal /* Function arguments */ + tdsqlite3_value **apVal /* Function arguments */ ){ if( nArg!=1 && nArg!=2 ){ - sqlite3_result_error(pCtx, + tdsqlite3_result_error(pCtx, "wrong number of arguments to function fts5_fold", -1 ); }else{ int iCode; int bRemoveDiacritics = 0; - iCode = sqlite3_value_int(apVal[0]); - if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]); - sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics)); + iCode = tdsqlite3_value_int(apVal[0]); + if( nArg==2 ) bRemoveDiacritics = tdsqlite3_value_int(apVal[1]); + tdsqlite3_result_int(pCtx, tdsqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics)); } } @@ -188869,10 +217099,10 @@ static void fts5ExprFold( ** This is called during initialization to register the fts5_expr() scalar ** UDF with the SQLite handle passed as the only argument. */ -static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){ +static int tdsqlite3Fts5ExprInit(Fts5Global *pGlobal, tdsqlite3 *db){ struct Fts5ExprFunc { const char *z; - void (*x)(sqlite3_context*,int,sqlite3_value**); + void (*x)(tdsqlite3_context*,int,tdsqlite3_value**); } aFunc[] = { { "fts5_expr", fts5ExprFunctionHr }, { "fts5_expr_tcl", fts5ExprFunctionTcl }, @@ -188885,13 +217115,15 @@ static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){ for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){ struct Fts5ExprFunc *p = &aFunc[i]; - rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0); + rc = tdsqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0); } - /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */ + /* Avoid warnings indicating that tdsqlite3Fts5ParserTrace() and + ** tdsqlite3Fts5ParserFallback() are unused */ #ifndef NDEBUG - (void)sqlite3Fts5ParserTrace; + (void)tdsqlite3Fts5ParserTrace; #endif + (void)tdsqlite3Fts5ParserFallback; return rc; } @@ -188899,14 +217131,14 @@ static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){ /* ** Return the number of phrases in expression pExpr. */ -static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){ +static int tdsqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){ return (pExpr ? pExpr->nPhrase : 0); } /* ** Return the number of terms in the iPhrase'th phrase in pExpr. */ -static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){ +static int tdsqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){ if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0; return pExpr->apExprPhrase[iPhrase]->nTerm; } @@ -188915,7 +217147,7 @@ static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){ ** This function is used to access the current position list for phrase ** iPhrase. */ -static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){ +static int tdsqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){ int nRet; Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase]; Fts5ExprNode *pNode = pPhrase->pNode; @@ -188935,9 +217167,9 @@ struct Fts5PoslistPopulator { int bMiss; }; -static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){ +static Fts5PoslistPopulator *tdsqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){ Fts5PoslistPopulator *pRet; - pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase); + pRet = tdsqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase); if( pRet ){ int i; memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase); @@ -188999,7 +217231,7 @@ static int fts5ExprPopulatePoslistsCb( if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix)) && memcmp(pTerm->zTerm, pToken, nTerm)==0 ){ - int rc = sqlite3Fts5PoslistWriterAppend( + int rc = tdsqlite3Fts5PoslistWriterAppend( &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff ); if( rc ) return rc; @@ -189010,7 +217242,7 @@ static int fts5ExprPopulatePoslistsCb( return SQLITE_OK; } -static int sqlite3Fts5ExprPopulatePoslists( +static int tdsqlite3Fts5ExprPopulatePoslists( Fts5Config *pConfig, Fts5Expr *pExpr, Fts5PoslistPopulator *aPopulator, @@ -189035,7 +217267,7 @@ static int sqlite3Fts5ExprPopulatePoslists( } } - return sqlite3Fts5Tokenize(pConfig, + return tdsqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb ); } @@ -189095,14 +217327,14 @@ static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){ return 1; } -static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){ +static void tdsqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){ fts5ExprCheckPoslists(pExpr->pRoot, iRowid); } /* ** This function is only called for detail=columns tables. */ -static int sqlite3Fts5ExprPhraseCollist( +static int tdsqlite3Fts5ExprPhraseCollist( Fts5Expr *pExpr, int iPhrase, const u8 **ppCollist, @@ -189137,7 +217369,6 @@ static int sqlite3Fts5ExprPhraseCollist( return rc; } - /* ** 2014 August 11 ** @@ -189176,9 +217407,10 @@ struct Fts5Hash { /* ** Each entry in the hash table is represented by an object of the -** following type. Each object, its key (zKey[]) and its current data -** are stored in a single memory allocation. The position list data -** immediately follows the key data in memory. +** following type. Each object, its key (a nul-terminated string) and +** its current data are stored in a single memory allocation. The +** key immediately follows the object in memory. The position list +** data immediately follows the key data in memory. ** ** The data that follows the key is in a similar, but not identical format ** to the doclist data stored in the database. It is: @@ -189202,47 +217434,47 @@ struct Fts5HashEntry { int nAlloc; /* Total size of allocation */ int iSzPoslist; /* Offset of space for 4-byte poslist size */ int nData; /* Total bytes of data (incl. structure) */ - int nKey; /* Length of zKey[] in bytes */ + int nKey; /* Length of key in bytes */ u8 bDel; /* Set delete-flag @ iSzPoslist */ u8 bContent; /* Set content-flag (detail=none mode) */ i16 iCol; /* Column of last value written */ int iPos; /* Position of last value written */ i64 iRowid; /* Rowid of last value written */ - char zKey[8]; /* Nul-terminated entry key */ }; /* -** Size of Fts5HashEntry without the zKey[] array. +** Eqivalent to: +** +** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; } */ -#define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8) - +#define fts5EntryKey(p) ( ((char *)(&(p)[1])) ) /* ** Allocate a new hash table. */ -static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){ +static int tdsqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){ int rc = SQLITE_OK; Fts5Hash *pNew; - *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash)); + *ppNew = pNew = (Fts5Hash*)tdsqlite3_malloc(sizeof(Fts5Hash)); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ - int nByte; + tdsqlite3_int64 nByte; memset(pNew, 0, sizeof(Fts5Hash)); pNew->pnByte = pnByte; pNew->eDetail = pConfig->eDetail; pNew->nSlot = 1024; nByte = sizeof(Fts5HashEntry*) * pNew->nSlot; - pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte); + pNew->aSlot = (Fts5HashEntry**)tdsqlite3_malloc64(nByte); if( pNew->aSlot==0 ){ - sqlite3_free(pNew); + tdsqlite3_free(pNew); *ppNew = 0; rc = SQLITE_NOMEM; }else{ - memset(pNew->aSlot, 0, nByte); + memset(pNew->aSlot, 0, (size_t)nByte); } } return rc; @@ -189251,25 +217483,25 @@ static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte /* ** Free a hash table object. */ -static void sqlite3Fts5HashFree(Fts5Hash *pHash){ +static void tdsqlite3Fts5HashFree(Fts5Hash *pHash){ if( pHash ){ - sqlite3Fts5HashClear(pHash); - sqlite3_free(pHash->aSlot); - sqlite3_free(pHash); + tdsqlite3Fts5HashClear(pHash); + tdsqlite3_free(pHash->aSlot); + tdsqlite3_free(pHash); } } /* ** Empty (but do not delete) a hash table. */ -static void sqlite3Fts5HashClear(Fts5Hash *pHash){ +static void tdsqlite3Fts5HashClear(Fts5Hash *pHash){ int i; for(i=0; i<pHash->nSlot; i++){ Fts5HashEntry *pNext; Fts5HashEntry *pSlot; for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){ pNext = pSlot->pHashNext; - sqlite3_free(pSlot); + tdsqlite3_free(pSlot); } } memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*)); @@ -189304,57 +217536,69 @@ static int fts5HashResize(Fts5Hash *pHash){ Fts5HashEntry **apNew; Fts5HashEntry **apOld = pHash->aSlot; - apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*)); + apNew = (Fts5HashEntry**)tdsqlite3_malloc64(nNew*sizeof(Fts5HashEntry*)); if( !apNew ) return SQLITE_NOMEM; memset(apNew, 0, nNew*sizeof(Fts5HashEntry*)); for(i=0; i<pHash->nSlot; i++){ while( apOld[i] ){ - int iHash; + unsigned int iHash; Fts5HashEntry *p = apOld[i]; apOld[i] = p->pHashNext; - iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey)); + iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p), + (int)strlen(fts5EntryKey(p))); p->pHashNext = apNew[iHash]; apNew[iHash] = p; } } - sqlite3_free(apOld); + tdsqlite3_free(apOld); pHash->nSlot = nNew; pHash->aSlot = apNew; return SQLITE_OK; } -static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){ +static int fts5HashAddPoslistSize( + Fts5Hash *pHash, + Fts5HashEntry *p, + Fts5HashEntry *p2 +){ + int nRet = 0; if( p->iSzPoslist ){ - u8 *pPtr = (u8*)p; + u8 *pPtr = p2 ? (u8*)p2 : (u8*)p; + int nData = p->nData; if( pHash->eDetail==FTS5_DETAIL_NONE ){ - assert( p->nData==p->iSzPoslist ); + assert( nData==p->iSzPoslist ); if( p->bDel ){ - pPtr[p->nData++] = 0x00; + pPtr[nData++] = 0x00; if( p->bContent ){ - pPtr[p->nData++] = 0x00; + pPtr[nData++] = 0x00; } } }else{ - int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */ + int nSz = (nData - p->iSzPoslist - 1); /* Size in bytes */ int nPos = nSz*2 + p->bDel; /* Value of nPos field */ assert( p->bDel==0 || p->bDel==1 ); if( nPos<=127 ){ pPtr[p->iSzPoslist] = (u8)nPos; }else{ - int nByte = sqlite3Fts5GetVarintLen((u32)nPos); + int nByte = tdsqlite3Fts5GetVarintLen((u32)nPos); memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz); - sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos); - p->nData += (nByte-1); + tdsqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos); + nData += (nByte-1); } } - p->iSzPoslist = 0; - p->bDel = 0; - p->bContent = 0; + nRet = nData - p->nData; + if( p2==0 ){ + p->iSzPoslist = 0; + p->bDel = 0; + p->bContent = 0; + p->nData = nData; + } } + return nRet; } /* @@ -189365,7 +217609,7 @@ static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){ ** ** Or, if iCol is negative, then the value is a delete marker. */ -static int sqlite3Fts5HashWrite( +static int tdsqlite3Fts5HashWrite( Fts5Hash *pHash, i64 iRowid, /* Rowid for this entry */ int iCol, /* Column token appears in (-ve -> delete) */ @@ -189384,9 +217628,10 @@ static int sqlite3Fts5HashWrite( /* Attempt to locate an existing hash entry */ iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken); for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){ - if( p->zKey[0]==bByte + char *zKey = fts5EntryKey(p); + if( zKey[0]==bByte && p->nKey==nToken - && memcmp(&p->zKey[1], pToken, nToken)==0 + && memcmp(&zKey[1], pToken, nToken)==0 ){ break; } @@ -189395,7 +217640,8 @@ static int sqlite3Fts5HashWrite( /* If an existing hash entry cannot be found, create a new one. */ if( p==0 ){ /* Figure out how much space to allocate */ - int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64; + char *zKey; + tdsqlite3_int64 nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64; if( nByte<128 ) nByte = 128; /* Grow the Fts5Hash.aSlot[] array if necessary. */ @@ -189406,22 +217652,23 @@ static int sqlite3Fts5HashWrite( } /* Allocate new Fts5HashEntry and add it to the hash table. */ - p = (Fts5HashEntry*)sqlite3_malloc(nByte); + p = (Fts5HashEntry*)tdsqlite3_malloc64(nByte); if( !p ) return SQLITE_NOMEM; - memset(p, 0, FTS5_HASHENTRYSIZE); - p->nAlloc = nByte; - p->zKey[0] = bByte; - memcpy(&p->zKey[1], pToken, nToken); - assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) ); + memset(p, 0, sizeof(Fts5HashEntry)); + p->nAlloc = (int)nByte; + zKey = fts5EntryKey(p); + zKey[0] = bByte; + memcpy(&zKey[1], pToken, nToken); + assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) ); p->nKey = nToken; - p->zKey[nToken+1] = '\0'; - p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE; + zKey[nToken+1] = '\0'; + p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry); p->pHashNext = pHash->aSlot[iHash]; pHash->aSlot[iHash] = p; pHash->nEntry++; /* Add the first rowid field to the hash-entry */ - p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid); + p->nData += tdsqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid); p->iRowid = iRowid; p->iSzPoslist = p->nData; @@ -189444,12 +217691,12 @@ static int sqlite3Fts5HashWrite( ** + 5 bytes for the new position offset (32-bit max). */ if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){ - int nNew = p->nAlloc * 2; + tdsqlite3_int64 nNew = p->nAlloc * 2; Fts5HashEntry *pNew; Fts5HashEntry **pp; - pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew); + pNew = (Fts5HashEntry*)tdsqlite3_realloc64(p, nNew); if( pNew==0 ) return SQLITE_NOMEM; - pNew->nAlloc = nNew; + pNew->nAlloc = (int)nNew; for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext); *pp = pNew; p = pNew; @@ -189463,8 +217710,8 @@ static int sqlite3Fts5HashWrite( /* If this is a new rowid, append the 4-byte size field for the previous ** entry, and the new rowid for this entry. */ if( iRowid!=p->iRowid ){ - fts5HashAddPoslistSize(pHash, p); - p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid); + fts5HashAddPoslistSize(pHash, p, 0); + p->nData += tdsqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid); p->iRowid = iRowid; bNew = 1; p->iSzPoslist = p->nData; @@ -189484,7 +217731,7 @@ static int sqlite3Fts5HashWrite( if( iCol!=p->iCol ){ if( pHash->eDetail==FTS5_DETAIL_FULL ){ pPtr[p->nData++] = 0x01; - p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol); + p->nData += tdsqlite3Fts5PutVarint(&pPtr[p->nData], iCol); p->iCol = (i16)iCol; p->iPos = 0; }else{ @@ -189495,7 +217742,7 @@ static int sqlite3Fts5HashWrite( /* Append the new position offset, if necessary */ if( bNew ){ - p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2); + p->nData += tdsqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2); p->iPos = iPos; } } @@ -189533,9 +217780,11 @@ static Fts5HashEntry *fts5HashEntryMerge( p1 = 0; }else{ int i = 0; - while( p1->zKey[i]==p2->zKey[i] ) i++; + char *zKey1 = fts5EntryKey(p1); + char *zKey2 = fts5EntryKey(p2); + while( zKey1[i]==zKey2[i] ) i++; - if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){ + if( ((u8)zKey1[i])>((u8)zKey2[i]) ){ /* p2 is smaller */ *ppOut = p2; ppOut = &p2->pScanNext; @@ -189571,14 +217820,16 @@ static int fts5HashEntrySort( int i; *ppSorted = 0; - ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot); + ap = tdsqlite3_malloc64(sizeof(Fts5HashEntry*) * nMergeSlot); if( !ap ) return SQLITE_NOMEM; memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot); for(iSlot=0; iSlot<pHash->nSlot; iSlot++){ Fts5HashEntry *pIter; for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){ - if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){ + if( pTerm==0 + || (pIter->nKey+1>=nTerm && 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm)) + ){ Fts5HashEntry *pEntry = pIter; pEntry->pScanNext = 0; for(i=0; ap[i]; i++){ @@ -189596,7 +217847,7 @@ static int fts5HashEntrySort( } pHash->nEntry = 0; - sqlite3_free(ap); + tdsqlite3_free(ap); *ppSorted = pList; return SQLITE_OK; } @@ -189604,48 +217855,61 @@ static int fts5HashEntrySort( /* ** Query the hash table for a doclist associated with term pTerm/nTerm. */ -static int sqlite3Fts5HashQuery( +static int tdsqlite3Fts5HashQuery( Fts5Hash *pHash, /* Hash table to query */ + int nPre, const char *pTerm, int nTerm, /* Query term */ - const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */ + void **ppOut, /* OUT: Pointer to new object */ int *pnDoclist /* OUT: Size of doclist in bytes */ ){ unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm); + char *zKey = 0; Fts5HashEntry *p; for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){ - if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break; + zKey = fts5EntryKey(p); + assert( p->nKey+1==(int)strlen(zKey) ); + if( nTerm==p->nKey+1 && memcmp(zKey, pTerm, nTerm)==0 ) break; } if( p ){ - fts5HashAddPoslistSize(pHash, p); - *ppDoclist = (const u8*)&p->zKey[nTerm+1]; - *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1); + int nHashPre = sizeof(Fts5HashEntry) + nTerm + 1; + int nList = p->nData - nHashPre; + u8 *pRet = (u8*)(*ppOut = tdsqlite3_malloc64(nPre + nList + 10)); + if( pRet ){ + Fts5HashEntry *pFaux = (Fts5HashEntry*)&pRet[nPre-nHashPre]; + memcpy(&pRet[nPre], &((u8*)p)[nHashPre], nList); + nList += fts5HashAddPoslistSize(pHash, p, pFaux); + *pnDoclist = nList; + }else{ + *pnDoclist = 0; + return SQLITE_NOMEM; + } }else{ - *ppDoclist = 0; + *ppOut = 0; *pnDoclist = 0; } return SQLITE_OK; } -static int sqlite3Fts5HashScanInit( +static int tdsqlite3Fts5HashScanInit( Fts5Hash *p, /* Hash table to query */ const char *pTerm, int nTerm /* Query prefix */ ){ return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan); } -static void sqlite3Fts5HashScanNext(Fts5Hash *p){ - assert( !sqlite3Fts5HashScanEof(p) ); +static void tdsqlite3Fts5HashScanNext(Fts5Hash *p){ + assert( !tdsqlite3Fts5HashScanEof(p) ); p->pScan = p->pScan->pScanNext; } -static int sqlite3Fts5HashScanEof(Fts5Hash *p){ +static int tdsqlite3Fts5HashScanEof(Fts5Hash *p){ return (p->pScan==0); } -static void sqlite3Fts5HashScanEntry( +static void tdsqlite3Fts5HashScanEntry( Fts5Hash *pHash, const char **pzTerm, /* OUT: term (nul-terminated) */ const u8 **ppDoclist, /* OUT: pointer to doclist */ @@ -189653,11 +217917,12 @@ static void sqlite3Fts5HashScanEntry( ){ Fts5HashEntry *p; if( (p = pHash->pScan) ){ - int nTerm = (int)strlen(p->zKey); - fts5HashAddPoslistSize(pHash, p); - *pzTerm = p->zKey; - *ppDoclist = (const u8*)&p->zKey[nTerm+1]; - *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1); + char *zKey = fts5EntryKey(p); + int nTerm = (int)strlen(zKey); + fts5HashAddPoslistSize(pHash, p, 0); + *pzTerm = zKey; + *ppDoclist = (const u8*)&zKey[nTerm+1]; + *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1); }else{ *pzTerm = 0; *ppDoclist = 0; @@ -189665,7 +217930,6 @@ static void sqlite3Fts5HashScanEntry( } } - /* ** 2014 May 31 ** @@ -189907,13 +218171,8 @@ static void sqlite3Fts5HashScanEntry( #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno) #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno) -/* -** Maximum segments permitted in a single index -*/ -#define FTS5_MAX_SEGMENT 2000 - #ifdef SQLITE_DEBUG -static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; } +static int tdsqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; } #endif @@ -189965,15 +218224,15 @@ struct Fts5Index { int rc; /* Current error code */ /* State used by the fts5DataXXX() functions. */ - sqlite3_blob *pReader; /* RO incr-blob open on %_data table */ - sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */ - sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */ - sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */ - sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */ - sqlite3_stmt *pIdxSelect; + tdsqlite3_blob *pReader; /* RO incr-blob open on %_data table */ + tdsqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */ + tdsqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */ + tdsqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */ + tdsqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */ + tdsqlite3_stmt *pIdxSelect; int nRead; /* Total number of blocks read */ - sqlite3_stmt *pDataVersion; + tdsqlite3_stmt *pDataVersion; i64 iStructVersion; /* data_version when pStruct read */ Fts5Structure *pStruct; /* Current db structure (or NULL) */ }; @@ -190173,14 +218432,13 @@ struct Fts5SegIter { ** the smallest key overall. aFirst[0] is unused. ** ** poslist: -** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered. +** Used by tdsqlite3Fts5IterPoslist() when the poslist needs to be buffered. ** There is no way to tell if this is populated or not. */ struct Fts5Iter { Fts5IndexIter base; /* Base class containing output vars */ Fts5Index *pIndex; /* Index that owns this iterator */ - Fts5Structure *pStruct; /* Database structure for this iterator */ Fts5Buffer poslist; /* Buffer containing current poslist */ Fts5Colset *pColset; /* Restrict matches to these columns */ @@ -190241,8 +218499,8 @@ static u16 fts5GetU16(const u8 *aIn){ ** If an OOM error is encountered, return NULL and set the error code in ** the Fts5Index handle passed as the first argument. */ -static void *fts5IdxMalloc(Fts5Index *p, int nByte){ - return sqlite3Fts5MallocZero(&p->rc, nByte); +static void *fts5IdxMalloc(Fts5Index *p, tdsqlite3_int64 nByte){ + return tdsqlite3Fts5MallocZero(&p->rc, nByte); } /* @@ -190275,7 +218533,7 @@ static int fts5BufferCompareBlob( */ static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){ int nCmp = MIN(pLeft->n, pRight->n); - int res = memcmp(pLeft->p, pRight->p, nCmp); + int res = fts5Memcmp(pLeft->p, pRight->p, nCmp); return (res==0 ? (pLeft->n - pRight->n) : res); } @@ -190288,15 +218546,14 @@ static int fts5LeafFirstTermOff(Fts5Data *pLeaf){ /* ** Close the read-only blob handle, if it is open. */ -static void fts5CloseReader(Fts5Index *p){ +static void tdsqlite3Fts5IndexCloseReader(Fts5Index *p){ if( p->pReader ){ - sqlite3_blob *pReader = p->pReader; + tdsqlite3_blob *pReader = p->pReader; p->pReader = 0; - sqlite3_blob_close(pReader); + tdsqlite3_blob_close(pReader); } } - /* ** Retrieve a record from the %_data table. ** @@ -190312,13 +218569,13 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){ /* This call may return SQLITE_ABORT if there has been a savepoint ** rollback since it was last used. In this case a new blob handle ** is required. */ - sqlite3_blob *pBlob = p->pReader; + tdsqlite3_blob *pBlob = p->pReader; p->pReader = 0; - rc = sqlite3_blob_reopen(pBlob, iRowid); + rc = tdsqlite3_blob_reopen(pBlob, iRowid); assert( p->pReader==0 ); p->pReader = pBlob; if( rc!=SQLITE_OK ){ - fts5CloseReader(p); + tdsqlite3Fts5IndexCloseReader(p); } if( rc==SQLITE_ABORT ) rc = SQLITE_OK; } @@ -190327,12 +218584,12 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){ ** to the requested entry. */ if( p->pReader==0 && rc==SQLITE_OK ){ Fts5Config *pConfig = p->pConfig; - rc = sqlite3_blob_open(pConfig->db, + rc = tdsqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader ); } - /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls + /* If either of the tdsqlite3_blob_open() or tdsqlite3_blob_reopen() calls ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead. ** All the reasons those functions might return SQLITE_ERROR - missing ** table, missing row, non-blob/text in block column - indicate @@ -190341,9 +218598,9 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){ if( rc==SQLITE_OK ){ u8 *aOut = 0; /* Read blob data into this buffer */ - int nByte = sqlite3_blob_bytes(p->pReader); - int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING; - pRet = (Fts5Data*)sqlite3_malloc(nAlloc); + int nByte = tdsqlite3_blob_bytes(p->pReader); + tdsqlite3_int64 nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING; + pRet = (Fts5Data*)tdsqlite3_malloc64(nAlloc); if( pRet ){ pRet->nn = nByte; aOut = pRet->p = (u8*)&pRet[1]; @@ -190352,13 +218609,15 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){ } if( rc==SQLITE_OK ){ - rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0); + rc = tdsqlite3_blob_read(p->pReader, aOut, nByte, 0); } if( rc!=SQLITE_OK ){ - sqlite3_free(pRet); + tdsqlite3_free(pRet); pRet = 0; }else{ /* TODO1: Fix this */ + pRet->p[nByte] = 0x00; + pRet->p[nByte+1] = 0x00; pRet->szLeaf = fts5GetU16(&pRet->p[2]); } } @@ -190375,13 +218634,13 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){ ** fts5DataRead(). */ static void fts5DataRelease(Fts5Data *pData){ - sqlite3_free(pData); + tdsqlite3_free(pData); } static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){ Fts5Data *pRet = fts5DataRead(p, iRowid); if( pRet ){ - if( pRet->szLeaf>pRet->nn ){ + if( pRet->nn<4 || pRet->szLeaf>pRet->nn ){ p->rc = FTS5_CORRUPT; fts5DataRelease(pRet); pRet = 0; @@ -190392,17 +218651,19 @@ static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){ static int fts5IndexPrepareStmt( Fts5Index *p, - sqlite3_stmt **ppStmt, + tdsqlite3_stmt **ppStmt, char *zSql ){ if( p->rc==SQLITE_OK ){ if( zSql ){ - p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0); + p->rc = tdsqlite3_prepare_v3(p->pConfig->db, zSql, -1, + SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB, + ppStmt, 0); }else{ p->rc = SQLITE_NOMEM; } } - sqlite3_free(zSql); + tdsqlite3_free(zSql); return p->rc; } @@ -190415,17 +218676,18 @@ static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){ if( p->pWriter==0 ){ Fts5Config *pConfig = p->pConfig; - fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf( + fts5IndexPrepareStmt(p, &p->pWriter, tdsqlite3_mprintf( "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)", pConfig->zDb, pConfig->zName )); if( p->rc ) return; } - sqlite3_bind_int64(p->pWriter, 1, iRowid); - sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC); - sqlite3_step(p->pWriter); - p->rc = sqlite3_reset(p->pWriter); + tdsqlite3_bind_int64(p->pWriter, 1, iRowid); + tdsqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC); + tdsqlite3_step(p->pWriter); + p->rc = tdsqlite3_reset(p->pWriter); + tdsqlite3_bind_null(p->pWriter, 2); } /* @@ -190437,28 +218699,18 @@ static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){ if( p->rc!=SQLITE_OK ) return; if( p->pDeleter==0 ){ - int rc; Fts5Config *pConfig = p->pConfig; - char *zSql = sqlite3_mprintf( + char *zSql = tdsqlite3_mprintf( "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?", pConfig->zDb, pConfig->zName ); - if( zSql==0 ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0); - sqlite3_free(zSql); - } - if( rc!=SQLITE_OK ){ - p->rc = rc; - return; - } + if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return; } - sqlite3_bind_int64(p->pDeleter, 1, iFirst); - sqlite3_bind_int64(p->pDeleter, 2, iLast); - sqlite3_step(p->pDeleter); - p->rc = sqlite3_reset(p->pDeleter); + tdsqlite3_bind_int64(p->pDeleter, 1, iFirst); + tdsqlite3_bind_int64(p->pDeleter, 2, iLast); + tdsqlite3_step(p->pDeleter); + p->rc = tdsqlite3_reset(p->pDeleter); } /* @@ -190470,15 +218722,15 @@ static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){ fts5DataDelete(p, iFirst, iLast); if( p->pIdxDeleter==0 ){ Fts5Config *pConfig = p->pConfig; - fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf( + fts5IndexPrepareStmt(p, &p->pIdxDeleter, tdsqlite3_mprintf( "DELETE FROM '%q'.'%q_idx' WHERE segid=?", pConfig->zDb, pConfig->zName )); } if( p->rc==SQLITE_OK ){ - sqlite3_bind_int(p->pIdxDeleter, 1, iSegid); - sqlite3_step(p->pIdxDeleter); - p->rc = sqlite3_reset(p->pIdxDeleter); + tdsqlite3_bind_int(p->pIdxDeleter, 1, iSegid); + tdsqlite3_step(p->pIdxDeleter); + p->rc = tdsqlite3_reset(p->pIdxDeleter); } } @@ -190491,9 +218743,9 @@ static void fts5StructureRelease(Fts5Structure *pStruct){ int i; assert( pStruct->nRef==0 ); for(i=0; i<pStruct->nLevel; i++){ - sqlite3_free(pStruct->aLevel[i].aSeg); + tdsqlite3_free(pStruct->aLevel[i].aSeg); } - sqlite3_free(pStruct); + tdsqlite3_free(pStruct); } } @@ -190524,28 +218776,33 @@ static int fts5StructureDecode( int iLvl; int nLevel = 0; int nSegment = 0; - int nByte; /* Bytes of space to allocate at pRet */ + tdsqlite3_int64 nByte; /* Bytes of space to allocate at pRet */ Fts5Structure *pRet = 0; /* Structure object to return */ /* Grab the cookie value */ - if( piCookie ) *piCookie = sqlite3Fts5Get32(pData); + if( piCookie ) *piCookie = tdsqlite3Fts5Get32(pData); i = 4; /* Read the total number of levels and segments from the start of the ** structure record. */ i += fts5GetVarint32(&pData[i], nLevel); i += fts5GetVarint32(&pData[i], nSegment); + if( nLevel>FTS5_MAX_SEGMENT || nLevel<0 + || nSegment>FTS5_MAX_SEGMENT || nSegment<0 + ){ + return FTS5_CORRUPT; + } nByte = ( sizeof(Fts5Structure) + /* Main structure */ sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */ ); - pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte); + pRet = (Fts5Structure*)tdsqlite3Fts5MallocZero(&rc, nByte); if( pRet ){ pRet->nRef = 1; pRet->nLevel = nLevel; pRet->nSegment = nSegment; - i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter); + i += tdsqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter); for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){ Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl]; @@ -190557,25 +218814,35 @@ static int fts5StructureDecode( }else{ i += fts5GetVarint32(&pData[i], pLvl->nMerge); i += fts5GetVarint32(&pData[i], nTotal); - assert( nTotal>=pLvl->nMerge ); - pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc, + if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT; + pLvl->aSeg = (Fts5StructureSegment*)tdsqlite3Fts5MallocZero(&rc, nTotal * sizeof(Fts5StructureSegment) ); + nSegment -= nTotal; } if( rc==SQLITE_OK ){ pLvl->nSeg = nTotal; for(iSeg=0; iSeg<nTotal; iSeg++){ + Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg]; if( i>=nData ){ rc = FTS5_CORRUPT; break; } - i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid); - i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst); - i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast); + i += fts5GetVarint32(&pData[i], pSeg->iSegid); + i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst); + i += fts5GetVarint32(&pData[i], pSeg->pgnoLast); + if( pSeg->pgnoLast<pSeg->pgnoFirst ){ + rc = FTS5_CORRUPT; + break; + } } + if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT; + if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT; } } + if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT; + if( rc!=SQLITE_OK ){ fts5StructureRelease(pRet); pRet = 0; @@ -190593,12 +218860,12 @@ static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){ if( *pRc==SQLITE_OK ){ Fts5Structure *pStruct = *ppStruct; int nLevel = pStruct->nLevel; - int nByte = ( + tdsqlite3_int64 nByte = ( sizeof(Fts5Structure) + /* Main structure */ sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */ ); - pStruct = sqlite3_realloc(pStruct, nByte); + pStruct = tdsqlite3_realloc64(pStruct, nByte); if( pStruct ){ memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel)); pStruct->nLevel++; @@ -190623,10 +218890,10 @@ static void fts5StructureExtendLevel( if( *pRc==SQLITE_OK ){ Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl]; Fts5StructureSegment *aNew; - int nByte; + tdsqlite3_int64 nByte; nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment); - aNew = sqlite3_realloc(pLvl->aSeg, nByte); + aNew = tdsqlite3_realloc64(pLvl->aSeg, nByte); if( aNew ){ if( bInsert==0 ){ memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra); @@ -190653,8 +218920,8 @@ static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){ /* TODO: Do we need this if the leaf-index is appended? Probably... */ memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING); p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet); - if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){ - p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie); + if( p->rc==SQLITE_OK && (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){ + p->rc = tdsqlite3Fts5ConfigLoad(pConfig, iCookie); } fts5DataRelease(pData); if( p->rc!=SQLITE_OK ){ @@ -190672,15 +218939,15 @@ static i64 fts5IndexDataVersion(Fts5Index *p){ if( p->rc==SQLITE_OK ){ if( p->pDataVersion==0 ){ p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion, - sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb) + tdsqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb) ); if( p->rc ) return 0; } - if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){ - iVersion = sqlite3_column_int64(p->pDataVersion, 0); + if( SQLITE_ROW==tdsqlite3_step(p->pDataVersion) ){ + iVersion = tdsqlite3_column_int64(p->pDataVersion, 0); } - p->rc = sqlite3_reset(p->pDataVersion); + p->rc = tdsqlite3_reset(p->pDataVersion); } return iVersion; @@ -190768,7 +219035,7 @@ static int fts5StructureCountSegments(Fts5Structure *pStruct){ } #define fts5BufferSafeAppendVarint(pBuf, iVal) { \ - (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \ + (pBuf)->n += tdsqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \ assert( (pBuf)->nSpace>=(pBuf)->n ); \ } @@ -190792,8 +219059,8 @@ static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){ iCookie = p->pConfig->iCookie; if( iCookie<0 ) iCookie = 0; - if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){ - sqlite3Fts5Put32(buf.p, iCookie); + if( 0==tdsqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){ + tdsqlite3Fts5Put32(buf.p, iCookie); buf.n = 4; fts5BufferSafeAppendVarint(&buf, pStruct->nLevel); fts5BufferSafeAppendVarint(&buf, pStruct->nSegment); @@ -191125,7 +219392,7 @@ static void fts5DlidxIterFree(Fts5DlidxIter *pIter){ for(i=0; i<pIter->nLvl; i++){ fts5DataRelease(pIter->aLvl[i].pData); } - sqlite3_free(pIter); + tdsqlite3_free(pIter); } } @@ -191140,10 +219407,10 @@ static Fts5DlidxIter *fts5DlidxIterInit( int bDone = 0; for(i=0; p->rc==SQLITE_OK && bDone==0; i++){ - int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl); + tdsqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl); Fts5DlidxIter *pNew; - pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte); + pNew = (Fts5DlidxIter*)tdsqlite3_realloc64(pIter, nByte); if( pNew==0 ){ p->rc = SQLITE_NOMEM; }else{ @@ -191288,7 +219555,7 @@ static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){ iOff = 4; a = pIter->pLeaf->p; } - iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid); + iOff += tdsqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid); pIter->iLeafOffset = iOff; } @@ -191313,12 +219580,13 @@ static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){ int nNew; /* Bytes of new data */ iOff += fts5GetVarint32(&a[iOff], nNew); - if( iOff+nNew>pIter->pLeaf->nn ){ + if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){ p->rc = FTS5_CORRUPT; return; } pIter->term.n = nKeep; fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]); + assert( pIter->term.n<=pIter->term.nSpace ); iOff += nNew; pIter->iTermLeafOffset = iOff; pIter->iTermLeafPgno = pIter->iLeafPgno; @@ -191383,7 +219651,7 @@ static void fts5SegIterInit( if( p->rc==SQLITE_OK ){ pIter->iLeafOffset = 4; assert_nc( pIter->pLeaf->nn>4 ); - assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 ); + assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 ); pIter->iPgidxOff = pIter->pLeaf->szLeaf+1; fts5SegIterLoadTerm(p, pIter, 0); fts5SegIterLoadNPos(p, pIter); @@ -191439,7 +219707,7 @@ static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){ /* If necessary, grow the pIter->aRowidOffset[] array. */ if( iRowidOffset>=pIter->nRowidOffset ){ int nNew = pIter->nRowidOffset + 8; - int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int)); + int *aNew = (int*)tdsqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int)); if( aNew==0 ){ p->rc = SQLITE_NOMEM; break; @@ -191579,7 +219847,7 @@ static void fts5SegIterNext_None( if( iOff<pIter->iEndofDoclist ){ /* Next entry is on the current page */ i64 iDelta; - iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta); + iOff += tdsqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta); pIter->iLeafOffset = iOff; pIter->iRowid += iDelta; }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){ @@ -191594,14 +219862,14 @@ static void fts5SegIterNext_None( const u8 *pList = 0; const char *zTerm = 0; int nList; - sqlite3Fts5HashScanNext(p->pHash); - sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList); + tdsqlite3Fts5HashScanNext(p->pHash); + tdsqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList); if( pList==0 ) goto next_none_eof; pIter->pLeaf->p = (u8*)pList; pIter->pLeaf->nn = nList; pIter->pLeaf->szLeaf = nList; pIter->iEndofDoclist = nList; - sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm); + tdsqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm); pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid); } @@ -191658,7 +219926,7 @@ static void fts5SegIterNext( } }else{ u64 iDelta; - iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta); + iOff += tdsqlite3Fts5GetVarint(&a[iOff], &iDelta); pIter->iRowid += iDelta; assert_nc( iDelta>0 ); } @@ -191670,8 +219938,8 @@ static void fts5SegIterNext( int nList = 0; assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm ); if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){ - sqlite3Fts5HashScanNext(p->pHash); - sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList); + tdsqlite3Fts5HashScanNext(p->pHash); + tdsqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList); } if( pList==0 ){ fts5DataRelease(pIter->pLeaf); @@ -191681,7 +219949,7 @@ static void fts5SegIterNext( pIter->pLeaf->nn = nList; pIter->pLeaf->szLeaf = nList; pIter->iEndofDoclist = nList+1; - sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm), + tdsqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm), (u8*)zTerm); pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid); *pbNewTerm = 1; @@ -191695,7 +219963,7 @@ static void fts5SegIterNext( if( pLeaf==0 ) break; ASSERT_SZLEAF_OK(pLeaf); if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){ - iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid); + iOff += tdsqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid); pIter->iLeafOffset = iOff; if( pLeaf->nn>pLeaf->szLeaf ){ @@ -191707,7 +219975,7 @@ static void fts5SegIterNext( else if( pLeaf->nn>pLeaf->szLeaf ){ pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32( &pLeaf->p[pLeaf->szLeaf], iOff - ); + ); pIter->iLeafOffset = iOff; pIter->iEndofDoclist = iOff; bNewTerm = 1; @@ -191741,6 +220009,7 @@ static void fts5SegIterNext( */ int nSz; assert( p->rc==SQLITE_OK ); + assert( pIter->iLeafOffset<=pIter->pLeaf->nn ); fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz); pIter->bDel = (nSz & 0x0001); pIter->nPos = nSz>>1; @@ -191892,10 +220161,10 @@ static void fts5LeafSeek( int szLeaf = pIter->pLeaf->szLeaf; int n = pIter->pLeaf->nn; - int nMatch = 0; - int nKeep = 0; - int nNew = 0; - int iTermOff; + u32 nMatch = 0; + u32 nKeep = 0; + u32 nNew = 0; + u32 iTermOff; int iPgidx; /* Current offset in pgidx */ int bEndOfPage = 0; @@ -191919,15 +220188,15 @@ static void fts5LeafSeek( assert( nKeep>=nMatch ); if( nKeep==nMatch ){ - int nCmp; - int i; - nCmp = MIN(nNew, nTerm-nMatch); + u32 nCmp; + u32 i; + nCmp = (u32)MIN(nNew, nTerm-nMatch); for(i=0; i<nCmp; i++){ if( a[iOff+i]!=pTerm[nMatch+i] ) break; } nMatch += i; - if( nTerm==nMatch ){ + if( (u32)nTerm==nMatch ){ if( i==nNew ){ goto search_success; }else{ @@ -191971,6 +220240,7 @@ static void fts5LeafSeek( iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff); if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){ p->rc = FTS5_CORRUPT; + return; }else{ nKeep = 0; iTermOff = iOff; @@ -191983,8 +220253,11 @@ static void fts5LeafSeek( } search_success: - pIter->iLeafOffset = iOff + nNew; + if( pIter->iLeafOffset>n || nNew<1 ){ + p->rc = FTS5_CORRUPT; + return; + } pIter->iTermLeafOffset = pIter->iLeafOffset; pIter->iTermLeafPgno = pIter->iLeafPgno; @@ -192004,10 +220277,10 @@ static void fts5LeafSeek( fts5SegIterLoadNPos(p, pIter); } -static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){ +static tdsqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){ if( p->pIdxSelect==0 ){ Fts5Config *pConfig = p->pConfig; - fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf( + fts5IndexPrepareStmt(p, &p->pIdxSelect, tdsqlite3_mprintf( "SELECT pgno FROM '%q'.'%q_idx' WHERE " "segid=? AND term<=? ORDER BY term DESC LIMIT 1", pConfig->zDb, pConfig->zName @@ -192033,7 +220306,7 @@ static void fts5SegIterSeekInit( int iPg = 1; int bGe = (flags & FTS5INDEX_QUERY_SCAN); int bDlidx = 0; /* True if there is a doclist-index */ - sqlite3_stmt *pIdxSelect = 0; + tdsqlite3_stmt *pIdxSelect = 0; assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 ); assert( pTerm && nTerm ); @@ -192044,14 +220317,15 @@ static void fts5SegIterSeekInit( ** contain term (pTerm/nTerm), if it is present in the segment. */ pIdxSelect = fts5IdxSelectStmt(p); if( p->rc ) return; - sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid); - sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC); - if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){ - i64 val = sqlite3_column_int(pIdxSelect, 0); + tdsqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid); + tdsqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC); + if( SQLITE_ROW==tdsqlite3_step(pIdxSelect) ){ + i64 val = tdsqlite3_column_int(pIdxSelect, 0); iPg = (int)(val>>1); bDlidx = (val & 0x0001); } - p->rc = sqlite3_reset(pIdxSelect); + p->rc = tdsqlite3_reset(pIdxSelect); + tdsqlite3_bind_null(pIdxSelect, 2); if( iPg<pSeg->pgnoFirst ){ iPg = pSeg->pgnoFirst; @@ -192090,7 +220364,7 @@ static void fts5SegIterSeekInit( ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points ** to an entry with a term greater than or equal to (pTerm/nTerm). */ - assert( p->rc!=SQLITE_OK /* 1 */ + assert_nc( p->rc!=SQLITE_OK /* 1 */ || pIter->pLeaf==0 /* 2 */ || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */ || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */ @@ -192111,31 +220385,40 @@ static void fts5SegIterHashInit( int flags, /* Mask of FTS5INDEX_XXX flags */ Fts5SegIter *pIter /* Object to populate */ ){ - const u8 *pList = 0; int nList = 0; const u8 *z = 0; int n = 0; + Fts5Data *pLeaf = 0; assert( p->pHash ); assert( p->rc==SQLITE_OK ); if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){ - p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm); - sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList); + const u8 *pList = 0; + + p->rc = tdsqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm); + tdsqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList); n = (z ? (int)strlen((const char*)z) : 0); + if( pList ){ + pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data)); + if( pLeaf ){ + pLeaf->p = (u8*)pList; + } + } }else{ - pIter->flags |= FTS5_SEGITER_ONETERM; - sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList); + p->rc = tdsqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data), + (const char*)pTerm, nTerm, (void**)&pLeaf, &nList + ); + if( pLeaf ){ + pLeaf->p = (u8*)&pLeaf[1]; + } z = pTerm; n = nTerm; + pIter->flags |= FTS5_SEGITER_ONETERM; } - if( pList ){ - Fts5Data *pLeaf; - sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z); - pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data)); - if( pLeaf==0 ) return; - pLeaf->p = (u8*)pList; + if( pLeaf ){ + tdsqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z); pLeaf->nn = pLeaf->szLeaf = nList; pIter->pLeaf = pLeaf; pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid); @@ -192160,7 +220443,7 @@ static void fts5SegIterClear(Fts5SegIter *pIter){ fts5DataRelease(pIter->pLeaf); fts5DataRelease(pIter->pNextLeaf); fts5DlidxIterFree(pIter->pDlidx); - sqlite3_free(pIter->aRowidOffset); + tdsqlite3_free(pIter->aRowidOffset); memset(pIter, 0, sizeof(Fts5SegIter)); } @@ -192188,7 +220471,7 @@ static void fts5AssertComparisonResult( assert( pRes->iFirst==i1 ); }else{ int nMin = MIN(p1->term.n, p2->term.n); - int res = memcmp(p1->term.p, p2->term.p, nMin); + int res = fts5Memcmp(p1->term.p, p2->term.p, nMin); if( res==0 ) res = p1->term.n - p2->term.n; if( res==0 ){ @@ -192288,8 +220571,8 @@ static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){ }else{ int res = fts5BufferCompare(&p1->term, &p2->term); if( res==0 ){ - assert( i2>i1 ); - assert( i2!=0 ); + assert_nc( i2>i1 ); + assert_nc( i2!=0 ); pRes->bTermEq = 1; if( p1->iRowid==p2->iRowid ){ p1->bDel = p2->bDel; @@ -192411,9 +220694,8 @@ static void fts5MultiIterFree(Fts5Iter *pIter){ for(i=0; i<pIter->nSeg; i++){ fts5SegIterClear(&pIter->aSeg[i]); } - fts5StructureRelease(pIter->pStruct); fts5BufferFree(&pIter->poslist); - sqlite3_free(pIter); + tdsqlite3_free(pIter); } } @@ -192546,7 +220828,8 @@ static void fts5MultiIterNext2( ){ assert( pIter->bSkipEmpty ); if( p->rc==SQLITE_OK ){ - do { + *pbNewTerm = 0; + do{ int iFirst = pIter->aFirst[1].iFirst; Fts5SegIter *pSeg = &pIter->aSeg[iFirst]; int bNewTerm = 0; @@ -192559,8 +220842,6 @@ static void fts5MultiIterNext2( fts5MultiIterAdvanced(p, pIter, iFirst, 1); fts5MultiIterSetEof(pIter); *pbNewTerm = 1; - }else{ - *pbNewTerm = 0; } fts5AssertMultiIterSetup(p, pIter); @@ -192735,7 +221016,7 @@ static void fts5ChunkIterate( break; }else{ pgno++; - pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno)); + pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno)); if( pData==0 ) break; pChunk = &pData->p[4]; nChunk = MIN(nRem, pData->szLeaf - 4); @@ -192760,7 +221041,8 @@ static void fts5SegiterPoslist( Fts5Colset *pColset, Fts5Buffer *pBuf ){ - if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){ + if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){ + memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING); if( pColset==0 ){ fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback); }else{ @@ -192826,23 +221108,23 @@ static int fts5IndexExtractCol( return p - (*pa); } -static int fts5IndexExtractColset ( +static void fts5IndexExtractColset( + int *pRc, Fts5Colset *pColset, /* Colset to filter on */ const u8 *pPos, int nPos, /* Position list */ Fts5Buffer *pBuf /* Output buffer */ ){ - int rc = SQLITE_OK; - int i; - - fts5BufferZero(pBuf); - for(i=0; i<pColset->nCol; i++){ - const u8 *pSub = pPos; - int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]); - if( nSub ){ - fts5BufferAppendBlob(&rc, pBuf, nSub, pSub); + if( *pRc==SQLITE_OK ){ + int i; + fts5BufferZero(pBuf); + for(i=0; i<pColset->nCol; i++){ + const u8 *pSub = pPos; + int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]); + if( nSub ){ + fts5BufferAppendBlob(pRc, pBuf, nSub, pSub); + } } } - return rc; } /* @@ -192966,8 +221248,9 @@ static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){ pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]); pIter->base.pData = a; }else{ + int *pRc = &pIter->pIndex->rc; fts5BufferZero(&pIter->poslist); - fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist); + fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist); pIter->base.pData = pIter->poslist.p; pIter->base.nData = pIter->poslist.n; } @@ -193005,7 +221288,7 @@ static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){ assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS ); if( pConfig->nCol<=100 ){ pIter->xSetOutputs = fts5IterSetOutputs_Col100; - sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol); + tdsqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol); }else{ pIter->xSetOutputs = fts5IterSetOutputs_Col; } @@ -193057,9 +221340,7 @@ static void fts5MultiIterNew( if( pNew==0 ) return; pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC)); pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY)); - pNew->pStruct = pStruct; pNew->pColset = pColset; - fts5StructureRef(pStruct); if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){ fts5IterSetOutputCb(&p->rc, pNew); } @@ -193237,33 +221518,34 @@ static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){ for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){ int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid; - if( iId<=FTS5_MAX_SEGMENT ){ - aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32); + if( iId<=FTS5_MAX_SEGMENT && iId>0 ){ + aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32); } } } for(i=0; aUsed[i]==0xFFFFFFFF; i++); mask = aUsed[i]; - for(iSegid=0; mask & (1 << iSegid); iSegid++); + for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++); iSegid += 1 + i*32; #ifdef SQLITE_DEBUG for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){ for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){ - assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid ); + assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid ); } } - assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT ); + assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT ); { - sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p); + tdsqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p); if( p->rc==SQLITE_OK ){ u8 aBlob[2] = {0xff, 0xff}; - sqlite3_bind_int(pIdxSelect, 1, iSegid); - sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC); - assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW ); - p->rc = sqlite3_reset(pIdxSelect); + tdsqlite3_bind_int(pIdxSelect, 1, iSegid); + tdsqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC); + assert_nc( tdsqlite3_step(pIdxSelect)!=SQLITE_ROW ); + p->rc = tdsqlite3_reset(pIdxSelect); + tdsqlite3_bind_null(pIdxSelect, 2); } } #endif @@ -193279,7 +221561,7 @@ static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){ static void fts5IndexDiscardData(Fts5Index *p){ assert( p->pHash || p->nPendingData==0 ); if( p->pHash ){ - sqlite3Fts5HashClear(p->pHash); + tdsqlite3Fts5HashClear(p->pHash); p->nPendingData = 0; } } @@ -193316,7 +221598,7 @@ static void fts5WriteDlidxClear( pDlidx->buf.p, pDlidx->buf.n ); } - sqlite3Fts5BufferZero(&pDlidx->buf); + tdsqlite3Fts5BufferZero(&pDlidx->buf); pDlidx->bPrevValid = 0; } } @@ -193331,13 +221613,13 @@ static int fts5WriteDlidxGrow( int nLvl ){ if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){ - Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc( + Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)tdsqlite3_realloc64( pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl ); if( aDlidx==0 ){ p->rc = SQLITE_NOMEM; }else{ - int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx); + size_t nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx); memset(&aDlidx[pWriter->nDlidx], 0, nByte); pWriter->aDlidx = aDlidx; pWriter->nDlidx = nLvl; @@ -193385,11 +221667,12 @@ static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){ if( p->rc==SQLITE_OK ){ const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:""); /* The following was already done in fts5WriteInit(): */ - /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */ - sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC); - sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1)); - sqlite3_step(p->pIdxWriter); - p->rc = sqlite3_reset(p->pIdxWriter); + /* tdsqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */ + tdsqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC); + tdsqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1)); + tdsqlite3_step(p->pIdxWriter); + p->rc = tdsqlite3_reset(p->pIdxWriter); + tdsqlite3_bind_null(p->pIdxWriter, 2); } pWriter->iBtPage = 0; } @@ -193409,8 +221692,10 @@ static void fts5WriteBtreeTerm( int nTerm, const u8 *pTerm /* First term on new page */ ){ fts5WriteFlushBtree(p, pWriter); - fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm); - pWriter->iBtPage = pWriter->writer.pgno; + if( p->rc==SQLITE_OK ){ + fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm); + pWriter->iBtPage = pWriter->writer.pgno; + } } /* @@ -193426,7 +221711,7 @@ static void fts5WriteBtreeNoTerm( if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){ Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0]; assert( pDlidx->bPrevValid ); - sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0); + tdsqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0); } /* Increment the "number of sequential leaves without a term" counter. */ @@ -193477,14 +221762,14 @@ static void fts5WriteDlidxAppend( /* This was the root node. Push its first rowid up to the new root. */ pDlidx[1].pgno = pDlidx->pgno; - sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0); - sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno); - sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst); + tdsqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0); + tdsqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno); + tdsqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst); pDlidx[1].bPrevValid = 1; pDlidx[1].iPrev = iFirst; } - sqlite3Fts5BufferZero(&pDlidx->buf); + tdsqlite3Fts5BufferZero(&pDlidx->buf); pDlidx->bPrevValid = 0; pDlidx->pgno++; }else{ @@ -193496,12 +221781,12 @@ static void fts5WriteDlidxAppend( }else{ i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno); assert( pDlidx->buf.n==0 ); - sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone); - sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno); + tdsqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone); + tdsqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno); iVal = iRowid; } - sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal); + tdsqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal); pDlidx->bPrevValid = 1; pDlidx->iPrev = iRowid; } @@ -193512,9 +221797,6 @@ static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){ Fts5PageWriter *pPage = &pWriter->writer; i64 iRowid; -static int nCall = 0; -nCall++; - assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) ); /* Set the szLeaf header field. */ @@ -193564,6 +221846,7 @@ static void fts5WriteAppendTerm( int nPrefix; /* Bytes of prefix compression for term */ Fts5PageWriter *pPage = &pWriter->writer; Fts5Buffer *pPgidx = &pWriter->writer.pgidx; + int nMin = MIN(pPage->term.n, nTerm); assert( p->rc==SQLITE_OK ); assert( pPage->buf.n>=4 ); @@ -193573,12 +221856,13 @@ static void fts5WriteAppendTerm( if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){ if( pPage->buf.n>4 ){ fts5WriteFlushLeaf(p, pWriter); + if( p->rc!=SQLITE_OK ) return; } fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING); } /* TODO1: Updating pgidx here. */ - pPgidx->n += sqlite3Fts5PutVarint( + pPgidx->n += tdsqlite3Fts5PutVarint( &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx ); pPage->iPrevPgidx = pPage->buf.n; @@ -193605,13 +221889,14 @@ static void fts5WriteAppendTerm( ** inefficient, but still correct. */ int n = nTerm; if( pPage->term.n ){ - n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm); + n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm); } fts5WriteBtreeTerm(p, pWriter, n, pTerm); + if( p->rc!=SQLITE_OK ) return; pPage = &pWriter->writer; } }else{ - nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm); + nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm); fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix); } @@ -193658,7 +221943,7 @@ static void fts5WriteAppendRowid( if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){ fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid); }else{ - assert( p->rc || iRowid>pWriter->iPrevRowid ); + assert_nc( p->rc || iRowid>pWriter->iPrevRowid ); fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid); } pWriter->iPrevRowid = iRowid; @@ -193724,9 +222009,9 @@ static void fts5WriteFinish( fts5BufferFree(&pWriter->btterm); for(i=0; i<pWriter->nDlidx; i++){ - sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf); + tdsqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf); } - sqlite3_free(pWriter->aDlidx); + tdsqlite3_free(pWriter->aDlidx); } static void fts5WriteInit( @@ -193748,12 +222033,12 @@ static void fts5WriteInit( assert( pWriter->writer.pgidx.n==0 ); /* Grow the two buffers to pgsz + padding bytes in size. */ - sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer); - sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer); + tdsqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer); + tdsqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer); if( p->pIdxWriter==0 ){ Fts5Config *pConfig = p->pConfig; - fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf( + fts5IndexPrepareStmt(p, &p->pIdxWriter, tdsqlite3_mprintf( "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)", pConfig->zDb, pConfig->zName )); @@ -193767,7 +222052,7 @@ static void fts5WriteInit( /* Bind the current output segment id to the index-writer. This is an ** optimization over binding the same value over and over as rows are ** inserted into %_idx by the current writer. */ - sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); + tdsqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); } } @@ -193780,7 +222065,7 @@ static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){ int i; Fts5Buffer buf; memset(&buf, 0, sizeof(Fts5Buffer)); - for(i=0; i<pIter->nSeg; i++){ + for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){ Fts5SegIter *pSeg = &pIter->aSeg[i]; if( pSeg->pSeg==0 ){ /* no-op */ @@ -193798,35 +222083,44 @@ static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){ u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00}; iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno); - pData = fts5DataRead(p, iLeafRowid); + pData = fts5LeafRead(p, iLeafRowid); if( pData ){ - fts5BufferZero(&buf); - fts5BufferGrow(&p->rc, &buf, pData->nn); - fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr); - fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n); - fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p); - fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]); - if( p->rc==SQLITE_OK ){ - /* Set the szLeaf field */ - fts5PutU16(&buf.p[2], (u16)buf.n); - } + if( iOff>pData->szLeaf ){ + /* This can occur if the pages that the segments occupy overlap - if + ** a single page has been assigned to more than one segment. In + ** this case a prior iteration of this loop may have corrupted the + ** segment currently being trimmed. */ + p->rc = FTS5_CORRUPT; + }else{ + fts5BufferZero(&buf); + fts5BufferGrow(&p->rc, &buf, pData->nn); + fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr); + fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n); + fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p); + fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff,&pData->p[iOff]); + if( p->rc==SQLITE_OK ){ + /* Set the szLeaf field */ + fts5PutU16(&buf.p[2], (u16)buf.n); + } - /* Set up the new page-index array */ - fts5BufferAppendVarint(&p->rc, &buf, 4); - if( pSeg->iLeafPgno==pSeg->iTermLeafPgno - && pSeg->iEndofDoclist<pData->szLeaf - ){ - int nDiff = pData->szLeaf - pSeg->iEndofDoclist; - fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4); - fts5BufferAppendBlob(&p->rc, &buf, - pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff] - ); - } + /* Set up the new page-index array */ + fts5BufferAppendVarint(&p->rc, &buf, 4); + if( pSeg->iLeafPgno==pSeg->iTermLeafPgno + && pSeg->iEndofDoclist<pData->szLeaf + && pSeg->iPgidxOff<=pData->nn + ){ + int nDiff = pData->szLeaf - pSeg->iEndofDoclist; + fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4); + fts5BufferAppendBlob(&p->rc, &buf, + pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff] + ); + } + pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno; + fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid); + fts5DataWrite(p, iLeafRowid, buf.p, buf.n); + } fts5DataRelease(pData); - pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno; - fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid); - fts5DataWrite(p, iLeafRowid, buf.p, buf.n); } } } @@ -193863,6 +222157,7 @@ static void fts5IndexMergeLevel( int bOldest; /* True if the output segment is the oldest */ int eDetail = p->pConfig->eDetail; const int flags = FTS5INDEX_QUERY_NOOUTPUT; + int bTermWritten = 0; /* True if current term already output */ assert( iLvl<pStruct->nLevel ); assert( pLvl->nMerge<=pLvl->nSeg ); @@ -193916,18 +222211,22 @@ static void fts5IndexMergeLevel( int nTerm; const u8 *pTerm; - /* Check for key annihilation. */ - if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue; - pTerm = fts5MultiIterTerm(pIter, &nTerm); - if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){ + if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){ if( pnRem && writer.nLeafWritten>nRem ){ break; } + fts5BufferSet(&p->rc, &term, nTerm, pTerm); + bTermWritten =0; + } + /* Check for key annihilation. */ + if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue; + + if( p->rc==SQLITE_OK && bTermWritten==0 ){ /* This is a new term. Append a term to the output segment. */ fts5WriteAppendTerm(p, &writer, nTerm, pTerm); - fts5BufferSet(&p->rc, &term, nTerm, pTerm); + bTermWritten = 1; } /* Append the rowid to the output */ @@ -194158,16 +222457,17 @@ static void fts5FlushOneHash(Fts5Index *p){ /* Begin scanning through hash table entries. This loop runs once for each ** term/doclist currently stored within the hash table. */ if( p->rc==SQLITE_OK ){ - p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0); + p->rc = tdsqlite3Fts5HashScanInit(pHash, 0, 0); } - while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){ + while( p->rc==SQLITE_OK && 0==tdsqlite3Fts5HashScanEof(pHash) ){ const char *zTerm; /* Buffer containing term */ const u8 *pDoclist; /* Pointer to doclist for this term */ int nDoclist; /* Size of doclist in bytes */ /* Write the term for this entry to disk. */ - sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist); + tdsqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist); fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm); + if( p->rc!=SQLITE_OK ) break; assert( writer.bFirstRowidInPage==0 ); if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){ @@ -194187,11 +222487,12 @@ static void fts5FlushOneHash(Fts5Index *p){ if( writer.bFirstRowidInPage ){ fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */ - pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid); + pBuf->n += tdsqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid); writer.bFirstRowidInPage = 0; fts5WriteDlidxAppend(p, &writer, iRowid); + if( p->rc!=SQLITE_OK ) break; }else{ - pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta); + pBuf->n += tdsqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta); } assert( pBuf->n<=pBuf->nSpace ); @@ -194247,9 +222548,9 @@ static void fts5FlushOneHash(Fts5Index *p){ /* TODO2: Doclist terminator written here. */ /* pBuf->p[pBuf->n++] = '\0'; */ assert( pBuf->n<=pBuf->nSpace ); - sqlite3Fts5HashScanNext(pHash); + if( p->rc==SQLITE_OK ) tdsqlite3Fts5HashScanNext(pHash); } - sqlite3Fts5HashClear(pHash); + tdsqlite3Fts5HashClear(pHash); fts5WriteFinish(p, &writer, &pgnoLast); /* Update the Fts5Structure. It is written back to the database by the @@ -194291,7 +222592,7 @@ static Fts5Structure *fts5IndexOptimizeStruct( Fts5Structure *pStruct ){ Fts5Structure *pNew = 0; - int nByte = sizeof(Fts5Structure); + tdsqlite3_int64 nByte = sizeof(Fts5Structure); int nSeg = pStruct->nSegment; int i; @@ -194316,7 +222617,7 @@ static Fts5Structure *fts5IndexOptimizeStruct( } nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel); - pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte); + pNew = (Fts5Structure*)tdsqlite3Fts5MallocZero(&p->rc, nByte); if( pNew ){ Fts5StructureLevel *pLvl; @@ -194325,7 +222626,7 @@ static Fts5Structure *fts5IndexOptimizeStruct( pNew->nRef = 1; pNew->nWriteCounter = pStruct->nWriteCounter; pLvl = &pNew->aLevel[pStruct->nLevel]; - pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte); + pLvl->aSeg = (Fts5StructureSegment*)tdsqlite3Fts5MallocZero(&p->rc, nByte); if( pLvl->aSeg ){ int iLvl, iSeg; int iSegOut = 0; @@ -194340,7 +222641,7 @@ static Fts5Structure *fts5IndexOptimizeStruct( } pNew->nSegment = pLvl->nSeg = nSeg; }else{ - sqlite3_free(pNew); + tdsqlite3_free(pNew); pNew = 0; } } @@ -194348,7 +222649,7 @@ static Fts5Structure *fts5IndexOptimizeStruct( return pNew; } -static int sqlite3Fts5IndexOptimize(Fts5Index *p){ +static int tdsqlite3Fts5IndexOptimize(Fts5Index *p){ Fts5Structure *pStruct; Fts5Structure *pNew = 0; @@ -194382,7 +222683,7 @@ static int sqlite3Fts5IndexOptimize(Fts5Index *p){ ** This is called to implement the special "VALUES('merge', $nMerge)" ** INSERT command. */ -static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){ +static int tdsqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){ Fts5Structure *pStruct = fts5StructureRead(p); if( pStruct ){ int nMin = p->pConfig->nUsermerge; @@ -194421,11 +222722,13 @@ static void fts5AppendPoslist( Fts5Buffer *pBuf ){ int nData = pMulti->base.nData; + int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING; assert( nData>0 ); - if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){ + if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){ fts5BufferSafeAppendVarint(pBuf, iDelta); fts5BufferSafeAppendVarint(pBuf, nData*2); fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData); + memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING); } } @@ -194505,7 +222808,7 @@ static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){ *piOff = -1; }else{ u64 iVal; - *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal); + *piOff = i + tdsqlite3Fts5GetVarint(&pBuf->p[i], &iVal); *piRowid += iVal; } } @@ -194527,7 +222830,7 @@ static void fts5MergeRowidLists( Fts5Buffer out; memset(&out, 0, sizeof(out)); - sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n); + tdsqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n); if( p->rc ) return; fts5NextRowid(p1, &i1, &iRowid1); @@ -194573,7 +222876,19 @@ static void fts5MergePrefixLists( Fts5Buffer out = {0, 0, 0}; Fts5Buffer tmp = {0, 0, 0}; - if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return; + /* The maximum size of the output is equal to the sum of the two + ** input sizes + 1 varint (9 bytes). The extra varint is because if the + ** first rowid in one input is a large negative number, and the first in + ** the other a non-negative number, the delta for the non-negative + ** number will be larger on disk than the literal integer value + ** was. + ** + ** Or, if the input position-lists are corrupt, then the output might + ** include up to 2 extra 10-byte positions created by interpreting -1 + ** (the value PoslistNext64() uses for EOF) as a position and appending + ** it to the output. This can happen at most once for each input + ** position-list, hence two 10 byte paddings. */ + if( tdsqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9+10+10) ) return; fts5DoclistIterInit(p1, &i1); fts5DoclistIterInit(p2, &i2); @@ -194584,6 +222899,7 @@ static void fts5MergePrefixLists( fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize); fts5DoclistIterNext(&i1); if( i1.aPoslist==0 ) break; + assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) ); } else if( i2.iRowid!=i1.iRowid ){ /* Copy entry from i2 */ @@ -194591,6 +222907,7 @@ static void fts5MergePrefixLists( fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize); fts5DoclistIterNext(&i2); if( i2.aPoslist==0 ) break; + assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) ); } else{ /* Merge the two position lists. */ @@ -194600,40 +222917,44 @@ static void fts5MergePrefixLists( int iOff2 = 0; u8 *a1 = &i1.aPoslist[i1.nSize]; u8 *a2 = &i2.aPoslist[i2.nSize]; + int nCopy; + u8 *aCopy; i64 iPrev = 0; Fts5PoslistWriter writer; memset(&writer, 0, sizeof(writer)); + /* See the earlier comment in this function for an explanation of why + ** corrupt input position lists might cause the output to consume + ** at most 20 bytes of unexpected space. */ fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid); fts5BufferZero(&tmp); - sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist); + tdsqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist + 10 + 10); if( p->rc ) break; - sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1); - sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2); - assert( iPos1>=0 && iPos2>=0 ); + tdsqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1); + tdsqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2); + assert_nc( iPos1>=0 && iPos2>=0 ); if( iPos1<iPos2 ){ - sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1); - sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1); + tdsqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1); + tdsqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1); }else{ - sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2); - sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2); + tdsqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2); + tdsqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2); } - if( iPos1>=0 && iPos2>=0 ){ while( 1 ){ if( iPos1<iPos2 ){ if( iPos1!=iPrev ){ - sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1); + tdsqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1); } - sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1); + tdsqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1); if( iPos1<0 ) break; }else{ - assert( iPos2!=iPrev ); - sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2); - sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2); + assert_nc( iPos2!=iPrev ); + tdsqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2); + tdsqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2); if( iPos2<0 ) break; } } @@ -194641,21 +222962,34 @@ static void fts5MergePrefixLists( if( iPos1>=0 ){ if( iPos1!=iPrev ){ - sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1); + tdsqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1); } - fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1); + aCopy = &a1[iOff1]; + nCopy = i1.nPoslist - iOff1; }else{ - assert( iPos2>=0 && iPos2!=iPrev ); - sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2); - fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2); + assert_nc( iPos2>=0 && iPos2!=iPrev ); + tdsqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2); + aCopy = &a2[iOff2]; + nCopy = i2.nPoslist - iOff2; + } + if( nCopy>0 ){ + fts5BufferSafeAppendBlob(&tmp, aCopy, nCopy); } /* WRITEPOSLISTSIZE */ + assert_nc( tmp.n<=i1.nPoslist+i2.nPoslist ); + assert( tmp.n<=i1.nPoslist+i2.nPoslist+10+10 ); + if( tmp.n>i1.nPoslist+i2.nPoslist ){ + if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT; + break; + } fts5BufferSafeAppendVarint(&out, tmp.n * 2); fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n); fts5DoclistIterNext(&i1); fts5DoclistIterNext(&i2); + assert_nc( out.n<=(p1->n+p2->n+9) ); if( i1.aPoslist==0 || i2.aPoslist==0 ) break; + assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) ); } } @@ -194667,6 +223001,7 @@ static void fts5MergePrefixLists( fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid); fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist); } + assert_nc( out.n<=(p1->n+p2->n+9) ); fts5BufferSet(&p->rc, p1, out.n, out.p); fts5BufferFree(&tmp); @@ -194755,31 +223090,31 @@ static void fts5SetupPrefixIter( } fts5MultiIterFree(p1); - pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n); + pData = fts5IdxMalloc(p, sizeof(Fts5Data)+doclist.n+FTS5_DATA_ZERO_PADDING); if( pData ){ pData->p = (u8*)&pData[1]; pData->nn = pData->szLeaf = doclist.n; - memcpy(pData->p, doclist.p, doclist.n); + if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n); fts5MultiIterNew2(p, pData, bDesc, ppIter); } fts5BufferFree(&doclist); } fts5StructureRelease(pStruct); - sqlite3_free(aBuf); + tdsqlite3_free(aBuf); } /* -** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain +** Indicate that all subsequent calls to tdsqlite3Fts5IndexWrite() pertain ** to the document with rowid iRowid. */ -static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){ +static int tdsqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){ assert( p->rc==SQLITE_OK ); /* Allocate the hash table if it has not already been allocated */ if( p->pHash==0 ){ - p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData); + p->rc = tdsqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData); } /* Flush the hash table to disk if required */ @@ -194798,10 +223133,10 @@ static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){ /* ** Commit data to disk. */ -static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){ +static int tdsqlite3Fts5IndexSync(Fts5Index *p){ assert( p->rc==SQLITE_OK ); fts5IndexFlush(p); - if( bCommit ) fts5CloseReader(p); + tdsqlite3Fts5IndexCloseReader(p); return fts5IndexReturn(p); } @@ -194811,8 +223146,8 @@ static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){ ** table may have changed on disk. So any in-memory caches of %_data ** records must be invalidated. */ -static int sqlite3Fts5IndexRollback(Fts5Index *p){ - fts5CloseReader(p); +static int tdsqlite3Fts5IndexRollback(Fts5Index *p){ + tdsqlite3Fts5IndexCloseReader(p); fts5IndexDiscardData(p); fts5StructureInvalidate(p); /* assert( p->rc==SQLITE_OK ); */ @@ -194824,9 +223159,10 @@ static int sqlite3Fts5IndexRollback(Fts5Index *p){ ** function populates it with the initial structure objects for each index, ** and the initial version of the "averages" record (a zero-byte blob). */ -static int sqlite3Fts5IndexReinit(Fts5Index *p){ +static int tdsqlite3Fts5IndexReinit(Fts5Index *p){ Fts5Structure s; fts5StructureInvalidate(p); + fts5IndexDiscardData(p); memset(&s, 0, sizeof(Fts5Structure)); fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0); fts5StructureWrite(p, &s); @@ -194840,7 +223176,7 @@ static int sqlite3Fts5IndexReinit(Fts5Index *p){ ** If successful, set *pp to point to the new object and return SQLITE_OK. ** Otherwise, set *pp to NULL and return an SQLite error code. */ -static int sqlite3Fts5IndexOpen( +static int tdsqlite3Fts5IndexOpen( Fts5Config *pConfig, int bCreate, Fts5Index **pp, @@ -194849,52 +223185,52 @@ static int sqlite3Fts5IndexOpen( int rc = SQLITE_OK; Fts5Index *p; /* New object */ - *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index)); + *pp = p = (Fts5Index*)tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5Index)); if( rc==SQLITE_OK ){ p->pConfig = pConfig; p->nWorkUnit = FTS5_WORK_UNIT; - p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName); + p->zDataTbl = tdsqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName); if( p->zDataTbl && bCreate ){ - rc = sqlite3Fts5CreateTable( + rc = tdsqlite3Fts5CreateTable( pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr ); if( rc==SQLITE_OK ){ - rc = sqlite3Fts5CreateTable(pConfig, "idx", + rc = tdsqlite3Fts5CreateTable(pConfig, "idx", "segid, term, pgno, PRIMARY KEY(segid, term)", 1, pzErr ); } if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IndexReinit(p); + rc = tdsqlite3Fts5IndexReinit(p); } } } assert( rc!=SQLITE_OK || p->rc==SQLITE_OK ); if( rc ){ - sqlite3Fts5IndexClose(p); + tdsqlite3Fts5IndexClose(p); *pp = 0; } return rc; } /* -** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen(). +** Close a handle opened by an earlier call to tdsqlite3Fts5IndexOpen(). */ -static int sqlite3Fts5IndexClose(Fts5Index *p){ +static int tdsqlite3Fts5IndexClose(Fts5Index *p){ int rc = SQLITE_OK; if( p ){ assert( p->pReader==0 ); fts5StructureInvalidate(p); - sqlite3_finalize(p->pWriter); - sqlite3_finalize(p->pDeleter); - sqlite3_finalize(p->pIdxWriter); - sqlite3_finalize(p->pIdxDeleter); - sqlite3_finalize(p->pIdxSelect); - sqlite3_finalize(p->pDataVersion); - sqlite3Fts5HashFree(p->pHash); - sqlite3_free(p->zDataTbl); - sqlite3_free(p); + tdsqlite3_finalize(p->pWriter); + tdsqlite3_finalize(p->pDeleter); + tdsqlite3_finalize(p->pIdxWriter); + tdsqlite3_finalize(p->pIdxDeleter); + tdsqlite3_finalize(p->pIdxSelect); + tdsqlite3_finalize(p->pDataVersion); + tdsqlite3Fts5HashFree(p->pHash); + tdsqlite3_free(p->zDataTbl); + tdsqlite3_free(p); } return rc; } @@ -194904,7 +223240,7 @@ static int sqlite3Fts5IndexClose(Fts5Index *p){ ** size. Return the number of bytes in the nChar character prefix of the ** buffer, or 0 if there are less than nChar characters in total. */ -static int sqlite3Fts5IndexCharlenToBytelen( +static int tdsqlite3Fts5IndexCharlenToBytelen( const char *p, int nByte, int nChar @@ -194914,7 +223250,14 @@ static int sqlite3Fts5IndexCharlenToBytelen( for(i=0; i<nChar; i++){ if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */ if( (unsigned char)p[n++]>=0xc0 ){ - while( (p[n] & 0xc0)==0x80 ) n++; + if( n>=nByte ) return 0; + while( (p[n] & 0xc0)==0x80 ){ + n++; + if( n>=nByte ){ + if( i+1==nChar ) break; + return 0; + } + } } } return n; @@ -194946,7 +223289,7 @@ static int fts5IndexCharlen(const char *pIn, int nIn){ ** unique token in the document with an iCol value less than zero. The iPos ** argument is ignored for a delete. */ -static int sqlite3Fts5IndexWrite( +static int tdsqlite3Fts5IndexWrite( Fts5Index *p, /* Index to write to */ int iCol, /* Column token appears in (-ve -> delete) */ int iPos, /* Position of token within column */ @@ -194960,15 +223303,15 @@ static int sqlite3Fts5IndexWrite( assert( (iCol<0)==p->bDelete ); /* Add the entry to the main terms index. */ - rc = sqlite3Fts5HashWrite( + rc = tdsqlite3Fts5HashWrite( p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken ); for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){ const int nChar = pConfig->aPrefix[i]; - int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar); + int nByte = tdsqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar); if( nByte ){ - rc = sqlite3Fts5HashWrite(p->pHash, + rc = tdsqlite3Fts5HashWrite(p->pHash, p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken, nByte ); @@ -194982,7 +223325,7 @@ static int sqlite3Fts5IndexWrite( ** Open a new iterator to iterate though all rowid that match the ** specified token or token prefix. */ -static int sqlite3Fts5IndexQuery( +static int tdsqlite3Fts5IndexQuery( Fts5Index *p, /* FTS index to query */ const char *pToken, int nToken, /* Token (or prefix) to query for */ int flags, /* Mask of FTS5INDEX_QUERY_X flags */ @@ -194996,9 +223339,9 @@ static int sqlite3Fts5IndexQuery( /* If the QUERY_SCAN flag is set, all other flags must be clear. */ assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN ); - if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){ + if( tdsqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){ int iIdx = 0; /* Index to search */ - memcpy(&buf.p[1], pToken, nToken); + if( nToken ) memcpy(&buf.p[1], pToken, nToken); /* Figure out which index to search and set iIdx accordingly. If this ** is a prefix query for which there is no prefix index, set iIdx to @@ -195047,13 +223390,13 @@ static int sqlite3Fts5IndexQuery( } if( p->rc ){ - sqlite3Fts5IterClose(&pRet->base); + tdsqlite3Fts5IterClose((Fts5IndexIter*)pRet); pRet = 0; - fts5CloseReader(p); + tdsqlite3Fts5IndexCloseReader(p); } - *ppIter = &pRet->base; - sqlite3Fts5BufferFree(&buf); + *ppIter = (Fts5IndexIter*)pRet; + tdsqlite3Fts5BufferFree(&buf); } return fts5IndexReturn(p); } @@ -195064,7 +223407,7 @@ static int sqlite3Fts5IndexQuery( /* ** Move to the next matching rowid. */ -static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){ +static int tdsqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; assert( pIter->pIndex->rc==SQLITE_OK ); fts5MultiIterNext(pIter->pIndex, pIter, 0, 0); @@ -195074,7 +223417,7 @@ static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){ /* ** Move to the next matching term/rowid. Used by the fts5vocab module. */ -static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){ +static int tdsqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; Fts5Index *p = pIter->pIndex; @@ -195098,7 +223441,7 @@ static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){ ** definition of "at or after" depends on whether this iterator iterates ** in ascending or descending rowid order. */ -static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){ +static int tdsqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch); return fts5IndexReturn(pIter->pIndex); @@ -195107,7 +223450,7 @@ static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){ /* ** Return the current term. */ -static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){ +static const char *tdsqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){ int n; const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n); *pn = n-1; @@ -195115,14 +223458,14 @@ static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){ } /* -** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery(). +** Close an iterator opened by an earlier call to tdsqlite3Fts5IndexQuery(). */ -static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){ +static void tdsqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){ if( pIndexIter ){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; Fts5Index *pIndex = pIter->pIndex; fts5MultiIterFree(pIter); - fts5CloseReader(pIndex); + tdsqlite3Fts5IndexCloseReader(pIndex); } } @@ -195132,7 +223475,7 @@ static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){ ** Parameter anSize must point to an array of size nCol, where nCol is ** the number of user defined columns in the FTS table. */ -static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){ +static int tdsqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){ int nCol = p->pConfig->nCol; Fts5Data *pData; @@ -195156,7 +223499,7 @@ static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){ ** Replace the current "averages" record with the contents of the buffer ** supplied as the second argument. */ -static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){ +static int tdsqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){ assert( p->rc==SQLITE_OK ); fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData); return fts5IndexReturn(p); @@ -195166,7 +223509,7 @@ static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData) ** Return the total number of blocks this module has read from the %_data ** table since it was created. */ -static int sqlite3Fts5IndexReads(Fts5Index *p){ +static int tdsqlite3Fts5IndexReads(Fts5Index *p){ return p->nRead; } @@ -195177,27 +223520,27 @@ static int sqlite3Fts5IndexReads(Fts5Index *p){ ** Return SQLITE_OK if successful, or an SQLite error code if an error ** occurs. */ -static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){ +static int tdsqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){ int rc; /* Return code */ Fts5Config *pConfig = p->pConfig; /* Configuration object */ u8 aCookie[4]; /* Binary representation of iNew */ - sqlite3_blob *pBlob = 0; + tdsqlite3_blob *pBlob = 0; assert( p->rc==SQLITE_OK ); - sqlite3Fts5Put32(aCookie, iNew); + tdsqlite3Fts5Put32(aCookie, iNew); - rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, + rc = tdsqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, "block", FTS5_STRUCTURE_ROWID, 1, &pBlob ); if( rc==SQLITE_OK ){ - sqlite3_blob_write(pBlob, aCookie, 4, 0); - rc = sqlite3_blob_close(pBlob); + tdsqlite3_blob_write(pBlob, aCookie, 4, 0); + rc = tdsqlite3_blob_close(pBlob); } return rc; } -static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){ +static int tdsqlite3Fts5IndexLoadConfig(Fts5Index *p){ Fts5Structure *pStruct; pStruct = fts5StructureRead(p); fts5StructureRelease(pStruct); @@ -195214,7 +223557,7 @@ static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){ /* ** Return a simple checksum value based on the arguments. */ -static u64 sqlite3Fts5IndexEntryCksum( +static u64 tdsqlite3Fts5IndexEntryCksum( i64 iRowid, int iCol, int iPos, @@ -195287,34 +223630,65 @@ static int fts5QueryCksum( int eDetail = p->pConfig->eDetail; u64 cksum = *pCksum; Fts5IndexIter *pIter = 0; - int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter); + int rc = tdsqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter); - while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){ + while( rc==SQLITE_OK && 0==tdsqlite3Fts5IterEof(pIter) ){ i64 rowid = pIter->iRowid; if( eDetail==FTS5_DETAIL_NONE ){ - cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n); + cksum ^= tdsqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n); }else{ Fts5PoslistReader sReader; - for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader); + for(tdsqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader); sReader.bEof==0; - sqlite3Fts5PoslistReaderNext(&sReader) + tdsqlite3Fts5PoslistReaderNext(&sReader) ){ int iCol = FTS5_POS2COLUMN(sReader.iPos); int iOff = FTS5_POS2OFFSET(sReader.iPos); - cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n); + cksum ^= tdsqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n); } } if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IterNext(pIter); + rc = tdsqlite3Fts5IterNext(pIter); } } - sqlite3Fts5IterClose(pIter); + tdsqlite3Fts5IterClose(pIter); *pCksum = cksum; return rc; } +/* +** Check if buffer z[], size n bytes, contains as series of valid utf-8 +** encoded codepoints. If so, return 0. Otherwise, if the buffer does not +** contain valid utf-8, return non-zero. +*/ +static int fts5TestUtf8(const char *z, int n){ + assert_nc( n>0 ); + int i = 0; + while( i<n ){ + if( (z[i] & 0x80)==0x00 ){ + i++; + }else + if( (z[i] & 0xE0)==0xC0 ){ + if( i+1>=n || (z[i+1] & 0xC0)!=0x80 ) return 1; + i += 2; + }else + if( (z[i] & 0xF0)==0xE0 ){ + if( i+2>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1; + i += 3; + }else + if( (z[i] & 0xF8)==0xF0 ){ + if( i+3>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1; + if( (z[i+2] & 0xC0)!=0x80 ) return 1; + i += 3; + }else{ + return 1; + } + } + + return 0; +} /* ** This function is also purely an internal test. It does not contribute to @@ -195355,8 +223729,14 @@ static void fts5TestTerm( ** This check may only be performed if the hash table is empty. This ** is because the hash table only supports a single scan query at ** a time, and the multi-iter loop from which this function is called - ** is already performing such a scan. */ - if( p->nPendingData==0 ){ + ** is already performing such a scan. + ** + ** Also only do this if buffer zTerm contains nTerm bytes of valid + ** utf-8. Otherwise, the last part of the buffer contents might contain + ** a non-utf-8 sequence that happens to be a prefix of a valid utf-8 + ** character stored in the main fts index, which will cause the + ** test to fail. */ + if( p->nPendingData==0 && 0==fts5TestUtf8(zTerm, nTerm) ){ if( iIdx>0 && rc==SQLITE_OK ){ int f = flags|FTS5INDEX_QUERY_TEST_NOIDX; ck2 = 0; @@ -195471,33 +223851,34 @@ static void fts5IndexIntegrityCheckSegment( Fts5StructureSegment *pSeg /* Segment to check internal consistency */ ){ Fts5Config *pConfig = p->pConfig; - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; int rc2; int iIdxPrevLeaf = pSeg->pgnoFirst-1; int iDlidxPrevLeaf = pSeg->pgnoLast; if( pSeg->pgnoFirst==0 ) return; - fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf( - "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d", + fts5IndexPrepareStmt(p, &pStmt, tdsqlite3_mprintf( + "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d " + "ORDER BY 1, 2", pConfig->zDb, pConfig->zName, pSeg->iSegid )); /* Iterate through the b-tree hierarchy. */ - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ + while( p->rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pStmt) ){ i64 iRow; /* Rowid for this leaf */ Fts5Data *pLeaf; /* Data for this leaf */ - int nIdxTerm = sqlite3_column_bytes(pStmt, 1); - const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1); - int iIdxLeaf = sqlite3_column_int(pStmt, 2); - int bIdxDlidx = sqlite3_column_int(pStmt, 3); + const char *zIdxTerm = (const char*)tdsqlite3_column_blob(pStmt, 1); + int nIdxTerm = tdsqlite3_column_bytes(pStmt, 1); + int iIdxLeaf = tdsqlite3_column_int(pStmt, 2); + int bIdxDlidx = tdsqlite3_column_int(pStmt, 3); /* If the leaf in question has already been trimmed from the segment, ** ignore this b-tree entry. Otherwise, load it into memory. */ if( iIdxLeaf<pSeg->pgnoFirst ) continue; iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf); - pLeaf = fts5DataRead(p, iRow); + pLeaf = fts5LeafRead(p, iRow); if( pLeaf==0 ) break; /* Check that the leaf contains at least one term, and that it is equal @@ -195514,11 +223895,11 @@ static void fts5IndexIntegrityCheckSegment( iOff = fts5LeafFirstTermOff(pLeaf); iRowidOff = fts5LeafFirstRowidOff(pLeaf); - if( iRowidOff>=iOff ){ + if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){ p->rc = FTS5_CORRUPT; }else{ iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm); - res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm)); + res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm)); if( res==0 ) res = nTerm - nIdxTerm; if( res<0 ) p->rc = FTS5_CORRUPT; } @@ -195588,7 +223969,7 @@ static void fts5IndexIntegrityCheckSegment( iIdxPrevLeaf = iIdxLeaf; } - rc2 = sqlite3_finalize(pStmt); + rc2 = tdsqlite3_finalize(pStmt); if( p->rc==SQLITE_OK ) p->rc = rc2; /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */ @@ -195603,14 +223984,14 @@ static void fts5IndexIntegrityCheckSegment( /* ** Run internal checks to ensure that the FTS index (a) is internally ** consistent and (b) contains entries for which the XOR of the checksums -** as calculated by sqlite3Fts5IndexEntryCksum() is cksum. +** as calculated by tdsqlite3Fts5IndexEntryCksum() is cksum. ** ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the ** checksum does not match. Return SQLITE_OK if all checks pass without ** error, or some other SQLite error code if another error (e.g. OOM) ** occurs. */ -static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){ +static int tdsqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){ int eDetail = p->pConfig->eDetail; u64 cksum2 = 0; /* Checksum based on contents of indexes */ Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */ @@ -195666,15 +224047,15 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){ if( eDetail==FTS5_DETAIL_NONE ){ if( 0==fts5MultiIterIsEmpty(p, pIter) ){ - cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n); + cksum2 ^= tdsqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n); } }else{ poslist.n = 0; fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist); - while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){ + while( 0==tdsqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){ int iCol = FTS5_POS2COLUMN(iPos); int iTokOff = FTS5_POS2OFFSET(iPos); - cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n); + cksum2 ^= tdsqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n); } } } @@ -195726,13 +224107,13 @@ static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){ if( iSegid==0 ){ if( iKey==FTS5_AVERAGES_ROWID ){ - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} "); + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} "); }else{ - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}"); + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}"); } } else{ - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}", + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}", bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno ); } @@ -195747,16 +224128,16 @@ static void fts5DebugStructure( for(iLvl=0; iLvl<p->nLevel; iLvl++){ Fts5StructureLevel *pLvl = &p->aLevel[iLvl]; - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg ); for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){ Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg]; - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}", + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}", pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast ); } - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}"); + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}"); } } @@ -195802,8 +224183,8 @@ static void fts5DecodeAverages( while( i<nBlob ){ u64 iVal; - i += sqlite3Fts5GetVarint(&pBlob[i], &iVal); - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal); + i += tdsqlite3Fts5GetVarint(&pBlob[i], &iVal); + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal); zSpace = " "; } } @@ -195820,7 +224201,7 @@ static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){ while( iOff<n ){ int iVal; iOff += fts5GetVarint32(&a[iOff], iVal); - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal); + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal); } return iOff; } @@ -195838,20 +224219,20 @@ static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){ int iOff = 0; if( n>0 ){ - iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid); - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid); + iOff = tdsqlite3Fts5GetVarint(a, (u64*)&iDocid); + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid); } while( iOff<n ){ int nPos; int bDel; iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel); - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":""); + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":""); iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos)); if( iOff<n ){ i64 iDelta; - iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta); + iOff += tdsqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta); iDocid += iDelta; - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid); + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid); } } @@ -195882,7 +224263,7 @@ static void fts5DecodeRowidList( while( i<nData ){ const char *zApp = ""; u64 iVal; - i += sqlite3Fts5GetVarint(&pData[i], &iVal); + i += tdsqlite3Fts5GetVarint(&pData[i], &iVal); iRowid += iVal; if( i<nData && pData[i]==0x00 ){ @@ -195895,7 +224276,7 @@ static void fts5DecodeRowidList( } } - sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp); + tdsqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp); } } @@ -195903,9 +224284,9 @@ static void fts5DecodeRowidList( ** The implementation of user-defined scalar function fts5_decode(). */ static void fts5DecodeFunction( - sqlite3_context *pCtx, /* Function call context */ + tdsqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args (always 2) */ - sqlite3_value **apVal /* Function arguments */ + tdsqlite3_value **apVal /* Function arguments */ ){ i64 iRowid; /* Rowid for record being decoded */ int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */ @@ -195913,24 +224294,23 @@ static void fts5DecodeFunction( u8 *a = 0; Fts5Buffer s; /* Build up text to return here */ int rc = SQLITE_OK; /* Return code */ - int nSpace = 0; - int eDetailNone = (sqlite3_user_data(pCtx)!=0); + tdsqlite3_int64 nSpace = 0; + int eDetailNone = (tdsqlite3_user_data(pCtx)!=0); assert( nArg==2 ); UNUSED_PARAM(nArg); memset(&s, 0, sizeof(Fts5Buffer)); - iRowid = sqlite3_value_int64(apVal[0]); + iRowid = tdsqlite3_value_int64(apVal[0]); /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[] ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents ** buffer overreads even if the record is corrupt. */ - n = sqlite3_value_bytes(apVal[1]); - aBlob = sqlite3_value_blob(apVal[1]); + n = tdsqlite3_value_bytes(apVal[1]); + aBlob = tdsqlite3_value_blob(apVal[1]); nSpace = n + FTS5_DATA_ZERO_PADDING; - a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace); + a = (u8*)tdsqlite3Fts5MallocZero(&rc, nSpace); if( a==0 ) goto decode_out; - memcpy(a, aBlob, n); - + if( n>0 ) memcpy(a, aBlob, n); fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno); @@ -195947,7 +224327,7 @@ static void fts5DecodeFunction( lvl.iLeafPgno = iPgno; for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){ - sqlite3Fts5BufferAppendPrintf(&rc, &s, + tdsqlite3Fts5BufferAppendPrintf(&rc, &s, " %d(%lld)", lvl.iLeafPgno, lvl.iRowid ); } @@ -195983,7 +224363,7 @@ static void fts5DecodeFunction( iOff += fts5GetVarint32(&a[iOff], nAppend); term.n = nKeep; fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]); - sqlite3Fts5BufferAppendPrintf( + tdsqlite3Fts5BufferAppendPrintf( &rc, &s, " term=%.*s", term.n, (const char*)term.p ); iOff += nAppend; @@ -196018,13 +224398,16 @@ static void fts5DecodeFunction( memset(&term, 0, sizeof(Fts5Buffer)); if( n<4 ){ - sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt"); + tdsqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt"); goto decode_out; }else{ iRowidOff = fts5GetU16(&a[0]); iPgidxOff = szLeaf = fts5GetU16(&a[2]); if( iPgidxOff<n ){ fts5GetVarint32(&a[iPgidxOff], iTermOff); + }else if( iPgidxOff>n ){ + rc = FTS5_CORRUPT; + goto decode_out; } } @@ -196036,14 +224419,22 @@ static void fts5DecodeFunction( }else{ iOff = szLeaf; } + if( iOff>n ){ + rc = FTS5_CORRUPT; + goto decode_out; + } fts5DecodePoslist(&rc, &s, &a[4], iOff-4); /* Decode any more doclist data that appears on the page before the ** first term. */ nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff; + if( nDoclist+iOff>n ){ + rc = FTS5_CORRUPT; + goto decode_out; + } fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist); - while( iPgidxOff<n ){ + while( iPgidxOff<n && rc==SQLITE_OK ){ int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */ int nByte; /* Bytes of data */ int iEnd; @@ -196058,16 +224449,28 @@ static void fts5DecodeFunction( }else{ iEnd = szLeaf; } + if( iEnd>szLeaf ){ + rc = FTS5_CORRUPT; + break; + } if( bFirst==0 ){ iOff += fts5GetVarint32(&a[iOff], nByte); + if( nByte>term.n ){ + rc = FTS5_CORRUPT; + break; + } term.n = nByte; } iOff += fts5GetVarint32(&a[iOff], nByte); + if( iOff+nByte>n ){ + rc = FTS5_CORRUPT; + break; + } fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]); iOff += nByte; - sqlite3Fts5BufferAppendPrintf( + tdsqlite3Fts5BufferAppendPrintf( &rc, &s, " term=%.*s", term.n, (const char*)term.p ); iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff); @@ -196077,11 +224480,11 @@ static void fts5DecodeFunction( } decode_out: - sqlite3_free(a); + tdsqlite3_free(a); if( rc==SQLITE_OK ){ - sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT); + tdsqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT); }else{ - sqlite3_result_error_code(pCtx, rc); + tdsqlite3_result_error_code(pCtx, rc); } fts5BufferFree(&s); } @@ -196090,30 +224493,30 @@ static void fts5DecodeFunction( ** The implementation of user-defined scalar function fts5_rowid(). */ static void fts5RowidFunction( - sqlite3_context *pCtx, /* Function call context */ + tdsqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args (always 2) */ - sqlite3_value **apVal /* Function arguments */ + tdsqlite3_value **apVal /* Function arguments */ ){ const char *zArg; if( nArg==0 ){ - sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1); + tdsqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1); }else{ - zArg = (const char*)sqlite3_value_text(apVal[0]); - if( 0==sqlite3_stricmp(zArg, "segment") ){ + zArg = (const char*)tdsqlite3_value_text(apVal[0]); + if( 0==tdsqlite3_stricmp(zArg, "segment") ){ i64 iRowid; int segid, pgno; if( nArg!=3 ){ - sqlite3_result_error(pCtx, + tdsqlite3_result_error(pCtx, "should be: fts5_rowid('segment', segid, pgno))", -1 ); }else{ - segid = sqlite3_value_int(apVal[1]); - pgno = sqlite3_value_int(apVal[2]); + segid = tdsqlite3_value_int(apVal[1]); + pgno = tdsqlite3_value_int(apVal[2]); iRowid = FTS5_SEGMENT_ROWID(segid, pgno); - sqlite3_result_int64(pCtx, iRowid); + tdsqlite3_result_int64(pCtx, iRowid); } }else{ - sqlite3_result_error(pCtx, + tdsqlite3_result_error(pCtx, "first arg to fts5_rowid() must be 'segment'" , -1 ); } @@ -196128,20 +224531,20 @@ static void fts5RowidFunction( ** If successful, SQLITE_OK is returned. If an error occurs, some other ** SQLite error code is returned instead. */ -static int sqlite3Fts5IndexInit(sqlite3 *db){ - int rc = sqlite3_create_function( +static int tdsqlite3Fts5IndexInit(tdsqlite3 *db){ + int rc = tdsqlite3_create_function( db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0 ); if( rc==SQLITE_OK ){ - rc = sqlite3_create_function( + rc = tdsqlite3_create_function( db, "fts5_decode_none", 2, SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0 ); } if( rc==SQLITE_OK ){ - rc = sqlite3_create_function( + rc = tdsqlite3_create_function( db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0 ); } @@ -196149,7 +224552,7 @@ static int sqlite3Fts5IndexInit(sqlite3 *db){ } -static int sqlite3Fts5IndexReset(Fts5Index *p){ +static int tdsqlite3Fts5IndexReset(Fts5Index *p){ assert( p->pStruct==0 || p->iStructVersion!=0 ); if( fts5IndexDataVersion(p)!=p->iStructVersion ){ fts5StructureInvalidate(p); @@ -196181,14 +224584,14 @@ static int sqlite3Fts5IndexReset(Fts5Index *p){ ** assert() conditions in the fts5 code are activated - conditions that are ** only true if it is guaranteed that the fts5 database is not corrupt. */ -SQLITE_API int sqlite3_fts5_may_be_corrupt = 1; +SQLITE_API int tdsqlite3_fts5_may_be_corrupt = 1; typedef struct Fts5Auxdata Fts5Auxdata; typedef struct Fts5Auxiliary Fts5Auxiliary; typedef struct Fts5Cursor Fts5Cursor; +typedef struct Fts5FullTable Fts5FullTable; typedef struct Fts5Sorter Fts5Sorter; -typedef struct Fts5Table Fts5Table; typedef struct Fts5TokenizerModule Fts5TokenizerModule; /* @@ -196234,7 +224637,7 @@ struct Fts5TransactionState { */ struct Fts5Global { fts5_api api; /* User visible part of object (see fts5.h) */ - sqlite3 *db; /* Associated database connection */ + tdsqlite3 *db; /* Associated database connection */ i64 iNextId; /* Used to allocate unique cursor ids */ Fts5Auxiliary *pAux; /* First in list of all aux. functions */ Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */ @@ -196269,13 +224672,8 @@ struct Fts5TokenizerModule { Fts5TokenizerModule *pNext; /* Next registered tokenizer module */ }; -/* -** Virtual-table object. -*/ -struct Fts5Table { - sqlite3_vtab base; /* Base class used by SQLite core */ - Fts5Config *pConfig; /* Virtual table configuration */ - Fts5Index *pIndex; /* Full-text index */ +struct Fts5FullTable { + Fts5Table p; /* Public class members from fts5Int.h */ Fts5Storage *pStorage; /* Document store */ Fts5Global *pGlobal; /* Global (connection wide) data */ Fts5Cursor *pSortCsr; /* Sort data from this cursor */ @@ -196299,7 +224697,7 @@ struct Fts5MatchPhrase { ** byte of the position list for the corresponding phrase. */ struct Fts5Sorter { - sqlite3_stmt *pStmt; + tdsqlite3_stmt *pStmt; i64 iRowid; /* Current rowid */ const u8 *aPoslist; /* Position lists for current row */ int nIdx; /* Number of entries in aIdx[] */ @@ -196327,7 +224725,7 @@ struct Fts5Sorter { ** the lower. */ struct Fts5Cursor { - sqlite3_vtab_cursor base; /* Base class used by SQLite core */ + tdsqlite3_vtab_cursor base; /* Base class used by SQLite core */ Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */ int *aColumnSize; /* Values for xColumnSize() */ i64 iCsrId; /* Cursor id */ @@ -196337,7 +224735,7 @@ struct Fts5Cursor { int bDesc; /* True for "ORDER BY rowid DESC" queries */ i64 iFirstRowid; /* Return no rowids earlier than this */ i64 iLastRowid; /* Return no rowids later than this */ - sqlite3_stmt *pStmt; /* Statement used to read %_content */ + tdsqlite3_stmt *pStmt; /* Statement used to read %_content */ Fts5Expr *pExpr; /* Expression for MATCH queries */ Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */ int csrflags; /* Mask of cursor flags (see below) */ @@ -196348,8 +224746,8 @@ struct Fts5Cursor { char *zRankArgs; /* Custom rank function args */ Fts5Auxiliary *pRank; /* Rank callback (or NULL) */ int nRankArg; /* Number of trailing arguments for rank() */ - sqlite3_value **apRankArg; /* Array of trailing arguments */ - sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */ + tdsqlite3_value **apRankArg; /* Array of trailing arguments */ + tdsqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */ /* Auxiliary data storage */ Fts5Auxiliary *pAux; /* Currently executing extension function */ @@ -196413,7 +224811,7 @@ struct Fts5Auxdata { #define FTS5_SAVEPOINT 5 #define FTS5_RELEASE 6 #define FTS5_ROLLBACKTO 7 -static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){ +static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){ switch( op ){ case FTS5_BEGIN: assert( p->ts.eState==0 ); @@ -196439,7 +224837,7 @@ static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){ case FTS5_SAVEPOINT: assert( p->ts.eState==1 ); assert( iSavepoint>=0 ); - assert( iSavepoint>p->ts.iSavepoint ); + assert( iSavepoint>=p->ts.iSavepoint ); p->ts.iSavepoint = iSavepoint; break; @@ -196452,8 +224850,11 @@ static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){ case FTS5_ROLLBACKTO: assert( p->ts.eState==1 ); - assert( iSavepoint>=0 ); - assert( iSavepoint<=p->ts.iSavepoint ); + assert( iSavepoint>=-1 ); + /* The following assert() can fail if another vtab strikes an error + ** within an xSavepoint() call then SQLite calls xRollbackTo() - without + ** having called xSavepoint() on this vtab. */ + /* assert( iSavepoint<=p->ts.iSavepoint ); */ p->ts.iSavepoint = iSavepoint; break; } @@ -196465,38 +224866,38 @@ static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){ /* ** Return true if pTab is a contentless table. */ -static int fts5IsContentless(Fts5Table *pTab){ - return pTab->pConfig->eContent==FTS5_CONTENT_NONE; +static int fts5IsContentless(Fts5FullTable *pTab){ + return pTab->p.pConfig->eContent==FTS5_CONTENT_NONE; } /* ** Delete a virtual table handle allocated by fts5InitVtab(). */ -static void fts5FreeVtab(Fts5Table *pTab){ +static void fts5FreeVtab(Fts5FullTable *pTab){ if( pTab ){ - sqlite3Fts5IndexClose(pTab->pIndex); - sqlite3Fts5StorageClose(pTab->pStorage); - sqlite3Fts5ConfigFree(pTab->pConfig); - sqlite3_free(pTab); + tdsqlite3Fts5IndexClose(pTab->p.pIndex); + tdsqlite3Fts5StorageClose(pTab->pStorage); + tdsqlite3Fts5ConfigFree(pTab->p.pConfig); + tdsqlite3_free(pTab); } } /* ** The xDisconnect() virtual table method. */ -static int fts5DisconnectMethod(sqlite3_vtab *pVtab){ - fts5FreeVtab((Fts5Table*)pVtab); +static int fts5DisconnectMethod(tdsqlite3_vtab *pVtab){ + fts5FreeVtab((Fts5FullTable*)pVtab); return SQLITE_OK; } /* ** The xDestroy() virtual table method. */ -static int fts5DestroyMethod(sqlite3_vtab *pVtab){ +static int fts5DestroyMethod(tdsqlite3_vtab *pVtab){ Fts5Table *pTab = (Fts5Table*)pVtab; - int rc = sqlite3Fts5DropAll(pTab->pConfig); + int rc = tdsqlite3Fts5DropAll(pTab->pConfig); if( rc==SQLITE_OK ){ - fts5FreeVtab((Fts5Table*)pVtab); + fts5FreeVtab((Fts5FullTable*)pVtab); } return rc; } @@ -196514,53 +224915,53 @@ static int fts5DestroyMethod(sqlite3_vtab *pVtab){ */ static int fts5InitVtab( int bCreate, /* True for xCreate, false for xConnect */ - sqlite3 *db, /* The SQLite database connection */ + tdsqlite3 *db, /* The SQLite database connection */ void *pAux, /* Hash table containing tokenizers */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ + tdsqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ char **pzErr /* Write any error message here */ ){ Fts5Global *pGlobal = (Fts5Global*)pAux; const char **azConfig = (const char**)argv; int rc = SQLITE_OK; /* Return code */ Fts5Config *pConfig = 0; /* Results of parsing argc/argv */ - Fts5Table *pTab = 0; /* New virtual table object */ + Fts5FullTable *pTab = 0; /* New virtual table object */ /* Allocate the new vtab object and parse the configuration */ - pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table)); + pTab = (Fts5FullTable*)tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5FullTable)); if( rc==SQLITE_OK ){ - rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr); + rc = tdsqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr); assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 ); } if( rc==SQLITE_OK ){ - pTab->pConfig = pConfig; + pTab->p.pConfig = pConfig; pTab->pGlobal = pGlobal; } /* Open the index sub-system */ if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr); + rc = tdsqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->p.pIndex, pzErr); } /* Open the storage sub-system */ if( rc==SQLITE_OK ){ - rc = sqlite3Fts5StorageOpen( - pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr + rc = tdsqlite3Fts5StorageOpen( + pConfig, pTab->p.pIndex, bCreate, &pTab->pStorage, pzErr ); } - /* Call sqlite3_declare_vtab() */ + /* Call tdsqlite3_declare_vtab() */ if( rc==SQLITE_OK ){ - rc = sqlite3Fts5ConfigDeclareVtab(pConfig); + rc = tdsqlite3Fts5ConfigDeclareVtab(pConfig); } /* Load the initial configuration */ if( rc==SQLITE_OK ){ assert( pConfig->pzErrmsg==0 ); pConfig->pzErrmsg = pzErr; - rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex); - sqlite3Fts5IndexRollback(pTab->pIndex); + rc = tdsqlite3Fts5IndexLoadConfig(pTab->p.pIndex); + tdsqlite3Fts5IndexRollback(pTab->p.pIndex); pConfig->pzErrmsg = 0; } @@ -196570,7 +224971,7 @@ static int fts5InitVtab( }else if( bCreate ){ fts5CheckTransactionState(pTab, FTS5_BEGIN, 0); } - *ppVTab = (sqlite3_vtab*)pTab; + *ppVTab = (tdsqlite3_vtab*)pTab; return rc; } @@ -196579,22 +224980,22 @@ static int fts5InitVtab( ** work is done in function fts5InitVtab(). */ static int fts5ConnectMethod( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ + tdsqlite3_vtab **ppVtab, /* OUT: New tdsqlite3_vtab object */ + char **pzErr /* OUT: tdsqlite3_malloc'd error message */ ){ return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); } static int fts5CreateMethod( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ + tdsqlite3_vtab **ppVtab, /* OUT: New tdsqlite3_vtab object */ + char **pzErr /* OUT: tdsqlite3_malloc'd error message */ ){ return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); } @@ -196614,10 +225015,10 @@ static int fts5CreateMethod( ** extension is currently being used by a version of SQLite too old to ** support index-info flags. In that case this function is a no-op. */ -static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){ +static void fts5SetUniqueFlag(tdsqlite3_index_info *pIdxInfo){ #if SQLITE_VERSION_NUMBER>=3008012 #ifndef SQLITE_CORE - if( sqlite3_libversion_number()>=3008012 ) + if( tdsqlite3_libversion_number()>=3008012 ) #endif { pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE; @@ -196629,17 +225030,39 @@ static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){ ** Implementation of the xBestIndex method for FTS5 tables. Within the ** WHERE constraint, it searches for the following: ** -** 1. A MATCH constraint against the special column. +** 1. A MATCH constraint against the table column. ** 2. A MATCH constraint against the "rank" column. -** 3. An == constraint against the rowid column. -** 4. A < or <= constraint against the rowid column. -** 5. A > or >= constraint against the rowid column. +** 3. A MATCH constraint against some other column. +** 4. An == constraint against the rowid column. +** 5. A < or <= constraint against the rowid column. +** 6. A > or >= constraint against the rowid column. ** -** Within the ORDER BY, either: +** Within the ORDER BY, the following are supported: ** ** 5. ORDER BY rank [ASC|DESC] ** 6. ORDER BY rowid [ASC|DESC] ** +** Information for the xFilter call is passed via both the idxNum and +** idxStr variables. Specifically, idxNum is a bitmask of the following +** flags used to encode the ORDER BY clause: +** +** FTS5_BI_ORDER_RANK +** FTS5_BI_ORDER_ROWID +** FTS5_BI_ORDER_DESC +** +** idxStr is used to encode data from the WHERE clause. For each argument +** passed to the xFilter method, the following is appended to idxStr: +** +** Match against table column: "m" +** Match against rank column: "r" +** Match against other column: "<column-number>" +** Equality constraint against the rowid: "=" +** A < or <= against the rowid: "<" +** A > or >= against the rowid: ">" +** +** This function ensures that there is at most one "r" or "=". And that if +** there exists an "=" then there is no "<" or ">". +** ** Costs are assigned as follows: ** ** a) If an unusable MATCH operator is present in the WHERE clause, the @@ -196662,61 +225085,109 @@ static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){ ** ** Costs are not modified by the ORDER BY clause. */ -static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ +static int fts5BestIndexMethod(tdsqlite3_vtab *pVTab, tdsqlite3_index_info *pInfo){ Fts5Table *pTab = (Fts5Table*)pVTab; Fts5Config *pConfig = pTab->pConfig; + const int nCol = pConfig->nCol; int idxFlags = 0; /* Parameter passed through to xFilter() */ - int bHasMatch; - int iNext; int i; - struct Constraint { - int op; /* Mask against sqlite3_index_constraint.op */ - int fts5op; /* FTS5 mask for idxFlags */ - int iCol; /* 0==rowid, 1==tbl, 2==rank */ - int omit; /* True to omit this if found */ - int iConsIndex; /* Index in pInfo->aConstraint[] */ - } aConstraint[] = { - {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, - FTS5_BI_MATCH, 1, 1, -1}, - {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, - FTS5_BI_RANK, 2, 1, -1}, - {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1}, - {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE, - FTS5_BI_ROWID_LE, 0, 0, -1}, - {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE, - FTS5_BI_ROWID_GE, 0, 0, -1}, - }; + char *idxStr; + int iIdxStr = 0; + int iCons = 0; + + int bSeenEq = 0; + int bSeenGt = 0; + int bSeenLt = 0; + int bSeenMatch = 0; + int bSeenRank = 0; + + + assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH ); + assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH ); + assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH ); + assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH ); + assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH ); - int aColMap[3]; - aColMap[0] = -1; - aColMap[1] = pConfig->nCol; - aColMap[2] = pConfig->nCol+1; + if( pConfig->bLock ){ + pTab->base.zErrMsg = tdsqlite3_mprintf( + "recursively defined fts5 content table" + ); + return SQLITE_ERROR; + } + + idxStr = (char*)tdsqlite3_malloc(pInfo->nConstraint * 6 + 1); + if( idxStr==0 ) return SQLITE_NOMEM; + pInfo->idxStr = idxStr; + pInfo->needToFreeIdxStr = 1; - /* Set idxFlags flags for all WHERE clause terms that will be used. */ for(i=0; i<pInfo->nConstraint; i++){ - struct sqlite3_index_constraint *p = &pInfo->aConstraint[i]; - int j; - for(j=0; j<ArraySize(aConstraint); j++){ - struct Constraint *pC = &aConstraint[j]; - if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){ - if( p->usable ){ - pC->iConsIndex = i; - idxFlags |= pC->fts5op; - }else if( j==0 ){ - /* As there exists an unusable MATCH constraint this is an - ** unusable plan. Set a prohibitively high cost. */ - pInfo->estimatedCost = 1e50; - return SQLITE_OK; + struct tdsqlite3_index_constraint *p = &pInfo->aConstraint[i]; + int iCol = p->iColumn; + if( p->op==SQLITE_INDEX_CONSTRAINT_MATCH + || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol>=nCol) + ){ + /* A MATCH operator or equivalent */ + if( p->usable==0 || iCol<0 ){ + /* As there exists an unusable MATCH constraint this is an + ** unusable plan. Set a prohibitively high cost. */ + pInfo->estimatedCost = 1e50; + assert( iIdxStr < pInfo->nConstraint*6 + 1 ); + idxStr[iIdxStr] = 0; + return SQLITE_OK; + }else{ + if( iCol==nCol+1 ){ + if( bSeenRank ) continue; + idxStr[iIdxStr++] = 'r'; + bSeenRank = 1; + }else{ + bSeenMatch = 1; + idxStr[iIdxStr++] = 'm'; + if( iCol<nCol ){ + tdsqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol); + idxStr += strlen(&idxStr[iIdxStr]); + assert( idxStr[iIdxStr]=='\0' ); + } + } + pInfo->aConstraintUsage[i].argvIndex = ++iCons; + pInfo->aConstraintUsage[i].omit = 1; + } + } + else if( p->usable && bSeenEq==0 + && p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol<0 + ){ + idxStr[iIdxStr++] = '='; + bSeenEq = 1; + pInfo->aConstraintUsage[i].argvIndex = ++iCons; + } + } + + if( bSeenEq==0 ){ + for(i=0; i<pInfo->nConstraint; i++){ + struct tdsqlite3_index_constraint *p = &pInfo->aConstraint[i]; + if( p->iColumn<0 && p->usable ){ + int op = p->op; + if( op==SQLITE_INDEX_CONSTRAINT_LT || op==SQLITE_INDEX_CONSTRAINT_LE ){ + if( bSeenLt ) continue; + idxStr[iIdxStr++] = '<'; + pInfo->aConstraintUsage[i].argvIndex = ++iCons; + bSeenLt = 1; + }else + if( op==SQLITE_INDEX_CONSTRAINT_GT || op==SQLITE_INDEX_CONSTRAINT_GE ){ + if( bSeenGt ) continue; + idxStr[iIdxStr++] = '>'; + pInfo->aConstraintUsage[i].argvIndex = ++iCons; + bSeenGt = 1; } } } } + idxStr[iIdxStr] = '\0'; /* Set idxFlags flags for the ORDER BY clause */ if( pInfo->nOrderBy==1 ){ int iSort = pInfo->aOrderBy[0].iColumn; - if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){ + if( iSort==(pConfig->nCol+1) && bSeenMatch ){ idxFlags |= FTS5_BI_ORDER_RANK; }else if( iSort==-1 ){ idxFlags |= FTS5_BI_ORDER_ROWID; @@ -196730,57 +225201,46 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ } /* Calculate the estimated cost based on the flags set in idxFlags. */ - bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH); - if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){ - pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0; - if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo); - }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){ - pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0; - }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){ - pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0; + if( bSeenEq ){ + pInfo->estimatedCost = bSeenMatch ? 100.0 : 10.0; + if( bSeenMatch==0 ) fts5SetUniqueFlag(pInfo); + }else if( bSeenLt && bSeenGt ){ + pInfo->estimatedCost = bSeenMatch ? 500.0 : 250000.0; + }else if( bSeenLt || bSeenGt ){ + pInfo->estimatedCost = bSeenMatch ? 750.0 : 750000.0; }else{ - pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0; - } - - /* Assign argvIndex values to each constraint in use. */ - iNext = 1; - for(i=0; i<ArraySize(aConstraint); i++){ - struct Constraint *pC = &aConstraint[i]; - if( pC->iConsIndex>=0 ){ - pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++; - pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit; - } + pInfo->estimatedCost = bSeenMatch ? 1000.0 : 1000000.0; } pInfo->idxNum = idxFlags; return SQLITE_OK; } -static int fts5NewTransaction(Fts5Table *pTab){ +static int fts5NewTransaction(Fts5FullTable *pTab){ Fts5Cursor *pCsr; for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){ - if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK; + if( pCsr->base.pVtab==(tdsqlite3_vtab*)pTab ) return SQLITE_OK; } - return sqlite3Fts5StorageReset(pTab->pStorage); + return tdsqlite3Fts5StorageReset(pTab->pStorage); } /* ** Implementation of xOpen method. */ -static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ - Fts5Table *pTab = (Fts5Table*)pVTab; - Fts5Config *pConfig = pTab->pConfig; +static int fts5OpenMethod(tdsqlite3_vtab *pVTab, tdsqlite3_vtab_cursor **ppCsr){ + Fts5FullTable *pTab = (Fts5FullTable*)pVTab; + Fts5Config *pConfig = pTab->p.pConfig; Fts5Cursor *pCsr = 0; /* New cursor object */ - int nByte; /* Bytes of space to allocate */ + tdsqlite3_int64 nByte; /* Bytes of space to allocate */ int rc; /* Return code */ rc = fts5NewTransaction(pTab); if( rc==SQLITE_OK ){ nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int); - pCsr = (Fts5Cursor*)sqlite3_malloc(nByte); + pCsr = (Fts5Cursor*)tdsqlite3_malloc64(nByte); if( pCsr ){ Fts5Global *pGlobal = pTab->pGlobal; - memset(pCsr, 0, nByte); + memset(pCsr, 0, (size_t)nByte); pCsr->aColumnSize = (int*)&pCsr[1]; pCsr->pNext = pGlobal->pCsr; pGlobal->pCsr = pCsr; @@ -196789,7 +225249,7 @@ static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ rc = SQLITE_NOMEM; } } - *ppCsr = (sqlite3_vtab_cursor*)pCsr; + *ppCsr = (tdsqlite3_vtab_cursor*)pCsr; return rc; } @@ -196815,40 +225275,41 @@ static void fts5CsrNewrow(Fts5Cursor *pCsr){ } static void fts5FreeCursorComponents(Fts5Cursor *pCsr){ - Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); + Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab); Fts5Auxdata *pData; Fts5Auxdata *pNext; - sqlite3_free(pCsr->aInstIter); - sqlite3_free(pCsr->aInst); + tdsqlite3_free(pCsr->aInstIter); + tdsqlite3_free(pCsr->aInst); if( pCsr->pStmt ){ int eStmt = fts5StmtType(pCsr); - sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt); + tdsqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt); } if( pCsr->pSorter ){ Fts5Sorter *pSorter = pCsr->pSorter; - sqlite3_finalize(pSorter->pStmt); - sqlite3_free(pSorter); + tdsqlite3_finalize(pSorter->pStmt); + tdsqlite3_free(pSorter); } if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){ - sqlite3Fts5ExprFree(pCsr->pExpr); + tdsqlite3Fts5ExprFree(pCsr->pExpr); } for(pData=pCsr->pAuxdata; pData; pData=pNext){ pNext = pData->pNext; if( pData->xDelete ) pData->xDelete(pData->pPtr); - sqlite3_free(pData); + tdsqlite3_free(pData); } - sqlite3_finalize(pCsr->pRankArgStmt); - sqlite3_free(pCsr->apRankArg); + tdsqlite3_finalize(pCsr->pRankArgStmt); + tdsqlite3_free(pCsr->apRankArg); if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){ - sqlite3_free(pCsr->zRank); - sqlite3_free(pCsr->zRankArgs); + tdsqlite3_free(pCsr->zRank); + tdsqlite3_free(pCsr->zRankArgs); } + tdsqlite3Fts5IndexCloseReader(pTab->p.pIndex); memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr)); } @@ -196857,9 +225318,9 @@ static void fts5FreeCursorComponents(Fts5Cursor *pCsr){ ** Close the cursor. For additional information see the documentation ** on the xClose method of the virtual table interface. */ -static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){ +static int fts5CloseMethod(tdsqlite3_vtab_cursor *pCursor){ if( pCursor ){ - Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab); + Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab); Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; Fts5Cursor **pp; @@ -196868,7 +225329,7 @@ static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){ for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext); *pp = pCsr->pNext; - sqlite3_free(pCsr); + tdsqlite3_free(pCsr); } return SQLITE_OK; } @@ -196877,7 +225338,7 @@ static int fts5SorterNext(Fts5Cursor *pCsr){ Fts5Sorter *pSorter = pCsr->pSorter; int rc; - rc = sqlite3_step(pSorter->pStmt); + rc = tdsqlite3_step(pSorter->pStmt); if( rc==SQLITE_DONE ){ rc = SQLITE_OK; CsrFlagSet(pCsr, FTS5CSR_EOF); @@ -196889,9 +225350,9 @@ static int fts5SorterNext(Fts5Cursor *pCsr){ int iOff = 0; rc = SQLITE_OK; - pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0); - nBlob = sqlite3_column_bytes(pSorter->pStmt, 1); - aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1); + pSorter->iRowid = tdsqlite3_column_int64(pSorter->pStmt, 0); + nBlob = tdsqlite3_column_bytes(pSorter->pStmt, 1); + aBlob = a = tdsqlite3_column_blob(pSorter->pStmt, 1); /* nBlob==0 in detail=none mode. */ if( nBlob>0 ){ @@ -196916,11 +225377,11 @@ static int fts5SorterNext(Fts5Cursor *pCsr){ ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors ** open on table pTab. */ -static void fts5TripCursors(Fts5Table *pTab){ +static void fts5TripCursors(Fts5FullTable *pTab){ Fts5Cursor *pCsr; for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){ if( pCsr->ePlan==FTS5_PLAN_MATCH - && pCsr->base.pVtab==(sqlite3_vtab*)pTab + && pCsr->base.pVtab==(tdsqlite3_vtab*)pTab ){ CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK); } @@ -196943,18 +225404,18 @@ static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){ int rc = SQLITE_OK; assert( *pbSkip==0 ); if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){ - Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); + Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab); int bDesc = pCsr->bDesc; - i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr); + i64 iRowid = tdsqlite3Fts5ExprRowid(pCsr->pExpr); - rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc); - if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){ + rc = tdsqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc); + if( rc==SQLITE_OK && iRowid!=tdsqlite3Fts5ExprRowid(pCsr->pExpr) ){ *pbSkip = 1; } CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK); fts5CsrNewrow(pCsr); - if( sqlite3Fts5ExprEof(pCsr->pExpr) ){ + if( tdsqlite3Fts5ExprEof(pCsr->pExpr) ){ CsrFlagSet(pCsr, FTS5CSR_EOF); *pbSkip = 1; } @@ -196971,7 +225432,7 @@ static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){ ** even if we reach end-of-file. The fts5EofMethod() will be called ** subsequently to determine whether or not an EOF was hit. */ -static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){ +static int fts5NextMethod(tdsqlite3_vtab_cursor *pCursor){ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; int rc; @@ -196983,8 +225444,8 @@ static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){ if( pCsr->ePlan<3 ){ int bSkip = 0; if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc; - rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid); - CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr)); + rc = tdsqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid); + CsrFlagSet(pCsr, tdsqlite3Fts5ExprEof(pCsr->pExpr)); fts5CsrNewrow(pCsr); }else{ switch( pCsr->ePlan ){ @@ -196999,15 +225460,24 @@ static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){ break; } - default: - rc = sqlite3_step(pCsr->pStmt); + default: { + Fts5Config *pConfig = ((Fts5Table*)pCursor->pVtab)->pConfig; + pConfig->bLock++; + rc = tdsqlite3_step(pCsr->pStmt); + pConfig->bLock--; if( rc!=SQLITE_ROW ){ CsrFlagSet(pCsr, FTS5CSR_EOF); - rc = sqlite3_reset(pCsr->pStmt); + rc = tdsqlite3_reset(pCsr->pStmt); + if( rc!=SQLITE_OK ){ + pCursor->pVtab->zErrMsg = tdsqlite3_mprintf( + "%s", tdsqlite3_errmsg(pConfig->db) + ); + } }else{ rc = SQLITE_OK; } break; + } } } @@ -197016,26 +225486,27 @@ static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){ static int fts5PrepareStatement( - sqlite3_stmt **ppStmt, + tdsqlite3_stmt **ppStmt, Fts5Config *pConfig, const char *zFmt, ... ){ - sqlite3_stmt *pRet = 0; + tdsqlite3_stmt *pRet = 0; int rc; char *zSql; va_list ap; va_start(ap, zFmt); - zSql = sqlite3_vmprintf(zFmt, ap); + zSql = tdsqlite3_vmprintf(zFmt, ap); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0); + rc = tdsqlite3_prepare_v3(pConfig->db, zSql, -1, + SQLITE_PREPARE_PERSISTENT, &pRet, 0); if( rc!=SQLITE_OK ){ - *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db)); + *pConfig->pzErrmsg = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(pConfig->db)); } - sqlite3_free(zSql); + tdsqlite3_free(zSql); } va_end(ap); @@ -197043,20 +225514,24 @@ static int fts5PrepareStatement( return rc; } -static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){ - Fts5Config *pConfig = pTab->pConfig; +static int fts5CursorFirstSorted( + Fts5FullTable *pTab, + Fts5Cursor *pCsr, + int bDesc +){ + Fts5Config *pConfig = pTab->p.pConfig; Fts5Sorter *pSorter; int nPhrase; - int nByte; + tdsqlite3_int64 nByte; int rc; const char *zRank = pCsr->zRank; const char *zRankArgs = pCsr->zRankArgs; - nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr); + nPhrase = tdsqlite3Fts5ExprPhraseCount(pCsr->pExpr); nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1); - pSorter = (Fts5Sorter*)sqlite3_malloc(nByte); + pSorter = (Fts5Sorter*)tdsqlite3_malloc64(nByte); if( pSorter==0 ) return SQLITE_NOMEM; - memset(pSorter, 0, nByte); + memset(pSorter, 0, (size_t)nByte); pSorter->nIdx = nPhrase; /* TODO: It would be better to have some system for reusing statement @@ -197067,7 +225542,7 @@ static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){ ** ** If SQLite a built-in statement cache, this wouldn't be a problem. */ rc = fts5PrepareStatement(&pSorter->pStmt, pConfig, - "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s", + "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(\"%w\"%s%s) %s", pConfig->zDb, pConfig->zName, zRank, pConfig->zName, (zRankArgs ? ", " : ""), (zRankArgs ? zRankArgs : ""), @@ -197083,19 +225558,19 @@ static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){ } if( rc!=SQLITE_OK ){ - sqlite3_finalize(pSorter->pStmt); - sqlite3_free(pSorter); + tdsqlite3_finalize(pSorter->pStmt); + tdsqlite3_free(pSorter); pCsr->pSorter = 0; } return rc; } -static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){ +static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){ int rc; Fts5Expr *pExpr = pCsr->pExpr; - rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc); - if( sqlite3Fts5ExprEof(pExpr) ){ + rc = tdsqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc); + if( tdsqlite3Fts5ExprEof(pExpr) ){ CsrFlagSet(pCsr, FTS5CSR_EOF); } fts5CsrNewrow(pCsr); @@ -197109,7 +225584,7 @@ static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){ ** parameters. */ static int fts5SpecialMatch( - Fts5Table *pTab, + Fts5FullTable *pTab, Fts5Cursor *pCsr, const char *zQuery ){ @@ -197120,18 +225595,18 @@ static int fts5SpecialMatch( while( z[0]==' ' ) z++; for(n=0; z[n] && z[n]!=' '; n++); - assert( pTab->base.zErrMsg==0 ); + assert( pTab->p.base.zErrMsg==0 ); pCsr->ePlan = FTS5_PLAN_SPECIAL; - if( 0==sqlite3_strnicmp("reads", z, n) ){ - pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex); + if( n==5 && 0==tdsqlite3_strnicmp("reads", z, n) ){ + pCsr->iSpecial = tdsqlite3Fts5IndexReads(pTab->p.pIndex); } - else if( 0==sqlite3_strnicmp("id", z, n) ){ + else if( n==2 && 0==tdsqlite3_strnicmp("id", z, n) ){ pCsr->iSpecial = pCsr->iCsrId; } else{ /* An unrecognized directive. Return an error message. */ - pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z); + pTab->p.base.zErrMsg = tdsqlite3_mprintf("unknown special query: %.*s", n, z); rc = SQLITE_ERROR; } @@ -197143,11 +225618,11 @@ static int fts5SpecialMatch( ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary ** structure. Otherwise, if no such function exists, return NULL. */ -static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){ +static Fts5Auxiliary *fts5FindAuxiliary(Fts5FullTable *pTab, const char *zName){ Fts5Auxiliary *pAux; for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){ - if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux; + if( tdsqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux; } /* No function of the specified name was found. Return 0. */ @@ -197156,35 +225631,36 @@ static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){ static int fts5FindRankFunction(Fts5Cursor *pCsr){ - Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); - Fts5Config *pConfig = pTab->pConfig; + Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab); + Fts5Config *pConfig = pTab->p.pConfig; int rc = SQLITE_OK; Fts5Auxiliary *pAux = 0; const char *zRank = pCsr->zRank; const char *zRankArgs = pCsr->zRankArgs; if( zRankArgs ){ - char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs); + char *zSql = tdsqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs); if( zSql ){ - sqlite3_stmt *pStmt = 0; - rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); + tdsqlite3_stmt *pStmt = 0; + rc = tdsqlite3_prepare_v3(pConfig->db, zSql, -1, + SQLITE_PREPARE_PERSISTENT, &pStmt, 0); + tdsqlite3_free(zSql); assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 ); if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - int nByte; - pCsr->nRankArg = sqlite3_column_count(pStmt); - nByte = sizeof(sqlite3_value*)*pCsr->nRankArg; - pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte); + if( SQLITE_ROW==tdsqlite3_step(pStmt) ){ + tdsqlite3_int64 nByte; + pCsr->nRankArg = tdsqlite3_column_count(pStmt); + nByte = sizeof(tdsqlite3_value*)*pCsr->nRankArg; + pCsr->apRankArg = (tdsqlite3_value**)tdsqlite3Fts5MallocZero(&rc, nByte); if( rc==SQLITE_OK ){ int i; for(i=0; i<pCsr->nRankArg; i++){ - pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i); + pCsr->apRankArg[i] = tdsqlite3_column_value(pStmt, i); } } pCsr->pRankArgStmt = pStmt; }else{ - rc = sqlite3_finalize(pStmt); + rc = tdsqlite3_finalize(pStmt); assert( rc!=SQLITE_OK ); } } @@ -197194,8 +225670,8 @@ static int fts5FindRankFunction(Fts5Cursor *pCsr){ if( rc==SQLITE_OK ){ pAux = fts5FindAuxiliary(pTab, zRank); if( pAux==0 ){ - assert( pTab->base.zErrMsg==0 ); - pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank); + assert( pTab->p.base.zErrMsg==0 ); + pTab->p.base.zErrMsg = tdsqlite3_mprintf("no such function: %s", zRank); rc = SQLITE_ERROR; } } @@ -197208,25 +225684,25 @@ static int fts5FindRankFunction(Fts5Cursor *pCsr){ static int fts5CursorParseRank( Fts5Config *pConfig, Fts5Cursor *pCsr, - sqlite3_value *pRank + tdsqlite3_value *pRank ){ int rc = SQLITE_OK; if( pRank ){ - const char *z = (const char*)sqlite3_value_text(pRank); + const char *z = (const char*)tdsqlite3_value_text(pRank); char *zRank = 0; char *zRankArgs = 0; if( z==0 ){ - if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR; + if( tdsqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR; }else{ - rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs); + rc = tdsqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs); } if( rc==SQLITE_OK ){ pCsr->zRank = zRank; pCsr->zRankArgs = zRankArgs; CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK); }else if( rc==SQLITE_ERROR ){ - pCsr->base.pVtab->zErrMsg = sqlite3_mprintf( + pCsr->base.pVtab->zErrMsg = tdsqlite3_mprintf( "parse error in rank function: %s", z ); } @@ -197242,11 +225718,11 @@ static int fts5CursorParseRank( return rc; } -static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){ +static i64 fts5GetRowidLimit(tdsqlite3_value *pVal, i64 iDefault){ if( pVal ){ - int eType = sqlite3_value_numeric_type(pVal); + int eType = tdsqlite3_value_numeric_type(pVal); if( eType==SQLITE_INTEGER ){ - return sqlite3_value_int64(pVal); + return tdsqlite3_value_int64(pVal); } } return iDefault; @@ -197264,28 +225740,34 @@ static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){ ** 3. A full-table scan. */ static int fts5FilterMethod( - sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + tdsqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ - const char *zUnused, /* Unused */ + const char *idxStr, /* Unused */ int nVal, /* Number of elements in apVal */ - sqlite3_value **apVal /* Arguments for the indexing scheme */ + tdsqlite3_value **apVal /* Arguments for the indexing scheme */ ){ - Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab); - Fts5Config *pConfig = pTab->pConfig; + Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab); + Fts5Config *pConfig = pTab->p.pConfig; Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; int rc = SQLITE_OK; /* Error code */ - int iVal = 0; /* Counter for apVal[] */ int bDesc; /* True if ORDER BY [rank|rowid] DESC */ int bOrderByRank; /* True if ORDER BY rank */ - sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */ - sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */ - sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */ - sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */ - sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */ + tdsqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */ + tdsqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */ + tdsqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */ + tdsqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */ + int iCol; /* Column on LHS of MATCH operator */ char **pzErrmsg = pConfig->pzErrmsg; + int i; + int iIdxStr = 0; + Fts5Expr *pExpr = 0; - UNUSED_PARAM(zUnused); - UNUSED_PARAM(nVal); + if( pConfig->bLock ){ + pTab->p.base.zErrMsg = tdsqlite3_mprintf( + "recursively defined fts5 content table" + ); + return SQLITE_ERROR; + } if( pCsr->ePlan ){ fts5FreeCursorComponents(pCsr); @@ -197298,27 +225780,66 @@ static int fts5FilterMethod( assert( pCsr->pRank==0 ); assert( pCsr->zRank==0 ); assert( pCsr->zRankArgs==0 ); + assert( pTab->pSortCsr==0 || nVal==0 ); - assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg ); - pConfig->pzErrmsg = &pTab->base.zErrMsg; + assert( pzErrmsg==0 || pzErrmsg==&pTab->p.base.zErrMsg ); + pConfig->pzErrmsg = &pTab->p.base.zErrMsg; - /* Decode the arguments passed through to this function. - ** - ** Note: The following set of if(...) statements must be in the same - ** order as the corresponding entries in the struct at the top of - ** fts5BestIndexMethod(). */ - if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++]; - if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++]; - if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++]; - if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++]; - if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++]; - assert( iVal==nVal ); + /* Decode the arguments passed through to this function. */ + for(i=0; i<nVal; i++){ + switch( idxStr[iIdxStr++] ){ + case 'r': + pRank = apVal[i]; + break; + case 'm': { + const char *zText = (const char*)tdsqlite3_value_text(apVal[i]); + if( zText==0 ) zText = ""; + + if( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' ){ + iCol = 0; + do{ + iCol = iCol*10 + (idxStr[iIdxStr]-'0'); + iIdxStr++; + }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' ); + }else{ + iCol = pConfig->nCol; + } + + if( zText[0]=='*' ){ + /* The user has issued a query of the form "MATCH '*...'". This + ** indicates that the MATCH expression is not a full text query, + ** but a request for an internal parameter. */ + rc = fts5SpecialMatch(pTab, pCsr, &zText[1]); + goto filter_out; + }else{ + char **pzErr = &pTab->p.base.zErrMsg; + rc = tdsqlite3Fts5ExprNew(pConfig, iCol, zText, &pExpr, pzErr); + if( rc==SQLITE_OK ){ + rc = tdsqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr); + pExpr = 0; + } + if( rc!=SQLITE_OK ) goto filter_out; + } + + break; + } + case '=': + pRowidEq = apVal[i]; + break; + case '<': + pRowidLe = apVal[i]; + break; + default: assert( idxStr[iIdxStr-1]=='>' ); + pRowidGe = apVal[i]; + break; + } + } bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0); pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0); /* Set the cursor upper and lower rowid limits. Only some strategies ** actually use them. This is ok, as the xBestIndex() method leaves the - ** sqlite3_index_constraint.omit flag clear for range constraints + ** tdsqlite3_index_constraint.omit flag clear for range constraints ** on the rowid field. */ if( pRowidEq ){ pRowidLe = pRowidGe = pRowidEq; @@ -197339,39 +225860,32 @@ static int fts5FilterMethod( ** (pCursor) is used to execute the query issued by function ** fts5CursorFirstSorted() above. */ assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 ); - assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 ); + assert( nVal==0 && bOrderByRank==0 && bDesc==0 ); assert( pCsr->iLastRowid==LARGEST_INT64 ); assert( pCsr->iFirstRowid==SMALLEST_INT64 ); + if( pTab->pSortCsr->bDesc ){ + pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid; + pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid; + }else{ + pCsr->iLastRowid = pTab->pSortCsr->iLastRowid; + pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid; + } pCsr->ePlan = FTS5_PLAN_SOURCE; pCsr->pExpr = pTab->pSortCsr->pExpr; rc = fts5CursorFirst(pTab, pCsr, bDesc); - }else if( pMatch ){ - const char *zExpr = (const char*)sqlite3_value_text(apVal[0]); - if( zExpr==0 ) zExpr = ""; - + }else if( pCsr->pExpr ){ rc = fts5CursorParseRank(pConfig, pCsr, pRank); if( rc==SQLITE_OK ){ - if( zExpr[0]=='*' ){ - /* The user has issued a query of the form "MATCH '*...'". This - ** indicates that the MATCH expression is not a full text query, - ** but a request for an internal parameter. */ - rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]); + if( bOrderByRank ){ + pCsr->ePlan = FTS5_PLAN_SORTED_MATCH; + rc = fts5CursorFirstSorted(pTab, pCsr, bDesc); }else{ - char **pzErr = &pTab->base.zErrMsg; - rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr); - if( rc==SQLITE_OK ){ - if( bOrderByRank ){ - pCsr->ePlan = FTS5_PLAN_SORTED_MATCH; - rc = fts5CursorFirstSorted(pTab, pCsr, bDesc); - }else{ - pCsr->ePlan = FTS5_PLAN_MATCH; - rc = fts5CursorFirst(pTab, pCsr, bDesc); - } - } + pCsr->ePlan = FTS5_PLAN_MATCH; + rc = fts5CursorFirst(pTab, pCsr, bDesc); } } }else if( pConfig->zContent==0 ){ - *pConfig->pzErrmsg = sqlite3_mprintf( + *pConfig->pzErrmsg = tdsqlite3_mprintf( "%s: table does not support scanning", pConfig->zName ); rc = SQLITE_ERROR; @@ -197379,20 +225893,22 @@ static int fts5FilterMethod( /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup ** by rowid (ePlan==FTS5_PLAN_ROWID). */ pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN); - rc = sqlite3Fts5StorageStmt( - pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg + rc = tdsqlite3Fts5StorageStmt( + pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg ); if( rc==SQLITE_OK ){ if( pCsr->ePlan==FTS5_PLAN_ROWID ){ - sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]); + tdsqlite3_bind_value(pCsr->pStmt, 1, pRowidEq); }else{ - sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid); - sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid); + tdsqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid); + tdsqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid); } rc = fts5NextMethod(pCursor); } } + filter_out: + tdsqlite3Fts5ExprFree(pExpr); pConfig->pzErrmsg = pzErrmsg; return rc; } @@ -197401,7 +225917,7 @@ static int fts5FilterMethod( ** This is the xEof method of the virtual table. SQLite calls this ** routine to find out if it has reached the end of a result set. */ -static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){ +static int fts5EofMethod(tdsqlite3_vtab_cursor *pCursor){ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0); } @@ -197417,7 +225933,7 @@ static i64 fts5CursorRowid(Fts5Cursor *pCsr){ if( pCsr->pSorter ){ return pCsr->pSorter->iRowid; }else{ - return sqlite3Fts5ExprRowid(pCsr->pExpr); + return tdsqlite3Fts5ExprRowid(pCsr->pExpr); } } @@ -197427,7 +225943,7 @@ static i64 fts5CursorRowid(Fts5Cursor *pCsr){ ** exposes %_content.rowid as the rowid for the virtual table. The ** rowid should be written to *pRowid. */ -static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ +static int fts5RowidMethod(tdsqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; int ePlan = pCsr->ePlan; @@ -197444,7 +225960,7 @@ static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ break; default: - *pRowid = sqlite3_column_int64(pCsr->pStmt, 0); + *pRowid = tdsqlite3_column_int64(pCsr->pStmt, 0); break; } @@ -197456,45 +225972,52 @@ static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise. ** ** If argument bErrormsg is true and an error occurs, an error message may -** be left in sqlite3_vtab.zErrMsg. +** be left in tdsqlite3_vtab.zErrMsg. */ static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){ int rc = SQLITE_OK; /* If the cursor does not yet have a statement handle, obtain one now. */ if( pCsr->pStmt==0 ){ - Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); + Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab); int eStmt = fts5StmtType(pCsr); - rc = sqlite3Fts5StorageStmt( - pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0) + rc = tdsqlite3Fts5StorageStmt( + pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->p.base.zErrMsg:0) ); - assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 ); + assert( rc!=SQLITE_OK || pTab->p.base.zErrMsg==0 ); assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ); } if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){ + Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); assert( pCsr->pExpr ); - sqlite3_reset(pCsr->pStmt); - sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr)); - rc = sqlite3_step(pCsr->pStmt); + tdsqlite3_reset(pCsr->pStmt); + tdsqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr)); + pTab->pConfig->bLock++; + rc = tdsqlite3_step(pCsr->pStmt); + pTab->pConfig->bLock--; if( rc==SQLITE_ROW ){ rc = SQLITE_OK; CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT); }else{ - rc = sqlite3_reset(pCsr->pStmt); + rc = tdsqlite3_reset(pCsr->pStmt); if( rc==SQLITE_OK ){ rc = FTS5_CORRUPT; + }else if( pTab->pConfig->pzErrmsg ){ + *pTab->pConfig->pzErrmsg = tdsqlite3_mprintf( + "%s", tdsqlite3_errmsg(pTab->pConfig->db) + ); } } } return rc; } -static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){ +static void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){ va_list ap; /* ... printf arguments */ va_start(ap, zFormat); - assert( p->base.zErrMsg==0 ); - p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap); + assert( p->p.base.zErrMsg==0 ); + p->p.base.zErrMsg = tdsqlite3_vmprintf(zFormat, ap); va_end(ap); } @@ -197514,15 +226037,15 @@ static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){ ** more commands are added to this function. */ static int fts5SpecialInsert( - Fts5Table *pTab, /* Fts5 table object */ + Fts5FullTable *pTab, /* Fts5 table object */ const char *zCmd, /* Text inserted into table-name column */ - sqlite3_value *pVal /* Value inserted into rank column */ + tdsqlite3_value *pVal /* Value inserted into rank column */ ){ - Fts5Config *pConfig = pTab->pConfig; + Fts5Config *pConfig = pTab->p.pConfig; int rc = SQLITE_OK; int bError = 0; - if( 0==sqlite3_stricmp("delete-all", zCmd) ){ + if( 0==tdsqlite3_stricmp("delete-all", zCmd) ){ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){ fts5SetVtabError(pTab, "'delete-all' may only be used with a " @@ -197530,38 +226053,38 @@ static int fts5SpecialInsert( ); rc = SQLITE_ERROR; }else{ - rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage); + rc = tdsqlite3Fts5StorageDeleteAll(pTab->pStorage); } - }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){ + }else if( 0==tdsqlite3_stricmp("rebuild", zCmd) ){ if( pConfig->eContent==FTS5_CONTENT_NONE ){ fts5SetVtabError(pTab, "'rebuild' may not be used with a contentless fts5 table" ); rc = SQLITE_ERROR; }else{ - rc = sqlite3Fts5StorageRebuild(pTab->pStorage); + rc = tdsqlite3Fts5StorageRebuild(pTab->pStorage); } - }else if( 0==sqlite3_stricmp("optimize", zCmd) ){ - rc = sqlite3Fts5StorageOptimize(pTab->pStorage); - }else if( 0==sqlite3_stricmp("merge", zCmd) ){ - int nMerge = sqlite3_value_int(pVal); - rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge); - }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){ - rc = sqlite3Fts5StorageIntegrity(pTab->pStorage); + }else if( 0==tdsqlite3_stricmp("optimize", zCmd) ){ + rc = tdsqlite3Fts5StorageOptimize(pTab->pStorage); + }else if( 0==tdsqlite3_stricmp("merge", zCmd) ){ + int nMerge = tdsqlite3_value_int(pVal); + rc = tdsqlite3Fts5StorageMerge(pTab->pStorage, nMerge); + }else if( 0==tdsqlite3_stricmp("integrity-check", zCmd) ){ + rc = tdsqlite3Fts5StorageIntegrity(pTab->pStorage); #ifdef SQLITE_DEBUG - }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){ - pConfig->bPrefixIndex = sqlite3_value_int(pVal); + }else if( 0==tdsqlite3_stricmp("prefix-index", zCmd) ){ + pConfig->bPrefixIndex = tdsqlite3_value_int(pVal); #endif }else{ - rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex); + rc = tdsqlite3Fts5IndexLoadConfig(pTab->p.pIndex); if( rc==SQLITE_OK ){ - rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError); + rc = tdsqlite3Fts5ConfigSetValue(pTab->p.pConfig, zCmd, pVal, &bError); } if( rc==SQLITE_OK ){ if( bError ){ rc = SQLITE_ERROR; }else{ - rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0); + rc = tdsqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0); } } } @@ -197569,30 +226092,30 @@ static int fts5SpecialInsert( } static int fts5SpecialDelete( - Fts5Table *pTab, - sqlite3_value **apVal + Fts5FullTable *pTab, + tdsqlite3_value **apVal ){ int rc = SQLITE_OK; - int eType1 = sqlite3_value_type(apVal[1]); + int eType1 = tdsqlite3_value_type(apVal[1]); if( eType1==SQLITE_INTEGER ){ - sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]); - rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]); + tdsqlite3_int64 iDel = tdsqlite3_value_int64(apVal[1]); + rc = tdsqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]); } return rc; } static void fts5StorageInsert( int *pRc, - Fts5Table *pTab, - sqlite3_value **apVal, + Fts5FullTable *pTab, + tdsqlite3_value **apVal, i64 *piRowid ){ int rc = *pRc; if( rc==SQLITE_OK ){ - rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid); + rc = tdsqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid); } if( rc==SQLITE_OK ){ - rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid); + rc = tdsqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid); } *pRc = rc; } @@ -197612,13 +226135,13 @@ static void fts5StorageInsert( ** 4. Values for the two hidden columns (<tablename> and "rank"). */ static int fts5UpdateMethod( - sqlite3_vtab *pVtab, /* Virtual table handle */ + tdsqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Size of argument array */ - sqlite3_value **apVal, /* Array of arguments */ + tdsqlite3_value **apVal, /* Array of arguments */ sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ ){ - Fts5Table *pTab = (Fts5Table*)pVtab; - Fts5Config *pConfig = pTab->pConfig; + Fts5FullTable *pTab = (Fts5FullTable*)pVtab; + Fts5Config *pConfig = pTab->p.pConfig; int eType0; /* value_type() of apVal[0] */ int rc = SQLITE_OK; /* Return code */ @@ -197627,24 +226150,23 @@ static int fts5UpdateMethod( assert( pVtab->zErrMsg==0 ); assert( nArg==1 || nArg==(2+pConfig->nCol+2) ); - assert( nArg==1 - || sqlite3_value_type(apVal[1])==SQLITE_INTEGER - || sqlite3_value_type(apVal[1])==SQLITE_NULL + assert( tdsqlite3_value_type(apVal[0])==SQLITE_INTEGER + || tdsqlite3_value_type(apVal[0])==SQLITE_NULL ); - assert( pTab->pConfig->pzErrmsg==0 ); - pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg; + assert( pTab->p.pConfig->pzErrmsg==0 ); + pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg; /* Put any active cursors into REQUIRE_SEEK state. */ fts5TripCursors(pTab); - eType0 = sqlite3_value_type(apVal[0]); + eType0 = tdsqlite3_value_type(apVal[0]); if( eType0==SQLITE_NULL - && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL + && tdsqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL ){ /* A "special" INSERT op. These are handled separately. */ - const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]); + const char *z = (const char*)tdsqlite3_value_text(apVal[2+pConfig->nCol]); if( pConfig->eContent!=FTS5_CONTENT_NORMAL - && 0==sqlite3_stricmp("delete", z) + && 0==tdsqlite3_stricmp("delete", z) ){ rc = fts5SpecialDelete(pTab, apVal); }else{ @@ -197664,7 +226186,7 @@ static int fts5UpdateMethod( */ int eConflict = SQLITE_ABORT; if( pConfig->eContent==FTS5_CONTENT_NORMAL ){ - eConflict = sqlite3_vtab_on_conflict(pConfig->db); + eConflict = tdsqlite3_vtab_on_conflict(pConfig->db); } assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL ); @@ -197673,7 +226195,7 @@ static int fts5UpdateMethod( /* Filter out attempts to run UPDATE or DELETE on contentless tables. ** This is not suported. */ if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){ - pTab->base.zErrMsg = sqlite3_mprintf( + pTab->p.base.zErrMsg = tdsqlite3_mprintf( "cannot %s contentless fts5 table: %s", (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName ); @@ -197682,73 +226204,79 @@ static int fts5UpdateMethod( /* DELETE */ else if( nArg==1 ){ - i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */ - rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0); + i64 iDel = tdsqlite3_value_int64(apVal[0]); /* Rowid to delete */ + rc = tdsqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0); } - /* INSERT */ - else if( eType0!=SQLITE_INTEGER ){ - /* If this is a REPLACE, first remove the current entry (if any) */ - if( eConflict==SQLITE_REPLACE - && sqlite3_value_type(apVal[1])==SQLITE_INTEGER - ){ - i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */ - rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0); + /* INSERT or UPDATE */ + else{ + int eType1 = tdsqlite3_value_numeric_type(apVal[1]); + + if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){ + rc = SQLITE_MISMATCH; } - fts5StorageInsert(&rc, pTab, apVal, pRowid); - } - /* UPDATE */ - else{ - i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */ - i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */ - if( iOld!=iNew ){ - if( eConflict==SQLITE_REPLACE ){ - rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0); + else if( eType0!=SQLITE_INTEGER ){ + /* If this is a REPLACE, first remove the current entry (if any) */ + if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){ + i64 iNew = tdsqlite3_value_int64(apVal[1]); /* Rowid to delete */ + rc = tdsqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0); + } + fts5StorageInsert(&rc, pTab, apVal, pRowid); + } + + /* UPDATE */ + else{ + i64 iOld = tdsqlite3_value_int64(apVal[0]); /* Old rowid */ + i64 iNew = tdsqlite3_value_int64(apVal[1]); /* New rowid */ + if( eType1==SQLITE_INTEGER && iOld!=iNew ){ + if( eConflict==SQLITE_REPLACE ){ + rc = tdsqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0); + if( rc==SQLITE_OK ){ + rc = tdsqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0); + } + fts5StorageInsert(&rc, pTab, apVal, pRowid); + }else{ + rc = tdsqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid); + if( rc==SQLITE_OK ){ + rc = tdsqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0); + } + if( rc==SQLITE_OK ){ + rc = tdsqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid); + } } - fts5StorageInsert(&rc, pTab, apVal, pRowid); }else{ - rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid); - if( rc==SQLITE_OK ){ - rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid); - } + rc = tdsqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0); + fts5StorageInsert(&rc, pTab, apVal, pRowid); } - }else{ - rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0); - fts5StorageInsert(&rc, pTab, apVal, pRowid); } } } - pTab->pConfig->pzErrmsg = 0; + pTab->p.pConfig->pzErrmsg = 0; return rc; } /* ** Implementation of xSync() method. */ -static int fts5SyncMethod(sqlite3_vtab *pVtab){ +static int fts5SyncMethod(tdsqlite3_vtab *pVtab){ int rc; - Fts5Table *pTab = (Fts5Table*)pVtab; + Fts5FullTable *pTab = (Fts5FullTable*)pVtab; fts5CheckTransactionState(pTab, FTS5_SYNC, 0); - pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg; + pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg; fts5TripCursors(pTab); - rc = sqlite3Fts5StorageSync(pTab->pStorage, 1); - pTab->pConfig->pzErrmsg = 0; + rc = tdsqlite3Fts5StorageSync(pTab->pStorage); + pTab->p.pConfig->pzErrmsg = 0; return rc; } /* ** Implementation of xBegin() method. */ -static int fts5BeginMethod(sqlite3_vtab *pVtab){ - fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0); - fts5NewTransaction((Fts5Table*)pVtab); +static int fts5BeginMethod(tdsqlite3_vtab *pVtab){ + fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0); + fts5NewTransaction((Fts5FullTable*)pVtab); return SQLITE_OK; } @@ -197757,9 +226285,9 @@ static int fts5BeginMethod(sqlite3_vtab *pVtab){ ** the pending-terms hash-table have already been flushed into the database ** by fts5SyncMethod(). */ -static int fts5CommitMethod(sqlite3_vtab *pVtab){ +static int fts5CommitMethod(tdsqlite3_vtab *pVtab){ UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */ - fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0); + fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_COMMIT, 0); return SQLITE_OK; } @@ -197767,11 +226295,11 @@ static int fts5CommitMethod(sqlite3_vtab *pVtab){ ** Implementation of xRollback(). Discard the contents of the pending-terms ** hash-table. Any changes made to the database are reverted by SQLite. */ -static int fts5RollbackMethod(sqlite3_vtab *pVtab){ +static int fts5RollbackMethod(tdsqlite3_vtab *pVtab){ int rc; - Fts5Table *pTab = (Fts5Table*)pVtab; + Fts5FullTable *pTab = (Fts5FullTable*)pVtab; fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0); - rc = sqlite3Fts5StorageRollback(pTab->pStorage); + rc = tdsqlite3Fts5StorageRollback(pTab->pStorage); return rc; } @@ -197790,17 +226318,17 @@ static int fts5ApiColumnCount(Fts5Context *pCtx){ static int fts5ApiColumnTotalSize( Fts5Context *pCtx, int iCol, - sqlite3_int64 *pnToken + tdsqlite3_int64 *pnToken ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; - Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); - return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken); + Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab); + return tdsqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken); } static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; - Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); - return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow); + Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab); + return tdsqlite3Fts5StorageRowCount(pTab->pStorage, pnRow); } static int fts5ApiTokenize( @@ -197811,19 +226339,19 @@ static int fts5ApiTokenize( ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); - return sqlite3Fts5Tokenize( + return tdsqlite3Fts5Tokenize( pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken ); } static int fts5ApiPhraseCount(Fts5Context *pCtx){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; - return sqlite3Fts5ExprPhraseCount(pCsr->pExpr); + return tdsqlite3Fts5ExprPhraseCount(pCsr->pExpr); } static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; - return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase); + return tdsqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase); } static int fts5ApiColumnText( @@ -197834,14 +226362,16 @@ static int fts5ApiColumnText( ){ int rc = SQLITE_OK; Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; - if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){ + if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab)) + || pCsr->ePlan==FTS5_PLAN_SPECIAL + ){ *pz = 0; *pn = 0; }else{ rc = fts5SeekCursor(pCsr, 0); if( rc==SQLITE_OK ){ - *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1); - *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1); + *pz = (const char*)tdsqlite3_column_text(pCsr->pStmt, iCol+1); + *pn = tdsqlite3_column_bytes(pCsr->pStmt, iCol+1); } } return rc; @@ -197862,21 +226392,21 @@ static int fts5CsrPoslist( if( pConfig->eDetail!=FTS5_DETAIL_FULL ){ Fts5PoslistPopulator *aPopulator; int i; - aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive); + aPopulator = tdsqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive); if( aPopulator==0 ) rc = SQLITE_NOMEM; for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){ int n; const char *z; rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n); if( rc==SQLITE_OK ){ - rc = sqlite3Fts5ExprPopulatePoslists( + rc = tdsqlite3Fts5ExprPopulatePoslists( pConfig, pCsr->pExpr, aPopulator, i, z, n ); } } - sqlite3_free(aPopulator); + tdsqlite3_free(aPopulator); if( pCsr->pSorter ){ - sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid); + tdsqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid); } } CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST); @@ -197888,7 +226418,7 @@ static int fts5CsrPoslist( *pn = pSorter->aIdx[iPhrase] - i1; *pa = &pSorter->aPoslist[i1]; }else{ - *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa); + *pn = tdsqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa); } return rc; @@ -197903,11 +226433,12 @@ static int fts5CacheInstArray(Fts5Cursor *pCsr){ int rc = SQLITE_OK; Fts5PoslistReader *aIter; /* One iterator for each phrase */ int nIter; /* Number of iterators/phrases */ + int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol; - nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr); + nIter = tdsqlite3Fts5ExprPhraseCount(pCsr->pExpr); if( pCsr->aInstIter==0 ){ - int nByte = sizeof(Fts5PoslistReader) * nIter; - pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte); + tdsqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter; + pCsr->aInstIter = (Fts5PoslistReader*)tdsqlite3Fts5MallocZero(&rc, nByte); } aIter = pCsr->aInstIter; @@ -197921,7 +226452,7 @@ static int fts5CacheInstArray(Fts5Cursor *pCsr){ int n; rc = fts5CsrPoslist(pCsr, i, &a, &n); if( rc==SQLITE_OK ){ - sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]); + tdsqlite3Fts5PoslistReaderInit(a, n, &aIter[i]); } } @@ -197941,7 +226472,7 @@ static int fts5CacheInstArray(Fts5Cursor *pCsr){ nInst++; if( nInst>=pCsr->nInstAlloc ){ pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32; - aInst = (int*)sqlite3_realloc( + aInst = (int*)tdsqlite3_realloc64( pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3 ); if( aInst ){ @@ -197956,7 +226487,11 @@ static int fts5CacheInstArray(Fts5Cursor *pCsr){ aInst[0] = iBest; aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos); aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos); - sqlite3Fts5PoslistReaderNext(&aIter[iBest]); + if( aInst[1]<0 || aInst[1]>=nCol ){ + rc = FTS5_CORRUPT; + break; + } + tdsqlite3Fts5PoslistReaderNext(&aIter[iBest]); } } @@ -198005,7 +226540,7 @@ static int fts5ApiInst( return rc; } -static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){ +static tdsqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){ return fts5CursorRowid((Fts5Cursor*)pCtx); } @@ -198028,14 +226563,14 @@ static int fts5ColumnSizeCb( static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; - Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); - Fts5Config *pConfig = pTab->pConfig; + Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab); + Fts5Config *pConfig = pTab->p.pConfig; int rc = SQLITE_OK; if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){ if( pConfig->bColumnsize ){ i64 iRowid = fts5CursorRowid(pCsr); - rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize); + rc = tdsqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize); }else if( pConfig->zContent==0 ){ int i; for(i=0; i<pConfig->nCol; i++){ @@ -198052,7 +226587,7 @@ static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){ pCsr->aColumnSize[i] = 0; rc = fts5ApiColumnText(pCtx, i, &z, &n); if( rc==SQLITE_OK ){ - rc = sqlite3Fts5Tokenize( + rc = tdsqlite3Fts5Tokenize( pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb ); } @@ -198099,7 +226634,7 @@ static int fts5ApiSetAuxdata( } }else{ int rc = SQLITE_OK; - pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata)); + pData = (Fts5Auxdata*)tdsqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata)); if( pData==0 ){ if( xDelete ) xDelete(pPtr); return rc; @@ -198222,7 +226757,7 @@ static int fts5ApiPhraseFirstColumn( n = pSorter->aIdx[iPhrase] - i1; pIter->a = &pSorter->aPoslist[i1]; }else{ - rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n); + rc = tdsqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n); } if( rc==SQLITE_OK ){ pIter->b = &pIter->a[n]; @@ -198285,23 +226820,23 @@ static int fts5ApiQueryPhrase( int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*) ){ Fts5Cursor *pCsr = (Fts5Cursor*)pCtx; - Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab); + Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab); int rc; Fts5Cursor *pNew = 0; - rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew); + rc = fts5OpenMethod(pCsr->base.pVtab, (tdsqlite3_vtab_cursor**)&pNew); if( rc==SQLITE_OK ){ pNew->ePlan = FTS5_PLAN_MATCH; pNew->iFirstRowid = SMALLEST_INT64; pNew->iLastRowid = LARGEST_INT64; - pNew->base.pVtab = (sqlite3_vtab*)pTab; - rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr); + pNew->base.pVtab = (tdsqlite3_vtab*)pTab; + rc = tdsqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr); } if( rc==SQLITE_OK ){ for(rc = fts5CursorFirst(pTab, pNew, 0); rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0; - rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew) + rc = fts5NextMethod((tdsqlite3_vtab_cursor*)pNew) ){ rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData); if( rc!=SQLITE_OK ){ @@ -198311,16 +226846,16 @@ static int fts5ApiQueryPhrase( } } - fts5CloseMethod((sqlite3_vtab_cursor*)pNew); + fts5CloseMethod((tdsqlite3_vtab_cursor*)pNew); return rc; } static void fts5ApiInvoke( Fts5Auxiliary *pAux, Fts5Cursor *pCsr, - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ assert( pCsr->pAux==0 ); pCsr->pAux = pAux; @@ -198337,9 +226872,9 @@ static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){ } static void fts5ApiCallback( - sqlite3_context *context, + tdsqlite3_context *context, int argc, - sqlite3_value **argv + tdsqlite3_value **argv ){ Fts5Auxiliary *pAux; @@ -198347,14 +226882,14 @@ static void fts5ApiCallback( i64 iCsrId; assert( argc>=1 ); - pAux = (Fts5Auxiliary*)sqlite3_user_data(context); - iCsrId = sqlite3_value_int64(argv[0]); + pAux = (Fts5Auxiliary*)tdsqlite3_user_data(context); + iCsrId = tdsqlite3_value_int64(argv[0]); pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId); - if( pCsr==0 ){ - char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId); - sqlite3_result_error(context, zErr, -1); - sqlite3_free(zErr); + if( pCsr==0 || pCsr->ePlan==0 ){ + char *zErr = tdsqlite3_mprintf("no such cursor: %lld", iCsrId); + tdsqlite3_result_error(context, zErr, -1); + tdsqlite3_free(zErr); }else{ fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]); } @@ -198362,30 +226897,24 @@ static void fts5ApiCallback( /* -** Given cursor id iId, return a pointer to the corresponding Fts5Index +** Given cursor id iId, return a pointer to the corresponding Fts5Table ** object. Or NULL If the cursor id does not exist. -** -** If successful, set *ppConfig to point to the associated config object -** before returning. */ -static Fts5Index *sqlite3Fts5IndexFromCsrid( +static Fts5Table *tdsqlite3Fts5TableFromCsrid( Fts5Global *pGlobal, /* FTS5 global context for db handle */ - i64 iCsrId, /* Id of cursor to find */ - Fts5Config **ppConfig /* OUT: Configuration object */ + i64 iCsrId /* Id of cursor to find */ ){ Fts5Cursor *pCsr; - Fts5Table *pTab; - pCsr = fts5CursorFromCsrid(pGlobal, iCsrId); - pTab = (Fts5Table*)pCsr->base.pVtab; - *ppConfig = pTab->pConfig; - - return pTab->pIndex; + if( pCsr ){ + return (Fts5Table*)pCsr->base.pVtab; + } + return 0; } /* ** Return a "position-list blob" corresponding to the current position of -** cursor pCsr via sqlite3_result_blob(). A position-list blob contains +** cursor pCsr via tdsqlite3_result_blob(). A position-list blob contains ** the current position-list for each phrase in the query associated with ** cursor pCsr. ** @@ -198398,10 +226927,10 @@ static Fts5Index *sqlite3Fts5IndexFromCsrid( ** list 1. And so on. There is no size field for the final position list, ** as it can be derived from the total size of the blob. */ -static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){ +static int fts5PoslistBlob(tdsqlite3_context *pCtx, Fts5Cursor *pCsr){ int i; int rc = SQLITE_OK; - int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr); + int nPhrase = tdsqlite3Fts5ExprPhraseCount(pCsr->pExpr); Fts5Buffer val; memset(&val, 0, sizeof(Fts5Buffer)); @@ -198411,16 +226940,16 @@ static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){ /* Append the varints */ for(i=0; i<(nPhrase-1); i++){ const u8 *dummy; - int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy); - sqlite3Fts5BufferAppendVarint(&rc, &val, nByte); + int nByte = tdsqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy); + tdsqlite3Fts5BufferAppendVarint(&rc, &val, nByte); } /* Append the position lists */ for(i=0; i<nPhrase; i++){ const u8 *pPoslist; int nPoslist; - nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist); - sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist); + nPoslist = tdsqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist); + tdsqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist); } break; @@ -198430,16 +226959,16 @@ static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){ for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){ const u8 *dummy; int nByte; - rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte); - sqlite3Fts5BufferAppendVarint(&rc, &val, nByte); + rc = tdsqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte); + tdsqlite3Fts5BufferAppendVarint(&rc, &val, nByte); } /* Append the position lists */ for(i=0; rc==SQLITE_OK && i<nPhrase; i++){ const u8 *pPoslist; int nPoslist; - rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist); - sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist); + rc = tdsqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist); + tdsqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist); } break; @@ -198447,7 +226976,7 @@ static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){ break; } - sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free); + tdsqlite3_result_blob(pCtx, val.p, val.n, tdsqlite3_free); return rc; } @@ -198456,12 +226985,12 @@ static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){ ** the row that the supplied cursor currently points to. */ static int fts5ColumnMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + tdsqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + tdsqlite3_context *pCtx, /* Context for tdsqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ - Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab); - Fts5Config *pConfig = pTab->pConfig; + Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab); + Fts5Config *pConfig = pTab->p.pConfig; Fts5Cursor *pCsr = (Fts5Cursor*)pCursor; int rc = SQLITE_OK; @@ -198469,7 +226998,7 @@ static int fts5ColumnMethod( if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){ if( iCol==pConfig->nCol ){ - sqlite3_result_int64(pCtx, pCsr->iSpecial); + tdsqlite3_result_int64(pCtx, pCsr->iSpecial); } }else @@ -198478,7 +227007,7 @@ static int fts5ColumnMethod( ** as the table. Return the cursor integer id number. This value is only ** useful in that it may be passed as the first argument to an FTS5 ** auxiliary function. */ - sqlite3_result_int64(pCtx, pCsr->iCsrId); + tdsqlite3_result_int64(pCtx, pCsr->iCsrId); }else if( iCol==pConfig->nCol+1 ){ /* The value of the "rank" column. */ @@ -198493,10 +227022,12 @@ static int fts5ColumnMethod( } } }else if( !fts5IsContentless(pTab) ){ + pConfig->pzErrmsg = &pTab->p.base.zErrMsg; rc = fts5SeekCursor(pCsr, 1); if( rc==SQLITE_OK ){ - sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1)); + tdsqlite3_result_value(pCtx, tdsqlite3_column_value(pCsr->pStmt, iCol+1)); } + pConfig->pzErrmsg = 0; } return rc; } @@ -198507,13 +227038,13 @@ static int fts5ColumnMethod( ** virtual table. */ static int fts5FindFunctionMethod( - sqlite3_vtab *pVtab, /* Virtual table handle */ + tdsqlite3_vtab *pVtab, /* Virtual table handle */ int nUnused, /* Number of SQL function arguments */ const char *zName, /* Name of SQL function */ - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ + void (**pxFunc)(tdsqlite3_context*,int,tdsqlite3_value**), /* OUT: Result */ void **ppArg /* OUT: User data for *pxFunc */ ){ - Fts5Table *pTab = (Fts5Table*)pVtab; + Fts5FullTable *pTab = (Fts5FullTable*)pVtab; Fts5Auxiliary *pAux; UNUSED_PARAM(nUnused); @@ -198532,11 +227063,16 @@ static int fts5FindFunctionMethod( ** Implementation of FTS5 xRename method. Rename an fts5 table. */ static int fts5RenameMethod( - sqlite3_vtab *pVtab, /* Virtual table handle */ + tdsqlite3_vtab *pVtab, /* Virtual table handle */ const char *zName /* New name of table */ ){ - Fts5Table *pTab = (Fts5Table*)pVtab; - return sqlite3Fts5StorageRename(pTab->pStorage, zName); + Fts5FullTable *pTab = (Fts5FullTable*)pVtab; + return tdsqlite3Fts5StorageRename(pTab->pStorage, zName); +} + +static int tdsqlite3Fts5FlushToDisk(Fts5Table *pTab){ + fts5TripCursors((Fts5FullTable*)pTab); + return tdsqlite3Fts5StorageSync(((Fts5FullTable*)pTab)->pStorage); } /* @@ -198544,12 +227080,10 @@ static int fts5RenameMethod( ** ** Flush the contents of the pending-terms table to disk. */ -static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ - Fts5Table *pTab = (Fts5Table*)pVtab; +static int fts5SavepointMethod(tdsqlite3_vtab *pVtab, int iSavepoint){ UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */ - fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint); - fts5TripCursors(pTab); - return sqlite3Fts5StorageSync(pTab->pStorage, 0); + fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_SAVEPOINT, iSavepoint); + return tdsqlite3Fts5FlushToDisk((Fts5Table*)pVtab); } /* @@ -198557,12 +227091,10 @@ static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ ** ** This is a no-op. */ -static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ - Fts5Table *pTab = (Fts5Table*)pVtab; +static int fts5ReleaseMethod(tdsqlite3_vtab *pVtab, int iSavepoint){ UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */ - fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint); - fts5TripCursors(pTab); - return sqlite3Fts5StorageSync(pTab->pStorage, 0); + fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_RELEASE, iSavepoint); + return tdsqlite3Fts5FlushToDisk((Fts5Table*)pVtab); } /* @@ -198570,12 +227102,12 @@ static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ ** ** Discard the contents of the pending terms table. */ -static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ - Fts5Table *pTab = (Fts5Table*)pVtab; +static int fts5RollbackToMethod(tdsqlite3_vtab *pVtab, int iSavepoint){ + Fts5FullTable *pTab = (Fts5FullTable*)pVtab; UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */ fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint); fts5TripCursors(pTab); - return sqlite3Fts5StorageRollback(pTab->pStorage); + return tdsqlite3Fts5StorageRollback(pTab->pStorage); } /* @@ -198589,17 +227121,17 @@ static int fts5CreateAux( void(*xDestroy)(void*) /* Destructor for pUserData */ ){ Fts5Global *pGlobal = (Fts5Global*)pApi; - int rc = sqlite3_overload_function(pGlobal->db, zName, -1); + int rc = tdsqlite3_overload_function(pGlobal->db, zName, -1); if( rc==SQLITE_OK ){ Fts5Auxiliary *pAux; - int nName; /* Size of zName in bytes, including \0 */ - int nByte; /* Bytes of space to allocate */ + tdsqlite3_int64 nName; /* Size of zName in bytes, including \0 */ + tdsqlite3_int64 nByte; /* Bytes of space to allocate */ - nName = (int)strlen(zName) + 1; + nName = strlen(zName) + 1; nByte = sizeof(Fts5Auxiliary) + nName; - pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte); + pAux = (Fts5Auxiliary*)tdsqlite3_malloc64(nByte); if( pAux ){ - memset(pAux, 0, nByte); + memset(pAux, 0, (size_t)nByte); pAux->zFunc = (char*)&pAux[1]; memcpy(pAux->zFunc, zName, nName); pAux->pGlobal = pGlobal; @@ -198629,15 +227161,15 @@ static int fts5CreateTokenizer( ){ Fts5Global *pGlobal = (Fts5Global*)pApi; Fts5TokenizerModule *pNew; - int nName; /* Size of zName and its \0 terminator */ - int nByte; /* Bytes of space to allocate */ + tdsqlite3_int64 nName; /* Size of zName and its \0 terminator */ + tdsqlite3_int64 nByte; /* Bytes of space to allocate */ int rc = SQLITE_OK; - nName = (int)strlen(zName) + 1; + nName = strlen(zName) + 1; nByte = sizeof(Fts5TokenizerModule) + nName; - pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte); + pNew = (Fts5TokenizerModule*)tdsqlite3_malloc64(nByte); if( pNew ){ - memset(pNew, 0, nByte); + memset(pNew, 0, (size_t)nByte); pNew->zName = (char*)&pNew[1]; memcpy(pNew->zName, zName, nName); pNew->pUserData = pUserData; @@ -198665,7 +227197,7 @@ static Fts5TokenizerModule *fts5LocateTokenizer( pMod = pGlobal->pDfltTok; }else{ for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){ - if( sqlite3_stricmp(zName, pMod->zName)==0 ) break; + if( tdsqlite3_stricmp(zName, pMod->zName)==0 ) break; } } @@ -198697,7 +227229,7 @@ static int fts5FindTokenizer( return rc; } -static int sqlite3Fts5GetTokenizer( +static int tdsqlite3Fts5GetTokenizer( Fts5Global *pGlobal, const char **azArg, int nArg, @@ -198712,12 +227244,12 @@ static int sqlite3Fts5GetTokenizer( if( pMod==0 ){ assert( nArg>0 ); rc = SQLITE_ERROR; - *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]); + *pzErr = tdsqlite3_mprintf("no such tokenizer: %s", azArg[0]); }else{ rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok); *ppTokApi = &pMod->x; if( rc!=SQLITE_OK && pzErr ){ - *pzErr = sqlite3_mprintf("error in tokenizer constructor"); + *pzErr = tdsqlite3_mprintf("error in tokenizer constructor"); } } @@ -198737,48 +227269,62 @@ static void fts5ModuleDestroy(void *pCtx){ for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){ pNextAux = pAux->pNext; if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData); - sqlite3_free(pAux); + tdsqlite3_free(pAux); } for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){ pNextTok = pTok->pNext; if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData); - sqlite3_free(pTok); + tdsqlite3_free(pTok); } - sqlite3_free(pGlobal); + tdsqlite3_free(pGlobal); } static void fts5Fts5Func( - sqlite3_context *pCtx, /* Function call context */ + tdsqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ - sqlite3_value **apUnused /* Function arguments */ + tdsqlite3_value **apArg /* Function arguments */ ){ - Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx); - char buf[8]; - UNUSED_PARAM2(nArg, apUnused); - assert( nArg==0 ); - assert( sizeof(buf)>=sizeof(pGlobal) ); - memcpy(buf, (void*)&pGlobal, sizeof(pGlobal)); - sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT); + Fts5Global *pGlobal = (Fts5Global*)tdsqlite3_user_data(pCtx); + fts5_api **ppApi; + UNUSED_PARAM(nArg); + assert( nArg==1 ); + ppApi = (fts5_api**)tdsqlite3_value_pointer(apArg[0], "fts5_api_ptr"); + if( ppApi ) *ppApi = &pGlobal->api; } /* ** Implementation of fts5_source_id() function. */ static void fts5SourceIdFunc( - sqlite3_context *pCtx, /* Function call context */ + tdsqlite3_context *pCtx, /* Function call context */ int nArg, /* Number of args */ - sqlite3_value **apUnused /* Function arguments */ + tdsqlite3_value **apUnused /* Function arguments */ ){ assert( nArg==0 ); UNUSED_PARAM2(nArg, apUnused); - sqlite3_result_text(pCtx, "fts5: 2016-11-28 19:13:37 bbd85d235f7037c6a033a9690534391ffeacecc8", -1, SQLITE_TRANSIENT); + tdsqlite3_result_text(pCtx, "fts5: 2020-01-22 18:38:59 f6affdd41608946fcfcea914ece149038a8b25a62bbe719ed2561c649b86d824", -1, SQLITE_TRANSIENT); } -static int fts5Init(sqlite3 *db){ - static const sqlite3_module fts5Mod = { - /* iVersion */ 2, +/* +** Return true if zName is the extension on one of the shadow tables used +** by this module. +*/ +static int fts5ShadowName(const char *zName){ + static const char *azName[] = { + "config", "content", "data", "docsize", "idx" + }; + unsigned int i; + for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){ + if( tdsqlite3_stricmp(zName, azName[i])==0 ) return 1; + } + return 0; +} + +static int fts5Init(tdsqlite3 *db){ + static const tdsqlite3_module fts5Mod = { + /* iVersion */ 3, /* xCreate */ fts5CreateMethod, /* xConnect */ fts5ConnectMethod, /* xBestIndex */ fts5BestIndexMethod, @@ -198801,12 +227347,13 @@ static int fts5Init(sqlite3 *db){ /* xSavepoint */ fts5SavepointMethod, /* xRelease */ fts5ReleaseMethod, /* xRollbackTo */ fts5RollbackToMethod, + /* xShadowName */ fts5ShadowName }; int rc; Fts5Global *pGlobal = 0; - pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global)); + pGlobal = (Fts5Global*)tdsqlite3_malloc(sizeof(Fts5Global)); if( pGlobal==0 ){ rc = SQLITE_NOMEM; }else{ @@ -198817,19 +227364,19 @@ static int fts5Init(sqlite3 *db){ pGlobal->api.xCreateFunction = fts5CreateAux; pGlobal->api.xCreateTokenizer = fts5CreateTokenizer; pGlobal->api.xFindTokenizer = fts5FindTokenizer; - rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy); - if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db); - if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db); - if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api); - if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api); - if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db); + rc = tdsqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy); + if( rc==SQLITE_OK ) rc = tdsqlite3Fts5IndexInit(db); + if( rc==SQLITE_OK ) rc = tdsqlite3Fts5ExprInit(pGlobal, db); + if( rc==SQLITE_OK ) rc = tdsqlite3Fts5AuxInit(&pGlobal->api); + if( rc==SQLITE_OK ) rc = tdsqlite3Fts5TokenizerInit(&pGlobal->api); + if( rc==SQLITE_OK ) rc = tdsqlite3Fts5VocabInit(pGlobal, db); if( rc==SQLITE_OK ){ - rc = sqlite3_create_function( - db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0 + rc = tdsqlite3_create_function( + db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0 ); } if( rc==SQLITE_OK ){ - rc = sqlite3_create_function( + rc = tdsqlite3_create_function( db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0 ); } @@ -198840,8 +227387,8 @@ static int fts5Init(sqlite3 *db){ ** its entry point to enable the matchinfo() demo. */ #ifdef SQLITE_FTS5_ENABLE_TEST_MI if( rc==SQLITE_OK ){ - extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*); - rc = sqlite3Fts5TestRegisterMatchinfo(db); + extern int tdsqlite3Fts5TestRegisterMatchinfo(tdsqlite3*); + rc = tdsqlite3Fts5TestRegisterMatchinfo(db); } #endif @@ -198851,20 +227398,20 @@ static int fts5Init(sqlite3 *db){ /* ** The following functions are used to register the module with SQLite. If ** this module is being built as part of the SQLite core (SQLITE_CORE is -** defined), then sqlite3_open() will call sqlite3Fts5Init() directly. +** defined), then tdsqlite3_open() will call tdsqlite3Fts5Init() directly. ** ** Or, if this module is being built as a loadable extension, -** sqlite3Fts5Init() is omitted and the two standard entry points -** sqlite3_fts_init() and sqlite3_fts5_init() defined instead. +** tdsqlite3Fts5Init() is omitted and the two standard entry points +** tdsqlite3_fts_init() and tdsqlite3_fts5_init() defined instead. */ #ifndef SQLITE_CORE #ifdef _WIN32 __declspec(dllexport) #endif -SQLITE_API int sqlite3_fts_init( - sqlite3 *db, +SQLITE_API int tdsqlite3_fts_init( + tdsqlite3 *db, char **pzErrMsg, - const sqlite3_api_routines *pApi + const tdsqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ @@ -198874,17 +227421,17 @@ SQLITE_API int sqlite3_fts_init( #ifdef _WIN32 __declspec(dllexport) #endif -SQLITE_API int sqlite3_fts5_init( - sqlite3 *db, +SQLITE_API int tdsqlite3_fts5_init( + tdsqlite3 *db, char **pzErrMsg, - const sqlite3_api_routines *pApi + const tdsqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ return fts5Init(db); } #else -SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){ +SQLITE_PRIVATE int tdsqlite3Fts5Init(tdsqlite3 *db){ return fts5Init(db); } #endif @@ -198913,7 +227460,7 @@ struct Fts5Storage { int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */ i64 nTotalRow; /* Total number of rows in FTS table */ i64 *aTotalSize; /* Total sizes of each column */ - sqlite3_stmt *aStmt[11]; + tdsqlite3_stmt *aStmt[11]; }; @@ -198945,7 +227492,7 @@ struct Fts5Storage { static int fts5StorageGetStmt( Fts5Storage *p, /* Storage handle */ int eStmt, /* FTS5_STMT_XXX constant */ - sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */ + tdsqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */ char **pzErrMsg /* OUT: Error message (if any) */ ){ int rc = SQLITE_OK; @@ -198981,21 +227528,21 @@ static int fts5StorageGetStmt( switch( eStmt ){ case FTS5_STMT_SCAN: - zSql = sqlite3_mprintf(azStmt[eStmt], + zSql = tdsqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, pC->zContent ); break; case FTS5_STMT_SCAN_ASC: case FTS5_STMT_SCAN_DESC: - zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, + zSql = tdsqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, pC->zContent, pC->zContentRowid, pC->zContentRowid, pC->zContentRowid ); break; case FTS5_STMT_LOOKUP: - zSql = sqlite3_mprintf(azStmt[eStmt], + zSql = tdsqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, pC->zContent, pC->zContentRowid ); break; @@ -199006,43 +227553,47 @@ static int fts5StorageGetStmt( char *zBind; int i; - zBind = sqlite3_malloc(1 + nCol*2); + zBind = tdsqlite3_malloc64(1 + nCol*2); if( zBind ){ for(i=0; i<nCol; i++){ zBind[i*2] = '?'; zBind[i*2 + 1] = ','; } zBind[i*2-1] = '\0'; - zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind); - sqlite3_free(zBind); + zSql = tdsqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind); + tdsqlite3_free(zBind); } break; } default: - zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName); + zSql = tdsqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName); break; } if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0); - sqlite3_free(zSql); + int f = SQLITE_PREPARE_PERSISTENT; + if( eStmt>FTS5_STMT_LOOKUP ) f |= SQLITE_PREPARE_NO_VTAB; + p->pConfig->bLock++; + rc = tdsqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0); + p->pConfig->bLock--; + tdsqlite3_free(zSql); if( rc!=SQLITE_OK && pzErrMsg ){ - *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db)); + *pzErrMsg = tdsqlite3_mprintf("%s", tdsqlite3_errmsg(pC->db)); } } } *ppStmt = p->aStmt[eStmt]; - sqlite3_reset(*ppStmt); + tdsqlite3_reset(*ppStmt); return rc; } static int fts5ExecPrintf( - sqlite3 *db, + tdsqlite3 *db, char **pzErr, const char *zFormat, ... @@ -199052,13 +227603,13 @@ static int fts5ExecPrintf( char *zSql; va_start(ap, zFormat); - zSql = sqlite3_vmprintf(zFormat, ap); + zSql = tdsqlite3_vmprintf(zFormat, ap); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_exec(db, zSql, 0, 0, pzErr); - sqlite3_free(zSql); + rc = tdsqlite3_exec(db, zSql, 0, 0, pzErr); + tdsqlite3_free(zSql); } va_end(ap); @@ -199069,7 +227620,7 @@ static int fts5ExecPrintf( ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error ** code otherwise. */ -static int sqlite3Fts5DropAll(Fts5Config *pConfig){ +static int tdsqlite3Fts5DropAll(Fts5Config *pConfig){ int rc = fts5ExecPrintf(pConfig->db, 0, "DROP TABLE IF EXISTS %Q.'%q_data';" "DROP TABLE IF EXISTS %Q.'%q_idx';" @@ -199107,9 +227658,9 @@ static void fts5StorageRenameOne( } } -static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){ +static int tdsqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){ Fts5Config *pConfig = pStorage->pConfig; - int rc = sqlite3Fts5StorageSync(pStorage, 1); + int rc = tdsqlite3Fts5StorageSync(pStorage); fts5StorageRenameOne(pConfig, &rc, "data", zName); fts5StorageRenameOne(pConfig, &rc, "idx", zName); @@ -199127,7 +227678,7 @@ static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){ ** Create the shadow table named zPost, with definition zDefn. Return ** SQLITE_OK if successful, or an SQLite error code otherwise. */ -static int sqlite3Fts5CreateTable( +static int tdsqlite3Fts5CreateTable( Fts5Config *pConfig, /* FTS5 configuration */ const char *zPost, /* Shadow table to create (e.g. "content") */ const char *zDefn, /* Columns etc. for shadow table */ @@ -199145,11 +227696,11 @@ static int sqlite3Fts5CreateTable( "" ); if( zErr ){ - *pzErr = sqlite3_mprintf( + *pzErr = tdsqlite3_mprintf( "fts5: error creating shadow table %q_%s: %s", pConfig->zName, zPost, zErr ); - sqlite3_free(zErr); + tdsqlite3_free(zErr); } return rc; @@ -199162,7 +227713,7 @@ static int sqlite3Fts5CreateTable( ** If successful, set *pp to point to the new object and return SQLITE_OK. ** Otherwise, set *pp to NULL and return an SQLite error code. */ -static int sqlite3Fts5StorageOpen( +static int tdsqlite3Fts5StorageOpen( Fts5Config *pConfig, Fts5Index *pIndex, int bCreate, @@ -199171,14 +227722,14 @@ static int sqlite3Fts5StorageOpen( ){ int rc = SQLITE_OK; Fts5Storage *p; /* New object */ - int nByte; /* Bytes of space to allocate */ + tdsqlite3_int64 nByte; /* Bytes of space to allocate */ nByte = sizeof(Fts5Storage) /* Fts5Storage object */ + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */ - *pp = p = (Fts5Storage*)sqlite3_malloc(nByte); + *pp = p = (Fts5Storage*)tdsqlite3_malloc64(nByte); if( !p ) return SQLITE_NOMEM; - memset(p, 0, nByte); + memset(p, 0, (size_t)nByte); p->aTotalSize = (i64*)&p[1]; p->pConfig = pConfig; p->pIndex = pIndex; @@ -199186,59 +227737,59 @@ static int sqlite3Fts5StorageOpen( if( bCreate ){ if( pConfig->eContent==FTS5_CONTENT_NORMAL ){ int nDefn = 32 + pConfig->nCol*10; - char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10); + char *zDefn = tdsqlite3_malloc64(32 + (tdsqlite3_int64)pConfig->nCol * 10); if( zDefn==0 ){ rc = SQLITE_NOMEM; }else{ int i; int iOff; - sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY"); + tdsqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY"); iOff = (int)strlen(zDefn); for(i=0; i<pConfig->nCol; i++){ - sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i); + tdsqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i); iOff += (int)strlen(&zDefn[iOff]); } - rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr); + rc = tdsqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr); } - sqlite3_free(zDefn); + tdsqlite3_free(zDefn); } if( rc==SQLITE_OK && pConfig->bColumnsize ){ - rc = sqlite3Fts5CreateTable( + rc = tdsqlite3Fts5CreateTable( pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr ); } if( rc==SQLITE_OK ){ - rc = sqlite3Fts5CreateTable( + rc = tdsqlite3Fts5CreateTable( pConfig, "config", "k PRIMARY KEY, v", 1, pzErr ); } if( rc==SQLITE_OK ){ - rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION); + rc = tdsqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION); } } if( rc ){ - sqlite3Fts5StorageClose(p); + tdsqlite3Fts5StorageClose(p); *pp = 0; } return rc; } /* -** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen(). +** Close a handle opened by an earlier call to tdsqlite3Fts5StorageOpen(). */ -static int sqlite3Fts5StorageClose(Fts5Storage *p){ +static int tdsqlite3Fts5StorageClose(Fts5Storage *p){ int rc = SQLITE_OK; if( p ){ int i; /* Finalize all SQL statements */ for(i=0; i<ArraySize(p->aStmt); i++){ - sqlite3_finalize(p->aStmt[i]); + tdsqlite3_finalize(p->aStmt[i]); } - sqlite3_free(p); + tdsqlite3_free(p); } return rc; } @@ -199268,7 +227819,7 @@ static int fts5StorageInsertCallback( if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){ pCtx->szCol++; } - return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken); + return tdsqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken); } /* @@ -199279,40 +227830,40 @@ static int fts5StorageInsertCallback( static int fts5StorageDeleteFromIndex( Fts5Storage *p, i64 iDel, - sqlite3_value **apVal + tdsqlite3_value **apVal ){ Fts5Config *pConfig = p->pConfig; - sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */ + tdsqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */ int rc; /* Return code */ - int rc2; /* sqlite3_reset() return code */ + int rc2; /* tdsqlite3_reset() return code */ int iCol; Fts5InsertCtx ctx; if( apVal==0 ){ rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0); if( rc!=SQLITE_OK ) return rc; - sqlite3_bind_int64(pSeek, 1, iDel); - if( sqlite3_step(pSeek)!=SQLITE_ROW ){ - return sqlite3_reset(pSeek); + tdsqlite3_bind_int64(pSeek, 1, iDel); + if( tdsqlite3_step(pSeek)!=SQLITE_ROW ){ + return tdsqlite3_reset(pSeek); } } ctx.pStorage = p; ctx.iCol = -1; - rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel); + rc = tdsqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel); for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){ if( pConfig->abUnindexed[iCol-1]==0 ){ const char *zText; int nText; if( pSeek ){ - zText = (const char*)sqlite3_column_text(pSeek, iCol); - nText = sqlite3_column_bytes(pSeek, iCol); + zText = (const char*)tdsqlite3_column_text(pSeek, iCol); + nText = tdsqlite3_column_bytes(pSeek, iCol); }else{ - zText = (const char*)sqlite3_value_text(apVal[iCol-1]); - nText = sqlite3_value_bytes(apVal[iCol-1]); + zText = (const char*)tdsqlite3_value_text(apVal[iCol-1]); + nText = tdsqlite3_value_bytes(apVal[iCol-1]); } ctx.szCol = 0; - rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, + rc = tdsqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, zText, nText, (void*)&ctx, fts5StorageInsertCallback ); p->aTotalSize[iCol-1] -= (i64)ctx.szCol; @@ -199320,7 +227871,7 @@ static int fts5StorageDeleteFromIndex( } p->nTotalRow--; - rc2 = sqlite3_reset(pSeek); + rc2 = tdsqlite3_reset(pSeek); if( rc==SQLITE_OK ) rc = rc2; return rc; } @@ -199341,13 +227892,14 @@ static int fts5StorageInsertDocsize( ){ int rc = SQLITE_OK; if( p->pConfig->bColumnsize ){ - sqlite3_stmt *pReplace = 0; + tdsqlite3_stmt *pReplace = 0; rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pReplace, 1, iRowid); - sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC); - sqlite3_step(pReplace); - rc = sqlite3_reset(pReplace); + tdsqlite3_bind_int64(pReplace, 1, iRowid); + tdsqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC); + tdsqlite3_step(pReplace); + rc = tdsqlite3_reset(pReplace); + tdsqlite3_bind_null(pReplace, 2); } } return rc; @@ -199366,7 +227918,7 @@ static int fts5StorageInsertDocsize( static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){ int rc = SQLITE_OK; if( p->bTotalsValid==0 ){ - rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize); + rc = tdsqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize); p->bTotalsValid = bCache; } return rc; @@ -199386,14 +227938,14 @@ static int fts5StorageSaveTotals(Fts5Storage *p){ int rc = SQLITE_OK; memset(&buf, 0, sizeof(buf)); - sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow); + tdsqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow); for(i=0; i<nCol; i++){ - sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]); + tdsqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]); } if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n); + rc = tdsqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n); } - sqlite3_free(buf.p); + tdsqlite3_free(buf.p); return rc; } @@ -199401,10 +227953,10 @@ static int fts5StorageSaveTotals(Fts5Storage *p){ /* ** Remove a row from the FTS table. */ -static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){ +static int tdsqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, tdsqlite3_value **apVal){ Fts5Config *pConfig = p->pConfig; int rc; - sqlite3_stmt *pDel = 0; + tdsqlite3_stmt *pDel = 0; assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 ); rc = fts5StorageLoadTotals(p, 1); @@ -199418,9 +227970,9 @@ static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **ap if( rc==SQLITE_OK && pConfig->bColumnsize ){ rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDel, 1, iDel); - sqlite3_step(pDel); - rc = sqlite3_reset(pDel); + tdsqlite3_bind_int64(pDel, 1, iDel); + tdsqlite3_step(pDel); + rc = tdsqlite3_reset(pDel); } } @@ -199430,27 +227982,24 @@ static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **ap rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0); } if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDel, 1, iDel); - sqlite3_step(pDel); - rc = sqlite3_reset(pDel); + tdsqlite3_bind_int64(pDel, 1, iDel); + tdsqlite3_step(pDel); + rc = tdsqlite3_reset(pDel); } } - /* Write the averages record */ - if( rc==SQLITE_OK ){ - rc = fts5StorageSaveTotals(p); - } - return rc; } /* ** Delete all entries in the FTS5 index. */ -static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){ +static int tdsqlite3Fts5StorageDeleteAll(Fts5Storage *p){ Fts5Config *pConfig = p->pConfig; int rc; + p->bTotalsValid = 0; + /* Delete the contents of the %_data and %_docsize tables. */ rc = fts5ExecPrintf(pConfig->db, 0, "DELETE FROM %Q.'%q_data';" @@ -199468,24 +228017,24 @@ static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){ /* Reinitialize the %_data table. This call creates the initial structure ** and averages records. */ if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IndexReinit(p->pIndex); + rc = tdsqlite3Fts5IndexReinit(p->pIndex); } if( rc==SQLITE_OK ){ - rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION); + rc = tdsqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION); } return rc; } -static int sqlite3Fts5StorageRebuild(Fts5Storage *p){ +static int tdsqlite3Fts5StorageRebuild(Fts5Storage *p){ Fts5Buffer buf = {0,0,0}; Fts5Config *pConfig = p->pConfig; - sqlite3_stmt *pScan = 0; + tdsqlite3_stmt *pScan = 0; Fts5InsertCtx ctx; - int rc; + int rc, rc2; memset(&ctx, 0, sizeof(Fts5InsertCtx)); ctx.pStorage = p; - rc = sqlite3Fts5StorageDeleteAll(p); + rc = tdsqlite3Fts5StorageDeleteAll(p); if( rc==SQLITE_OK ){ rc = fts5StorageLoadTotals(p, 1); } @@ -199494,23 +228043,24 @@ static int sqlite3Fts5StorageRebuild(Fts5Storage *p){ rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0); } - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){ - i64 iRowid = sqlite3_column_int64(pScan, 0); + while( rc==SQLITE_OK && SQLITE_ROW==tdsqlite3_step(pScan) ){ + i64 iRowid = tdsqlite3_column_int64(pScan, 0); - sqlite3Fts5BufferZero(&buf); - rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid); + tdsqlite3Fts5BufferZero(&buf); + rc = tdsqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid); for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){ ctx.szCol = 0; if( pConfig->abUnindexed[ctx.iCol]==0 ){ - rc = sqlite3Fts5Tokenize(pConfig, + const char *zText = (const char*)tdsqlite3_column_text(pScan, ctx.iCol+1); + int nText = tdsqlite3_column_bytes(pScan, ctx.iCol+1); + rc = tdsqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, - (const char*)sqlite3_column_text(pScan, ctx.iCol+1), - sqlite3_column_bytes(pScan, ctx.iCol+1), + zText, nText, (void*)&ctx, fts5StorageInsertCallback ); } - sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol); + tdsqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol); p->aTotalSize[ctx.iCol] += (i64)ctx.szCol; } p->nTotalRow++; @@ -199519,7 +228069,9 @@ static int sqlite3Fts5StorageRebuild(Fts5Storage *p){ rc = fts5StorageInsertDocsize(p, iRowid, &buf); } } - sqlite3_free(buf.p); + tdsqlite3_free(buf.p); + rc2 = tdsqlite3_reset(pScan); + if( rc==SQLITE_OK ) rc = rc2; /* Write the averages record */ if( rc==SQLITE_OK ){ @@ -199528,16 +228080,16 @@ static int sqlite3Fts5StorageRebuild(Fts5Storage *p){ return rc; } -static int sqlite3Fts5StorageOptimize(Fts5Storage *p){ - return sqlite3Fts5IndexOptimize(p->pIndex); +static int tdsqlite3Fts5StorageOptimize(Fts5Storage *p){ + return tdsqlite3Fts5IndexOptimize(p->pIndex); } -static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){ - return sqlite3Fts5IndexMerge(p->pIndex, nMerge); +static int tdsqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){ + return tdsqlite3Fts5IndexMerge(p->pIndex, nMerge); } -static int sqlite3Fts5StorageReset(Fts5Storage *p){ - return sqlite3Fts5IndexReset(p->pIndex); +static int tdsqlite3Fts5StorageReset(Fts5Storage *p){ + return tdsqlite3Fts5IndexReset(p->pIndex); } /* @@ -199552,16 +228104,16 @@ static int sqlite3Fts5StorageReset(Fts5Storage *p){ static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){ int rc = SQLITE_MISMATCH; if( p->pConfig->bColumnsize ){ - sqlite3_stmt *pReplace = 0; + tdsqlite3_stmt *pReplace = 0; rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_null(pReplace, 1); - sqlite3_bind_null(pReplace, 2); - sqlite3_step(pReplace); - rc = sqlite3_reset(pReplace); + tdsqlite3_bind_null(pReplace, 1); + tdsqlite3_bind_null(pReplace, 2); + tdsqlite3_step(pReplace); + rc = tdsqlite3_reset(pReplace); } if( rc==SQLITE_OK ){ - *piRowid = sqlite3_last_insert_rowid(p->pConfig->db); + *piRowid = tdsqlite3_last_insert_rowid(p->pConfig->db); } } return rc; @@ -199570,9 +228122,9 @@ static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){ /* ** Insert a new row into the FTS content table. */ -static int sqlite3Fts5StorageContentInsert( +static int tdsqlite3Fts5StorageContentInsert( Fts5Storage *p, - sqlite3_value **apVal, + tdsqlite3_value **apVal, i64 *piRowid ){ Fts5Config *pConfig = p->pConfig; @@ -199580,23 +228132,23 @@ static int sqlite3Fts5StorageContentInsert( /* Insert the new row into the %_content table. */ if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){ - if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){ - *piRowid = sqlite3_value_int64(apVal[1]); + if( tdsqlite3_value_type(apVal[1])==SQLITE_INTEGER ){ + *piRowid = tdsqlite3_value_int64(apVal[1]); }else{ rc = fts5StorageNewRowid(p, piRowid); } }else{ - sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */ + tdsqlite3_stmt *pInsert = 0; /* Statement to write %_content table */ int i; /* Counter variable */ rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0); for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){ - rc = sqlite3_bind_value(pInsert, i, apVal[i]); + rc = tdsqlite3_bind_value(pInsert, i, apVal[i]); } if( rc==SQLITE_OK ){ - sqlite3_step(pInsert); - rc = sqlite3_reset(pInsert); + tdsqlite3_step(pInsert); + rc = tdsqlite3_reset(pInsert); } - *piRowid = sqlite3_last_insert_rowid(pConfig->db); + *piRowid = tdsqlite3_last_insert_rowid(pConfig->db); } return rc; @@ -199605,9 +228157,9 @@ static int sqlite3Fts5StorageContentInsert( /* ** Insert new entries into the FTS index and %_docsize table. */ -static int sqlite3Fts5StorageIndexInsert( +static int tdsqlite3Fts5StorageIndexInsert( Fts5Storage *p, - sqlite3_value **apVal, + tdsqlite3_value **apVal, i64 iRowid ){ Fts5Config *pConfig = p->pConfig; @@ -199620,20 +228172,21 @@ static int sqlite3Fts5StorageIndexInsert( rc = fts5StorageLoadTotals(p, 1); if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid); + rc = tdsqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid); } for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){ ctx.szCol = 0; if( pConfig->abUnindexed[ctx.iCol]==0 ){ - rc = sqlite3Fts5Tokenize(pConfig, + const char *zText = (const char*)tdsqlite3_value_text(apVal[ctx.iCol+2]); + int nText = tdsqlite3_value_bytes(apVal[ctx.iCol+2]); + rc = tdsqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, - (const char*)sqlite3_value_text(apVal[ctx.iCol+2]), - sqlite3_value_bytes(apVal[ctx.iCol+2]), + zText, nText, (void*)&ctx, fts5StorageInsertCallback ); } - sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol); + tdsqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol); p->aTotalSize[ctx.iCol] += (i64)ctx.szCol; } p->nTotalRow++; @@ -199642,12 +228195,7 @@ static int sqlite3Fts5StorageIndexInsert( if( rc==SQLITE_OK ){ rc = fts5StorageInsertDocsize(p, iRowid, &buf); } - sqlite3_free(buf.p); - - /* Write the averages record */ - if( rc==SQLITE_OK ){ - rc = fts5StorageSaveTotals(p); - } + tdsqlite3_free(buf.p); return rc; } @@ -199657,28 +228205,28 @@ static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){ char *zSql; int rc; - zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'", + zSql = tdsqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'", pConfig->zDb, pConfig->zName, zSuffix ); if( zSql==0 ){ rc = SQLITE_NOMEM; }else{ - sqlite3_stmt *pCnt = 0; - rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0); + tdsqlite3_stmt *pCnt = 0; + rc = tdsqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0); if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pCnt) ){ - *pnRow = sqlite3_column_int64(pCnt, 0); + if( SQLITE_ROW==tdsqlite3_step(pCnt) ){ + *pnRow = tdsqlite3_column_int64(pCnt, 0); } - rc = sqlite3_finalize(pCnt); + rc = tdsqlite3_finalize(pCnt); } } - sqlite3_free(zSql); + tdsqlite3_free(zSql); return rc; } /* -** Context object used by sqlite3Fts5StorageIntegrity(). +** Context object used by tdsqlite3Fts5StorageIntegrity(). */ typedef struct Fts5IntegrityCtx Fts5IntegrityCtx; struct Fts5IntegrityCtx { @@ -199735,20 +228283,20 @@ static int fts5StorageIntegrityCallback( break; } - rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent); + rc = tdsqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent); if( rc==SQLITE_OK && bPresent==0 ){ - pCtx->cksum ^= sqlite3Fts5IndexEntryCksum( + pCtx->cksum ^= tdsqlite3Fts5IndexEntryCksum( pCtx->iRowid, iCol, iPos, 0, pToken, nToken ); } for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){ const int nChar = pCtx->pConfig->aPrefix[ii]; - int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar); + int nByte = tdsqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar); if( nByte ){ - rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent); + rc = tdsqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent); if( bPresent==0 ){ - pCtx->cksum ^= sqlite3Fts5IndexEntryCksum( + pCtx->cksum ^= tdsqlite3Fts5IndexEntryCksum( pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte ); } @@ -199764,17 +228312,17 @@ static int fts5StorageIntegrityCallback( ** some other SQLite error code if an error occurs while attempting to ** determine this. */ -static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){ +static int tdsqlite3Fts5StorageIntegrity(Fts5Storage *p){ Fts5Config *pConfig = p->pConfig; int rc; /* Return code */ int *aColSize; /* Array of size pConfig->nCol */ i64 *aTotalSize; /* Array of size pConfig->nCol */ Fts5IntegrityCtx ctx; - sqlite3_stmt *pScan; + tdsqlite3_stmt *pScan; memset(&ctx, 0, sizeof(Fts5IntegrityCtx)); ctx.pConfig = p->pConfig; - aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64))); + aTotalSize = (i64*)tdsqlite3_malloc64(pConfig->nCol*(sizeof(int)+sizeof(i64))); if( !aTotalSize ) return SQLITE_NOMEM; aColSize = (int*)&aTotalSize[pConfig->nCol]; memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol); @@ -199784,28 +228332,29 @@ static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){ rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0); if( rc==SQLITE_OK ){ int rc2; - while( SQLITE_ROW==sqlite3_step(pScan) ){ + while( SQLITE_ROW==tdsqlite3_step(pScan) ){ int i; - ctx.iRowid = sqlite3_column_int64(pScan, 0); + ctx.iRowid = tdsqlite3_column_int64(pScan, 0); ctx.szCol = 0; if( pConfig->bColumnsize ){ - rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize); + rc = tdsqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize); } if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){ - rc = sqlite3Fts5TermsetNew(&ctx.pTermset); + rc = tdsqlite3Fts5TermsetNew(&ctx.pTermset); } for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){ if( pConfig->abUnindexed[i] ) continue; ctx.iCol = i; ctx.szCol = 0; if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){ - rc = sqlite3Fts5TermsetNew(&ctx.pTermset); + rc = tdsqlite3Fts5TermsetNew(&ctx.pTermset); } if( rc==SQLITE_OK ){ - rc = sqlite3Fts5Tokenize(pConfig, + const char *zText = (const char*)tdsqlite3_column_text(pScan, i+1); + int nText = tdsqlite3_column_bytes(pScan, i+1); + rc = tdsqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, - (const char*)sqlite3_column_text(pScan, i+1), - sqlite3_column_bytes(pScan, i+1), + zText, nText, (void*)&ctx, fts5StorageIntegrityCallback ); @@ -199815,16 +228364,16 @@ static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){ } aTotalSize[i] += ctx.szCol; if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){ - sqlite3Fts5TermsetFree(ctx.pTermset); + tdsqlite3Fts5TermsetFree(ctx.pTermset); ctx.pTermset = 0; } } - sqlite3Fts5TermsetFree(ctx.pTermset); + tdsqlite3Fts5TermsetFree(ctx.pTermset); ctx.pTermset = 0; if( rc!=SQLITE_OK ) break; } - rc2 = sqlite3_reset(pScan); + rc2 = tdsqlite3_reset(pScan); if( rc==SQLITE_OK ) rc = rc2; } @@ -199854,10 +228403,10 @@ static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){ ** verify, amongst other things, that it matches the checksum generated by ** inspecting the index itself. */ if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum); + rc = tdsqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum); } - sqlite3_free(aTotalSize); + tdsqlite3_free(aTotalSize); return rc; } @@ -199865,10 +228414,10 @@ static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){ ** Obtain an SQLite statement handle that may be used to read data from the ** %_content table. */ -static int sqlite3Fts5StorageStmt( +static int tdsqlite3Fts5StorageStmt( Fts5Storage *p, int eStmt, - sqlite3_stmt **pp, + tdsqlite3_stmt **pp, char **pzErrMsg ){ int rc; @@ -199886,23 +228435,23 @@ static int sqlite3Fts5StorageStmt( /* ** Release an SQLite statement handle obtained via an earlier call to -** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function -** must match that passed to the sqlite3Fts5StorageStmt() call. +** tdsqlite3Fts5StorageStmt(). The eStmt parameter passed to this function +** must match that passed to the tdsqlite3Fts5StorageStmt() call. */ -static void sqlite3Fts5StorageStmtRelease( +static void tdsqlite3Fts5StorageStmtRelease( Fts5Storage *p, int eStmt, - sqlite3_stmt *pStmt + tdsqlite3_stmt *pStmt ){ assert( eStmt==FTS5_STMT_SCAN_ASC || eStmt==FTS5_STMT_SCAN_DESC || eStmt==FTS5_STMT_LOOKUP ); if( p->aStmt[eStmt]==0 ){ - sqlite3_reset(pStmt); + tdsqlite3_reset(pStmt); p->aStmt[eStmt] = pStmt; }else{ - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); } } @@ -199927,24 +228476,24 @@ static int fts5StorageDecodeSizeArray( ** An SQLite error code is returned if an error occurs, or SQLITE_OK ** otherwise. */ -static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){ +static int tdsqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){ int nCol = p->pConfig->nCol; /* Number of user columns in table */ - sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */ + tdsqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */ int rc; /* Return Code */ assert( p->pConfig->bColumnsize ); rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0); if( rc==SQLITE_OK ){ int bCorrupt = 1; - sqlite3_bind_int64(pLookup, 1, iRowid); - if( SQLITE_ROW==sqlite3_step(pLookup) ){ - const u8 *aBlob = sqlite3_column_blob(pLookup, 0); - int nBlob = sqlite3_column_bytes(pLookup, 0); + tdsqlite3_bind_int64(pLookup, 1, iRowid); + if( SQLITE_ROW==tdsqlite3_step(pLookup) ){ + const u8 *aBlob = tdsqlite3_column_blob(pLookup, 0); + int nBlob = tdsqlite3_column_bytes(pLookup, 0); if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){ bCorrupt = 0; } } - rc = sqlite3_reset(pLookup); + rc = tdsqlite3_reset(pLookup); if( bCorrupt && rc==SQLITE_OK ){ rc = FTS5_CORRUPT; } @@ -199953,7 +228502,7 @@ static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){ return rc; } -static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){ +static int tdsqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){ int rc = fts5StorageLoadTotals(p, 0); if( rc==SQLITE_OK ){ *pnToken = 0; @@ -199971,10 +228520,16 @@ static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){ return rc; } -static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){ +static int tdsqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){ int rc = fts5StorageLoadTotals(p, 0); if( rc==SQLITE_OK ){ + /* nTotalRow being zero does not necessarily indicate a corrupt + ** database - it might be that the FTS5 table really does contain zero + ** rows. However this function is only called from the xRowCount() API, + ** and there is no way for that API to be invoked if the table contains + ** no rows. Hence the FTS5_CORRUPT return. */ *pnRow = p->nTotalRow; + if( p->nTotalRow<=0 ) rc = FTS5_CORRUPT; } return rc; } @@ -199982,41 +228537,47 @@ static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){ /* ** Flush any data currently held in-memory to disk. */ -static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){ - if( bCommit && p->bTotalsValid ){ - int rc = fts5StorageSaveTotals(p); +static int tdsqlite3Fts5StorageSync(Fts5Storage *p){ + int rc = SQLITE_OK; + i64 iLastRowid = tdsqlite3_last_insert_rowid(p->pConfig->db); + if( p->bTotalsValid ){ + rc = fts5StorageSaveTotals(p); p->bTotalsValid = 0; - if( rc!=SQLITE_OK ) return rc; } - return sqlite3Fts5IndexSync(p->pIndex, bCommit); + if( rc==SQLITE_OK ){ + rc = tdsqlite3Fts5IndexSync(p->pIndex); + } + tdsqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid); + return rc; } -static int sqlite3Fts5StorageRollback(Fts5Storage *p){ +static int tdsqlite3Fts5StorageRollback(Fts5Storage *p){ p->bTotalsValid = 0; - return sqlite3Fts5IndexRollback(p->pIndex); + return tdsqlite3Fts5IndexRollback(p->pIndex); } -static int sqlite3Fts5StorageConfigValue( +static int tdsqlite3Fts5StorageConfigValue( Fts5Storage *p, const char *z, - sqlite3_value *pVal, + tdsqlite3_value *pVal, int iVal ){ - sqlite3_stmt *pReplace = 0; + tdsqlite3_stmt *pReplace = 0; int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0); if( rc==SQLITE_OK ){ - sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC); + tdsqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC); if( pVal ){ - sqlite3_bind_value(pReplace, 2, pVal); + tdsqlite3_bind_value(pReplace, 2, pVal); }else{ - sqlite3_bind_int(pReplace, 2, iVal); + tdsqlite3_bind_int(pReplace, 2, iVal); } - sqlite3_step(pReplace); - rc = sqlite3_reset(pReplace); + tdsqlite3_step(pReplace); + rc = tdsqlite3_reset(pReplace); + tdsqlite3_bind_null(pReplace, 1); } if( rc==SQLITE_OK && pVal ){ int iNew = p->pConfig->iCookie + 1; - rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew); + rc = tdsqlite3Fts5IndexSetCookie(p->pIndex, iNew); if( rc==SQLITE_OK ){ p->pConfig->iCookie = iNew; } @@ -200081,7 +228642,7 @@ static void fts5AsciiAddExceptions( ** Delete a "ascii" tokenizer. */ static void fts5AsciiDelete(Fts5Tokenizer *p){ - sqlite3_free(p); + tdsqlite3_free(p); } /* @@ -200098,7 +228659,7 @@ static int fts5AsciiCreate( if( nArg%2 ){ rc = SQLITE_ERROR; }else{ - p = sqlite3_malloc(sizeof(AsciiTokenizer)); + p = tdsqlite3_malloc(sizeof(AsciiTokenizer)); if( p==0 ){ rc = SQLITE_NOMEM; }else{ @@ -200107,10 +228668,10 @@ static int fts5AsciiCreate( memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar)); for(i=0; rc==SQLITE_OK && i<nArg; i+=2){ const char *zArg = azArg[i+1]; - if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){ + if( 0==tdsqlite3_stricmp(azArg[i], "tokenchars") ){ fts5AsciiAddExceptions(p, zArg, 1); }else - if( 0==sqlite3_stricmp(azArg[i], "separators") ){ + if( 0==tdsqlite3_stricmp(azArg[i], "separators") ){ fts5AsciiAddExceptions(p, zArg, 0); }else{ rc = SQLITE_ERROR; @@ -200177,8 +228738,8 @@ static int fts5AsciiTokenize( /* Fold to lower case */ nByte = ie-is; if( nByte>nFold ){ - if( pFold!=aFold ) sqlite3_free(pFold); - pFold = sqlite3_malloc(nByte*2); + if( pFold!=aFold ) tdsqlite3_free(pFold); + pFold = tdsqlite3_malloc64((tdsqlite3_int64)nByte*2); if( pFold==0 ){ rc = SQLITE_NOMEM; break; @@ -200192,7 +228753,7 @@ static int fts5AsciiTokenize( is = ie+1; } - if( pFold!=aFold ) sqlite3_free(pFold); + if( pFold!=aFold ) tdsqlite3_free(pFold); if( rc==SQLITE_DONE ) rc = SQLITE_OK; return rc; } @@ -200204,12 +228765,12 @@ static int fts5AsciiTokenize( /* ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied -** from the sqlite3 source file utf.c. If this file is compiled as part +** from the tdsqlite3 source file utf.c. If this file is compiled as part ** of the amalgamation, they are not required. */ #ifndef SQLITE_AMALGAMATION -static const unsigned char sqlite3Utf8Trans1[] = { +static const unsigned char tdsqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, @@ -200223,7 +228784,7 @@ static const unsigned char sqlite3Utf8Trans1[] = { #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ - c = sqlite3Utf8Trans1[c-0xc0]; \ + c = tdsqlite3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ @@ -200260,11 +228821,18 @@ struct Unicode61Tokenizer { unsigned char aTokenChar[128]; /* ASCII range token characters */ char *aFold; /* Buffer to fold text into */ int nFold; /* Size of aFold[] in bytes */ - int bRemoveDiacritic; /* True if remove_diacritics=1 is set */ + int eRemoveDiacritic; /* True if remove_diacritics=1 is set */ int nException; int *aiException; + + unsigned char aCategory[32]; /* True for token char categories */ }; +/* Values for eRemoveDiacritic (must match internals of fts5_unicode2.c) */ +#define FTS5_REMOVE_DIACRITICS_NONE 0 +#define FTS5_REMOVE_DIACRITICS_SIMPLE 1 +#define FTS5_REMOVE_DIACRITICS_COMPLEX 2 + static int fts5UnicodeAddExceptions( Unicode61Tokenizer *p, /* Tokenizer object */ const char *z, /* Characters to treat as exceptions */ @@ -200275,25 +228843,26 @@ static int fts5UnicodeAddExceptions( int *aNew; if( n>0 ){ - aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int)); + aNew = (int*)tdsqlite3_realloc64(p->aiException, + (n+p->nException)*sizeof(int)); if( aNew ){ int nNew = p->nException; const unsigned char *zCsr = (const unsigned char*)z; const unsigned char *zTerm = (const unsigned char*)&z[n]; while( zCsr<zTerm ){ - int iCode; + u32 iCode; int bToken; READ_UTF8(zCsr, zTerm, iCode); if( iCode<128 ){ p->aTokenChar[iCode] = (unsigned char)bTokenChars; }else{ - bToken = sqlite3Fts5UnicodeIsalnum(iCode); + bToken = p->aCategory[tdsqlite3Fts5UnicodeCategory(iCode)]; assert( (bToken==0 || bToken==1) ); assert( (bTokenChars==0 || bTokenChars==1) ); - if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){ + if( bToken!=bTokenChars && tdsqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){ int i; for(i=0; i<nNew; i++){ - if( aNew[i]>iCode ) break; + if( (u32)aNew[i]>iCode ) break; } memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int)); aNew[i] = iCode; @@ -200341,13 +228910,28 @@ static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){ static void fts5UnicodeDelete(Fts5Tokenizer *pTok){ if( pTok ){ Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok; - sqlite3_free(p->aiException); - sqlite3_free(p->aFold); - sqlite3_free(p); + tdsqlite3_free(p->aiException); + tdsqlite3_free(p->aFold); + tdsqlite3_free(p); } return; } +static int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){ + const char *z = zCat; + + while( *z ){ + while( *z==' ' || *z=='\t' ) z++; + if( *z && tdsqlite3Fts5UnicodeCatParse(z, p->aCategory) ){ + return SQLITE_ERROR; + } + while( *z!=' ' && *z!='\t' && *z!='\0' ) z++; + } + + tdsqlite3Fts5UnicodeAscii(p->aCategory, p->aTokenChar); + return SQLITE_OK; +} + /* ** Create a "unicode61" tokenizer. */ @@ -200364,34 +228948,56 @@ static int fts5UnicodeCreate( if( nArg%2 ){ rc = SQLITE_ERROR; }else{ - p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer)); + p = (Unicode61Tokenizer*)tdsqlite3_malloc(sizeof(Unicode61Tokenizer)); if( p ){ + const char *zCat = "L* N* Co"; int i; memset(p, 0, sizeof(Unicode61Tokenizer)); - memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar)); - p->bRemoveDiacritic = 1; + + p->eRemoveDiacritic = FTS5_REMOVE_DIACRITICS_SIMPLE; p->nFold = 64; - p->aFold = sqlite3_malloc(p->nFold * sizeof(char)); + p->aFold = tdsqlite3_malloc64(p->nFold * sizeof(char)); if( p->aFold==0 ){ rc = SQLITE_NOMEM; } + + /* Search for a "categories" argument */ + for(i=0; rc==SQLITE_OK && i<nArg; i+=2){ + if( 0==tdsqlite3_stricmp(azArg[i], "categories") ){ + zCat = azArg[i+1]; + } + } + + if( rc==SQLITE_OK ){ + rc = unicodeSetCategories(p, zCat); + } + for(i=0; rc==SQLITE_OK && i<nArg; i+=2){ const char *zArg = azArg[i+1]; - if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){ - if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){ + if( 0==tdsqlite3_stricmp(azArg[i], "remove_diacritics") ){ + if( (zArg[0]!='0' && zArg[0]!='1' && zArg[0]!='2') || zArg[1] ){ rc = SQLITE_ERROR; + }else{ + p->eRemoveDiacritic = (zArg[0] - '0'); + assert( p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_NONE + || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_SIMPLE + || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_COMPLEX + ); } - p->bRemoveDiacritic = (zArg[0]=='1'); }else - if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){ + if( 0==tdsqlite3_stricmp(azArg[i], "tokenchars") ){ rc = fts5UnicodeAddExceptions(p, zArg, 1); }else - if( 0==sqlite3_stricmp(azArg[i], "separators") ){ + if( 0==tdsqlite3_stricmp(azArg[i], "separators") ){ rc = fts5UnicodeAddExceptions(p, zArg, 0); + }else + if( 0==tdsqlite3_stricmp(azArg[i], "categories") ){ + /* no-op */ }else{ rc = SQLITE_ERROR; } } + }else{ rc = SQLITE_NOMEM; } @@ -200410,8 +229016,10 @@ static int fts5UnicodeCreate( ** character (not a separator). */ static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){ - assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); - return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode); + return ( + p->aCategory[tdsqlite3Fts5UnicodeCategory((u32)iCode)] + ^ fts5UnicodeIsException(p, iCode) + ); } static int fts5UnicodeTokenize( @@ -200438,7 +229046,7 @@ static int fts5UnicodeTokenize( /* Each iteration of this loop gobbles up a contiguous run of separators, ** then the next token. */ while( rc==SQLITE_OK ){ - int iCode; /* non-ASCII codepoint read from input */ + u32 iCode; /* non-ASCII codepoint read from input */ char *zOut = aFold; int is; int ie; @@ -200470,14 +229078,14 @@ static int fts5UnicodeTokenize( /* Grow the output buffer so that there is sufficient space to fit the ** largest possible utf-8 character. */ if( zOut>pEnd ){ - aFold = sqlite3_malloc(nFold*2); + aFold = tdsqlite3_malloc64((tdsqlite3_int64)nFold*2); if( aFold==0 ){ rc = SQLITE_NOMEM; goto tokenize_done; } zOut = &aFold[zOut - p->aFold]; memcpy(aFold, p->aFold, nFold); - sqlite3_free(p->aFold); + tdsqlite3_free(p->aFold); p->aFold = aFold; p->nFold = nFold = nFold*2; pEnd = &aFold[nFold-6]; @@ -200487,9 +229095,9 @@ static int fts5UnicodeTokenize( /* An non-ascii-range character. Fold it into the output buffer if ** it is a token character, or break out of the loop if it is not. */ READ_UTF8(zCsr, zTerm, iCode); - if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){ + if( fts5UnicodeIsAlnum(p,iCode)||tdsqlite3Fts5UnicodeIsdiacritic(iCode) ){ non_ascii_tokenchar: - iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic); + iCode = tdsqlite3Fts5UnicodeFold(iCode, p->eRemoveDiacritic); if( iCode ) WRITE_UTF8(zOut, iCode); }else{ break; @@ -200542,7 +229150,7 @@ static void fts5PorterDelete(Fts5Tokenizer *pTok){ if( p->pTokenizer ){ p->tokenizer.xDelete(p->pTokenizer); } - sqlite3_free(p); + tdsqlite3_free(p); } } @@ -200564,7 +229172,7 @@ static int fts5PorterCreate( zBase = azArg[0]; } - pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer)); + pRet = (PorterTokenizer*)tdsqlite3_malloc(sizeof(PorterTokenizer)); if( pRet ){ memset(pRet, 0, sizeof(PorterTokenizer)); rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer); @@ -201240,7 +229848,7 @@ static int fts5PorterTokenize( /* ** Register all built-in tokenizers with FTS5. */ -static int sqlite3Fts5TokenizerInit(fts5_api *pApi){ +static int tdsqlite3Fts5TokenizerInit(fts5_api *pApi){ struct BuiltinTokenizer { const char *zName; fts5_tokenizer x; @@ -201265,10 +229873,8 @@ static int sqlite3Fts5TokenizerInit(fts5_api *pApi){ return rc; } - - /* -** 2012 May 25 +** 2012-05-25 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: @@ -201287,135 +229893,6 @@ static int sqlite3Fts5TokenizerInit(fts5_api *pApi){ /* #include <assert.h> */ -/* -** Return true if the argument corresponds to a unicode codepoint -** classified as either a letter or a number. Otherwise false. -** -** The results are undefined if the value passed to this function -** is less than zero. -*/ -static int sqlite3Fts5UnicodeIsalnum(int c){ - /* Each unsigned integer in the following array corresponds to a contiguous - ** range of unicode codepoints that are not either letters or numbers (i.e. - ** codepoints for which this function should return 0). - ** - ** The most significant 22 bits in each 32-bit value contain the first - ** codepoint in the range. The least significant 10 bits are used to store - ** the size of the range (always at least 1). In other words, the value - ** ((C<<22) + N) represents a range of N codepoints starting with codepoint - ** C. It is not possible to represent a range larger than 1023 codepoints - ** using this format. - */ - static const unsigned int aEntry[] = { - 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07, - 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01, - 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401, - 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01, - 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01, - 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802, - 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F, - 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401, - 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804, - 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403, - 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812, - 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001, - 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802, - 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805, - 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401, - 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03, - 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807, - 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001, - 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01, - 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804, - 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001, - 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802, - 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01, - 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06, - 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007, - 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006, - 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417, - 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14, - 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07, - 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01, - 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001, - 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802, - 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F, - 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002, - 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802, - 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006, - 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D, - 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802, - 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027, - 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403, - 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805, - 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04, - 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401, - 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005, - 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B, - 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A, - 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001, - 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59, - 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807, - 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01, - 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E, - 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100, - 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10, - 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402, - 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804, - 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012, - 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004, - 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002, - 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803, - 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07, - 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02, - 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802, - 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013, - 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06, - 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003, - 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01, - 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403, - 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009, - 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003, - 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003, - 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E, - 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046, - 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401, - 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401, - 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F, - 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C, - 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002, - 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025, - 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6, - 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46, - 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060, - 0x380400F0, - }; - static const unsigned int aAscii[4] = { - 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001, - }; - - if( (unsigned int)c<128 ){ - return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 ); - }else if( (unsigned int)c<(1<<22) ){ - unsigned int key = (((unsigned int)c)<<10) | 0x000003FF; - int iRes = 0; - int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; - int iLo = 0; - while( iHi>=iLo ){ - int iTest = (iHi + iLo) / 2; - if( key >= aEntry[iTest] ){ - iRes = iTest; - iLo = iTest+1; - }else{ - iHi = iTest-1; - } - } - assert( aEntry[0]<key ); - assert( key>=aEntry[iRes] ); - return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF))); - } - return 1; -} /* @@ -201426,32 +229903,48 @@ static int sqlite3Fts5UnicodeIsalnum(int c){ ** E"). The resuls of passing a codepoint that corresponds to an ** uppercase letter are undefined. */ -static int fts5_remove_diacritic(int c){ +static int fts5_remove_diacritic(int c, int bComplex){ unsigned short aDia[] = { 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995, 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286, 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732, 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336, - 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928, - 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234, - 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504, - 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529, - 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, - 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, - 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, - 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, - 62924, 63050, 63082, 63274, 63390, + 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896, + 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106, + 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344, + 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198, + 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468, + 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704, + 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914, + 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218, + 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554, + 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766, + 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118, + 63182, 63242, 63274, 63310, 63368, 63390, }; - char aChar[] = { - '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c', - 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r', - 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o', - 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r', - 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0', - '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h', - 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't', - 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a', - 'e', 'i', 'o', 'u', 'y', +#define HIBIT ((unsigned char)0x80) + unsigned char aChar[] = { + '\0', 'a', 'c', 'e', 'i', 'n', + 'o', 'u', 'y', 'y', 'a', 'c', + 'd', 'e', 'e', 'g', 'h', 'i', + 'j', 'k', 'l', 'n', 'o', 'r', + 's', 't', 'u', 'u', 'w', 'y', + 'z', 'o', 'u', 'a', 'i', 'o', + 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o', + 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a', + 'e', 'i', 'o', 'r', 'u', 's', + 't', 'h', 'a', 'e', 'o'|HIBIT, 'o', + 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0', + '\0', '\0', '\0', '\0', 'a', 'b', + 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT, + 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT, + 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n', + 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's', + 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w', + 'w', 'x', 'y', 'z', 'h', 't', + 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT, + 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT, + 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y', }; unsigned int key = (((unsigned int)c)<<3) | 0x00000007; @@ -201468,7 +229961,8 @@ static int fts5_remove_diacritic(int c){ } } assert( key>=aDia[iRes] ); - return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]); + if( bComplex==0 && (aChar[iRes] & 0x80) ) return c; + return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F); } @@ -201476,13 +229970,13 @@ static int fts5_remove_diacritic(int c){ ** Return true if the argument interpreted as a unicode codepoint ** is a diacritical modifier character. */ -static int sqlite3Fts5UnicodeIsdiacritic(int c){ +static int tdsqlite3Fts5UnicodeIsdiacritic(int c){ unsigned int mask0 = 0x08029FDF; unsigned int mask1 = 0x000361F8; if( c<768 || c>817 ) return 0; return (c < 768+32) ? - (mask0 & (1 << (c-768))) : - (mask1 & (1 << (c-768-32))); + (mask0 & ((unsigned int)1 << (c-768))) : + (mask1 & ((unsigned int)1 << (c-768-32))); } @@ -201495,7 +229989,7 @@ static int sqlite3Fts5UnicodeIsdiacritic(int c){ ** The results are undefined if the value passed to this function ** is less than zero. */ -static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){ +static int tdsqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){ /* Each entry in the following array defines a rule for folding a range ** of codepoints to lower case. The rule applies to a range of nRange ** codepoints starting at codepoint iCode. @@ -201618,7 +230112,9 @@ static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){ assert( ret>0 ); } - if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret); + if( eRemoveDiacritic ){ + ret = fts5_remove_diacritic(ret, eRemoveDiacritic==2); + } } else if( c>=66560 && c<66600 ){ @@ -201628,6 +230124,532 @@ static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){ return ret; } + +static int tdsqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){ + aArray[0] = 1; + switch( zCat[0] ){ + case 'C': + switch( zCat[1] ){ + case 'c': aArray[1] = 1; break; + case 'f': aArray[2] = 1; break; + case 'n': aArray[3] = 1; break; + case 's': aArray[4] = 1; break; + case 'o': aArray[31] = 1; break; + case '*': + aArray[1] = 1; + aArray[2] = 1; + aArray[3] = 1; + aArray[4] = 1; + aArray[31] = 1; + break; + default: return 1; } + break; + + case 'L': + switch( zCat[1] ){ + case 'l': aArray[5] = 1; break; + case 'm': aArray[6] = 1; break; + case 'o': aArray[7] = 1; break; + case 't': aArray[8] = 1; break; + case 'u': aArray[9] = 1; break; + case 'C': aArray[30] = 1; break; + case '*': + aArray[5] = 1; + aArray[6] = 1; + aArray[7] = 1; + aArray[8] = 1; + aArray[9] = 1; + aArray[30] = 1; + break; + default: return 1; } + break; + + case 'M': + switch( zCat[1] ){ + case 'c': aArray[10] = 1; break; + case 'e': aArray[11] = 1; break; + case 'n': aArray[12] = 1; break; + case '*': + aArray[10] = 1; + aArray[11] = 1; + aArray[12] = 1; + break; + default: return 1; } + break; + + case 'N': + switch( zCat[1] ){ + case 'd': aArray[13] = 1; break; + case 'l': aArray[14] = 1; break; + case 'o': aArray[15] = 1; break; + case '*': + aArray[13] = 1; + aArray[14] = 1; + aArray[15] = 1; + break; + default: return 1; } + break; + + case 'P': + switch( zCat[1] ){ + case 'c': aArray[16] = 1; break; + case 'd': aArray[17] = 1; break; + case 'e': aArray[18] = 1; break; + case 'f': aArray[19] = 1; break; + case 'i': aArray[20] = 1; break; + case 'o': aArray[21] = 1; break; + case 's': aArray[22] = 1; break; + case '*': + aArray[16] = 1; + aArray[17] = 1; + aArray[18] = 1; + aArray[19] = 1; + aArray[20] = 1; + aArray[21] = 1; + aArray[22] = 1; + break; + default: return 1; } + break; + + case 'S': + switch( zCat[1] ){ + case 'c': aArray[23] = 1; break; + case 'k': aArray[24] = 1; break; + case 'm': aArray[25] = 1; break; + case 'o': aArray[26] = 1; break; + case '*': + aArray[23] = 1; + aArray[24] = 1; + aArray[25] = 1; + aArray[26] = 1; + break; + default: return 1; } + break; + + case 'Z': + switch( zCat[1] ){ + case 'l': aArray[27] = 1; break; + case 'p': aArray[28] = 1; break; + case 's': aArray[29] = 1; break; + case '*': + aArray[27] = 1; + aArray[28] = 1; + aArray[29] = 1; + break; + default: return 1; } + break; + + } + return 0; +} + +static u16 aFts5UnicodeBlock[] = { + 0, 1471, 1753, 1760, 1760, 1760, 1760, 1760, 1760, 1760, + 1760, 1760, 1760, 1760, 1760, 1763, 1765, + }; +static u16 aFts5UnicodeMap[] = { + 0, 32, 33, 36, 37, 40, 41, 42, 43, 44, + 45, 46, 48, 58, 60, 63, 65, 91, 92, 93, + 94, 95, 96, 97, 123, 124, 125, 126, 127, 160, + 161, 162, 166, 167, 168, 169, 170, 171, 172, 173, + 174, 175, 176, 177, 178, 180, 181, 182, 184, 185, + 186, 187, 188, 191, 192, 215, 216, 223, 247, 248, + 256, 312, 313, 329, 330, 377, 383, 385, 387, 388, + 391, 394, 396, 398, 402, 403, 405, 406, 409, 412, + 414, 415, 417, 418, 423, 427, 428, 431, 434, 436, + 437, 440, 442, 443, 444, 446, 448, 452, 453, 454, + 455, 456, 457, 458, 459, 460, 461, 477, 478, 496, + 497, 498, 499, 500, 503, 505, 506, 564, 570, 572, + 573, 575, 577, 580, 583, 584, 592, 660, 661, 688, + 706, 710, 722, 736, 741, 748, 749, 750, 751, 768, + 880, 884, 885, 886, 890, 891, 894, 900, 902, 903, + 904, 908, 910, 912, 913, 931, 940, 975, 977, 978, + 981, 984, 1008, 1012, 1014, 1015, 1018, 1020, 1021, 1072, + 1120, 1154, 1155, 1160, 1162, 1217, 1231, 1232, 1329, 1369, + 1370, 1377, 1417, 1418, 1423, 1425, 1470, 1471, 1472, 1473, + 1475, 1476, 1478, 1479, 1488, 1520, 1523, 1536, 1542, 1545, + 1547, 1548, 1550, 1552, 1563, 1566, 1568, 1600, 1601, 1611, + 1632, 1642, 1646, 1648, 1649, 1748, 1749, 1750, 1757, 1758, + 1759, 1765, 1767, 1769, 1770, 1774, 1776, 1786, 1789, 1791, + 1792, 1807, 1808, 1809, 1810, 1840, 1869, 1958, 1969, 1984, + 1994, 2027, 2036, 2038, 2039, 2042, 2048, 2070, 2074, 2075, + 2084, 2085, 2088, 2089, 2096, 2112, 2137, 2142, 2208, 2210, + 2276, 2304, 2307, 2308, 2362, 2363, 2364, 2365, 2366, 2369, + 2377, 2381, 2382, 2384, 2385, 2392, 2402, 2404, 2406, 2416, + 2417, 2418, 2425, 2433, 2434, 2437, 2447, 2451, 2474, 2482, + 2486, 2492, 2493, 2494, 2497, 2503, 2507, 2509, 2510, 2519, + 2524, 2527, 2530, 2534, 2544, 2546, 2548, 2554, 2555, 2561, + 2563, 2565, 2575, 2579, 2602, 2610, 2613, 2616, 2620, 2622, + 2625, 2631, 2635, 2641, 2649, 2654, 2662, 2672, 2674, 2677, + 2689, 2691, 2693, 2703, 2707, 2730, 2738, 2741, 2748, 2749, + 2750, 2753, 2759, 2761, 2763, 2765, 2768, 2784, 2786, 2790, + 2800, 2801, 2817, 2818, 2821, 2831, 2835, 2858, 2866, 2869, + 2876, 2877, 2878, 2879, 2880, 2881, 2887, 2891, 2893, 2902, + 2903, 2908, 2911, 2914, 2918, 2928, 2929, 2930, 2946, 2947, + 2949, 2958, 2962, 2969, 2972, 2974, 2979, 2984, 2990, 3006, + 3008, 3009, 3014, 3018, 3021, 3024, 3031, 3046, 3056, 3059, + 3065, 3066, 3073, 3077, 3086, 3090, 3114, 3125, 3133, 3134, + 3137, 3142, 3146, 3157, 3160, 3168, 3170, 3174, 3192, 3199, + 3202, 3205, 3214, 3218, 3242, 3253, 3260, 3261, 3262, 3263, + 3264, 3270, 3271, 3274, 3276, 3285, 3294, 3296, 3298, 3302, + 3313, 3330, 3333, 3342, 3346, 3389, 3390, 3393, 3398, 3402, + 3405, 3406, 3415, 3424, 3426, 3430, 3440, 3449, 3450, 3458, + 3461, 3482, 3507, 3517, 3520, 3530, 3535, 3538, 3542, 3544, + 3570, 3572, 3585, 3633, 3634, 3636, 3647, 3648, 3654, 3655, + 3663, 3664, 3674, 3713, 3716, 3719, 3722, 3725, 3732, 3737, + 3745, 3749, 3751, 3754, 3757, 3761, 3762, 3764, 3771, 3773, + 3776, 3782, 3784, 3792, 3804, 3840, 3841, 3844, 3859, 3860, + 3861, 3864, 3866, 3872, 3882, 3892, 3893, 3894, 3895, 3896, + 3897, 3898, 3899, 3900, 3901, 3902, 3904, 3913, 3953, 3967, + 3968, 3973, 3974, 3976, 3981, 3993, 4030, 4038, 4039, 4046, + 4048, 4053, 4057, 4096, 4139, 4141, 4145, 4146, 4152, 4153, + 4155, 4157, 4159, 4160, 4170, 4176, 4182, 4184, 4186, 4190, + 4193, 4194, 4197, 4199, 4206, 4209, 4213, 4226, 4227, 4229, + 4231, 4237, 4238, 4239, 4240, 4250, 4253, 4254, 4256, 4295, + 4301, 4304, 4347, 4348, 4349, 4682, 4688, 4696, 4698, 4704, + 4746, 4752, 4786, 4792, 4800, 4802, 4808, 4824, 4882, 4888, + 4957, 4960, 4969, 4992, 5008, 5024, 5120, 5121, 5741, 5743, + 5760, 5761, 5787, 5788, 5792, 5867, 5870, 5888, 5902, 5906, + 5920, 5938, 5941, 5952, 5970, 5984, 5998, 6002, 6016, 6068, + 6070, 6071, 6078, 6086, 6087, 6089, 6100, 6103, 6104, 6107, + 6108, 6109, 6112, 6128, 6144, 6150, 6151, 6155, 6158, 6160, + 6176, 6211, 6212, 6272, 6313, 6314, 6320, 6400, 6432, 6435, + 6439, 6441, 6448, 6450, 6451, 6457, 6464, 6468, 6470, 6480, + 6512, 6528, 6576, 6593, 6600, 6608, 6618, 6622, 6656, 6679, + 6681, 6686, 6688, 6741, 6742, 6743, 6744, 6752, 6753, 6754, + 6755, 6757, 6765, 6771, 6783, 6784, 6800, 6816, 6823, 6824, + 6912, 6916, 6917, 6964, 6965, 6966, 6971, 6972, 6973, 6978, + 6979, 6981, 6992, 7002, 7009, 7019, 7028, 7040, 7042, 7043, + 7073, 7074, 7078, 7080, 7082, 7083, 7084, 7086, 7088, 7098, + 7142, 7143, 7144, 7146, 7149, 7150, 7151, 7154, 7164, 7168, + 7204, 7212, 7220, 7222, 7227, 7232, 7245, 7248, 7258, 7288, + 7294, 7360, 7376, 7379, 7380, 7393, 7394, 7401, 7405, 7406, + 7410, 7412, 7413, 7424, 7468, 7531, 7544, 7545, 7579, 7616, + 7676, 7680, 7830, 7838, 7936, 7944, 7952, 7960, 7968, 7976, + 7984, 7992, 8000, 8008, 8016, 8025, 8027, 8029, 8031, 8033, + 8040, 8048, 8064, 8072, 8080, 8088, 8096, 8104, 8112, 8118, + 8120, 8124, 8125, 8126, 8127, 8130, 8134, 8136, 8140, 8141, + 8144, 8150, 8152, 8157, 8160, 8168, 8173, 8178, 8182, 8184, + 8188, 8189, 8192, 8203, 8208, 8214, 8216, 8217, 8218, 8219, + 8221, 8222, 8223, 8224, 8232, 8233, 8234, 8239, 8240, 8249, + 8250, 8251, 8255, 8257, 8260, 8261, 8262, 8263, 8274, 8275, + 8276, 8277, 8287, 8288, 8298, 8304, 8305, 8308, 8314, 8317, + 8318, 8319, 8320, 8330, 8333, 8334, 8336, 8352, 8400, 8413, + 8417, 8418, 8421, 8448, 8450, 8451, 8455, 8456, 8458, 8459, + 8462, 8464, 8467, 8468, 8469, 8470, 8472, 8473, 8478, 8484, + 8485, 8486, 8487, 8488, 8489, 8490, 8494, 8495, 8496, 8500, + 8501, 8505, 8506, 8508, 8510, 8512, 8517, 8519, 8522, 8523, + 8524, 8526, 8527, 8528, 8544, 8579, 8581, 8585, 8592, 8597, + 8602, 8604, 8608, 8609, 8611, 8612, 8614, 8615, 8622, 8623, + 8654, 8656, 8658, 8659, 8660, 8661, 8692, 8960, 8968, 8972, + 8992, 8994, 9001, 9002, 9003, 9084, 9085, 9115, 9140, 9180, + 9186, 9216, 9280, 9312, 9372, 9450, 9472, 9655, 9656, 9665, + 9666, 9720, 9728, 9839, 9840, 9985, 10088, 10089, 10090, 10091, + 10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101, + 10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217, + 10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627, + 10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637, + 10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647, + 10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750, + 11008, 11056, 11077, 11079, 11088, 11264, 11312, 11360, 11363, 11365, + 11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 11393, + 11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 11520, + 11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 11696, + 11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 11780, + 11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 11800, + 11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 11812, + 11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 11904, + 11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296, + 12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306, + 12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317, + 12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347, + 12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449, + 12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736, + 12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938, + 12977, 12992, 13056, 13312, 19893, 19904, 19968, 40908, 40960, 40981, + 40982, 42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528, + 42538, 42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624, + 42655, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800, + 42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42896, 42912, + 43000, 43002, 43003, 43010, 43011, 43014, 43015, 43019, 43020, 43043, + 43045, 43047, 43048, 43056, 43062, 43064, 43065, 43072, 43124, 43136, + 43138, 43188, 43204, 43214, 43216, 43232, 43250, 43256, 43259, 43264, + 43274, 43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395, + 43396, 43443, 43444, 43446, 43450, 43452, 43453, 43457, 43471, 43472, + 43486, 43520, 43561, 43567, 43569, 43571, 43573, 43584, 43587, 43588, + 43596, 43597, 43600, 43612, 43616, 43632, 43633, 43639, 43642, 43643, + 43648, 43696, 43697, 43698, 43701, 43703, 43705, 43710, 43712, 43713, + 43714, 43739, 43741, 43742, 43744, 43755, 43756, 43758, 43760, 43762, + 43763, 43765, 43766, 43777, 43785, 43793, 43808, 43816, 43968, 44003, + 44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 44032, 55203, + 55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 63744, 64112, + 64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 64318, 64320, + 64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 65008, 65020, + 65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 65073, 65075, + 65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086, + 65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 65096, 65097, + 65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 65117, 65118, + 65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 65142, 65279, + 65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 65293, 65294, + 65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 65342, 65343, + 65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 65377, 65378, + 65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 65482, 65490, + 65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 65517, 65529, + 65532, 0, 13, 40, 60, 63, 80, 128, 256, 263, + 311, 320, 373, 377, 394, 400, 464, 509, 640, 672, + 768, 800, 816, 833, 834, 842, 896, 927, 928, 968, + 976, 977, 1024, 1064, 1104, 1184, 2048, 2056, 2058, 2103, + 2108, 2111, 2135, 2136, 2304, 2326, 2335, 2336, 2367, 2432, + 2494, 2560, 2561, 2565, 2572, 2576, 2581, 2585, 2616, 2623, + 2624, 2640, 2656, 2685, 2687, 2816, 2873, 2880, 2904, 2912, + 2936, 3072, 3680, 4096, 4097, 4098, 4099, 4152, 4167, 4178, + 4198, 4224, 4226, 4227, 4272, 4275, 4279, 4281, 4283, 4285, + 4286, 4304, 4336, 4352, 4355, 4391, 4396, 4397, 4406, 4416, + 4480, 4482, 4483, 4531, 4534, 4543, 4545, 4549, 4560, 5760, + 5803, 5804, 5805, 5806, 5808, 5814, 5815, 5824, 8192, 9216, + 9328, 12288, 26624, 28416, 28496, 28497, 28559, 28563, 45056, 53248, + 53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 53635, 53637, + 53644, 53674, 53678, 53760, 53826, 53829, 54016, 54112, 54272, 54298, + 54324, 54350, 54358, 54376, 54402, 54428, 54430, 54434, 54437, 54441, + 54446, 54454, 54459, 54461, 54469, 54480, 54506, 54532, 54535, 54541, + 54550, 54558, 54584, 54587, 54592, 54598, 54602, 54610, 54636, 54662, + 54688, 54714, 54740, 54766, 54792, 54818, 54844, 54870, 54896, 54922, + 54952, 54977, 54978, 55003, 55004, 55010, 55035, 55036, 55061, 55062, + 55068, 55093, 55094, 55119, 55120, 55126, 55151, 55152, 55177, 55178, + 55184, 55209, 55210, 55235, 55236, 55242, 55246, 60928, 60933, 60961, + 60964, 60967, 60969, 60980, 60985, 60987, 60994, 60999, 61001, 61003, + 61005, 61009, 61012, 61015, 61017, 61019, 61021, 61023, 61025, 61028, + 61031, 61036, 61044, 61049, 61054, 61056, 61067, 61089, 61093, 61099, + 61168, 61440, 61488, 61600, 61617, 61633, 61649, 61696, 61712, 61744, + 61808, 61926, 61968, 62016, 62032, 62208, 62256, 62263, 62336, 62368, + 62406, 62432, 62464, 62528, 62530, 62713, 62720, 62784, 62800, 62971, + 63045, 63104, 63232, 0, 42710, 42752, 46900, 46912, 47133, 63488, + 1, 32, 256, 0, 65533, + }; +static u16 aFts5UnicodeData[] = { + 1025, 61, 117, 55, 117, 54, 50, 53, 57, 53, + 49, 85, 333, 85, 121, 85, 841, 54, 53, 50, + 56, 48, 56, 837, 54, 57, 50, 57, 1057, 61, + 53, 151, 58, 53, 56, 58, 39, 52, 57, 34, + 58, 56, 58, 57, 79, 56, 37, 85, 56, 47, + 39, 51, 111, 53, 745, 57, 233, 773, 57, 261, + 1822, 37, 542, 37, 1534, 222, 69, 73, 37, 126, + 126, 73, 69, 137, 37, 73, 37, 105, 101, 73, + 37, 73, 37, 190, 158, 37, 126, 126, 73, 37, + 126, 94, 37, 39, 94, 69, 135, 41, 40, 37, + 41, 40, 37, 41, 40, 37, 542, 37, 606, 37, + 41, 40, 37, 126, 73, 37, 1886, 197, 73, 37, + 73, 69, 126, 105, 37, 286, 2181, 39, 869, 582, + 152, 390, 472, 166, 248, 38, 56, 38, 568, 3596, + 158, 38, 56, 94, 38, 101, 53, 88, 41, 53, + 105, 41, 73, 37, 553, 297, 1125, 94, 37, 105, + 101, 798, 133, 94, 57, 126, 94, 37, 1641, 1541, + 1118, 58, 172, 75, 1790, 478, 37, 2846, 1225, 38, + 213, 1253, 53, 49, 55, 1452, 49, 44, 53, 76, + 53, 76, 53, 44, 871, 103, 85, 162, 121, 85, + 55, 85, 90, 364, 53, 85, 1031, 38, 327, 684, + 333, 149, 71, 44, 3175, 53, 39, 236, 34, 58, + 204, 70, 76, 58, 140, 71, 333, 103, 90, 39, + 469, 34, 39, 44, 967, 876, 2855, 364, 39, 333, + 1063, 300, 70, 58, 117, 38, 711, 140, 38, 300, + 38, 108, 38, 172, 501, 807, 108, 53, 39, 359, + 876, 108, 42, 1735, 44, 42, 44, 39, 106, 268, + 138, 44, 74, 39, 236, 327, 76, 85, 333, 53, + 38, 199, 231, 44, 74, 263, 71, 711, 231, 39, + 135, 44, 39, 106, 140, 74, 74, 44, 39, 42, + 71, 103, 76, 333, 71, 87, 207, 58, 55, 76, + 42, 199, 71, 711, 231, 71, 71, 71, 44, 106, + 76, 76, 108, 44, 135, 39, 333, 76, 103, 44, + 76, 42, 295, 103, 711, 231, 71, 167, 44, 39, + 106, 172, 76, 42, 74, 44, 39, 71, 76, 333, + 53, 55, 44, 74, 263, 71, 711, 231, 71, 167, + 44, 39, 42, 44, 42, 140, 74, 74, 44, 44, + 42, 71, 103, 76, 333, 58, 39, 207, 44, 39, + 199, 103, 135, 71, 39, 71, 71, 103, 391, 74, + 44, 74, 106, 106, 44, 39, 42, 333, 111, 218, + 55, 58, 106, 263, 103, 743, 327, 167, 39, 108, + 138, 108, 140, 76, 71, 71, 76, 333, 239, 58, + 74, 263, 103, 743, 327, 167, 44, 39, 42, 44, + 170, 44, 74, 74, 76, 74, 39, 71, 76, 333, + 71, 74, 263, 103, 1319, 39, 106, 140, 106, 106, + 44, 39, 42, 71, 76, 333, 207, 58, 199, 74, + 583, 775, 295, 39, 231, 44, 106, 108, 44, 266, + 74, 53, 1543, 44, 71, 236, 55, 199, 38, 268, + 53, 333, 85, 71, 39, 71, 39, 39, 135, 231, + 103, 39, 39, 71, 135, 44, 71, 204, 76, 39, + 167, 38, 204, 333, 135, 39, 122, 501, 58, 53, + 122, 76, 218, 333, 335, 58, 44, 58, 44, 58, + 44, 54, 50, 54, 50, 74, 263, 1159, 460, 42, + 172, 53, 76, 167, 364, 1164, 282, 44, 218, 90, + 181, 154, 85, 1383, 74, 140, 42, 204, 42, 76, + 74, 76, 39, 333, 213, 199, 74, 76, 135, 108, + 39, 106, 71, 234, 103, 140, 423, 44, 74, 76, + 202, 44, 39, 42, 333, 106, 44, 90, 1225, 41, + 41, 1383, 53, 38, 10631, 135, 231, 39, 135, 1319, + 135, 1063, 135, 231, 39, 135, 487, 1831, 135, 2151, + 108, 309, 655, 519, 346, 2727, 49, 19847, 85, 551, + 61, 839, 54, 50, 2407, 117, 110, 423, 135, 108, + 583, 108, 85, 583, 76, 423, 103, 76, 1671, 76, + 42, 236, 266, 44, 74, 364, 117, 38, 117, 55, + 39, 44, 333, 335, 213, 49, 149, 108, 61, 333, + 1127, 38, 1671, 1319, 44, 39, 2247, 935, 108, 138, + 76, 106, 74, 44, 202, 108, 58, 85, 333, 967, + 167, 1415, 554, 231, 74, 333, 47, 1114, 743, 76, + 106, 85, 1703, 42, 44, 42, 236, 44, 42, 44, + 74, 268, 202, 332, 44, 333, 333, 245, 38, 213, + 140, 42, 1511, 44, 42, 172, 42, 44, 170, 44, + 74, 231, 333, 245, 346, 300, 314, 76, 42, 967, + 42, 140, 74, 76, 42, 44, 74, 71, 333, 1415, + 44, 42, 76, 106, 44, 42, 108, 74, 149, 1159, + 266, 268, 74, 76, 181, 333, 103, 333, 967, 198, + 85, 277, 108, 53, 428, 42, 236, 135, 44, 135, + 74, 44, 71, 1413, 2022, 421, 38, 1093, 1190, 1260, + 140, 4830, 261, 3166, 261, 265, 197, 201, 261, 265, + 261, 265, 197, 201, 261, 41, 41, 41, 94, 229, + 265, 453, 261, 264, 261, 264, 261, 264, 165, 69, + 137, 40, 56, 37, 120, 101, 69, 137, 40, 120, + 133, 69, 137, 120, 261, 169, 120, 101, 69, 137, + 40, 88, 381, 162, 209, 85, 52, 51, 54, 84, + 51, 54, 52, 277, 59, 60, 162, 61, 309, 52, + 51, 149, 80, 117, 57, 54, 50, 373, 57, 53, + 48, 341, 61, 162, 194, 47, 38, 207, 121, 54, + 50, 38, 335, 121, 54, 50, 422, 855, 428, 139, + 44, 107, 396, 90, 41, 154, 41, 90, 37, 105, + 69, 105, 37, 58, 41, 90, 57, 169, 218, 41, + 58, 41, 58, 41, 58, 137, 58, 37, 137, 37, + 135, 37, 90, 69, 73, 185, 94, 101, 58, 57, + 90, 37, 58, 527, 1134, 94, 142, 47, 185, 186, + 89, 154, 57, 90, 57, 90, 57, 250, 57, 1018, + 89, 90, 57, 58, 57, 1018, 8601, 282, 153, 666, + 89, 250, 54, 50, 2618, 57, 986, 825, 1306, 217, + 602, 1274, 378, 1935, 2522, 719, 5882, 57, 314, 57, + 1754, 281, 3578, 57, 4634, 3322, 54, 50, 54, 50, + 54, 50, 54, 50, 54, 50, 54, 50, 54, 50, + 975, 1434, 185, 54, 50, 1017, 54, 50, 54, 50, + 54, 50, 54, 50, 54, 50, 537, 8218, 4217, 54, + 50, 54, 50, 54, 50, 54, 50, 54, 50, 54, + 50, 54, 50, 54, 50, 54, 50, 54, 50, 54, + 50, 2041, 54, 50, 54, 50, 1049, 54, 50, 8281, + 1562, 697, 90, 217, 346, 1513, 1509, 126, 73, 69, + 254, 105, 37, 94, 37, 94, 165, 70, 105, 37, + 3166, 37, 218, 158, 108, 94, 149, 47, 85, 1221, + 37, 37, 1799, 38, 53, 44, 743, 231, 231, 231, + 231, 231, 231, 231, 231, 1036, 85, 52, 51, 52, + 51, 117, 52, 51, 53, 52, 51, 309, 49, 85, + 49, 53, 52, 51, 85, 52, 51, 54, 50, 54, + 50, 54, 50, 54, 50, 181, 38, 341, 81, 858, + 2874, 6874, 410, 61, 117, 58, 38, 39, 46, 54, + 50, 54, 50, 54, 50, 54, 50, 54, 50, 90, + 54, 50, 54, 50, 54, 50, 54, 50, 49, 54, + 82, 58, 302, 140, 74, 49, 166, 90, 110, 38, + 39, 53, 90, 2759, 76, 88, 70, 39, 49, 2887, + 53, 102, 39, 1319, 3015, 90, 143, 346, 871, 1178, + 519, 1018, 335, 986, 271, 58, 495, 1050, 335, 1274, + 495, 2042, 8218, 39, 39, 2074, 39, 39, 679, 38, + 36583, 1786, 1287, 198, 85, 8583, 38, 117, 519, 333, + 71, 1502, 39, 44, 107, 53, 332, 53, 38, 798, + 44, 2247, 334, 76, 213, 760, 294, 88, 478, 69, + 2014, 38, 261, 190, 350, 38, 88, 158, 158, 382, + 70, 37, 231, 44, 103, 44, 135, 44, 743, 74, + 76, 42, 154, 207, 90, 55, 58, 1671, 149, 74, + 1607, 522, 44, 85, 333, 588, 199, 117, 39, 333, + 903, 268, 85, 743, 364, 74, 53, 935, 108, 42, + 1511, 44, 74, 140, 74, 44, 138, 437, 38, 333, + 85, 1319, 204, 74, 76, 74, 76, 103, 44, 263, + 44, 42, 333, 149, 519, 38, 199, 122, 39, 42, + 1543, 44, 39, 108, 71, 76, 167, 76, 39, 44, + 39, 71, 38, 85, 359, 42, 76, 74, 85, 39, + 70, 42, 44, 199, 199, 199, 231, 231, 1127, 74, + 44, 74, 44, 74, 53, 42, 44, 333, 39, 39, + 743, 1575, 36, 68, 68, 36, 63, 63, 11719, 3399, + 229, 165, 39, 44, 327, 57, 423, 167, 39, 71, + 71, 3463, 536, 11623, 54, 50, 2055, 1735, 391, 55, + 58, 524, 245, 54, 50, 53, 236, 53, 81, 80, + 54, 50, 54, 50, 54, 50, 54, 50, 54, 50, + 54, 50, 54, 50, 54, 50, 85, 54, 50, 149, + 112, 117, 149, 49, 54, 50, 54, 50, 54, 50, + 117, 57, 49, 121, 53, 55, 85, 167, 4327, 34, + 117, 55, 117, 54, 50, 53, 57, 53, 49, 85, + 333, 85, 121, 85, 841, 54, 53, 50, 56, 48, + 56, 837, 54, 57, 50, 57, 54, 50, 53, 54, + 50, 85, 327, 38, 1447, 70, 999, 199, 199, 199, + 103, 87, 57, 56, 58, 87, 58, 153, 90, 98, + 90, 391, 839, 615, 71, 487, 455, 3943, 117, 1455, + 314, 1710, 143, 570, 47, 410, 1466, 44, 935, 1575, + 999, 143, 551, 46, 263, 46, 967, 53, 1159, 263, + 53, 174, 1289, 1285, 2503, 333, 199, 39, 1415, 71, + 39, 743, 53, 271, 711, 207, 53, 839, 53, 1799, + 71, 39, 108, 76, 140, 135, 103, 871, 108, 44, + 271, 309, 935, 79, 53, 1735, 245, 711, 271, 615, + 271, 2343, 1007, 42, 44, 42, 1703, 492, 245, 655, + 333, 76, 42, 1447, 106, 140, 74, 76, 85, 34, + 149, 807, 333, 108, 1159, 172, 42, 268, 333, 149, + 76, 42, 1543, 106, 300, 74, 135, 149, 333, 1383, + 44, 42, 44, 74, 204, 42, 44, 333, 28135, 3182, + 149, 34279, 18215, 2215, 39, 1482, 140, 422, 71, 7898, + 1274, 1946, 74, 108, 122, 202, 258, 268, 90, 236, + 986, 140, 1562, 2138, 108, 58, 2810, 591, 841, 837, + 841, 229, 581, 841, 837, 41, 73, 41, 73, 137, + 265, 133, 37, 229, 357, 841, 837, 73, 137, 265, + 233, 837, 73, 137, 169, 41, 233, 837, 841, 837, + 841, 837, 841, 837, 841, 837, 841, 837, 841, 901, + 809, 57, 805, 57, 197, 809, 57, 805, 57, 197, + 809, 57, 805, 57, 197, 809, 57, 805, 57, 197, + 809, 57, 805, 57, 197, 94, 1613, 135, 871, 71, + 39, 39, 327, 135, 39, 39, 39, 39, 39, 39, + 103, 71, 39, 39, 39, 39, 39, 39, 71, 39, + 135, 231, 135, 135, 39, 327, 551, 103, 167, 551, + 89, 1434, 3226, 506, 474, 506, 506, 367, 1018, 1946, + 1402, 954, 1402, 314, 90, 1082, 218, 2266, 666, 1210, + 186, 570, 2042, 58, 5850, 154, 2010, 154, 794, 2266, + 378, 2266, 3738, 39, 39, 39, 39, 39, 39, 17351, + 34, 3074, 7692, 63, 63, + }; + +static int tdsqlite3Fts5UnicodeCategory(u32 iCode) { + int iRes = -1; + int iHi; + int iLo; + int ret; + u16 iKey; + + if( iCode>=(1<<20) ){ + return 0; + } + iLo = aFts5UnicodeBlock[(iCode>>16)]; + iHi = aFts5UnicodeBlock[1+(iCode>>16)]; + iKey = (iCode & 0xFFFF); + while( iHi>iLo ){ + int iTest = (iHi + iLo) / 2; + assert( iTest>=iLo && iTest<iHi ); + if( iKey>=aFts5UnicodeMap[iTest] ){ + iRes = iTest; + iLo = iTest+1; + }else{ + iHi = iTest; + } + } + + if( iRes<0 ) return 0; + if( iKey>=(aFts5UnicodeMap[iRes]+(aFts5UnicodeData[iRes]>>5)) ) return 0; + ret = aFts5UnicodeData[iRes] & 0x1F; + if( ret!=30 ) return ret; + return ((iKey - aFts5UnicodeMap[iRes]) & 0x01) ? 5 : 9; +} + +static void tdsqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){ + int i = 0; + int iTbl = 0; + while( i<128 ){ + int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ]; + int n = (aFts5UnicodeData[iTbl] >> 5) + i; + for(; i<128 && i<n; i++){ + aAscii[i] = (u8)bToken; + } + iTbl++; + } +} + /* ** 2015 May 30 ** @@ -201647,11 +230669,11 @@ static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){ /* #include "fts5Int.h" */ /* -** This is a copy of the sqlite3GetVarint32() routine from the SQLite core. +** This is a copy of the tdsqlite3GetVarint32() routine from the SQLite core. ** Except, this version does handle the single byte case that the core ** version depends on being handled before its function is called. */ -static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){ +static int tdsqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){ u32 a,b; /* The 1-byte case. Overwhelmingly the most common. */ @@ -201705,8 +230727,8 @@ static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){ u64 v64; u8 n; p -= 2; - n = sqlite3Fts5GetVarint(p, &v64); - *v = (u32)v64; + n = tdsqlite3Fts5GetVarint(p, &v64); + *v = ((u32)v64) & 0x7FFFFFFF; assert( n>3 && n<=9 ); return n; } @@ -201714,7 +230736,7 @@ static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){ /* -** Bitmasks used by sqlite3GetVarint(). These precomputed constants +** Bitmasks used by tdsqlite3GetVarint(). These precomputed constants ** are defined here rather than simply putting the constant expressions ** inline in order to work around bugs in the RVT compiler. ** @@ -201729,7 +230751,7 @@ static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){ ** Read a 64-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read. The value is stored in *v. */ -static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){ +static u8 tdsqlite3Fts5GetVarint(const unsigned char *p, u64 *v){ u32 a,b,s; a = *p; @@ -201948,7 +230970,7 @@ static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){ return n; } -static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){ +static int tdsqlite3Fts5PutVarint(unsigned char *p, u64 v){ if( v<=0x7f ){ p[0] = v&0x7f; return 1; @@ -201962,7 +230984,7 @@ static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){ } -static int sqlite3Fts5GetVarintLen(u32 iVal){ +static int tdsqlite3Fts5GetVarintLen(u32 iVal){ #if 0 if( iVal<(1 << 7 ) ) return 1; #endif @@ -201973,7 +230995,6 @@ static int sqlite3Fts5GetVarintLen(u32 iVal){ return 5; } - /* ** 2015 May 08 ** @@ -202005,6 +231026,11 @@ static int sqlite3Fts5GetVarintLen(u32 iVal){ ** the number of fts5 rows that contain at least one instance of term ** $term. Field $cnt is set to the total number of instances of term ** $term in the database. +** +** instance: +** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>)); +** +** One row for each term instance in the database. */ @@ -202015,18 +231041,18 @@ typedef struct Fts5VocabTable Fts5VocabTable; typedef struct Fts5VocabCursor Fts5VocabCursor; struct Fts5VocabTable { - sqlite3_vtab base; + tdsqlite3_vtab base; char *zFts5Tbl; /* Name of fts5 table */ char *zFts5Db; /* Db containing fts5 table */ - sqlite3 *db; /* Database handle */ + tdsqlite3 *db; /* Database handle */ Fts5Global *pGlobal; /* FTS5 global object for this database */ - int eType; /* FTS5_VOCAB_COL or ROW */ + int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */ }; struct Fts5VocabCursor { - sqlite3_vtab_cursor base; - sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */ - Fts5Index *pIndex; /* Associated FTS5 index */ + tdsqlite3_vtab_cursor base; + tdsqlite3_stmt *pStmt; /* Statement holding lock on pIndex */ + Fts5Table *pFts5; /* Associated FTS5 table */ int bEof; /* True if this cursor is at EOF */ Fts5IndexIter *pIter; /* Term/rowid iterator object */ @@ -202035,21 +231061,26 @@ struct Fts5VocabCursor { char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */ /* These are used by 'col' tables only */ - Fts5Config *pConfig; /* Fts5 table configuration */ int iCol; i64 *aCnt; i64 *aDoc; - /* Output values used by 'row' and 'col' tables */ + /* Output values used by all tables. */ i64 rowid; /* This table's current rowid value */ Fts5Buffer term; /* Current value of 'term' column */ + + /* Output values Used by 'instance' tables only */ + i64 iInstPos; + int iInstOff; }; -#define FTS5_VOCAB_COL 0 -#define FTS5_VOCAB_ROW 1 +#define FTS5_VOCAB_COL 0 +#define FTS5_VOCAB_ROW 1 +#define FTS5_VOCAB_INSTANCE 2 #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt" #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt" +#define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset" /* ** Bits for the mask used as the idxNum value by xBestIndex/xFilter. @@ -202067,21 +231098,24 @@ struct Fts5VocabCursor { */ static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){ int rc = SQLITE_OK; - char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1); + char *zCopy = tdsqlite3Fts5Strndup(&rc, zType, -1); if( rc==SQLITE_OK ){ - sqlite3Fts5Dequote(zCopy); - if( sqlite3_stricmp(zCopy, "col")==0 ){ + tdsqlite3Fts5Dequote(zCopy); + if( tdsqlite3_stricmp(zCopy, "col")==0 ){ *peType = FTS5_VOCAB_COL; }else - if( sqlite3_stricmp(zCopy, "row")==0 ){ + if( tdsqlite3_stricmp(zCopy, "row")==0 ){ *peType = FTS5_VOCAB_ROW; }else + if( tdsqlite3_stricmp(zCopy, "instance")==0 ){ + *peType = FTS5_VOCAB_INSTANCE; + }else { - *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy); + *pzErr = tdsqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy); rc = SQLITE_ERROR; } - sqlite3_free(zCopy); + tdsqlite3_free(zCopy); } return rc; @@ -202091,18 +231125,18 @@ static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){ /* ** The xDisconnect() virtual table method. */ -static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){ +static int fts5VocabDisconnectMethod(tdsqlite3_vtab *pVtab){ Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab; - sqlite3_free(pTab); + tdsqlite3_free(pTab); return SQLITE_OK; } /* ** The xDestroy() virtual table method. */ -static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){ +static int fts5VocabDestroyMethod(tdsqlite3_vtab *pVtab){ Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab; - sqlite3_free(pTab); + tdsqlite3_free(pTab); return SQLITE_OK; } @@ -202128,16 +231162,17 @@ static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){ ** argv[5] -> type of fts5vocab table */ static int fts5VocabInitVtab( - sqlite3 *db, /* The SQLite database connection */ + tdsqlite3 *db, /* The SQLite database connection */ void *pAux, /* Pointer to Fts5Global object */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ + tdsqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ char **pzErr /* Write any error message here */ ){ const char *azSchema[] = { "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")", - "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")" + "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")", + "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")" }; Fts5VocabTable *pRet = 0; @@ -202147,7 +231182,7 @@ static int fts5VocabInitVtab( bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0); if( argc!=5 && bDb==0 ){ - *pzErr = sqlite3_mprintf("wrong number of vtable arguments"); + *pzErr = tdsqlite3_mprintf("wrong number of vtable arguments"); rc = SQLITE_ERROR; }else{ int nByte; /* Bytes of space to allocate */ @@ -202161,11 +231196,11 @@ static int fts5VocabInitVtab( rc = fts5VocabTableType(zType, pzErr, &eType); if( rc==SQLITE_OK ){ assert( eType>=0 && eType<ArraySize(azSchema) ); - rc = sqlite3_declare_vtab(db, azSchema[eType]); + rc = tdsqlite3_declare_vtab(db, azSchema[eType]); } nByte = sizeof(Fts5VocabTable) + nDb + nTab; - pRet = sqlite3Fts5MallocZero(&rc, nByte); + pRet = tdsqlite3Fts5MallocZero(&rc, nByte); if( pRet ){ pRet->pGlobal = (Fts5Global*)pAux; pRet->eType = eType; @@ -202174,12 +231209,12 @@ static int fts5VocabInitVtab( pRet->zFts5Db = &pRet->zFts5Tbl[nTab]; memcpy(pRet->zFts5Tbl, zTab, nTab); memcpy(pRet->zFts5Db, zDb, nDb); - sqlite3Fts5Dequote(pRet->zFts5Tbl); - sqlite3Fts5Dequote(pRet->zFts5Db); + tdsqlite3Fts5Dequote(pRet->zFts5Tbl); + tdsqlite3Fts5Dequote(pRet->zFts5Db); } } - *ppVTab = (sqlite3_vtab*)pRet; + *ppVTab = (tdsqlite3_vtab*)pRet; return rc; } @@ -202189,32 +231224,41 @@ static int fts5VocabInitVtab( ** work is done in function fts5VocabInitVtab(). */ static int fts5VocabConnectMethod( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ + tdsqlite3_vtab **ppVtab, /* OUT: New tdsqlite3_vtab object */ + char **pzErr /* OUT: tdsqlite3_malloc'd error message */ ){ return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr); } static int fts5VocabCreateMethod( - sqlite3 *db, /* Database connection */ + tdsqlite3 *db, /* Database connection */ void *pAux, /* Pointer to tokenizer hash table */ int argc, /* Number of elements in argv array */ const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ + tdsqlite3_vtab **ppVtab, /* OUT: New tdsqlite3_vtab object */ + char **pzErr /* OUT: tdsqlite3_malloc'd error message */ ){ return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr); } /* ** Implementation of the xBestIndex method. +** +** Only constraints of the form: +** +** term <= ? +** term == ? +** term >= ? +** +** are interpreted. Less-than and less-than-or-equal are treated +** identically, as are greater-than and greater-than-or-equal. */ static int fts5VocabBestIndexMethod( - sqlite3_vtab *pUnused, - sqlite3_index_info *pInfo + tdsqlite3_vtab *pUnused, + tdsqlite3_index_info *pInfo ){ int i; int iTermEq = -1; @@ -202226,7 +231270,7 @@ static int fts5VocabBestIndexMethod( UNUSED_PARAM(pUnused); for(i=0; i<pInfo->nConstraint; i++){ - struct sqlite3_index_constraint *p = &pInfo->aConstraint[i]; + struct tdsqlite3_index_constraint *p = &pInfo->aConstraint[i]; if( p->usable==0 ) continue; if( p->iColumn==0 ){ /* term column */ if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i; @@ -202258,7 +231302,7 @@ static int fts5VocabBestIndexMethod( /* This virtual table always delivers results in ascending order of ** the "term" column (column 0). So if the user has requested this ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the - ** sqlite3_index_info.orderByConsumed flag to tell the core the results + ** tdsqlite3_index_info.orderByConsumed flag to tell the core the results ** are already in sorted order. */ if( pInfo->nOrderBy==1 && pInfo->aOrderBy[0].iColumn==0 @@ -202275,111 +231319,169 @@ static int fts5VocabBestIndexMethod( ** Implementation of xOpen method. */ static int fts5VocabOpenMethod( - sqlite3_vtab *pVTab, - sqlite3_vtab_cursor **ppCsr + tdsqlite3_vtab *pVTab, + tdsqlite3_vtab_cursor **ppCsr ){ Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab; - Fts5Index *pIndex = 0; - Fts5Config *pConfig = 0; + Fts5Table *pFts5 = 0; Fts5VocabCursor *pCsr = 0; int rc = SQLITE_OK; - sqlite3_stmt *pStmt = 0; + tdsqlite3_stmt *pStmt = 0; char *zSql = 0; - zSql = sqlite3Fts5Mprintf(&rc, + zSql = tdsqlite3Fts5Mprintf(&rc, "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'", pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl ); if( zSql ){ - rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0); + rc = tdsqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0); } - sqlite3_free(zSql); + tdsqlite3_free(zSql); assert( rc==SQLITE_OK || pStmt==0 ); if( rc==SQLITE_ERROR ) rc = SQLITE_OK; - if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ - i64 iId = sqlite3_column_int64(pStmt, 0); - pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig); + if( pStmt && tdsqlite3_step(pStmt)==SQLITE_ROW ){ + i64 iId = tdsqlite3_column_int64(pStmt, 0); + pFts5 = tdsqlite3Fts5TableFromCsrid(pTab->pGlobal, iId); } - if( rc==SQLITE_OK && pIndex==0 ){ - rc = sqlite3_finalize(pStmt); - pStmt = 0; - if( rc==SQLITE_OK ){ - pVTab->zErrMsg = sqlite3_mprintf( - "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl - ); - rc = SQLITE_ERROR; + if( rc==SQLITE_OK ){ + if( pFts5==0 ){ + rc = tdsqlite3_finalize(pStmt); + pStmt = 0; + if( rc==SQLITE_OK ){ + pVTab->zErrMsg = tdsqlite3_mprintf( + "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl + ); + rc = SQLITE_ERROR; + } + }else{ + rc = tdsqlite3Fts5FlushToDisk(pFts5); } } if( rc==SQLITE_OK ){ - int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor); - pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte); + int nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor); + pCsr = (Fts5VocabCursor*)tdsqlite3Fts5MallocZero(&rc, nByte); } if( pCsr ){ - pCsr->pIndex = pIndex; + pCsr->pFts5 = pFts5; pCsr->pStmt = pStmt; - pCsr->pConfig = pConfig; pCsr->aCnt = (i64*)&pCsr[1]; - pCsr->aDoc = &pCsr->aCnt[pConfig->nCol]; + pCsr->aDoc = &pCsr->aCnt[pFts5->pConfig->nCol]; }else{ - sqlite3_finalize(pStmt); + tdsqlite3_finalize(pStmt); } - *ppCsr = (sqlite3_vtab_cursor*)pCsr; + *ppCsr = (tdsqlite3_vtab_cursor*)pCsr; return rc; } static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){ pCsr->rowid = 0; - sqlite3Fts5IterClose(pCsr->pIter); + tdsqlite3Fts5IterClose(pCsr->pIter); pCsr->pIter = 0; - sqlite3_free(pCsr->zLeTerm); + tdsqlite3_free(pCsr->zLeTerm); pCsr->nLeTerm = -1; pCsr->zLeTerm = 0; + pCsr->bEof = 0; } /* ** Close the cursor. For additional information see the documentation ** on the xClose method of the virtual table interface. */ -static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){ +static int fts5VocabCloseMethod(tdsqlite3_vtab_cursor *pCursor){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; fts5VocabResetCursor(pCsr); - sqlite3Fts5BufferFree(&pCsr->term); - sqlite3_finalize(pCsr->pStmt); - sqlite3_free(pCsr); + tdsqlite3Fts5BufferFree(&pCsr->term); + tdsqlite3_finalize(pCsr->pStmt); + tdsqlite3_free(pCsr); return SQLITE_OK; } +static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){ + int rc = SQLITE_OK; + + if( tdsqlite3Fts5IterEof(pCsr->pIter) ){ + pCsr->bEof = 1; + }else{ + const char *zTerm; + int nTerm; + zTerm = tdsqlite3Fts5IterTerm(pCsr->pIter, &nTerm); + if( pCsr->nLeTerm>=0 ){ + int nCmp = MIN(nTerm, pCsr->nLeTerm); + int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp); + if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){ + pCsr->bEof = 1; + } + } + + tdsqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm); + } + return rc; +} + +static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){ + int eDetail = pCsr->pFts5->pConfig->eDetail; + int rc = SQLITE_OK; + Fts5IndexIter *pIter = pCsr->pIter; + i64 *pp = &pCsr->iInstPos; + int *po = &pCsr->iInstOff; + + assert( tdsqlite3Fts5IterEof(pIter)==0 ); + assert( pCsr->bEof==0 ); + while( eDetail==FTS5_DETAIL_NONE + || tdsqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp) + ){ + pCsr->iInstPos = 0; + pCsr->iInstOff = 0; + + rc = tdsqlite3Fts5IterNextScan(pCsr->pIter); + if( rc==SQLITE_OK ){ + rc = fts5VocabInstanceNewTerm(pCsr); + if( pCsr->bEof || eDetail==FTS5_DETAIL_NONE ) break; + } + if( rc ){ + pCsr->bEof = 1; + break; + } + } + + return rc; +} /* ** Advance the cursor to the next row in the table. */ -static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){ +static int fts5VocabNextMethod(tdsqlite3_vtab_cursor *pCursor){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab; int rc = SQLITE_OK; - int nCol = pCsr->pConfig->nCol; + int nCol = pCsr->pFts5->pConfig->nCol; pCsr->rowid++; + if( pTab->eType==FTS5_VOCAB_INSTANCE ){ + return fts5VocabInstanceNext(pCsr); + } + if( pTab->eType==FTS5_VOCAB_COL ){ for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){ if( pCsr->aDoc[pCsr->iCol] ) break; } } - if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){ - if( sqlite3Fts5IterEof(pCsr->pIter) ){ + if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){ + if( tdsqlite3Fts5IterEof(pCsr->pIter) ){ pCsr->bEof = 1; }else{ const char *zTerm; int nTerm; - zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm); + zTerm = tdsqlite3Fts5IterTerm(pCsr->pIter, &nTerm); + assert( nTerm>=0 ); if( pCsr->nLeTerm>=0 ){ int nCmp = MIN(nTerm, pCsr->nLeTerm); int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp); @@ -202389,33 +231491,36 @@ static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){ } } - sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm); + tdsqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm); memset(pCsr->aCnt, 0, nCol * sizeof(i64)); memset(pCsr->aDoc, 0, nCol * sizeof(i64)); pCsr->iCol = 0; assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW ); while( rc==SQLITE_OK ){ + int eDetail = pCsr->pFts5->pConfig->eDetail; const u8 *pPos; int nPos; /* Position list */ i64 iPos = 0; /* 64-bit position read from poslist */ int iOff = 0; /* Current offset within position list */ pPos = pCsr->pIter->pData; nPos = pCsr->pIter->nData; - switch( pCsr->pConfig->eDetail ){ - case FTS5_DETAIL_FULL: - pPos = pCsr->pIter->pData; - nPos = pCsr->pIter->nData; - if( pTab->eType==FTS5_VOCAB_ROW ){ - while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){ + + switch( pTab->eType ){ + case FTS5_VOCAB_ROW: + if( eDetail==FTS5_DETAIL_FULL ){ + while( 0==tdsqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){ pCsr->aCnt[0]++; } - pCsr->aDoc[0]++; - }else{ + } + pCsr->aDoc[0]++; + break; + + case FTS5_VOCAB_COL: + if( eDetail==FTS5_DETAIL_FULL ){ int iCol = -1; - while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){ + while( 0==tdsqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){ int ii = FTS5_POS2COLUMN(iPos); - pCsr->aCnt[ii]++; if( iCol!=ii ){ if( ii>=nCol ){ rc = FTS5_CORRUPT; @@ -202424,15 +231529,10 @@ static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){ pCsr->aDoc[ii]++; iCol = ii; } + pCsr->aCnt[ii]++; } - } - break; - - case FTS5_DETAIL_COLUMNS: - if( pTab->eType==FTS5_VOCAB_ROW ){ - pCsr->aDoc[0]++; - }else{ - while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){ + }else if( eDetail==FTS5_DETAIL_COLUMNS ){ + while( 0==tdsqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){ assert_nc( iPos>=0 && iPos<nCol ); if( iPos>=nCol ){ rc = FTS5_CORRUPT; @@ -202440,33 +231540,40 @@ static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){ } pCsr->aDoc[iPos]++; } + }else{ + assert( eDetail==FTS5_DETAIL_NONE ); + pCsr->aDoc[0]++; } break; - default: - assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE ); - pCsr->aDoc[0]++; + default: + assert( pTab->eType==FTS5_VOCAB_INSTANCE ); break; } if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IterNextScan(pCsr->pIter); + rc = tdsqlite3Fts5IterNextScan(pCsr->pIter); } + if( pTab->eType==FTS5_VOCAB_INSTANCE ) break; if( rc==SQLITE_OK ){ - zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm); - if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){ + zTerm = tdsqlite3Fts5IterTerm(pCsr->pIter, &nTerm); + if( nTerm!=pCsr->term.n + || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm)) + ){ break; } - if( sqlite3Fts5IterEof(pCsr->pIter) ) break; + if( tdsqlite3Fts5IterEof(pCsr->pIter) ) break; } } } } if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){ - while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++; - assert( pCsr->iCol<pCsr->pConfig->nCol ); + for(/* noop */; pCsr->iCol<nCol && pCsr->aDoc[pCsr->iCol]==0; pCsr->iCol++); + if( pCsr->iCol==nCol ){ + rc = FTS5_CORRUPT; + } } return rc; } @@ -202475,13 +231582,15 @@ static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){ ** This is the xFilter implementation for the virtual table. */ static int fts5VocabFilterMethod( - sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ + tdsqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, /* Strategy index */ const char *zUnused, /* Unused */ int nUnused, /* Number of elements in apVal */ - sqlite3_value **apVal /* Arguments for the indexing scheme */ + tdsqlite3_value **apVal /* Arguments for the indexing scheme */ ){ + Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab; Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; + int eType = pTab->eType; int rc = SQLITE_OK; int iVal = 0; @@ -202489,9 +231598,9 @@ static int fts5VocabFilterMethod( const char *zTerm = 0; int nTerm = 0; - sqlite3_value *pEq = 0; - sqlite3_value *pGe = 0; - sqlite3_value *pLe = 0; + tdsqlite3_value *pEq = 0; + tdsqlite3_value *pGe = 0; + tdsqlite3_value *pLe = 0; UNUSED_PARAM2(zUnused, nUnused); @@ -202501,18 +231610,19 @@ static int fts5VocabFilterMethod( if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++]; if( pEq ){ - zTerm = (const char *)sqlite3_value_text(pEq); - nTerm = sqlite3_value_bytes(pEq); + zTerm = (const char *)tdsqlite3_value_text(pEq); + nTerm = tdsqlite3_value_bytes(pEq); f = 0; }else{ if( pGe ){ - zTerm = (const char *)sqlite3_value_text(pGe); - nTerm = sqlite3_value_bytes(pGe); + zTerm = (const char *)tdsqlite3_value_text(pGe); + nTerm = tdsqlite3_value_bytes(pGe); } if( pLe ){ - const char *zCopy = (const char *)sqlite3_value_text(pLe); - pCsr->nLeTerm = sqlite3_value_bytes(pLe); - pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1); + const char *zCopy = (const char *)tdsqlite3_value_text(pLe); + if( zCopy==0 ) zCopy = ""; + pCsr->nLeTerm = tdsqlite3_value_bytes(pLe); + pCsr->zLeTerm = tdsqlite3_malloc(pCsr->nLeTerm+1); if( pCsr->zLeTerm==0 ){ rc = SQLITE_NOMEM; }else{ @@ -202521,11 +231631,17 @@ static int fts5VocabFilterMethod( } } - if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter); + Fts5Index *pIndex = pCsr->pFts5->pIndex; + rc = tdsqlite3Fts5IndexQuery(pIndex, zTerm, nTerm, f, 0, &pCsr->pIter); } - if( rc==SQLITE_OK ){ + if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){ + rc = fts5VocabInstanceNewTerm(pCsr); + } + if( rc==SQLITE_OK && !pCsr->bEof + && (eType!=FTS5_VOCAB_INSTANCE + || pCsr->pFts5->pConfig->eDetail!=FTS5_DETAIL_NONE) + ){ rc = fts5VocabNextMethod(pCursor); } @@ -202536,47 +231652,75 @@ static int fts5VocabFilterMethod( ** This is the xEof method of the virtual table. SQLite calls this ** routine to find out if it has reached the end of a result set. */ -static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){ +static int fts5VocabEofMethod(tdsqlite3_vtab_cursor *pCursor){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; return pCsr->bEof; } static int fts5VocabColumnMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ + tdsqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ + tdsqlite3_context *pCtx, /* Context for tdsqlite3_result_xxx() calls */ int iCol /* Index of column to read value from */ ){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; - int eDetail = pCsr->pConfig->eDetail; + int eDetail = pCsr->pFts5->pConfig->eDetail; int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType; i64 iVal = 0; if( iCol==0 ){ - sqlite3_result_text( + tdsqlite3_result_text( pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT ); }else if( eType==FTS5_VOCAB_COL ){ assert( iCol==1 || iCol==2 || iCol==3 ); if( iCol==1 ){ if( eDetail!=FTS5_DETAIL_NONE ){ - const char *z = pCsr->pConfig->azCol[pCsr->iCol]; - sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC); + const char *z = pCsr->pFts5->pConfig->azCol[pCsr->iCol]; + tdsqlite3_result_text(pCtx, z, -1, SQLITE_STATIC); } }else if( iCol==2 ){ iVal = pCsr->aDoc[pCsr->iCol]; }else{ iVal = pCsr->aCnt[pCsr->iCol]; } - }else{ + }else if( eType==FTS5_VOCAB_ROW ){ assert( iCol==1 || iCol==2 ); if( iCol==1 ){ iVal = pCsr->aDoc[0]; }else{ iVal = pCsr->aCnt[0]; } + }else{ + assert( eType==FTS5_VOCAB_INSTANCE ); + switch( iCol ){ + case 1: + tdsqlite3_result_int64(pCtx, pCsr->pIter->iRowid); + break; + case 2: { + int ii = -1; + if( eDetail==FTS5_DETAIL_FULL ){ + ii = FTS5_POS2COLUMN(pCsr->iInstPos); + }else if( eDetail==FTS5_DETAIL_COLUMNS ){ + ii = (int)pCsr->iInstPos; + } + if( ii>=0 && ii<pCsr->pFts5->pConfig->nCol ){ + const char *z = pCsr->pFts5->pConfig->azCol[ii]; + tdsqlite3_result_text(pCtx, z, -1, SQLITE_STATIC); + } + break; + } + default: { + assert( iCol==3 ); + if( eDetail==FTS5_DETAIL_FULL ){ + int ii = FTS5_POS2OFFSET(pCsr->iInstPos); + tdsqlite3_result_int(pCtx, ii); + } + break; + } + } } - if( iVal>0 ) sqlite3_result_int64(pCtx, iVal); + if( iVal>0 ) tdsqlite3_result_int64(pCtx, iVal); return SQLITE_OK; } @@ -202586,7 +231730,7 @@ static int fts5VocabColumnMethod( ** rowid should be written to *pRowid. */ static int fts5VocabRowidMethod( - sqlite3_vtab_cursor *pCursor, + tdsqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid ){ Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor; @@ -202594,8 +231738,8 @@ static int fts5VocabRowidMethod( return SQLITE_OK; } -static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){ - static const sqlite3_module fts5Vocab = { +static int tdsqlite3Fts5VocabInit(Fts5Global *pGlobal, tdsqlite3 *db){ + static const tdsqlite3_module fts5Vocab = { /* iVersion */ 2, /* xCreate */ fts5VocabCreateMethod, /* xConnect */ fts5VocabConnectMethod, @@ -202619,16 +231763,324 @@ static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){ /* xSavepoint */ 0, /* xRelease */ 0, /* xRollbackTo */ 0, + /* xShadowName */ 0 }; void *p = (void*)pGlobal; - return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0); + return tdsqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0); } - - #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */ /************** End of fts5.c ************************************************/ +/************** Begin file stmt.c ********************************************/ +/* +** 2017-05-31 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file demonstrates an eponymous virtual table that returns information +** about all prepared statements for the database connection. +** +** Usage example: +** +** .load ./stmt +** .mode line +** .header on +** SELECT * FROM stmt; +*/ +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) +#if !defined(SQLITEINT_H) +/* #include "tdsqlite3ext.h" */ +#endif +SQLITE_EXTENSION_INIT1 +/* #include <assert.h> */ +/* #include <string.h> */ + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* stmt_vtab is a subclass of tdsqlite3_vtab which will +** serve as the underlying representation of a stmt virtual table +*/ +typedef struct stmt_vtab stmt_vtab; +struct stmt_vtab { + tdsqlite3_vtab base; /* Base class - must be first */ + tdsqlite3 *db; /* Database connection for this stmt vtab */ +}; + +/* stmt_cursor is a subclass of tdsqlite3_vtab_cursor which will +** serve as the underlying representation of a cursor that scans +** over rows of the result +*/ +typedef struct stmt_cursor stmt_cursor; +struct stmt_cursor { + tdsqlite3_vtab_cursor base; /* Base class - must be first */ + tdsqlite3 *db; /* Database connection for this cursor */ + tdsqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */ + tdsqlite3_int64 iRowid; /* The rowid */ +}; + +/* +** The stmtConnect() method is invoked to create a new +** stmt_vtab that describes the stmt virtual table. +** +** Think of this routine as the constructor for stmt_vtab objects. +** +** All this routine needs to do is: +** +** (1) Allocate the stmt_vtab object and initialize all fields. +** +** (2) Tell SQLite (via the tdsqlite3_declare_vtab() interface) what the +** result set of queries against stmt will look like. +*/ +static int stmtConnect( + tdsqlite3 *db, + void *pAux, + int argc, const char *const*argv, + tdsqlite3_vtab **ppVtab, + char **pzErr +){ + stmt_vtab *pNew; + int rc; + +/* Column numbers */ +#define STMT_COLUMN_SQL 0 /* SQL for the statement */ +#define STMT_COLUMN_NCOL 1 /* Number of result columns */ +#define STMT_COLUMN_RO 2 /* True if read-only */ +#define STMT_COLUMN_BUSY 3 /* True if currently busy */ +#define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */ +#define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */ +#define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */ +#define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */ +#define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */ +#define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */ +#define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */ + + + rc = tdsqlite3_declare_vtab(db, + "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep," + "reprep,run,mem)"); + if( rc==SQLITE_OK ){ + pNew = tdsqlite3_malloc( sizeof(*pNew) ); + *ppVtab = (tdsqlite3_vtab*)pNew; + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + pNew->db = db; + } + return rc; +} + +/* +** This method is the destructor for stmt_cursor objects. +*/ +static int stmtDisconnect(tdsqlite3_vtab *pVtab){ + tdsqlite3_free(pVtab); + return SQLITE_OK; +} + +/* +** Constructor for a new stmt_cursor object. +*/ +static int stmtOpen(tdsqlite3_vtab *p, tdsqlite3_vtab_cursor **ppCursor){ + stmt_cursor *pCur; + pCur = tdsqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + pCur->db = ((stmt_vtab*)p)->db; + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Destructor for a stmt_cursor. +*/ +static int stmtClose(tdsqlite3_vtab_cursor *cur){ + tdsqlite3_free(cur); + return SQLITE_OK; +} + + +/* +** Advance a stmt_cursor to its next row of output. +*/ +static int stmtNext(tdsqlite3_vtab_cursor *cur){ + stmt_cursor *pCur = (stmt_cursor*)cur; + pCur->iRowid++; + pCur->pStmt = tdsqlite3_next_stmt(pCur->db, pCur->pStmt); + return SQLITE_OK; +} + +/* +** Return values of columns for the row at which the stmt_cursor +** is currently pointing. +*/ +static int stmtColumn( + tdsqlite3_vtab_cursor *cur, /* The cursor */ + tdsqlite3_context *ctx, /* First argument to tdsqlite3_result_...() */ + int i /* Which column to return */ +){ + stmt_cursor *pCur = (stmt_cursor*)cur; + switch( i ){ + case STMT_COLUMN_SQL: { + tdsqlite3_result_text(ctx, tdsqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT); + break; + } + case STMT_COLUMN_NCOL: { + tdsqlite3_result_int(ctx, tdsqlite3_column_count(pCur->pStmt)); + break; + } + case STMT_COLUMN_RO: { + tdsqlite3_result_int(ctx, tdsqlite3_stmt_readonly(pCur->pStmt)); + break; + } + case STMT_COLUMN_BUSY: { + tdsqlite3_result_int(ctx, tdsqlite3_stmt_busy(pCur->pStmt)); + break; + } + case STMT_COLUMN_MEM: { + i = SQLITE_STMTSTATUS_MEMUSED + + STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP; + /* Fall thru */ + } + case STMT_COLUMN_NSCAN: + case STMT_COLUMN_NSORT: + case STMT_COLUMN_NAIDX: + case STMT_COLUMN_NSTEP: + case STMT_COLUMN_REPREP: + case STMT_COLUMN_RUN: { + tdsqlite3_result_int(ctx, tdsqlite3_stmt_status(pCur->pStmt, + i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0)); + break; + } + } + return SQLITE_OK; +} + +/* +** Return the rowid for the current row. In this implementation, the +** rowid is the same as the output value. +*/ +static int stmtRowid(tdsqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + stmt_cursor *pCur = (stmt_cursor*)cur; + *pRowid = pCur->iRowid; + return SQLITE_OK; +} + +/* +** Return TRUE if the cursor has been moved off of the last +** row of output. +*/ +static int stmtEof(tdsqlite3_vtab_cursor *cur){ + stmt_cursor *pCur = (stmt_cursor*)cur; + return pCur->pStmt==0; +} + +/* +** This method is called to "rewind" the stmt_cursor object back +** to the first row of output. This method is always called at least +** once prior to any call to stmtColumn() or stmtRowid() or +** stmtEof(). +*/ +static int stmtFilter( + tdsqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, tdsqlite3_value **argv +){ + stmt_cursor *pCur = (stmt_cursor *)pVtabCursor; + pCur->pStmt = 0; + pCur->iRowid = 0; + return stmtNext(pVtabCursor); +} + +/* +** SQLite will invoke this method one or more times while planning a query +** that uses the stmt virtual table. This routine needs to create +** a query plan for each invocation and compute an estimated cost for that +** plan. +*/ +static int stmtBestIndex( + tdsqlite3_vtab *tab, + tdsqlite3_index_info *pIdxInfo +){ + pIdxInfo->estimatedCost = (double)500; + pIdxInfo->estimatedRows = 500; + return SQLITE_OK; +} + +/* +** This following structure defines all the methods for the +** stmt virtual table. +*/ +static tdsqlite3_module stmtModule = { + 0, /* iVersion */ + 0, /* xCreate */ + stmtConnect, /* xConnect */ + stmtBestIndex, /* xBestIndex */ + stmtDisconnect, /* xDisconnect */ + 0, /* xDestroy */ + stmtOpen, /* xOpen - open a cursor */ + stmtClose, /* xClose - close a cursor */ + stmtFilter, /* xFilter - configure scan constraints */ + stmtNext, /* xNext - advance a cursor */ + stmtEof, /* xEof - check for end of scan */ + stmtColumn, /* xColumn - read data */ + stmtRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0, /* xShadowName */ +}; + +#endif /* SQLITE_OMIT_VIRTUALTABLE */ + +SQLITE_PRIVATE int tdsqlite3StmtVtabInit(tdsqlite3 *db){ + int rc = SQLITE_OK; +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = tdsqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0); +#endif + return rc; +} + +#ifndef SQLITE_CORE +#ifdef _WIN32 +__declspec(dllexport) +#endif +SQLITE_API int tdsqlite3_stmt_init( + tdsqlite3 *db, + char **pzErrMsg, + const tdsqlite3_api_routines *pApi +){ + int rc = SQLITE_OK; + SQLITE_EXTENSION_INIT2(pApi); +#ifndef SQLITE_OMIT_VIRTUALTABLE + rc = tdsqlite3StmtVtabInit(db); +#endif + return rc; +} +#endif /* SQLITE_CORE */ +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */ + +/************** End of stmt.c ************************************************/ +#if __LINE__!=232867 +#undef SQLITE_SOURCE_ID +#define SQLITE_SOURCE_ID "2020-01-22 18:38:59 f6affdd41608946fcfcea914ece149038a8b25a62bbe719ed2561c649b86alt2" +#endif +/* Return the source-id for this library */ +SQLITE_API const char *tdsqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } +/************************** End of sqlite3.c ******************************/ diff --git a/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.h b/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.h index 8222b7930e..44de2ee213 100644 --- a/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.h +++ b/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3.h @@ -1,5 +1,5 @@ /* -** 2001 September 15 +** 2001-09-15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: @@ -114,20 +114,22 @@ extern "C" { ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to ** a string which identifies a particular check-in of SQLite ** within its configuration management system. ^The SQLITE_SOURCE_ID -** string contains the date and time of the check-in (UTC) and an SHA1 -** hash of the entire source tree. +** string contains the date and time of the check-in (UTC) and a SHA1 +** or SHA3-256 hash of the entire source tree. If the source code has +** been edited in any way since it was last checked in, then the last +** four hexadecimal digits of the hash may be modified. ** -** See also: [sqlite3_libversion()], -** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** See also: [tdsqlite3_libversion()], +** [tdsqlite3_libversion_number()], [tdsqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ -#define SQLITE_VERSION "3.15.2" -#define SQLITE_VERSION_NUMBER 3015002 -#define SQLITE_SOURCE_ID "2016-11-28 19:13:37 bbd85d235f7037c6a033a9690534391ffeacecc8" +#define SQLITE_VERSION "3.31.0" +#define SQLITE_VERSION_NUMBER 3031000 +#define SQLITE_SOURCE_ID "2020-01-22 18:38:59 f6affdd41608946fcfcea914ece149038a8b25a62bbe719ed2561c649b86alt1" /* ** CAPI3REF: Run-Time Library Version Numbers -** KEYWORDS: sqlite3_version, sqlite3_sourceid +** KEYWORDS: tdsqlite3_version tdsqlite3_sourceid ** ** These interfaces provide the same information as the [SQLITE_VERSION], ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros @@ -138,59 +140,64 @@ extern "C" { ** compiled with matching library and header files. ** ** <blockquote><pre> -** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER ); -** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 ); -** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 ); +** assert( tdsqlite3_libversion_number()==SQLITE_VERSION_NUMBER ); +** assert( strncmp(tdsqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 ); +** assert( strcmp(tdsqlite3_libversion(),SQLITE_VERSION)==0 ); ** </pre></blockquote>)^ ** -** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] -** macro. ^The sqlite3_libversion() function returns a pointer to the -** to the sqlite3_version[] string constant. The sqlite3_libversion() +** ^The tdsqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The tdsqlite3_libversion() function returns a pointer to the +** to the tdsqlite3_version[] string constant. The tdsqlite3_libversion() ** function is provided for use in DLLs since DLL users usually do not have ** direct access to string constants within the DLL. ^The -** sqlite3_libversion_number() function returns an integer equal to -** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns +** tdsqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^(The tdsqlite3_sourceid() function returns ** a pointer to a string constant whose value is the same as the -** [SQLITE_SOURCE_ID] C preprocessor macro. +** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built +** using an edited copy of [the amalgamation], then the last four characters +** of the hash might be different from [SQLITE_SOURCE_ID].)^ ** ** See also: [sqlite_version()] and [sqlite_source_id()]. */ -SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; -SQLITE_API const char *sqlite3_libversion(void); -SQLITE_API const char *sqlite3_sourceid(void); -SQLITE_API int sqlite3_libversion_number(void); +SQLITE_API SQLITE_EXTERN const char tdsqlite3_version[]; +SQLITE_API const char *tdsqlite3_libversion(void); +SQLITE_API const char *tdsqlite3_sourceid(void); +SQLITE_API int tdsqlite3_libversion_number(void); /* ** CAPI3REF: Run-Time Library Compilation Options Diagnostics ** -** ^The sqlite3_compileoption_used() function returns 0 or 1 +** ^The tdsqlite3_compileoption_used() function returns 0 or 1 ** indicating whether the specified option was defined at ** compile time. ^The SQLITE_ prefix may be omitted from the -** option name passed to sqlite3_compileoption_used(). +** option name passed to tdsqlite3_compileoption_used(). ** -** ^The sqlite3_compileoption_get() function allows iterating +** ^The tdsqlite3_compileoption_get() function allows iterating ** over the list of options that were defined at compile time by ** returning the N-th compile time option string. ^If N is out of range, -** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** tdsqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ ** prefix is omitted from any strings returned by -** sqlite3_compileoption_get(). +** tdsqlite3_compileoption_get(). ** -** ^Support for the diagnostic functions sqlite3_compileoption_used() -** and sqlite3_compileoption_get() may be omitted by specifying the +** ^Support for the diagnostic functions tdsqlite3_compileoption_used() +** and tdsqlite3_compileoption_get() may be omitted by specifying the ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. ** ** See also: SQL functions [sqlite_compileoption_used()] and ** [sqlite_compileoption_get()] and the [compile_options pragma]. */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -SQLITE_API int sqlite3_compileoption_used(const char *zOptName); -SQLITE_API const char *sqlite3_compileoption_get(int N); +SQLITE_API int tdsqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *tdsqlite3_compileoption_get(int N); +#else +# define tdsqlite3_compileoption_used(X) 0 +# define tdsqlite3_compileoption_get(X) ((void*)0) #endif /* ** CAPI3REF: Test To See If The Library Is Threadsafe ** -** ^The sqlite3_threadsafe() function returns zero if and only if +** ^The tdsqlite3_threadsafe() function returns zero if and only if ** SQLite was compiled with mutexing code omitted due to the ** [SQLITE_THREADSAFE] compile-time option being set to 0. ** @@ -213,33 +220,33 @@ SQLITE_API const char *sqlite3_compileoption_get(int N); ** This interface only reports on the compile-time mutex setting ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but -** can be fully or partially disabled using a call to [sqlite3_config()] +** can be fully or partially disabled using a call to [tdsqlite3_config()] ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the -** sqlite3_threadsafe() function shows only the compile-time setting of +** tdsqlite3_threadsafe() function shows only the compile-time setting of ** thread safety, not any run-time changes to that setting made by -** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() -** is unchanged by calls to sqlite3_config().)^ +** tdsqlite3_config(). In other words, the return value from tdsqlite3_threadsafe() +** is unchanged by calls to tdsqlite3_config().)^ ** ** See the [threading mode] documentation for additional information. */ -SQLITE_API int sqlite3_threadsafe(void); +SQLITE_API int tdsqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle ** KEYWORDS: {database connection} {database connections} ** ** Each open SQLite database is represented by a pointer to an instance of -** the opaque structure named "sqlite3". It is useful to think of an sqlite3 -** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] -** and [sqlite3_close_v2()] are its destructors. There are many other +** the opaque structure named "tdsqlite3". It is useful to think of an tdsqlite3 +** pointer as an object. The [tdsqlite3_open()], [tdsqlite3_open16()], and +** [tdsqlite3_open_v2()] interfaces are its constructors, and [tdsqlite3_close()] +** and [tdsqlite3_close_v2()] are its destructors. There are many other ** interfaces (such as -** [sqlite3_prepare_v2()], [sqlite3_create_function()], and -** [sqlite3_busy_timeout()] to name but three) that are methods on an -** sqlite3 object. +** [tdsqlite3_prepare_v2()], [tdsqlite3_create_function()], and +** [tdsqlite3_busy_timeout()] to name but three) that are methods on an +** tdsqlite3 object. */ -typedef struct sqlite3 sqlite3; +typedef struct tdsqlite3 tdsqlite3; /* ** CAPI3REF: 64-Bit Integer Types @@ -248,18 +255,22 @@ typedef struct sqlite3 sqlite3; ** Because there is no cross-platform way to specify 64-bit integer types ** SQLite includes typedefs for 64-bit signed and unsigned integers. ** -** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The tdsqlite3_int64 and tdsqlite3_uint64 are the preferred type definitions. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards ** compatibility only. ** -** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** ^The tdsqlite3_int64 and sqlite_int64 types can store integer values ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The -** sqlite3_uint64 and sqlite_uint64 types can store integer values +** tdsqlite3_uint64 and sqlite_uint64 types can store integer values ** between 0 and +18446744073709551615 inclusive. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; - typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +# ifdef SQLITE_UINT64_TYPE + typedef SQLITE_UINT64_TYPE sqlite_uint64; +# else + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +# endif #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef __int64 sqlite_int64; typedef unsigned __int64 sqlite_uint64; @@ -267,116 +278,116 @@ typedef struct sqlite3 sqlite3; typedef long long int sqlite_int64; typedef unsigned long long int sqlite_uint64; #endif -typedef sqlite_int64 sqlite3_int64; -typedef sqlite_uint64 sqlite3_uint64; +typedef sqlite_int64 tdsqlite3_int64; +typedef sqlite_uint64 tdsqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point. */ #ifdef SQLITE_OMIT_FLOATING_POINT -# define double sqlite3_int64 +# define double tdsqlite3_int64 #endif /* ** CAPI3REF: Closing A Database Connection -** DESTRUCTOR: sqlite3 +** DESTRUCTOR: tdsqlite3 ** -** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors -** for the [sqlite3] object. -** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if -** the [sqlite3] object is successfully destroyed and all associated +** ^The tdsqlite3_close() and tdsqlite3_close_v2() routines are destructors +** for the [tdsqlite3] object. +** ^Calls to tdsqlite3_close() and tdsqlite3_close_v2() return [SQLITE_OK] if +** the [tdsqlite3] object is successfully destroyed and all associated ** resources are deallocated. ** ** ^If the database connection is associated with unfinalized prepared -** statements or unfinished sqlite3_backup objects then sqlite3_close() +** statements or unfinished tdsqlite3_backup objects then tdsqlite3_close() ** will leave the database connection open and return [SQLITE_BUSY]. -** ^If sqlite3_close_v2() is called with unfinalized prepared statements -** and/or unfinished sqlite3_backups, then the database connection becomes +** ^If tdsqlite3_close_v2() is called with unfinalized prepared statements +** and/or unfinished tdsqlite3_backups, then the database connection becomes ** an unusable "zombie" which will automatically be deallocated when the -** last prepared statement is finalized or the last sqlite3_backup is -** finished. The sqlite3_close_v2() interface is intended for use with +** last prepared statement is finalized or the last tdsqlite3_backup is +** finished. The tdsqlite3_close_v2() interface is intended for use with ** host languages that are garbage collected, and where the order in which ** destructors are called is arbitrary. ** -** Applications should [sqlite3_finalize | finalize] all [prepared statements], -** [sqlite3_blob_close | close] all [BLOB handles], and -** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated -** with the [sqlite3] object prior to attempting to close the object. ^If -** sqlite3_close_v2() is called on a [database connection] that still has +** Applications should [tdsqlite3_finalize | finalize] all [prepared statements], +** [tdsqlite3_blob_close | close] all [BLOB handles], and +** [tdsqlite3_backup_finish | finish] all [tdsqlite3_backup] objects associated +** with the [tdsqlite3] object prior to attempting to close the object. ^If +** tdsqlite3_close_v2() is called on a [database connection] that still has ** outstanding [prepared statements], [BLOB handles], and/or -** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation +** [tdsqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation ** of resources is deferred until all [prepared statements], [BLOB handles], -** and [sqlite3_backup] objects are also destroyed. +** and [tdsqlite3_backup] objects are also destroyed. ** -** ^If an [sqlite3] object is destroyed while a transaction is open, +** ^If an [tdsqlite3] object is destroyed while a transaction is open, ** the transaction is automatically rolled back. ** -** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] +** The C parameter to [tdsqlite3_close(C)] and [tdsqlite3_close_v2(C)] ** must be either a NULL -** pointer or an [sqlite3] object pointer obtained -** from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()], and not previously closed. -** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer +** pointer or an [tdsqlite3] object pointer obtained +** from [tdsqlite3_open()], [tdsqlite3_open16()], or +** [tdsqlite3_open_v2()], and not previously closed. +** ^Calling tdsqlite3_close() or tdsqlite3_close_v2() with a NULL pointer ** argument is a harmless no-op. */ -SQLITE_API int sqlite3_close(sqlite3*); -SQLITE_API int sqlite3_close_v2(sqlite3*); +SQLITE_API int tdsqlite3_close(tdsqlite3*); +SQLITE_API int tdsqlite3_close_v2(tdsqlite3*); /* ** The type for a callback function. ** This is legacy and deprecated. It is included for historical ** compatibility and is not documented. */ -typedef int (*sqlite3_callback)(void*,int,char**, char**); +typedef int (*tdsqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** The sqlite3_exec() interface is a convenience wrapper around -** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** The tdsqlite3_exec() interface is a convenience wrapper around +** [tdsqlite3_prepare_v2()], [tdsqlite3_step()], and [tdsqlite3_finalize()], ** that allows an application to run multiple statements of SQL ** without having to use a lot of C code. ** -** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** ^The tdsqlite3_exec() interface runs zero or more UTF-8 encoded, ** semicolon-separate SQL statements passed into its 2nd argument, ** in the context of the [database connection] passed in as its 1st ** argument. ^If the callback function of the 3rd argument to -** sqlite3_exec() is not NULL, then it is invoked for each result row +** tdsqlite3_exec() is not NULL, then it is invoked for each result row ** coming out of the evaluated SQL statements. ^The 4th argument to -** sqlite3_exec() is relayed through to the 1st argument of each -** callback invocation. ^If the callback pointer to sqlite3_exec() +** tdsqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to tdsqlite3_exec() ** is NULL, then no callback is ever invoked and result rows are ** ignored. ** ** ^If an error occurs while evaluating the SQL statements passed into -** sqlite3_exec(), then execution of the current statement stops and -** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** tdsqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to tdsqlite3_exec() ** is not NULL then any error message is written into memory obtained -** from [sqlite3_malloc()] and passed back through the 5th parameter. -** To avoid memory leaks, the application should invoke [sqlite3_free()] +** from [tdsqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [tdsqlite3_free()] ** on error message strings returned through the 5th parameter of -** sqlite3_exec() after the error message string is no longer needed. -** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors -** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** tdsqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to tdsqlite3_exec() is not NULL and no errors +** occur, then tdsqlite3_exec() sets the pointer in its 5th parameter to ** NULL before returning. ** -** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** ^If an tdsqlite3_exec() callback returns non-zero, the tdsqlite3_exec() ** routine returns SQLITE_ABORT without invoking the callback again and ** without running any subsequent SQL statements. ** -** ^The 2nd argument to the sqlite3_exec() callback function is the -** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** ^The 2nd argument to the tdsqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the tdsqlite3_exec() ** callback is an array of pointers to strings obtained as if from -** [sqlite3_column_text()], one for each column. ^If an element of a +** [tdsqlite3_column_text()], one for each column. ^If an element of a ** result row is NULL then the corresponding string pointer for the -** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the -** sqlite3_exec() callback is an array of pointers to strings where each +** tdsqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** tdsqlite3_exec() callback is an array of pointers to strings where each ** entry represents the name of corresponding result column as obtained -** from [sqlite3_column_name()]. +** from [tdsqlite3_column_name()]. ** -** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** ^If the 2nd parameter to tdsqlite3_exec() is a NULL pointer, a pointer ** to an empty string, or a pointer that contains only whitespace and/or ** SQL comments, then no SQL statements are evaluated and the database ** is not changed. @@ -384,16 +395,16 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); ** Restrictions: ** ** <ul> -** <li> The application must ensure that the 1st parameter to sqlite3_exec() +** <li> The application must ensure that the 1st parameter to tdsqlite3_exec() ** is a valid and open [database connection]. ** <li> The application must not close the [database connection] specified by -** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +** the 1st parameter to tdsqlite3_exec() while tdsqlite3_exec() is running. ** <li> The application must not modify the SQL statement text passed into -** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +** the 2nd parameter of tdsqlite3_exec() while tdsqlite3_exec() is running. ** </ul> */ -SQLITE_API int sqlite3_exec( - sqlite3*, /* An open database */ +SQLITE_API int tdsqlite3_exec( + tdsqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ @@ -413,7 +424,7 @@ SQLITE_API int sqlite3_exec( */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ -#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_ERROR 1 /* Generic error */ #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ #define SQLITE_PERM 3 /* Access permission denied */ #define SQLITE_ABORT 4 /* Callback routine requested an abort */ @@ -421,14 +432,14 @@ SQLITE_API int sqlite3_exec( #define SQLITE_LOCKED 6 /* A table in the database is locked */ #define SQLITE_NOMEM 7 /* A malloc() failed */ #define SQLITE_READONLY 8 /* Attempt to write a readonly database */ -#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_INTERRUPT 9 /* Operation terminated by tdsqlite3_interrupt()*/ #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ #define SQLITE_CORRUPT 11 /* The database disk image is malformed */ -#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in tdsqlite3_file_control() */ #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ -#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_EMPTY 16 /* Internal use only */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ @@ -436,13 +447,13 @@ SQLITE_API int sqlite3_exec( #define SQLITE_MISUSE 21 /* Library used incorrectly */ #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ #define SQLITE_AUTH 23 /* Authorization denied */ -#define SQLITE_FORMAT 24 /* Auxiliary database format error */ -#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_FORMAT 24 /* Not used */ +#define SQLITE_RANGE 25 /* 2nd parameter to tdsqlite3_bind out of range */ #define SQLITE_NOTADB 26 /* File opened that is not a database file */ -#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ -#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ -#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ -#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +#define SQLITE_NOTICE 27 /* Notifications from tdsqlite3_log() */ +#define SQLITE_WARNING 28 /* Warnings from tdsqlite3_log() */ +#define SQLITE_ROW 100 /* tdsqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* tdsqlite3_step() has finished executing */ /* end-of-error-codes */ /* @@ -458,10 +469,13 @@ SQLITE_API int sqlite3_exec( ** support for additional result codes that provide more detailed information ** about errors. These [extended result codes] are enabled or disabled ** on a per database connection basis using the -** [sqlite3_extended_result_codes()] API. Or, the extended code for +** [tdsqlite3_extended_result_codes()] API. Or, the extended code for ** the most recent error can be obtained using -** [sqlite3_extended_errcode()]. +** [tdsqlite3_extended_errcode()]. */ +#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8)) +#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8)) +#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8)) #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) @@ -490,18 +504,27 @@ SQLITE_API int sqlite3_exec( #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) +#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8)) +#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8)) +#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) +#define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */ +#define SQLITE_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8)) #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) +#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8)) #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8)) +#define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8)) +#define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8)) #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) @@ -513,27 +536,29 @@ SQLITE_API int sqlite3_exec( #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) +#define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8)) #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) +#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* ** CAPI3REF: Flags For File Open Operations ** ** These bit values are intended for use in the -** 3rd parameter to the [sqlite3_open_v2()] interface and -** in the 4th parameter to the [sqlite3_vfs.xOpen] method. +** 3rd parameter to the [tdsqlite3_open_v2()] interface and +** in the 4th parameter to the [tdsqlite3_vfs.xOpen] method. */ -#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for tdsqlite3_open_v2() */ #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ -#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_URI 0x00000040 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for tdsqlite3_open_v2() */ #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ @@ -541,21 +566,22 @@ SQLITE_API int sqlite3_exec( #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ -#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for tdsqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for tdsqlite3_open_v2() */ #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ +#define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for tdsqlite3_open_v2() */ /* Reserved: 0x00F00000 */ /* ** CAPI3REF: Device Characteristics ** -** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** The xDeviceCharacteristics method of the [tdsqlite3_io_methods] ** object returns an integer which is a vector of these ** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] +** device that holds the file that the [tdsqlite3_io_methods] ** refers to. ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of @@ -572,10 +598,15 @@ SQLITE_API int sqlite3_exec( ** file that were written at the application level might have changed ** and that adjacent bytes, even bytes within the same sector are ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN -** flag indicate that a file cannot be deleted when open. The +** flag indicates that a file cannot be deleted when open. The ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on ** read-only media and cannot be changed even by processes with ** elevated privileges. +** +** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying +** filesystem supports doing multiple write operations atomically when those +** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and +** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. */ #define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC512 0x00000002 @@ -591,13 +622,14 @@ SQLITE_API int sqlite3_exec( #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000 +#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000 /* ** CAPI3REF: File Locking Levels ** ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods -** of an [sqlite3_io_methods] object. +** of an [tdsqlite3_io_methods] object. */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 @@ -609,7 +641,7 @@ SQLITE_API int sqlite3_exec( ** CAPI3REF: Synchronization Type Flags ** ** When SQLite invokes the xSync() method of an -** [sqlite3_io_methods] object it uses a combination of +** [tdsqlite3_io_methods] object it uses a combination of ** these integer values as the second argument. ** ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the @@ -638,33 +670,33 @@ SQLITE_API int sqlite3_exec( /* ** CAPI3REF: OS Interface Open File Handle ** -** An [sqlite3_file] object represents an open file in the -** [sqlite3_vfs | OS interface layer]. Individual OS interface +** An [tdsqlite3_file] object represents an open file in the +** [tdsqlite3_vfs | OS interface layer]. Individual OS interface ** implementations will ** want to subclass this object by appending additional fields ** for their own use. The pMethods entry is a pointer to an -** [sqlite3_io_methods] object that defines methods for performing +** [tdsqlite3_io_methods] object that defines methods for performing ** I/O operations on the open file. */ -typedef struct sqlite3_file sqlite3_file; -struct sqlite3_file { - const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +typedef struct tdsqlite3_file tdsqlite3_file; +struct tdsqlite3_file { + const struct tdsqlite3_io_methods *pMethods; /* Methods for an open file */ }; /* ** CAPI3REF: OS Interface File Virtual Methods Object ** -** Every file opened by the [sqlite3_vfs.xOpen] method populates an -** [sqlite3_file] object (or, more commonly, a subclass of the -** [sqlite3_file] object) with a pointer to an instance of this object. +** Every file opened by the [tdsqlite3_vfs.xOpen] method populates an +** [tdsqlite3_file] object (or, more commonly, a subclass of the +** [tdsqlite3_file] object) with a pointer to an instance of this object. ** This object defines the methods used to perform various operations -** against the open file represented by the [sqlite3_file] object. +** against the open file represented by the [tdsqlite3_file] object. ** -** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element -** to a non-NULL pointer, then the sqlite3_io_methods.xClose method -** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The -** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] -** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element +** If the [tdsqlite3_vfs.xOpen] method sets the tdsqlite3_file.pMethods element +** to a non-NULL pointer, then the tdsqlite3_io_methods.xClose method +** may be invoked even if the [tdsqlite3_vfs.xOpen] reported that it failed. The +** only way to prevent a call to xClose following a failed [tdsqlite3_vfs.xOpen] +** is for the [tdsqlite3_vfs.xOpen] to set the tdsqlite3_file.pMethods element ** to NULL. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or @@ -689,7 +721,7 @@ struct sqlite3_file { ** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the -** [sqlite3_file_control()] interface. The second "op" argument is an +** [tdsqlite3_file_control()] interface. The second "op" argument is an ** integer opcode. The third argument is a generic pointer intended to ** point to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be @@ -722,6 +754,10 @@ struct sqlite3_file { ** <li> [SQLITE_IOCAP_ATOMIC64K] ** <li> [SQLITE_IOCAP_SAFE_APPEND] ** <li> [SQLITE_IOCAP_SEQUENTIAL] +** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN] +** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE] +** <li> [SQLITE_IOCAP_IMMUTABLE] +** <li> [SQLITE_IOCAP_BATCH_ATOMIC] ** </ul> ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of @@ -741,29 +777,29 @@ struct sqlite3_file { ** failure to zero-fill short reads will eventually lead to ** database corruption. */ -typedef struct sqlite3_io_methods sqlite3_io_methods; -struct sqlite3_io_methods { +typedef struct tdsqlite3_io_methods tdsqlite3_io_methods; +struct tdsqlite3_io_methods { int iVersion; - int (*xClose)(sqlite3_file*); - int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); - int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); - int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); - int (*xSync)(sqlite3_file*, int flags); - int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); - int (*xLock)(sqlite3_file*, int); - int (*xUnlock)(sqlite3_file*, int); - int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); - int (*xFileControl)(sqlite3_file*, int op, void *pArg); - int (*xSectorSize)(sqlite3_file*); - int (*xDeviceCharacteristics)(sqlite3_file*); + int (*xClose)(tdsqlite3_file*); + int (*xRead)(tdsqlite3_file*, void*, int iAmt, tdsqlite3_int64 iOfst); + int (*xWrite)(tdsqlite3_file*, const void*, int iAmt, tdsqlite3_int64 iOfst); + int (*xTruncate)(tdsqlite3_file*, tdsqlite3_int64 size); + int (*xSync)(tdsqlite3_file*, int flags); + int (*xFileSize)(tdsqlite3_file*, tdsqlite3_int64 *pSize); + int (*xLock)(tdsqlite3_file*, int); + int (*xUnlock)(tdsqlite3_file*, int); + int (*xCheckReservedLock)(tdsqlite3_file*, int *pResOut); + int (*xFileControl)(tdsqlite3_file*, int op, void *pArg); + int (*xSectorSize)(tdsqlite3_file*); + int (*xDeviceCharacteristics)(tdsqlite3_file*); /* Methods above are valid for version 1 */ - int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); - int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); - void (*xShmBarrier)(sqlite3_file*); - int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + int (*xShmMap)(tdsqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(tdsqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(tdsqlite3_file*); + int (*xShmUnmap)(tdsqlite3_file*, int deleteFlag); /* Methods above are valid for version 2 */ - int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); - int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); + int (*xFetch)(tdsqlite3_file*, tdsqlite3_int64 iOfst, int iAmt, void **pp); + int (*xUnfetch)(tdsqlite3_file*, tdsqlite3_int64 iOfst, void *p); /* Methods above are valid for version 3 */ /* Additional methods may be added in future releases */ }; @@ -773,7 +809,7 @@ struct sqlite3_io_methods { ** KEYWORDS: {file control opcodes} {file control opcode} ** ** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** of the [tdsqlite3_io_methods] object and for the [tdsqlite3_file_control()] ** interface. ** ** <ul> @@ -794,10 +830,19 @@ struct sqlite3_io_methods { ** file space based on this hint in order to help writes to the database ** file run faster. ** +** <li>[[SQLITE_FCNTL_SIZE_LIMIT]] +** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that +** implements [tdsqlite3_deserialize()] to set an upper bound on the size +** of the in-memory database. The argument is a pointer to a [tdsqlite3_int64]. +** If the integer pointed to is negative, then it is filled in with the +** current limit. Otherwise the limit is set to the larger of the value +** of the integer pointed to and the current database size. The integer +** pointed to is set to the new limit. +** ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]] ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS ** extends and truncates the database file in chunks of a size specified -** by the user. The fourth argument to [sqlite3_file_control()] should +** by the user. The fourth argument to [tdsqlite3_file_control()] should ** point to an integer (type int) containing the new chunk-size to use ** for the nominated database. Allocating database file space in large ** chunks (say 1MB at a time), may reduce file-system fragmentation and @@ -805,12 +850,12 @@ struct sqlite3_io_methods { ** ** <li>[[SQLITE_FCNTL_FILE_POINTER]] ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer -** to the [sqlite3_file] object associated with a particular database +** to the [tdsqlite3_file] object associated with a particular database ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. ** ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]] ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer -** to the [sqlite3_file] object associated with the journal file (either +** to the [tdsqlite3_file] object associated with the journal file (either ** the [rollback journal] or the [write-ahead log]) for a particular database ** connection. See also [SQLITE_FCNTL_FILE_POINTER]. ** @@ -828,7 +873,7 @@ struct sqlite3_io_methods { ** as part of a multi-database commit, the argument points to a nul-terminated ** string containing the transactions master-journal file name. VFSes that ** do not need this signal should silently ignore this opcode. Applications -** should not call [sqlite3_file_control()] with this opcode as doing so may +** should not call [tdsqlite3_file_control()] with this opcode as doing so may ** disrupt the operation of the specialized VFSes that do require it. ** ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]] @@ -836,7 +881,7 @@ struct sqlite3_io_methods { ** and sent to the VFS after a transaction has been committed immediately ** but before the database is unlocked. VFSes that do not need this signal ** should silently ignore this opcode. Applications should not call -** [sqlite3_file_control()] with this opcode as doing so may disrupt the +** [tdsqlite3_file_control()] with this opcode as doing so may disrupt the ** operation of the specialized VFSes that do require it. ** ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]] @@ -850,7 +895,7 @@ struct sqlite3_io_methods { ** opcode allows these two values (10 retries and 25 milliseconds of delay) ** to be adjusted. The values are changed for all database connections ** within the same process. The argument is a pointer to an array of two -** integers where the first integer i the new retry count and the second +** integers where the first integer is the new retry count and the second ** integer is the delay. If either integer is negative, then the setting ** is not changed but instead the prior value of that setting is written ** into the array entry, allowing the current retry settings to be @@ -859,14 +904,15 @@ struct sqlite3_io_methods { ** <li>[[SQLITE_FCNTL_PERSIST_WAL]] ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary -** write ahead log and shared memory files used for transaction control +** write ahead log ([WAL file]) and shared memory +** files used for transaction control ** are automatically deleted when the latest connection to the database ** closes. Setting persistent WAL mode causes those files to persist after ** close. Persisting the files is useful when other processes that do not ** have write permission on the directory containing the database file want ** to read the database file, as the WAL and shared memory files must exist ** in order for the database to be readable. The fourth parameter to -** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** [tdsqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent ** WAL mode. If the integer is -1, then it is overwritten with the current ** WAL persistence setting. @@ -876,7 +922,7 @@ struct sqlite3_io_methods { ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the ** xDeviceCharacteristics methods. The fourth parameter to -** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** [tdsqlite3_file_control()] for this opcode should be a pointer to an integer. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage ** mode. If the integer is -1, then it is overwritten with the current ** zero-damage mode setting. @@ -891,8 +937,8 @@ struct sqlite3_io_methods { ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of ** all [VFSes] in the VFS stack. The names are of all VFS shims and the ** final bottom-level VFS are written into memory obtained from -** [sqlite3_malloc()] and the result is stored in the char* variable -** that the fourth parameter of [sqlite3_file_control()] points to. +** [tdsqlite3_malloc()] and the result is stored in the char* variable +** that the fourth parameter of [tdsqlite3_file_control()] points to. ** The caller is responsible for freeing the memory when done. As with ** all file-control actions, there is no guarantee that this will actually ** do anything. Callers should initialize the char* variable to a NULL @@ -902,22 +948,22 @@ struct sqlite3_io_methods { ** <li>[[SQLITE_FCNTL_VFS_POINTER]] ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level ** [VFSes] currently in use. ^(The argument X in -** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be -** of type "[sqlite3_vfs] **". This opcodes will set *X +** tdsqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be +** of type "[tdsqlite3_vfs] **". This opcodes will set *X ** to a pointer to the top-level VFS.)^ ** ^When there are multiple VFS shims in the stack, this opcode finds the ** upper-most shim only. ** ** <li>[[SQLITE_FCNTL_PRAGMA]] ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] -** file control is sent to the open [sqlite3_file] object corresponding +** file control is sent to the open [tdsqlite3_file] object corresponding ** to the database file to which the pragma statement refers. ^The argument ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of ** pointers to strings (char**) in which the second element of the array ** is the name of the pragma and the third element is the argument to the ** pragma or NULL if the pragma has no argument. ^The handler for an ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element -** of the char** argument point to a string obtained from [sqlite3_mprintf()] +** of the char** argument point to a string obtained from [tdsqlite3_mprintf()] ** or the equivalent and that string will become the result of the pragma or ** the error message if the pragma fails. ^If the ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal @@ -937,27 +983,27 @@ struct sqlite3_io_methods { ** ^The [SQLITE_FCNTL_BUSYHANDLER] ** file-control may be invoked by SQLite on the database file handle ** shortly after it is opened in order to provide a custom VFS with access -** to the connections busy-handler callback. The argument is of type (void **) +** to the connection's busy-handler callback. The argument is of type (void**) ** - an array of two (void *) values. The first (void *) actually points -** to a function of type (int (*)(void *)). In order to invoke the connections +** to a function of type (int (*)(void *)). In order to invoke the connection's ** busy-handler, this function should be invoked with the second (void *) in ** the array as the only argument. If it returns non-zero, then the operation ** should be retried. If it returns zero, the custom VFS should abandon the ** current operation. ** ** <li>[[SQLITE_FCNTL_TEMPFILENAME]] -** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control +** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control ** to have SQLite generate a ** temporary filename using the same algorithm that is followed to generate ** temporary filenames for TEMP tables and other internal uses. The ** argument should be a char** which will be filled with the filename -** written into memory obtained from [sqlite3_malloc()]. The caller should -** invoke [sqlite3_free()] on the result to avoid a memory leak. +** written into memory obtained from [tdsqlite3_malloc()]. The caller should +** invoke [tdsqlite3_free()] on the result to avoid a memory leak. ** ** <li>[[SQLITE_FCNTL_MMAP_SIZE]] ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the ** maximum number of bytes that will be used for memory-mapped I/O. -** The argument is a pointer to a value of type sqlite3_int64 that +** The argument is a pointer to a value of type tdsqlite3_int64 that ** is an advisory maximum number of bytes in the file to memory map. The ** pointer is overwritten with the old value. The limit is not changed if ** the value originally pointed to is negative, and so the current limit @@ -1005,6 +1051,72 @@ struct sqlite3_io_methods { ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for ** this opcode. +** +** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]] +** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then +** the file descriptor is placed in "batch write mode", which +** means all subsequent write operations will be deferred and done +** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems +** that do not support batch atomic writes will return SQLITE_NOTFOUND. +** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to +** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or +** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make +** no VFS interface calls on the same [tdsqlite3_file] file descriptor +** except for calls to the xWrite method and the xFileControl method +** with [SQLITE_FCNTL_SIZE_HINT]. +** +** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]] +** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write +** operations since the previous successful call to +** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically. +** This file control returns [SQLITE_OK] if and only if the writes were +** all performed successfully and have been committed to persistent storage. +** ^Regardless of whether or not it is successful, this file control takes +** the file descriptor out of batch write mode so that all subsequent +** write operations are independent. +** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without +** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. +** +** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]] +** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write +** operations since the previous successful call to +** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back. +** ^This file control takes the file descriptor out of batch write mode +** so that all subsequent write operations are independent. +** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without +** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. +** +** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]] +** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain +** a file lock using the xLock or xShmLock methods of the VFS to wait +** for up to M milliseconds before failing, where M is the single +** unsigned integer parameter. +** +** <li>[[SQLITE_FCNTL_DATA_VERSION]] +** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to +** a database file. The argument is a pointer to a 32-bit unsigned integer. +** The "data version" for the pager is written into the pointer. The +** "data version" changes whenever any change occurs to the corresponding +** database file, either through SQL statements on the same database +** connection or through transactions committed by separate database +** connections possibly in other processes. The [tdsqlite3_total_changes()] +** interface can be used to find if any database on the connection has changed, +** but that interface responds to changes on TEMP as well as MAIN and does +** not provide a mechanism to detect changes to MAIN only. Also, the +** [tdsqlite3_total_changes()] interface responds to internal changes only and +** omits changes made by other database connections. The +** [PRAGMA data_version] command provides a mechanism to detect changes to +** a single attached database that occur due to other database connections, +** but omits changes implemented by the database connection on which it is +** called. This file control is the only mechanism to detect changes that +** happen either internally or externally and that are associated with +** a particular attached database. +** +** <li>[[SQLITE_FCNTL_CKPT_DONE]] +** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint +** in wal mode after the client has finished copying pages from the wal +** file to the database file, but before the *-shm file is updated to +** record the fact that the pages have been checkpointed. ** </ul> */ #define SQLITE_FCNTL_LOCKSTATE 1 @@ -1035,6 +1147,14 @@ struct sqlite3_io_methods { #define SQLITE_FCNTL_VFS_POINTER 27 #define SQLITE_FCNTL_JOURNAL_POINTER 28 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29 +#define SQLITE_FCNTL_PDB 30 +#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31 +#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32 +#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33 +#define SQLITE_FCNTL_LOCK_TIMEOUT 34 +#define SQLITE_FCNTL_DATA_VERSION 35 +#define SQLITE_FCNTL_SIZE_LIMIT 36 +#define SQLITE_FCNTL_CKPT_DONE 37 /* deprecated names */ #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE @@ -1045,61 +1165,67 @@ struct sqlite3_io_methods { /* ** CAPI3REF: Mutex Handle ** -** The mutex module within SQLite defines [sqlite3_mutex] to be an +** The mutex module within SQLite defines [tdsqlite3_mutex] to be an ** abstract type for a mutex object. The SQLite core never looks -** at the internal representation of an [sqlite3_mutex]. It only -** deals with pointers to the [sqlite3_mutex] object. +** at the internal representation of an [tdsqlite3_mutex]. It only +** deals with pointers to the [tdsqlite3_mutex] object. ** -** Mutexes are created using [sqlite3_mutex_alloc()]. +** Mutexes are created using [tdsqlite3_mutex_alloc()]. */ -typedef struct sqlite3_mutex sqlite3_mutex; +typedef struct tdsqlite3_mutex tdsqlite3_mutex; /* ** CAPI3REF: Loadable Extension Thunk ** -** A pointer to the opaque sqlite3_api_routines structure is passed as +** A pointer to the opaque tdsqlite3_api_routines structure is passed as ** the third parameter to entry points of [loadable extensions]. This ** structure must be typedefed in order to work around compiler warnings ** on some platforms. */ -typedef struct sqlite3_api_routines sqlite3_api_routines; +typedef struct tdsqlite3_api_routines tdsqlite3_api_routines; /* ** CAPI3REF: OS Interface Object ** -** An instance of the sqlite3_vfs object defines the interface between +** An instance of the tdsqlite3_vfs object defines the interface between ** the SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". See ** the [VFS | VFS documentation] for further information. ** -** The value of the iVersion field is initially 1 but may be larger in -** future versions of SQLite. Additional fields may be appended to this -** object when the iVersion value is increased. Note that the structure -** of the sqlite3_vfs object changes in the transaction between -** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not -** modified. -** -** The szOsFile field is the size of the subclassed [sqlite3_file] +** The VFS interface is sometimes extended by adding new methods onto +** the end. Each time such an extension occurs, the iVersion field +** is incremented. The iVersion value started out as 1 in +** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2 +** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased +** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields +** may be appended to the tdsqlite3_vfs object and the iVersion value +** may increase again in future versions of SQLite. +** Note that due to an oversight, the structure +** of the tdsqlite3_vfs object changed in the transition from +** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0] +** and yet the iVersion field was not increased. +** +** The szOsFile field is the size of the subclassed [tdsqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** -** Registered sqlite3_vfs objects are kept on a linked list formed by -** the pNext pointer. The [sqlite3_vfs_register()] -** and [sqlite3_vfs_unregister()] interfaces manage this list -** in a thread-safe way. The [sqlite3_vfs_find()] interface +** Registered tdsqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [tdsqlite3_vfs_register()] +** and [tdsqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [tdsqlite3_vfs_find()] interface ** searches the list. Neither the application code nor the VFS ** implementation should use the pNext pointer. ** -** The pNext field is the only field in the sqlite3_vfs +** The pNext field is the only field in the tdsqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. -** The application should never modify anything within the sqlite3_vfs +** The application should never modify anything within the tdsqlite3_vfs ** object once the object has been registered. ** ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** -** [[sqlite3_vfs.xOpen]] +** [[tdsqlite3_vfs.xOpen]] ** ^SQLite guarantees that the zFilename parameter to xOpen ** is either a NULL pointer or string obtained ** from xFullPathname() with an optional suffix added. @@ -1109,7 +1235,7 @@ typedef struct sqlite3_api_routines sqlite3_api_routines; ** ^SQLite further guarantees that ** the string will be valid and unchanged until xClose() is ** called. Because of the previous sentence, -** the [sqlite3_file] can safely store a pointer to the +** the [tdsqlite3_file] can safely store a pointer to the ** filename if it needs to remember the filename for some reason. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen ** must invent its own temporary name for the file. ^Whenever the @@ -1117,8 +1243,8 @@ typedef struct sqlite3_api_routines sqlite3_api_routines; ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** The flags argument to xOpen() includes all bits set in -** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] -** or [sqlite3_open16()] is used, then flags includes at least +** the flags argument to [tdsqlite3_open_v2()]. Or if [tdsqlite3_open()] +** or [tdsqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. ** If xOpen() opens a file read-only then it sets *pOutFlags to ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. @@ -1168,21 +1294,27 @@ typedef struct sqlite3_api_routines sqlite3_api_routines; ** for exclusive access. ** ** ^At least szOsFile bytes of memory are allocated by SQLite -** to hold the [sqlite3_file] structure passed as the third +** to hold the [tdsqlite3_file] structure passed as the third ** argument to xOpen. The xOpen method does not have to ** allocate the structure; it should just fill it in. Note that -** the xOpen method must set the sqlite3_file.pMethods to either -** a valid [sqlite3_io_methods] object or to NULL. xOpen must do -** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** the xOpen method must set the tdsqlite3_file.pMethods to either +** a valid [tdsqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the tdsqlite3_file.pMethods ** element will be valid after xOpen returns regardless of the success ** or failure of the xOpen call. ** -** [[sqlite3_vfs.xAccess]] +** [[tdsqlite3_vfs.xAccess]] ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] -** to test whether a file is at least readable. The file can be a -** directory. +** to test whether a file is at least readable. The SQLITE_ACCESS_READ +** flag is never actually used and is not implemented in the built-in +** VFSes of SQLite. The file is named by the second argument and can be a +** directory. The xAccess method returns [SQLITE_OK] on success or some +** non-zero error code if there is an I/O error or if the name of +** the file given in the second argument is illegal. If SQLITE_OK +** is returned, then non-zero or zero is written into *pResOut to indicate +** whether or not the file is accessible. ** ** ^SQLite will always allocate at least mxPathname+1 bytes for the ** output buffer xFullPathname. The exact size of the output buffer @@ -1221,40 +1353,40 @@ typedef struct sqlite3_api_routines sqlite3_api_routines; ** from one release to the next. Applications must not attempt to access ** any of these methods if the iVersion of the VFS is less than 3. */ -typedef struct sqlite3_vfs sqlite3_vfs; -typedef void (*sqlite3_syscall_ptr)(void); -struct sqlite3_vfs { +typedef struct tdsqlite3_vfs tdsqlite3_vfs; +typedef void (*tdsqlite3_syscall_ptr)(void); +struct tdsqlite3_vfs { int iVersion; /* Structure version number (currently 3) */ - int szOsFile; /* Size of subclassed sqlite3_file */ + int szOsFile; /* Size of subclassed tdsqlite3_file */ int mxPathname; /* Maximum file pathname length */ - sqlite3_vfs *pNext; /* Next registered VFS */ + tdsqlite3_vfs *pNext; /* Next registered VFS */ const char *zName; /* Name of this virtual file system */ void *pAppData; /* Pointer to application-specific data */ - int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int (*xOpen)(tdsqlite3_vfs*, const char *zName, tdsqlite3_file*, int flags, int *pOutFlags); - int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); - int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); - int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); - void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); - void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); - void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); - void (*xDlClose)(sqlite3_vfs*, void*); - int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); - int (*xSleep)(sqlite3_vfs*, int microseconds); - int (*xCurrentTime)(sqlite3_vfs*, double*); - int (*xGetLastError)(sqlite3_vfs*, int, char *); + int (*xDelete)(tdsqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(tdsqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(tdsqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(tdsqlite3_vfs*, const char *zFilename); + void (*xDlError)(tdsqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(tdsqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(tdsqlite3_vfs*, void*); + int (*xRandomness)(tdsqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(tdsqlite3_vfs*, int microseconds); + int (*xCurrentTime)(tdsqlite3_vfs*, double*); + int (*xGetLastError)(tdsqlite3_vfs*, int, char *); /* ** The methods above are in version 1 of the sqlite_vfs object ** definition. Those that follow are added in version 2 or later */ - int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + int (*xCurrentTimeInt64)(tdsqlite3_vfs*, tdsqlite3_int64*); /* ** The methods above are in versions 1 and 2 of the sqlite_vfs object. ** Those below are for version 3 and greater. */ - int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); - sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); - const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); + int (*xSetSystemCall)(tdsqlite3_vfs*, const char *zName, tdsqlite3_syscall_ptr); + tdsqlite3_syscall_ptr (*xGetSystemCall)(tdsqlite3_vfs*, const char *zName); + const char *(*xNextSystemCall)(tdsqlite3_vfs*, const char *zName); /* ** The methods above are in versions 1 through 3 of the sqlite_vfs object. ** New fields may be appended in future versions. The iVersion @@ -1266,7 +1398,7 @@ struct sqlite3_vfs { ** CAPI3REF: Flags for the xAccess VFS method ** ** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine +** the xAccess method of an [tdsqlite3_vfs] object. They determine ** what kind of permissions the xAccess method is looking for. ** With SQLITE_ACCESS_EXISTS, the xAccess method ** simply checks whether the file exists. @@ -1290,7 +1422,7 @@ struct sqlite3_vfs { ** CAPI3REF: Flags for the xShmLock VFS method ** ** These integer constants define the various locking operations -** allowed by the xShmLock method of [sqlite3_io_methods]. The +** allowed by the xShmLock method of [tdsqlite3_io_methods]. The ** following are the only legal combinations of flags to the ** xShmLock method: ** @@ -1316,7 +1448,7 @@ struct sqlite3_vfs { /* ** CAPI3REF: Maximum xShmLock index ** -** The xShmLock method on [sqlite3_io_methods] may use values +** The xShmLock method on [tdsqlite3_io_methods] may use values ** between 0 and this upper bound as its "offset" argument. ** The SQLite core will never attempt to acquire or release a ** lock outside of this range @@ -1327,134 +1459,134 @@ struct sqlite3_vfs { /* ** CAPI3REF: Initialize The SQLite Library ** -** ^The sqlite3_initialize() routine initializes the -** SQLite library. ^The sqlite3_shutdown() routine -** deallocates any resources that were allocated by sqlite3_initialize(). +** ^The tdsqlite3_initialize() routine initializes the +** SQLite library. ^The tdsqlite3_shutdown() routine +** deallocates any resources that were allocated by tdsqlite3_initialize(). ** These routines are designed to aid in process initialization and ** shutdown on embedded systems. Workstation applications using ** SQLite normally do not need to invoke either of these routines. ** -** A call to sqlite3_initialize() is an "effective" call if it is -** the first time sqlite3_initialize() is invoked during the lifetime of -** the process, or if it is the first time sqlite3_initialize() is invoked -** following a call to sqlite3_shutdown(). ^(Only an effective call -** of sqlite3_initialize() does any initialization. All other calls +** A call to tdsqlite3_initialize() is an "effective" call if it is +** the first time tdsqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time tdsqlite3_initialize() is invoked +** following a call to tdsqlite3_shutdown(). ^(Only an effective call +** of tdsqlite3_initialize() does any initialization. All other calls ** are harmless no-ops.)^ ** -** A call to sqlite3_shutdown() is an "effective" call if it is the first -** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only -** an effective call to sqlite3_shutdown() does any deinitialization. -** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** A call to tdsqlite3_shutdown() is an "effective" call if it is the first +** call to tdsqlite3_shutdown() since the last tdsqlite3_initialize(). ^(Only +** an effective call to tdsqlite3_shutdown() does any deinitialization. +** All other valid calls to tdsqlite3_shutdown() are harmless no-ops.)^ ** -** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() -** is not. The sqlite3_shutdown() interface must only be called from a +** The tdsqlite3_initialize() interface is threadsafe, but tdsqlite3_shutdown() +** is not. The tdsqlite3_shutdown() interface must only be called from a ** single thread. All open [database connections] must be closed and all ** other SQLite resources must be deallocated prior to invoking -** sqlite3_shutdown(). +** tdsqlite3_shutdown(). ** -** Among other things, ^sqlite3_initialize() will invoke -** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() -** will invoke sqlite3_os_end(). +** Among other things, ^tdsqlite3_initialize() will invoke +** tdsqlite3_os_init(). Similarly, ^tdsqlite3_shutdown() +** will invoke tdsqlite3_os_end(). ** -** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. -** ^If for some reason, sqlite3_initialize() is unable to initialize +** ^The tdsqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, tdsqlite3_initialize() is unable to initialize ** the library (perhaps it is unable to allocate a needed resource such ** as a mutex) it returns an [error code] other than [SQLITE_OK]. ** -** ^The sqlite3_initialize() routine is called internally by many other +** ^The tdsqlite3_initialize() routine is called internally by many other ** SQLite interfaces so that an application usually does not need to -** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] -** calls sqlite3_initialize() so the SQLite library will be automatically -** initialized when [sqlite3_open()] is called if it has not be initialized +** invoke tdsqlite3_initialize() directly. For example, [tdsqlite3_open()] +** calls tdsqlite3_initialize() so the SQLite library will be automatically +** initialized when [tdsqlite3_open()] is called if it has not be initialized ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] -** compile-time option, then the automatic calls to sqlite3_initialize() -** are omitted and the application must call sqlite3_initialize() directly +** compile-time option, then the automatic calls to tdsqlite3_initialize() +** are omitted and the application must call tdsqlite3_initialize() directly ** prior to using any other SQLite interface. For maximum portability, -** it is recommended that applications always invoke sqlite3_initialize() +** it is recommended that applications always invoke tdsqlite3_initialize() ** directly prior to using any other SQLite interface. Future releases ** of SQLite may require this. In other words, the behavior exhibited ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the ** default behavior in some future release of SQLite. ** -** The sqlite3_os_init() routine does operating-system specific -** initialization of the SQLite library. The sqlite3_os_end() -** routine undoes the effect of sqlite3_os_init(). Typical tasks +** The tdsqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The tdsqlite3_os_end() +** routine undoes the effect of tdsqlite3_os_init(). Typical tasks ** performed by these routines include allocation or deallocation ** of static resources, initialization of global variables, -** setting up a default [sqlite3_vfs] module, or setting up -** a default configuration using [sqlite3_config()]. -** -** The application should never invoke either sqlite3_os_init() -** or sqlite3_os_end() directly. The application should only invoke -** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() -** interface is called automatically by sqlite3_initialize() and -** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate -** implementations for sqlite3_os_init() and sqlite3_os_end() +** setting up a default [tdsqlite3_vfs] module, or setting up +** a default configuration using [tdsqlite3_config()]. +** +** The application should never invoke either tdsqlite3_os_init() +** or tdsqlite3_os_end() directly. The application should only invoke +** tdsqlite3_initialize() and tdsqlite3_shutdown(). The tdsqlite3_os_init() +** interface is called automatically by tdsqlite3_initialize() and +** tdsqlite3_os_end() is called by tdsqlite3_shutdown(). Appropriate +** implementations for tdsqlite3_os_init() and tdsqlite3_os_end() ** are built into SQLite when it is compiled for Unix, Windows, or OS/2. ** When [custom builds | built for other platforms] ** (using the [SQLITE_OS_OTHER=1] compile-time ** option) the application must supply a suitable implementation for -** sqlite3_os_init() and sqlite3_os_end(). An application-supplied -** implementation of sqlite3_os_init() or sqlite3_os_end() +** tdsqlite3_os_init() and tdsqlite3_os_end(). An application-supplied +** implementation of tdsqlite3_os_init() or tdsqlite3_os_end() ** must return [SQLITE_OK] on success and some other [error code] upon ** failure. */ -SQLITE_API int sqlite3_initialize(void); -SQLITE_API int sqlite3_shutdown(void); -SQLITE_API int sqlite3_os_init(void); -SQLITE_API int sqlite3_os_end(void); +SQLITE_API int tdsqlite3_initialize(void); +SQLITE_API int tdsqlite3_shutdown(void); +SQLITE_API int tdsqlite3_os_init(void); +SQLITE_API int tdsqlite3_os_end(void); /* ** CAPI3REF: Configuring The SQLite Library ** -** The sqlite3_config() interface is used to make global configuration +** The tdsqlite3_config() interface is used to make global configuration ** changes to SQLite in order to tune SQLite to the specific needs of ** the application. The default configuration is recommended for most ** applications and so this routine is usually not necessary. It is ** provided to support rare applications with unusual needs. ** -** <b>The sqlite3_config() interface is not threadsafe. The application +** <b>The tdsqlite3_config() interface is not threadsafe. The application ** must ensure that no other SQLite interfaces are invoked by other -** threads while sqlite3_config() is running.</b> +** threads while tdsqlite3_config() is running.</b> ** -** The sqlite3_config() interface +** The tdsqlite3_config() interface ** may only be invoked prior to library initialization using -** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. -** ^If sqlite3_config() is called after [sqlite3_initialize()] and before -** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. -** Note, however, that ^sqlite3_config() can be called as part of the -** implementation of an application-defined [sqlite3_os_init()]. +** [tdsqlite3_initialize()] or after shutdown by [tdsqlite3_shutdown()]. +** ^If tdsqlite3_config() is called after [tdsqlite3_initialize()] and before +** [tdsqlite3_shutdown()] then it will return SQLITE_MISUSE. +** Note, however, that ^tdsqlite3_config() can be called as part of the +** implementation of an application-defined [tdsqlite3_os_init()]. ** -** The first argument to sqlite3_config() is an integer +** The first argument to tdsqlite3_config() is an integer ** [configuration option] that determines ** what property of SQLite is to be configured. Subsequent arguments ** vary depending on the [configuration option] ** in the first argument. ** -** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^When a configuration option is set, tdsqlite3_config() returns [SQLITE_OK]. ** ^If the option is unknown or SQLite is unable to set the option ** then this routine returns a non-zero [error code]. */ -SQLITE_API int sqlite3_config(int, ...); +SQLITE_API int tdsqlite3_config(int, ...); /* ** CAPI3REF: Configure database connections -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** The sqlite3_db_config() interface is used to make configuration +** The tdsqlite3_db_config() interface is used to make configuration ** changes to a [database connection]. The interface is similar to -** [sqlite3_config()] except that the changes apply to a single +** [tdsqlite3_config()] except that the changes apply to a single ** [database connection] (specified in the first argument). ** -** The second argument to sqlite3_db_config(D,V,...) is the +** The second argument to tdsqlite3_db_config(D,V,...) is the ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code ** that indicates what aspect of the [database connection] is being configured. ** Subsequent arguments vary depending on the configuration verb. ** -** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** ^Calls to tdsqlite3_db_config() return SQLITE_OK if and only if ** the call is considered successful. */ -SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); +SQLITE_API int tdsqlite3_db_config(tdsqlite3*, int op, ...); /* ** CAPI3REF: Memory Allocation Routines @@ -1464,10 +1596,10 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); ** ** This object is used in only one place in the SQLite interface. ** A pointer to an instance of this object is the argument to -** [sqlite3_config()] when the configuration option is +** [tdsqlite3_config()] when the configuration option is ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. ** By creating an instance of this object -** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** and passing it to [tdsqlite3_config]([SQLITE_CONFIG_MALLOC]) ** during configuration, an application can specify an alternative ** memory allocation subsystem for SQLite to use for all of its ** dynamic memory needs. @@ -1494,20 +1626,20 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); ** a memory allocation given a particular requested size. Most memory ** allocators round up memory allocations at least to the next multiple ** of 8. Some allocators round up to a larger multiple or to a power of 2. -** Every memory allocation request coming in through [sqlite3_malloc()] -** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** Every memory allocation request coming in through [tdsqlite3_malloc()] +** or [tdsqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, ** that causes the corresponding memory allocation to fail. ** ** The xInit method initializes the memory allocator. For example, -** it might allocate any require mutexes or initialize internal data +** it might allocate any required mutexes or initialize internal data ** structures. The xShutdown method is invoked (indirectly) by -** [sqlite3_shutdown()] and should deallocate any resources acquired +** [tdsqlite3_shutdown()] and should deallocate any resources acquired ** by xInit. The pAppData pointer is used as the only parameter to ** xInit and xShutdown. ** ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes ** the xInit method, so the xInit method need not be threadsafe. The -** xShutdown method is only called from [sqlite3_shutdown()] so it does +** xShutdown method is only called from [tdsqlite3_shutdown()] so it does ** not need to be threadsafe either. For all other methods, SQLite ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which @@ -1519,8 +1651,8 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); ** SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). */ -typedef struct sqlite3_mem_methods sqlite3_mem_methods; -struct sqlite3_mem_methods { +typedef struct tdsqlite3_mem_methods tdsqlite3_mem_methods; +struct tdsqlite3_mem_methods { void *(*xMalloc)(int); /* Memory allocation function */ void (*xFree)(void*); /* Free a prior allocation */ void *(*xRealloc)(void*,int); /* Resize an allocation */ @@ -1536,12 +1668,12 @@ struct sqlite3_mem_methods { ** KEYWORDS: {configuration option} ** ** These constants are the available integer configuration options that -** can be passed as the first argument to the [sqlite3_config()] interface. +** can be passed as the first argument to the [tdsqlite3_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_config()] to make sure that -** the call worked. The [sqlite3_config()] interface will return a +** should check the return code from [tdsqlite3_config()] to make sure that +** the call worked. The [tdsqlite3_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** @@ -1553,7 +1685,7 @@ struct sqlite3_mem_methods { ** by a single thread. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to change the [threading mode] from its default -** value of Single-thread and so [sqlite3_config()] will return +** value of Single-thread and so [tdsqlite3_config()] will return ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD ** configuration option.</dd> ** @@ -1568,7 +1700,7 @@ struct sqlite3_mem_methods { ** [database connection] at the same time. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Multi-thread [threading mode] and -** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** [tdsqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd> ** ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt> @@ -1584,37 +1716,48 @@ struct sqlite3_mem_methods { ** ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** it is not possible to set the Serialized [threading mode] and -** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** [tdsqlite3_config()] will return [SQLITE_ERROR] if called with the ** SQLITE_CONFIG_SERIALIZED configuration option.</dd> ** ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt> ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is -** a pointer to an instance of the [sqlite3_mem_methods] structure. +** a pointer to an instance of the [tdsqlite3_mem_methods] structure. ** The argument specifies ** alternative low-level memory allocation routines to be used in place of ** the memory allocation routines built into SQLite.)^ ^SQLite makes -** its own private copy of the content of the [sqlite3_mem_methods] structure -** before the [sqlite3_config()] call returns.</dd> +** its own private copy of the content of the [tdsqlite3_mem_methods] structure +** before the [tdsqlite3_config()] call returns.</dd> ** ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt> ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which -** is a pointer to an instance of the [sqlite3_mem_methods] structure. -** The [sqlite3_mem_methods] +** is a pointer to an instance of the [tdsqlite3_mem_methods] structure. +** The [tdsqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines.)^ ** This option can be used to overload the default memory allocation ** routines with a wrapper that simulations memory allocation failure or ** tracks memory usage, for example. </dd> ** +** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt> +** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of +** type int, interpreted as a boolean, which if true provides a hint to +** SQLite that it should avoid large memory allocations if possible. +** SQLite will run faster if it is free to make large memory allocations, +** but some application might prefer to run slower in exchange for +** guarantees about memory fragmentation that are possible if large +** allocations are avoided. This hint is normally off. +** </dd> +** ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt> ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, ** interpreted as a boolean, which enables or disables the collection of ** memory allocation statistics. ^(When memory allocation statistics are ** disabled, the following SQLite interfaces become non-operational: ** <ul> -** <li> [sqlite3_memory_used()] -** <li> [sqlite3_memory_highwater()] -** <li> [sqlite3_soft_heap_limit64()] -** <li> [sqlite3_status64()] +** <li> [tdsqlite3_hard_heap_limit64()] +** <li> [tdsqlite3_memory_used()] +** <li> [tdsqlite3_memory_highwater()] +** <li> [tdsqlite3_soft_heap_limit64()] +** <li> [tdsqlite3_status64()] ** </ul>)^ ** ^Memory allocation statistics are enabled by default unless SQLite is ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory @@ -1622,32 +1765,14 @@ struct sqlite3_mem_methods { ** </dd> ** ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt> -** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer -** that SQLite can use for scratch memory. ^(There are three arguments -** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte -** aligned memory buffer from which the scratch allocations will be -** drawn, the size of each scratch allocation (sz), -** and the maximum number of scratch allocations (N).)^ -** The first argument must be a pointer to an 8-byte aligned buffer -** of at least sz*N bytes of memory. -** ^SQLite will not use more than one scratch buffers per thread. -** ^SQLite will never request a scratch buffer that is more than 6 -** times the database page size. -** ^If SQLite needs needs additional -** scratch memory beyond what is provided by this configuration option, then -** [sqlite3_malloc()] will be used to obtain the memory needed.<p> -** ^When the application provides any amount of scratch memory using -** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large -** [sqlite3_malloc|heap allocations]. -** This can help [Robson proof|prevent memory allocation failures] due to heap -** fragmentation in low-memory embedded systems. +** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used. ** </dd> ** ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt> ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool ** that SQLite can use for the database page cache with the default page ** cache implementation. -** This configuration option is a no-op if an application-define page +** This configuration option is a no-op if an application-defined page ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to ** 8-byte aligned memory (pMem), the size of each page cache line (sz), @@ -1662,22 +1787,21 @@ struct sqlite3_mem_methods { ** aligned block of memory of at least sz*N bytes, otherwise ** subsequent behavior is undefined. ** ^When pMem is not NULL, SQLite will strive to use the memory provided -** to satisfy page cache needs, falling back to [sqlite3_malloc()] if +** to satisfy page cache needs, falling back to [tdsqlite3_malloc()] if ** a page cache line is larger than sz bytes or if all of the pMem buffer ** is exhausted. ** ^If pMem is NULL and N is non-zero, then each database connection ** does an initial bulk allocation for page cache memory -** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or +** from [tdsqlite3_malloc()] sufficient for N cache lines if N is positive or ** of -1024*N bytes if N is negative, . ^If additional ** page cache memory is needed beyond what is provided by the initial -** allocation, then SQLite goes to [sqlite3_malloc()] separately for each +** allocation, then SQLite goes to [tdsqlite3_malloc()] separately for each ** additional cache line. </dd> ** ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt> ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer ** that SQLite will use for all of its dynamic memory allocation needs -** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and -** [SQLITE_CONFIG_PAGECACHE]. +** beyond those provided for by [SQLITE_CONFIG_PAGECACHE]. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns ** [SQLITE_ERROR] if invoked otherwise. @@ -1696,27 +1820,27 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt> ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a -** pointer to an instance of the [sqlite3_mutex_methods] structure. +** pointer to an instance of the [tdsqlite3_mutex_methods] structure. ** The argument specifies alternative low-level mutex routines to be used ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of -** the content of the [sqlite3_mutex_methods] structure before the call to -** [sqlite3_config()] returns. ^If SQLite is compiled with +** the content of the [tdsqlite3_mutex_methods] structure before the call to +** [tdsqlite3_config()] returns. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to -** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** [tdsqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will ** return [SQLITE_ERROR].</dd> ** ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt> ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which -** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The -** [sqlite3_mutex_methods] +** is a pointer to an instance of the [tdsqlite3_mutex_methods] structure. The +** [tdsqlite3_mutex_methods] ** structure is filled with the currently defined mutex routines.)^ ** This option can be used to overload the default mutex allocation ** routines with a wrapper used to track mutex usage for performance ** profiling or testing, for example. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then ** the entire mutexing subsystem is omitted from the build and hence calls to -** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** [tdsqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will ** return [SQLITE_ERROR].</dd> ** ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt> @@ -1726,18 +1850,18 @@ struct sqlite3_mem_methods { ** size of each lookaside buffer slot and the second is the number of ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] -** option to [sqlite3_db_config()] can be used to change the lookaside +** option to [tdsqlite3_db_config()] can be used to change the lookaside ** configuration on individual connections.)^ </dd> ** ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is -** a pointer to an [sqlite3_pcache_methods2] object. This object specifies +** a pointer to an [tdsqlite3_pcache_methods2] object. This object specifies ** the interface to a custom page cache implementation.)^ -** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd> +** ^SQLite makes a copy of the [tdsqlite3_pcache_methods2] object.</dd> ** ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which -** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of +** is a pointer to an [tdsqlite3_pcache_methods2] object. SQLite copies of ** the current page cache implementation into that object.)^ </dd> ** ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt> @@ -1746,15 +1870,15 @@ struct sqlite3_mem_methods { ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a ** function with a call signature of void(*)(void*,int,const char*), ** and a pointer to void. ^If the function pointer is not NULL, it is -** invoked by [sqlite3_log()] to process each logging event. ^If the -** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** invoked by [tdsqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [tdsqlite3_log()] interface becomes a no-op. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is ** passed through as the first parameter to the application-defined logger ** function whenever that function is invoked. ^The second parameter to ** the logger function is a copy of the first parameter to the corresponding -** [sqlite3_log()] call and is intended to be a [result code] or an +** [tdsqlite3_log()] call and is intended to be a [result code] or an ** [extended result code]. ^The third parameter passed to the logger is -** log message after formatting via [sqlite3_snprintf()]. +** log message after formatting via [tdsqlite3_snprintf()]. ** The SQLite logging interface is not reentrant; the logger function ** supplied by the application must not invoke any SQLite interface. ** In a multi-threaded application, the application-defined logger @@ -1764,8 +1888,8 @@ struct sqlite3_mem_methods { ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int. ** If non-zero, then URI handling is globally enabled. If the parameter is zero, ** then URI handling is globally disabled.)^ ^If URI handling is globally -** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], -** [sqlite3_open16()] or +** enabled, all filenames passed to [tdsqlite3_open()], [tdsqlite3_open_v2()], +** [tdsqlite3_open16()] or ** specified as part of [ATTACH] commands are interpreted as URIs, regardless ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database ** connection is opened. ^If it is globally disabled, filenames are @@ -1797,7 +1921,7 @@ struct sqlite3_mem_methods { ** <dt>SQLITE_CONFIG_SQLLOG ** <dd>This option is only available if sqlite is compiled with the ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should -** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). +** be a pointer to a function of type void(*)(void*,tdsqlite3*,const char*, int). ** The second should be of type (void*). The callback is invoked by the library ** in three separate circumstances, identified by the value passed as the ** fourth parameter. If the fourth parameter is 0, then the database connection @@ -1812,7 +1936,7 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_CONFIG_MMAP_SIZE]] ** <dt>SQLITE_CONFIG_MMAP_SIZE -** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values +** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (tdsqlite3_int64) values ** that are the default mmap size limit (the default setting for ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. ** ^The default setting can be overridden by each database connection using @@ -1863,57 +1987,88 @@ struct sqlite3_mem_methods { ** I/O required to support statement rollback. ** The default value for this setting is controlled by the ** [SQLITE_STMTJRNL_SPILL] compile-time option. +** +** [[SQLITE_CONFIG_SORTERREF_SIZE]] +** <dt>SQLITE_CONFIG_SORTERREF_SIZE +** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter +** of type (int) - the new value of the sorter-reference size threshold. +** Usually, when SQLite uses an external sort to order records according +** to an ORDER BY clause, all fields required by the caller are present in the +** sorted records. However, if SQLite determines based on the declared type +** of a table column that its values are likely to be very large - larger +** than the configured sorter-reference size threshold - then a reference +** is stored in each sorted record and the required column values loaded +** from the database as records are returned in sorted order. The default +** value for this option is to never use this optimization. Specifying a +** negative value for this option restores the default behaviour. +** This option is only available if SQLite is compiled with the +** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option. +** +** [[SQLITE_CONFIG_MEMDB_MAXSIZE]] +** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE +** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter +** [tdsqlite3_int64] parameter which is the default maximum size for an in-memory +** database created using [tdsqlite3_deserialize()]. This default maximum +** size can be adjusted up or down for individual databases using the +** [SQLITE_FCNTL_SIZE_LIMIT] [tdsqlite3_file_control|file-control]. If this +** configuration setting is never used, then the default maximum is determined +** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that +** compile-time option is not set, then the default maximum is 1073741824. ** </dl> */ #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ #define SQLITE_CONFIG_SERIALIZED 3 /* nil */ -#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ +#define SQLITE_CONFIG_MALLOC 4 /* tdsqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* tdsqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* No longer used */ #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ -#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ -#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_MUTEX 10 /* tdsqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* tdsqlite3_mutex_methods* */ /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ #define SQLITE_CONFIG_PCACHE 14 /* no-op */ #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ #define SQLITE_CONFIG_URI 17 /* int */ -#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ -#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_PCACHE2 18 /* tdsqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_GETPCACHE2 19 /* tdsqlite3_pcache_methods2* */ #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ -#define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ +#define SQLITE_CONFIG_MMAP_SIZE 22 /* tdsqlite3_int64, tdsqlite3_int64 */ #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */ #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */ +#define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */ +#define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */ +#define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* tdsqlite3_int64 */ /* ** CAPI3REF: Database Connection Configuration Options ** ** These constants are the available integer configuration options that -** can be passed as the second argument to the [sqlite3_db_config()] interface. +** can be passed as the second argument to the [tdsqlite3_db_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_db_config()] to make sure that -** the call worked. ^The [sqlite3_db_config()] interface will return a +** should check the return code from [tdsqlite3_db_config()] to make sure that +** the call worked. ^The [tdsqlite3_db_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** ** <dl> +** [[SQLITE_DBCONFIG_LOOKASIDE]] ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt> ** <dd> ^This option takes three additional arguments that determine the ** [lookaside memory allocator] configuration for the [database connection]. -** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** ^The first argument (the third parameter to [tdsqlite3_db_config()] is a ** pointer to a memory buffer to use for lookaside memory. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb ** may be NULL in which case SQLite will allocate the -** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the +** lookaside buffer itself using [tdsqlite3_malloc()]. ^The second argument is the ** size of each lookaside buffer slot. ^The third argument is the number of ** slots. The size of the buffer in the first argument must be greater than ** or equal to the product of the second and third arguments. The buffer @@ -1923,11 +2078,12 @@ struct sqlite3_mem_methods { ** configuration for a database connection can only be changed when that ** connection is not currently using lookaside memory, or in other words ** when the "current value" returned by -** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. +** [tdsqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. ** Any attempt to change the lookaside memory configuration when lookaside ** memory is in use leaves the configuration unchanged and returns ** [SQLITE_BUSY].)^</dd> ** +** [[SQLITE_DBCONFIG_ENABLE_FKEY]] ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt> ** <dd> ^This option is used to enable or disable the enforcement of ** [foreign key constraints]. There should be two additional arguments. @@ -1938,6 +2094,7 @@ struct sqlite3_mem_methods { ** following this call. The second parameter may be a NULL pointer, in ** which case the FK enforcement setting is not reported back. </dd> ** +** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]] ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt> ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers]. ** There should be two additional arguments. @@ -1948,9 +2105,21 @@ struct sqlite3_mem_methods { ** following this call. The second parameter may be a NULL pointer, in ** which case the trigger setting is not reported back. </dd> ** +** [[SQLITE_DBCONFIG_ENABLE_VIEW]] +** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt> +** <dd> ^This option is used to enable or disable [CREATE VIEW | views]. +** There should be two additional arguments. +** The first argument is an integer which is 0 to disable views, +** positive to enable views or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether views are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the view setting is not reported back. </dd> +** +** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]] ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt> -** <dd> ^This option is used to enable or disable the two-argument -** version of the [fts3_tokenizer()] function which is part of the +** <dd> ^This option is used to enable or disable the +** [fts3_tokenizer()] function which is part of the ** [FTS3] full-text search engine extension. ** There should be two additional arguments. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or @@ -1961,11 +2130,12 @@ struct sqlite3_mem_methods { ** following this call. The second parameter may be a NULL pointer, in ** which case the new setting is not reported back. </dd> ** +** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]] ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt> -** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()] +** <dd> ^This option is used to enable or disable the [tdsqlite3_load_extension()] ** interface independently of the [load_extension()] SQL function. -** The [sqlite3_enable_load_extension()] API enables or disables both the -** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. +** The [tdsqlite3_enable_load_extension()] API enables or disables both the +** C-API [tdsqlite3_load_extension()] and the SQL function [load_extension()]. ** There should be two additional arguments. ** When the first argument to this interface is 1, then only the C-API is ** enabled and the SQL function remains disabled. If the first argument to @@ -1973,12 +2143,12 @@ struct sqlite3_mem_methods { ** If the first argument is -1, then no changes are made to state of either the ** C-API or the SQL function. ** The second parameter is a pointer to an integer into which -** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface +** is written 0 or 1 to indicate whether [tdsqlite3_load_extension()] interface ** is disabled or enabled following this call. The second parameter may ** be a NULL pointer, in which case the new setting is not reported back. ** </dd> ** -** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt> +** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt> ** <dd> ^This option is used to change the name of the "main" database ** schema. ^The sole argument is a pointer to a constant UTF8 string ** which will become the new schema name in place of "main". ^SQLite @@ -1987,6 +2157,163 @@ struct sqlite3_mem_methods { ** until after the database connection closes. ** </dd> ** +** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] +** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt> +** <dd> Usually, when a database in wal mode is closed or detached from a +** database handle, SQLite checks if this will mean that there are now no +** connections at all to the database. If so, it performs a checkpoint +** operation before closing the connection. This option may be used to +** override this behaviour. The first parameter passed to this operation +** is an integer - positive to disable checkpoints-on-close, or zero (the +** default) to enable them, and negative to leave the setting unchanged. +** The second parameter is a pointer to an integer +** into which is written 0 or 1 to indicate whether checkpoints-on-close +** have been disabled - 0 if they are not disabled, 1 if they are. +** </dd> +** +** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt> +** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates +** the [query planner stability guarantee] (QPSG). When the QPSG is active, +** a single SQL query statement will always use the same algorithm regardless +** of values of [bound parameters].)^ The QPSG disables some query optimizations +** that look at the values of bound parameters, which can make some queries +** slower. But the QPSG has the advantage of more predictable behavior. With +** the QPSG active, SQLite will always use the same query plan in the field as +** was used during testing in the lab. +** The first argument to this setting is an integer which is 0 to disable +** the QPSG, positive to enable QPSG, or negative to leave the setting +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether the QPSG is disabled or enabled +** following this call. +** </dd> +** +** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt> +** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not +** include output for any operations performed by trigger programs. This +** option is used to set or clear (the default) a flag that governs this +** behavior. The first parameter passed to this operation is an integer - +** positive to enable output for trigger programs, or zero to disable it, +** or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which is written +** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if +** it is not disabled, 1 if it is. +** </dd> +** +** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt> +** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run +** [VACUUM] in order to reset a database back to an empty database +** with no schema and no content. The following process works even for +** a badly corrupted database file: +** <ol> +** <li> If the database connection is newly opened, make sure it has read the +** database schema by preparing then discarding some query against the +** database, or calling tdsqlite3_table_column_metadata(), ignoring any +** errors. This step is only necessary if the application desires to keep +** the database in WAL mode after the reset if it was in WAL mode before +** the reset. +** <li> tdsqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0); +** <li> [tdsqlite3_exec](db, "[VACUUM]", 0, 0, 0); +** <li> tdsqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0); +** </ol> +** Because resetting a database is destructive and irreversible, the +** process requires the use of this obscure API and multiple steps to help +** ensure that it does not happen by accident. +** +** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt> +** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the +** "defensive" flag for a database connection. When the defensive +** flag is enabled, language features that allow ordinary SQL to +** deliberately corrupt the database file are disabled. The disabled +** features include but are not limited to the following: +** <ul> +** <li> The [PRAGMA writable_schema=ON] statement. +** <li> The [PRAGMA journal_mode=OFF] statement. +** <li> Writes to the [sqlite_dbpage] virtual table. +** <li> Direct writes to [shadow tables]. +** </ul> +** </dd> +** +** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt> +** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the +** "writable_schema" flag. This has the same effect and is logically equivalent +** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF]. +** The first argument to this setting is an integer which is 0 to disable +** the writable_schema, positive to enable writable_schema, or negative to +** leave the setting unchanged. The second parameter is a pointer to an +** integer into which is written 0 or 1 to indicate whether the writable_schema +** is enabled or disabled following this call. +** </dd> +** +** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]] +** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt> +** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates +** the legacy behavior of the [ALTER TABLE RENAME] command such it +** behaves as it did prior to [version 3.24.0] (2018-06-04). See the +** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for +** additional information. This feature can also be turned on and off +** using the [PRAGMA legacy_alter_table] statement. +** </dd> +** +** [[SQLITE_DBCONFIG_DQS_DML]] +** <dt>SQLITE_DBCONFIG_DQS_DML</td> +** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates +** the legacy [double-quoted string literal] misfeature for DML statements +** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The +** default value of this setting is determined by the [-DSQLITE_DQS] +** compile-time option. +** </dd> +** +** [[SQLITE_DBCONFIG_DQS_DDL]] +** <dt>SQLITE_DBCONFIG_DQS_DDL</td> +** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates +** the legacy [double-quoted string literal] misfeature for DDL statements, +** such as CREATE TABLE and CREATE INDEX. The +** default value of this setting is determined by the [-DSQLITE_DQS] +** compile-time option. +** </dd> +** +** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]] +** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td> +** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to +** assume that database schemas (the contents of the [sqlite_master] tables) +** are untainted by malicious content. +** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite +** takes additional defensive steps to protect the application from harm +** including: +** <ul> +** <li> Prohibit the use of SQL functions inside triggers, views, +** CHECK constraints, DEFAULT clauses, expression indexes, +** partial indexes, or generated columns +** unless those functions are tagged with [SQLITE_INNOCUOUS]. +** <li> Prohibit the use of virtual tables inside of triggers or views +** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS]. +** </ul> +** This setting defaults to "on" for legacy compatibility, however +** all applications are advised to turn it off if possible. This setting +** can also be controlled using the [PRAGMA trusted_schema] statement. +** </dd> +** +** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]] +** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td> +** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates +** the legacy file format flag. When activated, this flag causes all newly +** created database file to have a schema format version number (the 4-byte +** integer found at offset 44 into the database header) of 1. This in turn +** means that the resulting database file will be readable and writable by +** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting, +** newly created databases are generally not understandable by SQLite versions +** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there +** is now scarcely any need to generated database files that are compatible +** all the way back to version 3.0.0, and so this setting is of little +** practical use, but is provided so that SQLite can continue to claim the +** ability to generate new database files that are compatible with version +** 3.0.0. +** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on, +** the [VACUUM] command will fail with an obscure error when attempting to +** process a table with generated columns and a descending index. This is +** not considered a bug since SQLite versions 3.3.0 and earlier do not support +** either generated columns or decending indexes. +** </dd> ** </dl> */ #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ @@ -1995,21 +2322,33 @@ struct sqlite3_mem_methods { #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */ - +#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */ +#define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */ +#define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */ +#define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */ +#define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */ +#define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */ +#define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */ +#define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_VIEW 1015 /* int int* */ +#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT 1016 /* int int* */ +#define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */ +#define SQLITE_DBCONFIG_MAX 1017 /* Largest DBCONFIG */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_extended_result_codes() routine enables or disables the +** ^The tdsqlite3_extended_result_codes() routine enables or disables the ** [extended result codes] feature of SQLite. ^The extended result ** codes are disabled by default for historical compatibility. */ -SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); +SQLITE_API int tdsqlite3_extended_result_codes(tdsqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) ** has a unique 64-bit signed @@ -2019,20 +2358,30 @@ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); ** the table has a column of type [INTEGER PRIMARY KEY] then that column ** is another alias for the rowid. ** -** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the -** most recent successful [INSERT] into a rowid table or [virtual table] -** on database connection D. -** ^Inserts into [WITHOUT ROWID] tables are not recorded. -** ^If no successful [INSERT]s into rowid tables -** have ever occurred on the database connection D, -** then sqlite3_last_insert_rowid(D) returns zero. -** -** ^(If an [INSERT] occurs within a trigger or within a [virtual table] -** method, then this routine will return the [rowid] of the inserted -** row as long as the trigger or virtual table method is running. -** But once the trigger or virtual table method ends, the value returned -** by this routine reverts to what it was before the trigger or virtual -** table method began.)^ +** ^The tdsqlite3_last_insert_rowid(D) interface usually returns the [rowid] of +** the most recent successful [INSERT] into a rowid table or [virtual table] +** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not +** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred +** on the database connection D, then tdsqlite3_last_insert_rowid(D) returns +** zero. +** +** As well as being set automatically as rows are inserted into database +** tables, the value returned by this function may be set explicitly by +** [tdsqlite3_set_last_insert_rowid()] +** +** Some virtual table implementations may INSERT rows into rowid tables as +** part of committing a transaction (e.g. to flush data accumulated in memory +** to disk). In this case subsequent calls to this function return the rowid +** associated with these internal INSERT operations, which leads to +** unintuitive results. Virtual table implementations that do write to rowid +** tables in this way can avoid this problem by restoring the original +** rowid value using [tdsqlite3_set_last_insert_rowid()] before returning +** control to the user. +** +** ^(If an [INSERT] occurs within a trigger then this routine will +** return the [rowid] of the inserted row as long as the trigger is +** running. Once the trigger program ends, the value returned +** by this routine reverts to what it was before the trigger was fired.)^ ** ** ^An [INSERT] that fails due to a constraint violation is not a ** successful [INSERT] and does not change the value returned by this @@ -2051,17 +2400,27 @@ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); ** [last_insert_rowid() SQL function]. ** ** If a separate thread performs a new [INSERT] on the same -** database connection while the [sqlite3_last_insert_rowid()] +** database connection while the [tdsqlite3_last_insert_rowid()] ** function is running and thus changes the last insert [rowid], -** then the value returned by [sqlite3_last_insert_rowid()] is +** then the value returned by [tdsqlite3_last_insert_rowid()] is ** unpredictable and might not equal either the old or the new ** last insert [rowid]. */ -SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); +SQLITE_API tdsqlite3_int64 tdsqlite3_last_insert_rowid(tdsqlite3*); + +/* +** CAPI3REF: Set the Last Insert Rowid value. +** METHOD: tdsqlite3 +** +** The tdsqlite3_set_last_insert_rowid(D, R) method allows the application to +** set the value returned by calling tdsqlite3_last_insert_rowid(D) to R +** without inserting a row into the database. +*/ +SQLITE_API void tdsqlite3_set_last_insert_rowid(tdsqlite3*,tdsqlite3_int64); /* ** CAPI3REF: Count The Number Of Rows Modified -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This function returns the number of rows modified, inserted or ** deleted by the most recently completed INSERT, UPDATE or DELETE @@ -2075,24 +2434,24 @@ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); ** ** Changes to a view that are intercepted by ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value -** returned by sqlite3_changes() immediately after an INSERT, UPDATE or +** returned by tdsqlite3_changes() immediately after an INSERT, UPDATE or ** DELETE statement run on a view is always zero. Only changes made to real ** tables are counted. ** -** Things are more complicated if the sqlite3_changes() function is +** Things are more complicated if the tdsqlite3_changes() function is ** executed while a trigger program is running. This may happen if the ** program uses the [changes() SQL function], or if some other callback -** function invokes sqlite3_changes() directly. Essentially: +** function invokes tdsqlite3_changes() directly. Essentially: ** ** <ul> ** <li> ^(Before entering a trigger program the value returned by -** sqlite3_changes() function is saved. After the trigger program +** tdsqlite3_changes() function is saved. After the trigger program ** has finished, the original value is restored.)^ ** ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE -** statement sets the value returned by sqlite3_changes() +** statement sets the value returned by tdsqlite3_changes() ** upon completion as normal. Of course, this value will not include -** any changes performed by sub-triggers, as the sqlite3_changes() +** any changes performed by sub-triggers, as the tdsqlite3_changes() ** value will be saved and restored after each sub-trigger has run.)^ ** </ul> ** @@ -2103,42 +2462,60 @@ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); ** program, the value returned reflects the number of rows modified by the ** previous INSERT, UPDATE or DELETE statement within the same trigger. ** -** See also the [sqlite3_total_changes()] interface, the -** [count_changes pragma], and the [changes() SQL function]. -** ** If a separate thread makes changes on the same database connection -** while [sqlite3_changes()] is running then the value returned +** while [tdsqlite3_changes()] is running then the value returned ** is unpredictable and not meaningful. +** +** See also: +** <ul> +** <li> the [tdsqlite3_total_changes()] interface +** <li> the [count_changes pragma] +** <li> the [changes() SQL function] +** <li> the [data_version pragma] +** </ul> */ -SQLITE_API int sqlite3_changes(sqlite3*); +SQLITE_API int tdsqlite3_changes(tdsqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This function returns the total number of rows inserted, modified or ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed ** since the database connection was opened, including those executed as ** part of trigger programs. ^Executing any other type of SQL statement -** does not affect the value returned by sqlite3_total_changes(). +** does not affect the value returned by tdsqlite3_total_changes(). ** ** ^Changes made as part of [foreign key actions] are included in the ** count, but those made as part of REPLACE constraint resolution are ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers ** are not counted. -** -** See also the [sqlite3_changes()] interface, the -** [count_changes pragma], and the [total_changes() SQL function]. ** +** The [tdsqlite3_total_changes(D)] interface only reports the number +** of rows that changed due to SQL statement run against database +** connection D. Any changes by other database connections are ignored. +** To detect changes against a database file from other database +** connections use the [PRAGMA data_version] command or the +** [SQLITE_FCNTL_DATA_VERSION] [file control]. +** ** If a separate thread makes changes on the same database connection -** while [sqlite3_total_changes()] is running then the value +** while [tdsqlite3_total_changes()] is running then the value ** returned is unpredictable and not meaningful. +** +** See also: +** <ul> +** <li> the [tdsqlite3_changes()] interface +** <li> the [count_changes pragma] +** <li> the [changes() SQL function] +** <li> the [data_version pragma] +** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control] +** </ul> */ -SQLITE_API int sqlite3_total_changes(sqlite3*); +SQLITE_API int tdsqlite3_total_changes(tdsqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This function causes any pending database operation to abort and ** return at its earliest opportunity. This routine is typically @@ -2149,10 +2526,10 @@ SQLITE_API int sqlite3_total_changes(sqlite3*); ** ^It is safe to call this routine from a thread different from the ** thread that is currently running the database operation. But it ** is not safe to call this routine with a [database connection] that -** is closed or might close before sqlite3_interrupt() returns. +** is closed or might close before tdsqlite3_interrupt() returns. ** ** ^If an SQL operation is very nearly finished at the time when -** sqlite3_interrupt() is called, then it might not have an opportunity +** tdsqlite3_interrupt() is called, then it might not have an opportunity ** to be interrupted and might continue to completion. ** ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. @@ -2160,21 +2537,18 @@ SQLITE_API int sqlite3_total_changes(sqlite3*); ** that is inside an explicit transaction, then the entire transaction ** will be rolled back automatically. ** -** ^The sqlite3_interrupt(D) call is in effect until all currently running +** ^The tdsqlite3_interrupt(D) call is in effect until all currently running ** SQL statements on [database connection] D complete. ^Any new SQL statements -** that are started after the sqlite3_interrupt() call and before the -** running statements reaches zero are interrupted as if they had been -** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the tdsqlite3_interrupt() call and before the +** running statement count reaches zero are interrupted as if they had been +** running prior to the tdsqlite3_interrupt() call. ^New SQL statements ** that are started after the running statement count reaches zero are -** not effected by the sqlite3_interrupt(). -** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** not effected by the tdsqlite3_interrupt(). +** ^A call to tdsqlite3_interrupt(D) that occurs when there are no running ** SQL statements is a no-op and has no effect on SQL statements -** that are started after the sqlite3_interrupt() call returns. -** -** If the database connection closes while [sqlite3_interrupt()] -** is running then bad things will likely happen. +** that are started after the tdsqlite3_interrupt() call returns. */ -SQLITE_API void sqlite3_interrupt(sqlite3*); +SQLITE_API void tdsqlite3_interrupt(tdsqlite3*); /* ** CAPI3REF: Determine If An SQL Statement Is Complete @@ -2197,40 +2571,40 @@ SQLITE_API void sqlite3_interrupt(sqlite3*); ** ^These routines do not parse the SQL statements thus ** will not detect syntactically incorrect SQL. ** -** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior -** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked -** automatically by sqlite3_complete16(). If that initialization fails, -** then the return value from sqlite3_complete16() will be non-zero +** ^(If SQLite has not been initialized using [tdsqlite3_initialize()] prior +** to invoking tdsqlite3_complete16() then tdsqlite3_initialize() is invoked +** automatically by tdsqlite3_complete16(). If that initialization fails, +** then the return value from tdsqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete.)^ ** -** The input to [sqlite3_complete()] must be a zero-terminated +** The input to [tdsqlite3_complete()] must be a zero-terminated ** UTF-8 string. ** -** The input to [sqlite3_complete16()] must be a zero-terminated +** The input to [tdsqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ -SQLITE_API int sqlite3_complete(const char *sql); -SQLITE_API int sqlite3_complete16(const void *sql); +SQLITE_API int tdsqlite3_complete(const char *sql); +SQLITE_API int tdsqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors ** KEYWORDS: {busy-handler callback} {busy handler} -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X +** ^The tdsqlite3_busy_handler(D,X,P) routine sets a callback function X ** that might be invoked with argument P whenever ** an attempt is made to access a database table associated with ** [database connection] D when another thread ** or process has the table locked. -** The sqlite3_busy_handler() interface is used to implement -** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. +** The tdsqlite3_busy_handler() interface is used to implement +** [tdsqlite3_busy_timeout()] and [PRAGMA busy_timeout]. ** ** ^If the busy callback is NULL, then [SQLITE_BUSY] ** is returned immediately upon encountering the lock. ^If the busy callback ** is not NULL, then the callback might be invoked with two arguments. ** ** ^The first argument to the busy handler is a copy of the void* pointer which -** is the third argument to sqlite3_busy_handler(). ^The second argument to +** is the third argument to tdsqlite3_busy_handler(). ^The second argument to ** the busy handler callback is the number of times that the busy handler has ** been invoked previously for the same locking event. ^If the ** busy callback returns 0, then no additional attempts are made to @@ -2259,7 +2633,7 @@ SQLITE_API int sqlite3_complete16(const void *sql); ** ** ^(There can only be a single busy handler defined for each ** [database connection]. Setting a new busy handler clears any -** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** previously set handler.)^ ^Note that calling [tdsqlite3_busy_timeout()] ** or evaluating [PRAGMA busy_timeout=N] will change the ** busy handler and thus clear any previously set busy handler. ** @@ -2271,17 +2645,17 @@ SQLITE_API int sqlite3_complete16(const void *sql); ** A busy handler must not close the database connection ** or [prepared statement] that invoked the busy handler. */ -SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); +SQLITE_API int tdsqlite3_busy_handler(tdsqlite3*,int(*)(void*,int),void*); /* ** CAPI3REF: Set A Busy Timeout -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** ^This routine sets a [tdsqlite3_busy_handler | busy handler] that sleeps ** for a specified amount of time when a table is locked. ^The handler ** will sleep multiple times until at least "ms" milliseconds of sleeping ** have accumulated. ^After at least "ms" milliseconds of sleeping, -** the handler returns 0 which causes [sqlite3_step()] to return +** the handler returns 0 which causes [tdsqlite3_step()] to return ** [SQLITE_BUSY]. ** ** ^Calling this routine with an argument less than or equal to zero @@ -2289,22 +2663,22 @@ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); ** ** ^(There can only be a single busy handler for a particular ** [database connection] at any given moment. If another busy handler -** was defined (using [sqlite3_busy_handler()]) prior to calling +** was defined (using [tdsqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared.)^ ** ** See also: [PRAGMA busy_timeout] */ -SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); +SQLITE_API int tdsqlite3_busy_timeout(tdsqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** This is a legacy interface that is preserved for backwards compatibility. ** Use of this interface is not recommended. ** ** Definition: A <b>result table</b> is memory data structure created by the -** [sqlite3_get_table()] interface. A result table records the +** [tdsqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** ** The table conceptually has a number of rows and columns. But @@ -2317,11 +2691,11 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); ** to zero-terminated strings that contain the names of the columns. ** The remaining entries all point to query results. NULL values result ** in NULL pointers. All other values are in their UTF-8 zero-terminated -** string representation as returned by [sqlite3_column_text()]. +** string representation as returned by [tdsqlite3_column_text()]. ** ** A result table might consist of one or more memory allocations. -** It is not safe to pass a result table directly to [sqlite3_free()]. -** A result table should be deallocated using [sqlite3_free_table()]. +** It is not safe to pass a result table directly to [tdsqlite3_free()]. +** A result table should be deallocated using [tdsqlite3_free_table()]. ** ** ^(As an example of the result table format, suppose a query result ** is as follows: @@ -2334,9 +2708,9 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); ** Cindy | 21 ** </pre></blockquote> ** -** There are two column (M==2) and three rows (N==3). Thus the +** There are two columns (M==2) and three rows (N==3). Thus the ** result table has 8 entries. Suppose the result table is stored -** in an array names azResult. Then azResult holds this content: +** in an array named azResult. Then azResult holds this content: ** ** <blockquote><pre> ** azResult[0] = "Name"; @@ -2349,265 +2723,188 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); ** azResult[7] = "21"; ** </pre></blockquote>)^ ** -** ^The sqlite3_get_table() function evaluates one or more +** ^The tdsqlite3_get_table() function evaluates one or more ** semicolon-separated SQL statements in the zero-terminated UTF-8 ** string of its 2nd parameter and returns a result table to the ** pointer given in its 3rd parameter. ** -** After the application has finished with the result from sqlite3_get_table(), -** it must pass the result table pointer to sqlite3_free_table() in order to +** After the application has finished with the result from tdsqlite3_get_table(), +** it must pass the result table pointer to tdsqlite3_free_table() in order to ** release the memory that was malloced. Because of the way the -** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling -** function must not try to call [sqlite3_free()] directly. Only -** [sqlite3_free_table()] is able to release the memory properly and safely. +** [tdsqlite3_malloc()] happens within tdsqlite3_get_table(), the calling +** function must not try to call [tdsqlite3_free()] directly. Only +** [tdsqlite3_free_table()] is able to release the memory properly and safely. ** -** The sqlite3_get_table() interface is implemented as a wrapper around -** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** The tdsqlite3_get_table() interface is implemented as a wrapper around +** [tdsqlite3_exec()]. The tdsqlite3_get_table() routine does not have access ** to any internal data structures of SQLite. It uses only the public ** interface defined here. As a consequence, errors that occur in the -** wrapper layer outside of the internal [sqlite3_exec()] call are not -** reflected in subsequent calls to [sqlite3_errcode()] or -** [sqlite3_errmsg()]. +** wrapper layer outside of the internal [tdsqlite3_exec()] call are not +** reflected in subsequent calls to [tdsqlite3_errcode()] or +** [tdsqlite3_errmsg()]. */ -SQLITE_API int sqlite3_get_table( - sqlite3 *db, /* An open database */ +SQLITE_API int tdsqlite3_get_table( + tdsqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ int *pnRow, /* Number of result rows written here */ int *pnColumn, /* Number of result columns written here */ char **pzErrmsg /* Error msg written here */ ); -SQLITE_API void sqlite3_free_table(char **result); +SQLITE_API void tdsqlite3_free_table(char **result); /* ** CAPI3REF: Formatted String Printing Functions ** ** These routines are work-alikes of the "printf()" family of functions ** from the standard C library. -** These routines understand most of the common K&R formatting options, -** plus some additional non-standard formats, detailed below. -** Note that some of the more obscure formatting options from recent -** C-library standards are omitted from this implementation. +** These routines understand most of the common formatting options from +** the standard library printf() +** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]). +** See the [built-in printf()] documentation for details. ** -** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their -** results into memory obtained from [sqlite3_malloc()]. +** ^The tdsqlite3_mprintf() and tdsqlite3_vmprintf() routines write their +** results into memory obtained from [tdsqlite3_malloc64()]. ** The strings returned by these two routines should be -** released by [sqlite3_free()]. ^Both routines return a -** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** released by [tdsqlite3_free()]. ^Both routines return a +** NULL pointer if [tdsqlite3_malloc64()] is unable to allocate enough ** memory to hold the resulting string. ** -** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** ^(The tdsqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by ** the first parameter. Note that the order of the ** first two parameters is reversed from snprintf().)^ This is an ** historical accident that cannot be fixed without breaking -** backwards compatibility. ^(Note also that sqlite3_snprintf() +** backwards compatibility. ^(Note also that tdsqlite3_snprintf() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer.)^ We admit that ** the number of characters written would be a more useful return -** value but we cannot change the implementation of sqlite3_snprintf() +** value but we cannot change the implementation of tdsqlite3_snprintf() ** now without breaking compatibility. ** -** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** ^As long as the buffer size is greater than zero, tdsqlite3_snprintf() ** guarantees that the buffer is always zero-terminated. ^The first ** parameter "n" is the total size of the buffer, including space for ** the zero terminator. So the longest string that can be completely ** written will be n-1 characters. ** -** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). -** -** These routines all implement some additional formatting -** options that are useful for constructing SQL statements. -** All of the usual printf() formatting options apply. In addition, there -** is are "%q", "%Q", "%w" and "%z" options. -** -** ^(The %q option works like %s in that it substitutes a nul-terminated -** string from the argument list. But %q also doubles every '\'' character. -** %q is designed for use inside a string literal.)^ By doubling each '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, assume the string variable zText contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** This second example is an SQL syntax error. As a general rule you should -** always use %q instead of %s when inserting text into a string literal. -** -** ^(The %Q option works like %q except it also adds single quotes around -** the outside of the total string. Additionally, if the parameter in the -** argument list is a NULL pointer, %Q substitutes the text "NULL" (without -** single quotes).)^ So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** The code above will render a correct SQL statement in the zSQL -** variable even if the zText variable is a NULL pointer. +** ^The tdsqlite3_vsnprintf() routine is a varargs version of tdsqlite3_snprintf(). ** -** ^(The "%w" formatting option is like "%q" except that it expects to -** be contained within double-quotes instead of single quotes, and it -** escapes the double-quote character instead of the single-quote -** character.)^ The "%w" formatting option is intended for safely inserting -** table and column names into a constructed SQL statement. -** -** ^(The "%z" formatting option works like "%s" but with the -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string.)^ +** See also: [built-in printf()], [printf() SQL function] */ -SQLITE_API char *sqlite3_mprintf(const char*,...); -SQLITE_API char *sqlite3_vmprintf(const char*, va_list); -SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); -SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); +SQLITE_API char *tdsqlite3_mprintf(const char*,...); +SQLITE_API char *tdsqlite3_vmprintf(const char*, va_list); +SQLITE_API char *tdsqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *tdsqlite3_vsnprintf(int,char*,const char*, va_list); /* ** CAPI3REF: Memory Allocation Subsystem ** ** The SQLite core uses these three routines for all of its own ** internal memory allocation needs. "Core" in the previous sentence -** does not include operating-system specific VFS implementation. The +** does not include operating-system specific [VFS] implementation. The ** Windows VFS uses native malloc() and free() for some operations. ** -** ^The sqlite3_malloc() routine returns a pointer to a block +** ^The tdsqlite3_malloc() routine returns a pointer to a block ** of memory at least N bytes in length, where N is the parameter. -** ^If sqlite3_malloc() is unable to obtain sufficient free +** ^If tdsqlite3_malloc() is unable to obtain sufficient free ** memory, it returns a NULL pointer. ^If the parameter N to -** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** tdsqlite3_malloc() is zero or negative then tdsqlite3_malloc() returns ** a NULL pointer. ** -** ^The sqlite3_malloc64(N) routine works just like -** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead +** ^The tdsqlite3_malloc64(N) routine works just like +** tdsqlite3_malloc(N) except that N is an unsigned 64-bit integer instead ** of a signed 32-bit integer. ** -** ^Calling sqlite3_free() with a pointer previously returned -** by sqlite3_malloc() or sqlite3_realloc() releases that memory so -** that it might be reused. ^The sqlite3_free() routine is +** ^Calling tdsqlite3_free() with a pointer previously returned +** by tdsqlite3_malloc() or tdsqlite3_realloc() releases that memory so +** that it might be reused. ^The tdsqlite3_free() routine is ** a no-op if is called with a NULL pointer. Passing a NULL pointer -** to sqlite3_free() is harmless. After being freed, memory +** to tdsqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. ** Memory corruption, a segmentation fault, or other severe error -** might result if sqlite3_free() is called with a non-NULL pointer that -** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** might result if tdsqlite3_free() is called with a non-NULL pointer that +** was not obtained from tdsqlite3_malloc() or tdsqlite3_realloc(). ** -** ^The sqlite3_realloc(X,N) interface attempts to resize a +** ^The tdsqlite3_realloc(X,N) interface attempts to resize a ** prior memory allocation X to be at least N bytes. -** ^If the X parameter to sqlite3_realloc(X,N) +** ^If the X parameter to tdsqlite3_realloc(X,N) ** is a NULL pointer then its behavior is identical to calling -** sqlite3_malloc(N). -** ^If the N parameter to sqlite3_realloc(X,N) is zero or +** tdsqlite3_malloc(N). +** ^If the N parameter to tdsqlite3_realloc(X,N) is zero or ** negative then the behavior is exactly the same as calling -** sqlite3_free(X). -** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation +** tdsqlite3_free(X). +** ^tdsqlite3_realloc(X,N) returns a pointer to a memory allocation ** of at least N bytes in size or NULL if insufficient memory is available. ** ^If M is the size of the prior allocation, then min(N,M) bytes ** of the prior allocation are copied into the beginning of buffer returned -** by sqlite3_realloc(X,N) and the prior allocation is freed. -** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the +** by tdsqlite3_realloc(X,N) and the prior allocation is freed. +** ^If tdsqlite3_realloc(X,N) returns NULL and N is positive, then the ** prior allocation is not freed. ** -** ^The sqlite3_realloc64(X,N) interfaces works the same as -** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead +** ^The tdsqlite3_realloc64(X,N) interfaces works the same as +** tdsqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead ** of a 32-bit signed integer. ** -** ^If X is a memory allocation previously obtained from sqlite3_malloc(), -** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then -** sqlite3_msize(X) returns the size of that memory allocation in bytes. -** ^The value returned by sqlite3_msize(X) might be larger than the number +** ^If X is a memory allocation previously obtained from tdsqlite3_malloc(), +** tdsqlite3_malloc64(), tdsqlite3_realloc(), or tdsqlite3_realloc64(), then +** tdsqlite3_msize(X) returns the size of that memory allocation in bytes. +** ^The value returned by tdsqlite3_msize(X) might be larger than the number ** of bytes requested when X was allocated. ^If X is a NULL pointer then -** sqlite3_msize(X) returns zero. If X points to something that is not +** tdsqlite3_msize(X) returns zero. If X points to something that is not ** the beginning of memory allocation, or if it points to a formerly ** valid memory allocation that has now been freed, then the behavior -** of sqlite3_msize(X) is undefined and possibly harmful. +** of tdsqlite3_msize(X) is undefined and possibly harmful. ** -** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), -** sqlite3_malloc64(), and sqlite3_realloc64() +** ^The memory returned by tdsqlite3_malloc(), tdsqlite3_realloc(), +** tdsqlite3_malloc64(), and tdsqlite3_realloc64() ** is always aligned to at least an 8 byte boundary, or to a ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time ** option is used. ** -** In SQLite version 3.5.0 and 3.5.1, it was possible to define -** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in -** implementation of these routines to be omitted. That capability -** is no longer provided. Only built-in memory allocators can be used. -** -** Prior to SQLite version 3.7.10, the Windows OS interface layer called -** the system malloc() and free() directly when converting -** filenames between the UTF-8 encoding used by SQLite -** and whatever filename encoding is used by the particular Windows -** installation. Memory allocation errors were detected, but -** they were reported back as [SQLITE_CANTOPEN] or -** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. -** -** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** The pointer arguments to [tdsqlite3_free()] and [tdsqlite3_realloc()] ** must be either NULL or else pointers obtained from a prior -** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** invocation of [tdsqlite3_malloc()] or [tdsqlite3_realloc()] that have ** not yet been released. ** ** The application must not read or write any part of ** a block of memory after it has been released using -** [sqlite3_free()] or [sqlite3_realloc()]. +** [tdsqlite3_free()] or [tdsqlite3_realloc()]. */ -SQLITE_API void *sqlite3_malloc(int); -SQLITE_API void *sqlite3_malloc64(sqlite3_uint64); -SQLITE_API void *sqlite3_realloc(void*, int); -SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64); -SQLITE_API void sqlite3_free(void*); -SQLITE_API sqlite3_uint64 sqlite3_msize(void*); +SQLITE_API void *tdsqlite3_malloc(int); +SQLITE_API void *tdsqlite3_malloc64(tdsqlite3_uint64); +SQLITE_API void *tdsqlite3_realloc(void*, int); +SQLITE_API void *tdsqlite3_realloc64(void*, tdsqlite3_uint64); +SQLITE_API void tdsqlite3_free(void*); +SQLITE_API tdsqlite3_uint64 tdsqlite3_msize(void*); /* ** CAPI3REF: Memory Allocator Statistics ** ** SQLite provides these two interfaces for reporting on the status -** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** of the [tdsqlite3_malloc()], [tdsqlite3_free()], and [tdsqlite3_realloc()] ** routines, which form the built-in memory allocation subsystem. ** -** ^The [sqlite3_memory_used()] routine returns the number of bytes +** ^The [tdsqlite3_memory_used()] routine returns the number of bytes ** of memory currently outstanding (malloced but not freed). -** ^The [sqlite3_memory_highwater()] routine returns the maximum -** value of [sqlite3_memory_used()] since the high-water mark -** was last reset. ^The values returned by [sqlite3_memory_used()] and -** [sqlite3_memory_highwater()] include any overhead -** added by SQLite in its implementation of [sqlite3_malloc()], +** ^The [tdsqlite3_memory_highwater()] routine returns the maximum +** value of [tdsqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [tdsqlite3_memory_used()] and +** [tdsqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [tdsqlite3_malloc()], ** but not overhead added by the any underlying system library -** routines that [sqlite3_malloc()] may call. +** routines that [tdsqlite3_malloc()] may call. ** ** ^The memory high-water mark is reset to the current value of -** [sqlite3_memory_used()] if and only if the parameter to -** [sqlite3_memory_highwater()] is true. ^The value returned -** by [sqlite3_memory_highwater(1)] is the high-water mark +** [tdsqlite3_memory_used()] if and only if the parameter to +** [tdsqlite3_memory_highwater()] is true. ^The value returned +** by [tdsqlite3_memory_highwater(1)] is the high-water mark ** prior to the reset. */ -SQLITE_API sqlite3_int64 sqlite3_memory_used(void); -SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); +SQLITE_API tdsqlite3_int64 tdsqlite3_memory_used(void); +SQLITE_API tdsqlite3_int64 tdsqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator @@ -2615,7 +2912,7 @@ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to ** select random [ROWID | ROWIDs] when inserting new records into a table that ** already uses the largest possible [ROWID]. The PRNG is also used for -** the build-in random() and randomblob() SQL functions. This interface allows +** the built-in random() and randomblob() SQL functions. This interface allows ** applications to access the same PRNG for other purposes. ** ** ^A call to this routine stores N bytes of randomness into buffer P. @@ -2624,23 +2921,25 @@ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); ** ^If this routine has not been previously called or if the previous ** call had N less than one or a NULL pointer for P, then the PRNG is ** seeded using randomness obtained from the xRandomness method of -** the default [sqlite3_vfs] object. +** the default [tdsqlite3_vfs] object. ** ^If the previous call to this routine had an N of 1 or more and a ** non-NULL P then the pseudo-randomness is generated -** internally and without recourse to the [sqlite3_vfs] xRandomness +** internally and without recourse to the [tdsqlite3_vfs] xRandomness ** method. */ -SQLITE_API void sqlite3_randomness(int N, void *P); +SQLITE_API void tdsqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 +** KEYWORDS: {authorizer callback} ** ** ^This routine registers an authorizer callback with a particular ** [database connection], supplied in the first argument. ** ^The authorizer callback is invoked as SQL statements are being compiled -** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], -** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various +** by [tdsqlite3_prepare()] or its variants [tdsqlite3_prepare_v2()], +** [tdsqlite3_prepare_v3()], [tdsqlite3_prepare16()], [tdsqlite3_prepare16_v2()], +** and [tdsqlite3_prepare16_v3()]. ^At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. ^The authorizer callback should @@ -2649,21 +2948,23 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be ** rejected with an error. ^If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] -** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** then the [tdsqlite3_prepare_v2()] or equivalent call that triggered ** the authorizer will fail with an error message. ** ** When the callback returns [SQLITE_OK], that means the operation ** requested is ok. ^When the callback returns [SQLITE_DENY], the -** [sqlite3_prepare_v2()] or equivalent call that triggered the +** [tdsqlite3_prepare_v2()] or equivalent call that triggered the ** authorizer will fail with an error message explaining that ** access is denied. ** ** ^The first parameter to the authorizer callback is a copy of the third -** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** parameter to the tdsqlite3_set_authorizer() interface. ^The second parameter ** to the callback is an integer [SQLITE_COPY | action code] that specifies ** the particular action to be authorized. ^The third through sixth parameters -** to the callback are zero-terminated strings that contain additional -** details about the action to be authorized. +** to the callback are either NULL pointers or zero-terminated strings +** that contain additional details about the action to be authorized. +** Applications must always be prepared to encounter a NULL pointer in any +** of the third through the sixth parameters of the authorization callback. ** ** ^If the action code is [SQLITE_READ] ** and the callback returns [SQLITE_IGNORE] then the @@ -2672,11 +2973,15 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] ** return can be used to deny an untrusted user access to individual ** columns of a table. +** ^When a table is referenced by a [SELECT] but no column values are +** extracted from that table (for example in a query like +** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback +** is invoked once for that table with a column name that is an empty string. ** ^If the action code is [SQLITE_DELETE] and the callback returns ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the ** [truncate optimization] is disabled and all rows are deleted individually. ** -** An authorizer is used when [sqlite3_prepare | preparing] +** An authorizer is used when [tdsqlite3_prepare | preparing] ** SQL statements from an untrusted source, to ensure that the SQL statements ** do not try to access data they are not allowed to see, or that they do not ** try to execute malicious statements that damage the database. For @@ -2684,37 +2989,37 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the -** user-entered SQL is being [sqlite3_prepare | prepared] that +** user-entered SQL is being [tdsqlite3_prepare | prepared] that ** disallows everything except [SELECT] statements. ** ** Applications that need to process SQL from untrusted sources -** might also consider lowering resource limits using [sqlite3_limit()] +** might also consider lowering resource limits using [tdsqlite3_limit()] ** and limiting database size using the [max_page_count] [PRAGMA] ** in addition to using an authorizer. ** ** ^(Only a single authorizer can be in place on a database connection -** at a time. Each call to sqlite3_set_authorizer overrides the +** at a time. Each call to tdsqlite3_set_authorizer overrides the ** previous call.)^ ^Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** ** The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** Note that [tdsqlite3_prepare_v2()] and [tdsqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** -** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the -** statement might be re-prepared during [sqlite3_step()] due to a +** ^When [tdsqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [tdsqlite3_step()] due to a ** schema change. Hence, the application should ensure that the -** correct authorizer callback remains in place during the [sqlite3_step()]. +** correct authorizer callback remains in place during the [tdsqlite3_step()]. ** ** ^Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()], unless -** as stated in the previous paragraph, sqlite3_step() invokes -** sqlite3_prepare_v2() to reprepare a statement after a schema change. +** [tdsqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [tdsqlite3_step()], unless +** as stated in the previous paragraph, tdsqlite3_step() invokes +** tdsqlite3_prepare_v2() to reprepare a statement after a schema change. */ -SQLITE_API int sqlite3_set_authorizer( - sqlite3*, +SQLITE_API int tdsqlite3_set_authorizer( + tdsqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData ); @@ -2722,14 +3027,14 @@ SQLITE_API int sqlite3_set_authorizer( /* ** CAPI3REF: Authorizer Return Codes ** -** The [sqlite3_set_authorizer | authorizer callback function] must +** The [tdsqlite3_set_authorizer | authorizer callback function] must ** return either [SQLITE_OK] or one of these two constants in order ** to signal SQLite whether or not the action is permitted. See the -** [sqlite3_set_authorizer | authorizer documentation] for additional +** [tdsqlite3_set_authorizer | authorizer documentation] for additional ** information. ** ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] -** returned from the [sqlite3_vtab_on_conflict()] interface. +** returned from the [tdsqlite3_vtab_on_conflict()] interface. */ #define SQLITE_DENY 1 /* Abort the SQL statement with an error */ #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ @@ -2737,7 +3042,7 @@ SQLITE_API int sqlite3_set_authorizer( /* ** CAPI3REF: Authorizer Action Codes ** -** The [sqlite3_set_authorizer()] interface registers a callback function +** The [tdsqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorize certain SQL statement actions. The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that @@ -2791,48 +3096,48 @@ SQLITE_API int sqlite3_set_authorizer( /* ** CAPI3REF: Tracing And Profiling Functions -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** These routines are deprecated. Use the [sqlite3_trace_v2()] interface +** These routines are deprecated. Use the [tdsqlite3_trace_v2()] interface ** instead of the routines described here. ** ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** -** ^The callback function registered by sqlite3_trace() is invoked at -** various times when an SQL statement is being run by [sqlite3_step()]. -** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** ^The callback function registered by tdsqlite3_trace() is invoked at +** various times when an SQL statement is being run by [tdsqlite3_step()]. +** ^The tdsqlite3_trace() callback is invoked with a UTF-8 rendering of the ** SQL statement text as the statement first begins executing. -** ^(Additional sqlite3_trace() callbacks might occur +** ^(Additional tdsqlite3_trace() callbacks might occur ** as each triggered subprogram is entered. The callbacks for triggers ** contain a UTF-8 SQL comment that identifies the trigger.)^ ** ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit -** the length of [bound parameter] expansion in the output of sqlite3_trace(). +** the length of [bound parameter] expansion in the output of tdsqlite3_trace(). ** -** ^The callback function registered by sqlite3_profile() is invoked +** ^The callback function registered by tdsqlite3_profile() is invoked ** as each SQL statement finishes. ^The profile callback contains ** the original statement text and an estimate of wall-clock time ** of how long that statement took to run. ^The profile callback ** time is in units of nanoseconds, however the current implementation ** is only capable of millisecond resolution so the six least significant ** digits in the time are meaningless. Future versions of SQLite -** might provide greater resolution on the profiler callback. The -** sqlite3_profile() function is considered experimental and is -** subject to change in future versions of SQLite. +** might provide greater resolution on the profiler callback. Invoking +** either [tdsqlite3_trace()] or [tdsqlite3_trace_v2()] will cancel the +** profile callback. */ -SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*, +SQLITE_API SQLITE_DEPRECATED void *tdsqlite3_trace(tdsqlite3*, void(*xTrace)(void*,const char*), void*); -SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, - void(*xProfile)(void*,const char*,sqlite3_uint64), void*); +SQLITE_API SQLITE_DEPRECATED void *tdsqlite3_profile(tdsqlite3*, + void(*xProfile)(void*,const char*,tdsqlite3_uint64), void*); /* ** CAPI3REF: SQL Trace Event Codes ** KEYWORDS: SQLITE_TRACE ** ** These constants identify classes of events that can be monitored -** using the [sqlite3_trace_v2()] tracing logic. The third argument -** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of +** using the [tdsqlite3_trace_v2()] tracing logic. The M argument +** to [tdsqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of ** the following constants. ^The first argument to the trace callback ** is one of the following constants. ** @@ -2841,7 +3146,7 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, ** ^A trace callback has four arguments: xCallback(T,C,P,X). ** ^The T argument is one of the integer type codes above. ** ^The C argument is a copy of the context pointer passed in as the -** fourth argument to [sqlite3_trace_v2()]. +** fourth argument to [tdsqlite3_trace_v2()]. ** The P and X arguments are pointers whose meanings depend on T. ** ** <dl> @@ -2853,13 +3158,13 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, ** [prepared statement]. ^The X argument is a pointer to a string which ** is the unexpanded SQL text of the prepared statement or an SQL comment ** that indicates the invocation of a trigger. ^The callback can compute -** the same text that would have been returned by the legacy [sqlite3_trace()] +** the same text that would have been returned by the legacy [tdsqlite3_trace()] ** interface by using the X argument when X begins with "--" and invoking -** [sqlite3_expanded_sql(P)] otherwise. +** [tdsqlite3_expanded_sql(P)] otherwise. ** ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt> ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same -** information as is provided by the [sqlite3_profile()] callback. +** information as is provided by the [tdsqlite3_profile()] callback. ** ^The P argument is a pointer to the [prepared statement] and the ** X argument points to a 64-bit integer which is the estimated of ** the number of nanosecond that the prepared statement took to run. @@ -2885,17 +3190,17 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, /* ** CAPI3REF: SQL Trace Hook -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback +** ^The tdsqlite3_trace_v2(D,M,X,P) interface registers a trace callback ** function X against [database connection] D, using property mask M ** and context pointer P. ^If the X callback is ** NULL or if the M mask is zero, then tracing is disabled. The ** M argument should be the bitwise OR-ed combination of ** zero or more [SQLITE_TRACE] constants. ** -** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides -** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2(). +** ^Each call to either tdsqlite3_trace() or tdsqlite3_trace_v2() overrides +** (cancels) any prior calls to tdsqlite3_trace() or tdsqlite3_trace_v2(). ** ** ^The X callback is invoked whenever any of the events identified by ** mask M occur. ^The integer return value from the callback is currently @@ -2908,12 +3213,12 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, ** ^The C argument is a copy of the context pointer. ** The P and X arguments are pointers whose meanings depend on T. ** -** The sqlite3_trace_v2() interface is intended to replace the legacy -** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which +** The tdsqlite3_trace_v2() interface is intended to replace the legacy +** interfaces [tdsqlite3_trace()] and [tdsqlite3_profile()], both of which ** are deprecated. */ -SQLITE_API int sqlite3_trace_v2( - sqlite3*, +SQLITE_API int tdsqlite3_trace_v2( + tdsqlite3*, unsigned uMask, int(*xCallback)(unsigned,void*,void*,void*), void *pCtx @@ -2921,11 +3226,11 @@ SQLITE_API int sqlite3_trace_v2( /* ** CAPI3REF: Query Progress Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** ^The tdsqlite3_progress_handler(D,N,X,P) interface causes the callback ** function X to be invoked periodically during long running calls to -** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for +** [tdsqlite3_exec()], [tdsqlite3_step()] and [tdsqlite3_get_table()] for ** database connection D. An example use for this ** interface is to keep a GUI updated during a large query. ** @@ -2947,44 +3252,42 @@ SQLITE_API int sqlite3_trace_v2( ** ** The progress handler callback must not do anything that will modify ** the database connection that invoked the progress handler. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** Note that [tdsqlite3_prepare_v2()] and [tdsqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** */ -SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); +SQLITE_API void tdsqlite3_progress_handler(tdsqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection -** CONSTRUCTOR: sqlite3 +** CONSTRUCTOR: tdsqlite3 ** ** ^These routines open an SQLite database file as specified by the ** filename argument. ^The filename argument is interpreted as UTF-8 for -** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte -** order for sqlite3_open16(). ^(A [database connection] handle is usually +** tdsqlite3_open() and tdsqlite3_open_v2() and as UTF-16 in the native byte +** order for tdsqlite3_open16(). ^(A [database connection] handle is usually ** returned in *ppDb, even if an error occurs. The only exception is that -** if SQLite is unable to allocate memory to hold the [sqlite3] object, -** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** if SQLite is unable to allocate memory to hold the [tdsqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [tdsqlite3] ** object.)^ ^(If the database is opened (and/or created) successfully, then ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The -** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** [tdsqlite3_errmsg()] or [tdsqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error following a failure of any -** of the sqlite3_open() routines. +** of the tdsqlite3_open() routines. ** ** ^The default encoding will be UTF-8 for databases created using -** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases -** created using sqlite3_open16() will be UTF-16 in the native byte order. +** tdsqlite3_open() or tdsqlite3_open_v2(). ^The default encoding for databases +** created using tdsqlite3_open16() will be UTF-16 in the native byte order. ** ** Whether or not an error occurs when it is opened, resources ** associated with the [database connection] handle should be released by -** passing it to [sqlite3_close()] when it is no longer required. +** passing it to [tdsqlite3_close()] when it is no longer required. ** -** The sqlite3_open_v2() interface works like sqlite3_open() +** The tdsqlite3_open_v2() interface works like tdsqlite3_open() ** except that it accepts two additional parameters for additional control ** over the new database connection. ^(The flags parameter to -** sqlite3_open_v2() can take one of -** the following three values, optionally combined with the -** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], -** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ +** tdsqlite3_open_v2() must include, at a minimum, one of the following +** three flag combinations:)^ ** ** <dl> ** ^(<dt>[SQLITE_OPEN_READONLY]</dt> @@ -2999,30 +3302,58 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt> ** <dd>The database is opened for reading and writing, and is created if ** it does not already exist. This is the behavior that is always used for -** sqlite3_open() and sqlite3_open16().</dd>)^ +** tdsqlite3_open() and tdsqlite3_open16().</dd>)^ ** </dl> ** -** If the 3rd parameter to sqlite3_open_v2() is not one of the -** combinations shown above optionally combined with other +** In addition to the required flags, the following optional flags are +** also supported: +** +** <dl> +** ^(<dt>[SQLITE_OPEN_URI]</dt> +** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^ +** +** ^(<dt>[SQLITE_OPEN_MEMORY]</dt> +** <dd>The database will be opened as an in-memory database. The database +** is named by the "filename" argument for the purposes of cache-sharing, +** if shared cache mode is enabled, but the "filename" is otherwise ignored. +** </dd>)^ +** +** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt> +** <dd>The new database connection will use the "multi-thread" +** [threading mode].)^ This means that separate threads are allowed +** to use SQLite at the same time, as long as each thread is using +** a different [database connection]. +** +** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt> +** <dd>The new database connection will use the "serialized" +** [threading mode].)^ This means the multiple threads can safely +** attempt to use the same database connection at the same time. +** (Mutexes will block any actual concurrency, but in this mode +** there is no harm in trying.) +** +** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt> +** <dd>The database is opened [shared cache] enabled, overriding +** the default shared cache setting provided by +** [tdsqlite3_enable_shared_cache()].)^ +** +** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt> +** <dd>The database is opened [shared cache] disabled, overriding +** the default shared cache setting provided by +** [tdsqlite3_enable_shared_cache()].)^ +** +** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt> +** <dd>The database filename is not allowed to be a symbolic link</dd> +** </dl>)^ +** +** If the 3rd parameter to tdsqlite3_open_v2() is not one of the +** required combinations shown above optionally combined with other ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] ** then the behavior is undefined. ** -** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection -** opens in the multi-thread [threading mode] as long as the single-thread -** mode has not been set at compile-time or start-time. ^If the -** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens -** in the serialized [threading mode] unless single-thread was -** previously selected at compile-time or start-time. -** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be -** eligible to use [shared cache mode], regardless of whether or not shared -** cache is enabled using [sqlite3_enable_shared_cache()]. ^The -** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not -** participate in [shared cache mode] even if it is enabled. -** -** ^The fourth parameter to sqlite3_open_v2() is the name of the -** [sqlite3_vfs] object that defines the operating system interface that +** ^The fourth parameter to tdsqlite3_open_v2() is the name of the +** [tdsqlite3_vfs] object that defines the operating system interface that ** the new database connection should use. ^If the fourth parameter is -** a NULL pointer then the default [sqlite3_vfs] object is used. +** a NULL pointer then the default [tdsqlite3_vfs] object is used. ** ** ^If the filename is ":memory:", then a private, temporary in-memory database ** is created for the connection. ^This in-memory database will vanish when @@ -3036,15 +3367,15 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** on-disk database will be created. ^This private database will be ** automatically deleted as soon as the database connection is closed. ** -** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3> +** [[URI filenames in tdsqlite3_open()]] <h3>URI Filenames</h3> ** ** ^If [URI filename] interpretation is enabled, and the filename argument ** begins with "file:", then the filename is interpreted as a URI. ^URI ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is -** set in the fourth argument to sqlite3_open_v2(), or if it has +** set in the third argument to tdsqlite3_open_v2(), or if it has ** been enabled globally using the [SQLITE_CONFIG_URI] option with the -** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. -** As of SQLite version 3.7.7, URI filename interpretation is turned off +** [tdsqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. +** URI filename interpretation is turned off ** by default, but future releases of SQLite might enable URI filename ** interpretation by default. See "[URI filenames]" for additional ** information. @@ -3074,16 +3405,16 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** a VFS object that provides the operating system interface that should ** be used to access the database file on disk. ^If this option is set to ** an empty string the default VFS object is used. ^Specifying an unknown -** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is +** VFS is an error. ^If tdsqlite3_open_v2() is used and the vfs option is ** present, then the VFS specified by the option takes precedence over -** the value passed as the fourth parameter to sqlite3_open_v2(). +** the value passed as the fourth parameter to tdsqlite3_open_v2(). ** ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw", ** "rwc", or "memory". Attempting to set it to any other value is ** an error)^. ** ^If "ro" is specified, then the database is opened for read-only ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the -** third argument to sqlite3_open_v2(). ^If the mode option is set to +** third argument to tdsqlite3_open_v2(). ^If the mode option is set to ** "rw", then the database is opened for read-write (but not create) ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had ** been set. ^Value "rwc" is equivalent to setting both @@ -3091,14 +3422,14 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** set to "memory" then a pure [in-memory database] that never reads ** or writes from disk is used. ^It is an error to specify a value for ** the mode parameter that is less restrictive than that specified by -** the flags passed in the third parameter to sqlite3_open_v2(). +** the flags passed in the third parameter to tdsqlite3_open_v2(). ** ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or ** "private". ^Setting it to "shared" is equivalent to setting the ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to -** sqlite3_open_v2(). ^Setting the cache parameter to "private" is +** tdsqlite3_open_v2(). ^Setting the cache parameter to "private" is ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. -** ^If sqlite3_open_v2() is used and the "cache" parameter is present in +** ^If tdsqlite3_open_v2() is used and the "cache" parameter is present in ** a URI filename, its value overrides any behavior requested by setting ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. ** @@ -3169,28 +3500,28 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** the results are undefined. ** ** <b>Note to Windows users:</b> The encoding used for the filename argument -** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** of tdsqlite3_open() and tdsqlite3_open_v2() must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into -** sqlite3_open() or sqlite3_open_v2(). +** tdsqlite3_open() or tdsqlite3_open_v2(). ** ** <b>Note to Windows Runtime users:</b> The temporary directory must be set -** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various +** prior to calling tdsqlite3_open() or tdsqlite3_open_v2(). Otherwise, various ** features that require the use of temporary files may fail. ** -** See also: [sqlite3_temp_directory] +** See also: [tdsqlite3_temp_directory] */ -SQLITE_API int sqlite3_open( +SQLITE_API int tdsqlite3_open( const char *filename, /* Database filename (UTF-8) */ - sqlite3 **ppDb /* OUT: SQLite db handle */ + tdsqlite3 **ppDb /* OUT: SQLite db handle */ ); -SQLITE_API int sqlite3_open16( +SQLITE_API int tdsqlite3_open16( const void *filename, /* Database filename (UTF-16) */ - sqlite3 **ppDb /* OUT: SQLite db handle */ + tdsqlite3 **ppDb /* OUT: SQLite db handle */ ); -SQLITE_API int sqlite3_open_v2( +SQLITE_API int tdsqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ - sqlite3 **ppDb, /* OUT: SQLite db handle */ + tdsqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ); @@ -3198,70 +3529,129 @@ SQLITE_API int sqlite3_open_v2( /* ** CAPI3REF: Obtain Values For URI Parameters ** -** These are utility routines, useful to VFS implementations, that check -** to see if a database file was a URI that contained a specific query +** These are utility routines, useful to [VFS|custom VFS implementations], +** that check if a database file was a URI that contained a specific query ** parameter, and if so obtains the value of that query parameter. ** ** If F is the database filename pointer passed into the xOpen() method of -** a VFS implementation when the flags parameter to xOpen() has one or -** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and -** P is the name of the query parameter, then -** sqlite3_uri_parameter(F,P) returns the value of the P +** a VFS implementation or it is the return value of [tdsqlite3_db_filename()] +** and if P is the name of the query parameter, then +** tdsqlite3_uri_parameter(F,P) returns the value of the P ** parameter if it exists or a NULL pointer if P does not appear as a -** query parameter on F. If P is a query parameter of F -** has no explicit value, then sqlite3_uri_parameter(F,P) returns +** query parameter on F. If P is a query parameter of F and it +** has no explicit value, then tdsqlite3_uri_parameter(F,P) returns ** a pointer to an empty string. ** -** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean +** The tdsqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean ** parameter and returns true (1) or false (0) according to the value -** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the +** of P. The tdsqlite3_uri_boolean(F,P,B) routine returns true (1) if the ** value of query parameter P is one of "yes", "true", or "on" in any ** case or if the value begins with a non-zero number. The -** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of +** tdsqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of ** query parameter P is one of "no", "false", or "off" in any case or ** if the value begins with a numeric zero. If P is not a query -** parameter on F or if the value of P is does not match any of the -** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). +** parameter on F or if the value of P does not match any of the +** above, then tdsqlite3_uri_boolean(F,P,B) returns (B!=0). ** -** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a +** The tdsqlite3_uri_int64(F,P,D) routine converts the value of P into a ** 64-bit signed integer and returns that integer, or D if P does not ** exist. If the value of P is something other than an integer, then ** zero is returned. +** +** The tdsqlite3_uri_key(F,N) returns a pointer to the name (not +** the value) of the N-th query parameter for filename F, or a NULL +** pointer if N is less than zero or greater than the number of query +** parameters minus 1. The N value is zero-based so N should be 0 to obtain +** the name of the first query parameter, 1 for the second parameter, and +** so forth. ** -** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and -** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and -** is not a database file pathname pointer that SQLite passed into the xOpen -** VFS method, then the behavior of this routine is undefined and probably -** undesirable. +** If F is a NULL pointer, then tdsqlite3_uri_parameter(F,P) returns NULL and +** tdsqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and +** is not a database file pathname pointer that the SQLite core passed +** into the xOpen VFS method, then the behavior of this routine is undefined +** and probably undesirable. +** +** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F +** parameter can also be the name of a rollback journal file or WAL file +** in addition to the main database file. Prior to version 3.31.0, these +** routines would only work if F was the name of the main database file. +** When the F parameter is the name of the rollback journal or WAL file, +** it has access to all the same query parameters as were found on the +** main database file. +** +** See the [URI filename] documentation for additional information. */ -SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); -SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); -SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); +SQLITE_API const char *tdsqlite3_uri_parameter(const char *zFilename, const char *zParam); +SQLITE_API int tdsqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); +SQLITE_API tdsqlite3_int64 tdsqlite3_uri_int64(const char*, const char*, tdsqlite3_int64); +SQLITE_API const char *tdsqlite3_uri_key(const char *zFilename, int N); + +/* +** CAPI3REF: Translate filenames +** +** These routines are available to [VFS|custom VFS implementations] for +** translating filenames between the main database file, the journal file, +** and the WAL file. +** +** If F is the name of an sqlite database file, journal file, or WAL file +** passed by the SQLite core into the VFS, then tdsqlite3_filename_database(F) +** returns the name of the corresponding database file. +** +** If F is the name of an sqlite database file, journal file, or WAL file +** passed by the SQLite core into the VFS, or if F is a database filename +** obtained from [tdsqlite3_db_filename()], then tdsqlite3_filename_journal(F) +** returns the name of the corresponding rollback journal file. +** +** If F is the name of an sqlite database file, journal file, or WAL file +** that was passed by the SQLite core into the VFS, or if F is a database +** filename obtained from [tdsqlite3_db_filename()], then +** tdsqlite3_filename_wal(F) returns the name of the corresponding +** WAL file. +** +** In all of the above, if F is not the name of a database, journal or WAL +** filename passed into the VFS from the SQLite core and F is not the +** return value from [tdsqlite3_db_filename()], then the result is +** undefined and is likely a memory access violation. +*/ +SQLITE_API const char *tdsqlite3_filename_database(const char*); +SQLITE_API const char *tdsqlite3_filename_journal(const char*); +SQLITE_API const char *tdsqlite3_filename_wal(const char*); /* ** CAPI3REF: Error Codes And Messages -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^If the most recent sqlite3_* API call associated with -** [database connection] D failed, then the sqlite3_errcode(D) interface +** ^If the most recent tdsqlite3_* API call associated with +** [database connection] D failed, then the tdsqlite3_errcode(D) interface ** returns the numeric [result code] or [extended result code] for that ** API call. -** If the most recent API call was successful, -** then the return value from sqlite3_errcode() is undefined. -** ^The sqlite3_extended_errcode() +** ^The tdsqlite3_extended_errcode() ** interface is the same except that it always returns the ** [extended result code] even when extended result codes are ** disabled. ** -** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** The values returned by tdsqlite3_errcode() and/or +** tdsqlite3_extended_errcode() might change with each API call. +** Except, there are some interfaces that are guaranteed to never +** change the value of the error code. The error-code preserving +** interfaces are: +** +** <ul> +** <li> tdsqlite3_errcode() +** <li> tdsqlite3_extended_errcode() +** <li> tdsqlite3_errmsg() +** <li> tdsqlite3_errmsg16() +** </ul> +** +** ^The tdsqlite3_errmsg() and tdsqlite3_errmsg16() return English-language ** text that describes the error, as either UTF-8 or UTF-16 respectively. ** ^(Memory to hold the error message string is managed internally. ** The application does not need to worry about freeing the result. ** However, the error string might be overwritten or deallocated by ** subsequent calls to other SQLite interface functions.)^ ** -** ^The sqlite3_errstr() interface returns the English-language text +** ^The tdsqlite3_errstr() interface returns the English-language text ** that describes the [result code], as UTF-8. ** ^(Memory to hold the error message string is managed internally ** and must not be freed by the application)^. @@ -3272,19 +3662,19 @@ SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int ** When that happens, the second error will be reported since these ** interfaces always report the most recent result. To avoid ** this, each thread can obtain exclusive use of the [database connection] D -** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning -** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** by invoking [tdsqlite3_mutex_enter]([tdsqlite3_db_mutex](D)) before beginning +** to use D and invoking [tdsqlite3_mutex_leave]([tdsqlite3_db_mutex](D)) after ** all calls to the interfaces listed here are completed. ** ** If an interface fails with SQLITE_MISUSE, that means the interface ** was invoked incorrectly by the application. In that case, the ** error code and message may or may not be set. */ -SQLITE_API int sqlite3_errcode(sqlite3 *db); -SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); -SQLITE_API const char *sqlite3_errmsg(sqlite3*); -SQLITE_API const void *sqlite3_errmsg16(sqlite3*); -SQLITE_API const char *sqlite3_errstr(int); +SQLITE_API int tdsqlite3_errcode(tdsqlite3 *db); +SQLITE_API int tdsqlite3_extended_errcode(tdsqlite3 *db); +SQLITE_API const char *tdsqlite3_errmsg(tdsqlite3*); +SQLITE_API const void *tdsqlite3_errmsg16(tdsqlite3*); +SQLITE_API const char *tdsqlite3_errstr(int); /* ** CAPI3REF: Prepared Statement Object @@ -3301,20 +3691,20 @@ SQLITE_API const char *sqlite3_errstr(int); ** The life-cycle of a prepared statement object usually goes like this: ** ** <ol> -** <li> Create the prepared statement object using [sqlite3_prepare_v2()]. -** <li> Bind values to [parameters] using the sqlite3_bind_*() +** <li> Create the prepared statement object using [tdsqlite3_prepare_v2()]. +** <li> Bind values to [parameters] using the tdsqlite3_bind_*() ** interfaces. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the prepared statement using [sqlite3_reset()] then go back +** <li> Run the SQL by calling [tdsqlite3_step()] one or more times. +** <li> Reset the prepared statement using [tdsqlite3_reset()] then go back ** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. +** <li> Destroy the object using [tdsqlite3_finalize()]. ** </ol> */ -typedef struct sqlite3_stmt sqlite3_stmt; +typedef struct tdsqlite3_stmt tdsqlite3_stmt; /* ** CAPI3REF: Run-time Limits -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^(This interface allows the size of various constructs to be limited ** on a connection by connection basis. The first parameter is the @@ -3333,7 +3723,7 @@ typedef struct sqlite3_stmt sqlite3_stmt; ** silently truncated to the hard upper bound. ** ** ^Regardless of whether or not the limit was changed, the -** [sqlite3_limit()] interface returns the prior value of the limit. +** [tdsqlite3_limit()] interface returns the prior value of the limit. ** ^Hence, to find the current value of a limit without changing it, ** simply invoke this interface with the third parameter set to -1. ** @@ -3345,21 +3735,21 @@ typedef struct sqlite3_stmt sqlite3_stmt; ** off the Internet. The internal databases can be given the ** large, default limits. Databases managed by external sources can ** be given much smaller limits designed to prevent a denial of service -** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** attack. Developers might also want to use the [tdsqlite3_set_authorizer()] ** interface to further control untrusted SQL. The size of the database ** created by an untrusted script can be contained using the ** [max_page_count] [PRAGMA]. ** ** New run-time limit categories may be added in future releases. */ -SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); +SQLITE_API int tdsqlite3_limit(tdsqlite3*, int id, int newVal); /* ** CAPI3REF: Run-Time Limit Categories ** KEYWORDS: {limit category} {*limit categories} ** ** These constants define various performance limits -** that can be lowered at run-time using [sqlite3_limit()]. +** that can be lowered at run-time using [tdsqlite3_limit()]. ** The synopsis of the meanings of the various limits is shown below. ** Additional information is available at [limits | Limits in SQLite]. ** @@ -3383,9 +3773,9 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt> ** <dd>The maximum number of instructions in a virtual machine program -** used to implement an SQL statement. This limit is not currently -** enforced, though that might be added in some future release of -** SQLite.</dd>)^ +** used to implement an SQL statement. If [tdsqlite3_prepare_v2()] or +** the equivalent tries to allocate space for more than this many opcodes +** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^ ** ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt> ** <dd>The maximum number of arguments on a function.</dd>)^ @@ -3424,22 +3814,73 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); #define SQLITE_LIMIT_WORKER_THREADS 11 /* +** CAPI3REF: Prepare Flags +** +** These constants define various flags that can be passed into +** "prepFlags" parameter of the [tdsqlite3_prepare_v3()] and +** [tdsqlite3_prepare16_v3()] interfaces. +** +** New flags may be added in future releases of SQLite. +** +** <dl> +** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt> +** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner +** that the prepared statement will be retained for a long time and +** probably reused many times.)^ ^Without this flag, [tdsqlite3_prepare_v3()] +** and [tdsqlite3_prepare16_v3()] assume that the prepared statement will +** be used just once or at most a few times and then destroyed using +** [tdsqlite3_finalize()] relatively soon. The current implementation acts +** on this hint by avoiding the use of [lookaside memory] so as not to +** deplete the limited store of lookaside memory. Future versions of +** SQLite may act on this hint differently. +** +** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt> +** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used +** to be required for any prepared statement that wanted to use the +** [tdsqlite3_normalized_sql()] interface. However, the +** [tdsqlite3_normalized_sql()] interface is now available to all +** prepared statements, regardless of whether or not they use this +** flag. +** +** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt> +** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler +** to return an error (error code SQLITE_ERROR) if the statement uses +** any virtual tables. +** </dl> +*/ +#define SQLITE_PREPARE_PERSISTENT 0x01 +#define SQLITE_PREPARE_NORMALIZE 0x02 +#define SQLITE_PREPARE_NO_VTAB 0x04 + +/* ** CAPI3REF: Compiling An SQL Statement ** KEYWORDS: {SQL statement compiler} -** METHOD: sqlite3 -** CONSTRUCTOR: sqlite3_stmt +** METHOD: tdsqlite3 +** CONSTRUCTOR: tdsqlite3_stmt +** +** To execute an SQL statement, it must first be compiled into a byte-code +** program using one of these routines. Or, in other words, these routines +** are constructors for the [prepared statement] object. ** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. +** The preferred routine to use is [tdsqlite3_prepare_v2()]. The +** [tdsqlite3_prepare()] interface is legacy and should be avoided. +** [tdsqlite3_prepare_v3()] has an extra "prepFlags" option that is used +** for special purposes. +** +** The use of the UTF-8 interfaces is preferred, as SQLite currently +** does all parsing using UTF-8. The UTF-16 interfaces are provided +** as a convenience. The UTF-16 interfaces work by converting the +** input text into UTF-8, then invoking the corresponding UTF-8 interface. ** ** The first argument, "db", is a [database connection] obtained from a -** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or -** [sqlite3_open16()]. The database connection must not have been closed. +** prior successful call to [tdsqlite3_open()], [tdsqlite3_open_v2()] or +** [tdsqlite3_open16()]. The database connection must not have been closed. ** ** The second argument, "zSql", is the statement to be compiled, encoded -** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() -** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() -** use UTF-16. +** as either UTF-8 or UTF-16. The tdsqlite3_prepare(), tdsqlite3_prepare_v2(), +** and tdsqlite3_prepare_v3() +** interfaces use UTF-8, and tdsqlite3_prepare16(), tdsqlite3_prepare16_v2(), +** and tdsqlite3_prepare16_v3() use UTF-16. ** ** ^If the nByte argument is negative, then zSql is read up to the ** first zero terminator. ^If nByte is positive, then it is the @@ -3456,129 +3897,160 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** what remains uncompiled. ** ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be -** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** executed using [tdsqlite3_step()]. ^If there is an error, *ppStmt is set ** to NULL. ^If the input text contains no SQL (if the input is an empty ** string or a comment) then *ppStmt is set to NULL. ** The calling procedure is responsible for deleting the compiled -** SQL statement using [sqlite3_finalize()] after it has finished with it. +** SQL statement using [tdsqlite3_finalize()] after it has finished with it. ** ppStmt may not be NULL. ** -** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** ^On success, the tdsqlite3_prepare() family of routines return [SQLITE_OK]; ** otherwise an [error code] is returned. ** -** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are -** recommended for all new programs. The two older interfaces are retained -** for backwards compatibility, but their use is discouraged. -** ^In the "v2" interfaces, the prepared statement -** that is returned (the [sqlite3_stmt] object) contains a copy of the -** original SQL text. This causes the [sqlite3_step()] interface to +** The tdsqlite3_prepare_v2(), tdsqlite3_prepare_v3(), tdsqlite3_prepare16_v2(), +** and tdsqlite3_prepare16_v3() interfaces are recommended for all new programs. +** The older interfaces (tdsqlite3_prepare() and tdsqlite3_prepare16()) +** are retained for backwards compatibility, but their use is discouraged. +** ^In the "vX" interfaces, the prepared statement +** that is returned (the [tdsqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [tdsqlite3_step()] interface to ** behave differently in three ways: ** ** <ol> ** <li> ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it -** always used to do, [sqlite3_step()] will automatically recompile the SQL +** always used to do, [tdsqlite3_step()] will automatically recompile the SQL ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] -** retries will occur before sqlite3_step() gives up and returns an error. +** retries will occur before tdsqlite3_step() gives up and returns an error. ** </li> ** ** <li> -** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** ^When an error occurs, [tdsqlite3_step()] will return one of the detailed ** [error codes] or [extended error codes]. ^The legacy behavior was that -** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code -** and the application would have to make a second call to [sqlite3_reset()] +** [tdsqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [tdsqlite3_reset()] ** in order to find the underlying cause of the problem. With the "v2" prepare ** interfaces, the underlying reason for the error is returned immediately. ** </li> ** ** <li> -** ^If the specific value bound to [parameter | host parameter] in the +** ^If the specific value bound to a [parameter | host parameter] in the ** WHERE clause might influence the choice of query plan for a statement, ** then the statement will be automatically recompiled, as if there had been -** a schema change, on the first [sqlite3_step()] call following any change -** to the [sqlite3_bind_text | bindings] of that [parameter]. -** ^The specific value of WHERE-clause [parameter] might influence the +** a schema change, on the first [tdsqlite3_step()] call following any change +** to the [tdsqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of a WHERE-clause [parameter] might influence the ** choice of query plan if the parameter is the left-hand side of a [LIKE] ** or [GLOB] operator or if the parameter is compared to an indexed column -** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. +** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled. ** </li> ** </ol> +** +** <p>^tdsqlite3_prepare_v3() differs from tdsqlite3_prepare_v2() only in having +** the extra prepFlags parameter, which is a bit array consisting of zero or +** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The +** tdsqlite3_prepare_v2() interface works exactly the same as +** tdsqlite3_prepare_v3() with a zero prepFlags parameter. */ -SQLITE_API int sqlite3_prepare( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_prepare( + tdsqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int tdsqlite3_prepare_v2( + tdsqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); -SQLITE_API int sqlite3_prepare_v2( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_prepare_v3( + tdsqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); -SQLITE_API int sqlite3_prepare16( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_prepare16( + tdsqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); -SQLITE_API int sqlite3_prepare16_v2( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_prepare16_v2( + tdsqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int tdsqlite3_prepare16_v3( + tdsqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */ + tdsqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); /* ** CAPI3REF: Retrieving Statement SQL -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 +** ^The tdsqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 ** SQL text used to create [prepared statement] P if P was -** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. -** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 +** created by [tdsqlite3_prepare_v2()], [tdsqlite3_prepare_v3()], +** [tdsqlite3_prepare16_v2()], or [tdsqlite3_prepare16_v3()]. +** ^The tdsqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 ** string containing the SQL text of prepared statement P with ** [bound parameters] expanded. +** ^The tdsqlite3_normalized_sql(P) interface returns a pointer to a UTF-8 +** string containing the normalized SQL text of prepared statement P. The +** semantics used to normalize a SQL statement are unspecified and subject +** to change. At a minimum, literal values will be replaced with suitable +** placeholders. ** ** ^(For example, if a prepared statement is created using the SQL ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345 -** and parameter :xyz is unbound, then sqlite3_sql() will return -** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql() +** and parameter :xyz is unbound, then tdsqlite3_sql() will return +** the original string, "SELECT $abc,:xyz" but tdsqlite3_expanded_sql() ** will return "SELECT 2345,NULL".)^ ** -** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory +** ^The tdsqlite3_expanded_sql() interface returns NULL if insufficient memory ** is available to hold the result, or if the result would exceed the ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. ** ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time -** option causes sqlite3_expanded_sql() to always return NULL. +** option causes tdsqlite3_expanded_sql() to always return NULL. ** -** ^The string returned by sqlite3_sql(P) is managed by SQLite and is -** automatically freed when the prepared statement is finalized. -** ^The string returned by sqlite3_expanded_sql(P), on the other hand, -** is obtained from [sqlite3_malloc()] and must be free by the application -** by passing it to [sqlite3_free()]. +** ^The strings returned by tdsqlite3_sql(P) and tdsqlite3_normalized_sql(P) +** are managed by SQLite and are automatically freed when the prepared +** statement is finalized. +** ^The string returned by tdsqlite3_expanded_sql(P), on the other hand, +** is obtained from [tdsqlite3_malloc()] and must be free by the application +** by passing it to [tdsqlite3_free()]. */ -SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); -SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); +SQLITE_API const char *tdsqlite3_sql(tdsqlite3_stmt *pStmt); +SQLITE_API char *tdsqlite3_expanded_sql(tdsqlite3_stmt *pStmt); +SQLITE_API const char *tdsqlite3_normalized_sql(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If An SQL Statement Writes The Database -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** ^The tdsqlite3_stmt_readonly(X) interface returns true (non-zero) if ** and only if the [prepared statement] X makes no direct changes to ** the content of the database file. ** ** Note that [application-defined SQL functions] or ** [virtual tables] might change the database indirectly as a side effect. ** ^(For example, if an application defines a function "eval()" that -** calls [sqlite3_exec()], then the following SQL statement would +** calls [tdsqlite3_exec()], then the following SQL statement would ** change the database file through side-effects: ** ** <blockquote><pre> @@ -3586,102 +4058,119 @@ SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); ** </pre></blockquote> ** ** But because the [SELECT] statement does not change the database file -** directly, sqlite3_stmt_readonly() would still return true.)^ +** directly, tdsqlite3_stmt_readonly() would still return true.)^ ** ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], -** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** [SAVEPOINT], and [RELEASE] cause tdsqlite3_stmt_readonly() to return true, ** since the statements themselves do not actually modify the database but ** rather they control the timing of when other statements modify the ** database. ^The [ATTACH] and [DETACH] statements also cause -** sqlite3_stmt_readonly() to return true since, while those statements +** tdsqlite3_stmt_readonly() to return true since, while those statements ** change the configuration of a database connection, they do not make ** changes to the content of the database files on disk. +** ^The tdsqlite3_stmt_readonly() interface returns true for [BEGIN] since +** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and +** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so +** tdsqlite3_stmt_readonly() returns false for those commands. */ -SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_stmt_readonly(tdsqlite3_stmt *pStmt); + +/* +** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement +** METHOD: tdsqlite3_stmt +** +** ^The tdsqlite3_stmt_isexplain(S) interface returns 1 if the +** prepared statement S is an EXPLAIN statement, or 2 if the +** statement S is an EXPLAIN QUERY PLAN. +** ^The tdsqlite3_stmt_isexplain(S) interface returns 0 if S is +** an ordinary statement or a NULL pointer. +*/ +SQLITE_API int tdsqlite3_stmt_isexplain(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Determine If A Prepared Statement Has Been Reset -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the +** ^The tdsqlite3_stmt_busy(S) interface returns true (non-zero) if the ** [prepared statement] S has been stepped at least once using -** [sqlite3_step(S)] but has neither run to completion (returned -** [SQLITE_DONE] from [sqlite3_step(S)]) nor -** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) +** [tdsqlite3_step(S)] but has neither run to completion (returned +** [SQLITE_DONE] from [tdsqlite3_step(S)]) nor +** been reset using [tdsqlite3_reset(S)]. ^The tdsqlite3_stmt_busy(S) ** interface returns false if S is a NULL pointer. If S is not a ** NULL pointer and is not a pointer to a valid [prepared statement] ** object, then the behavior is undefined and probably undesirable. ** -** This interface can be used in combination [sqlite3_next_stmt()] +** This interface can be used in combination [tdsqlite3_next_stmt()] ** to locate all prepared statements associated with a database ** connection that are in need of being reset. This can be used, ** for example, in diagnostic routines to search for prepared ** statements that are holding a transaction open. */ -SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); +SQLITE_API int tdsqlite3_stmt_busy(tdsqlite3_stmt*); /* ** CAPI3REF: Dynamically Typed Value Object -** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** KEYWORDS: {protected tdsqlite3_value} {unprotected tdsqlite3_value} ** -** SQLite uses the sqlite3_value object to represent all values +** SQLite uses the tdsqlite3_value object to represent all values ** that can be stored in a database table. SQLite uses dynamic typing -** for the values it stores. ^Values stored in sqlite3_value objects +** for the values it stores. ^Values stored in tdsqlite3_value objects ** can be integers, floating point values, strings, BLOBs, or NULL. ** -** An sqlite3_value object may be either "protected" or "unprotected". -** Some interfaces require a protected sqlite3_value. Other interfaces -** will accept either a protected or an unprotected sqlite3_value. -** Every interface that accepts sqlite3_value arguments specifies -** whether or not it requires a protected sqlite3_value. The -** [sqlite3_value_dup()] interface can be used to construct a new -** protected sqlite3_value from an unprotected sqlite3_value. +** An tdsqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected tdsqlite3_value. Other interfaces +** will accept either a protected or an unprotected tdsqlite3_value. +** Every interface that accepts tdsqlite3_value arguments specifies +** whether or not it requires a protected tdsqlite3_value. The +** [tdsqlite3_value_dup()] interface can be used to construct a new +** protected tdsqlite3_value from an unprotected tdsqlite3_value. ** ** The terms "protected" and "unprotected" refer to whether or not ** a mutex is held. An internal mutex is held for a protected -** sqlite3_value object but no mutex is held for an unprotected -** sqlite3_value object. If SQLite is compiled to be single-threaded -** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** tdsqlite3_value object but no mutex is held for an unprotected +** tdsqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [tdsqlite3_threadsafe()] returning 0) ** or if SQLite is run in one of reduced mutex modes ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] ** then there is no distinction between protected and unprotected -** sqlite3_value objects and they can be used interchangeably. However, +** tdsqlite3_value objects and they can be used interchangeably. However, ** for maximum code portability it is recommended that applications ** still make the distinction between protected and unprotected -** sqlite3_value objects even when not strictly required. +** tdsqlite3_value objects even when not strictly required. ** -** ^The sqlite3_value objects that are passed as parameters into the +** ^The tdsqlite3_value objects that are passed as parameters into the ** implementation of [application-defined SQL functions] are protected. -** ^The sqlite3_value object returned by -** [sqlite3_column_value()] is unprotected. -** Unprotected sqlite3_value objects may only be used with -** [sqlite3_result_value()] and [sqlite3_bind_value()]. -** The [sqlite3_value_blob | sqlite3_value_type()] family of -** interfaces require protected sqlite3_value objects. +** ^The tdsqlite3_value object returned by +** [tdsqlite3_column_value()] is unprotected. +** Unprotected tdsqlite3_value objects may only be used as arguments +** to [tdsqlite3_result_value()], [tdsqlite3_bind_value()], and +** [tdsqlite3_value_dup()]. +** The [tdsqlite3_value_blob | tdsqlite3_value_type()] family of +** interfaces require protected tdsqlite3_value objects. */ -typedef struct Mem sqlite3_value; +typedef struct tdsqlite3_value tdsqlite3_value; /* ** CAPI3REF: SQL Function Context Object ** ** The context in which an SQL function executes is stored in an -** sqlite3_context object. ^A pointer to an sqlite3_context object +** tdsqlite3_context object. ^A pointer to an tdsqlite3_context object ** is always first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this -** pointer through into calls to [sqlite3_result_int | sqlite3_result()], -** [sqlite3_aggregate_context()], [sqlite3_user_data()], -** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], -** and/or [sqlite3_set_auxdata()]. +** pointer through into calls to [tdsqlite3_result_int | tdsqlite3_result()], +** [tdsqlite3_aggregate_context()], [tdsqlite3_user_data()], +** [tdsqlite3_context_db_handle()], [tdsqlite3_get_auxdata()], +** and/or [tdsqlite3_set_auxdata()]. */ -typedef struct sqlite3_context sqlite3_context; +typedef struct tdsqlite3_context tdsqlite3_context; /* ** CAPI3REF: Binding Values To Prepared Statements ** KEYWORDS: {host parameter} {host parameters} {host parameter name} ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** ^(In the SQL statement text input to [tdsqlite3_prepare_v2()] and its variants, ** literals may be replaced by a [parameter] that matches one of following ** templates: ** @@ -3696,37 +4185,37 @@ typedef struct sqlite3_context sqlite3_context; ** In the templates above, NNN represents an integer literal, ** and VVV represents an alphanumeric identifier.)^ ^The values of these ** parameters (also called "host parameter names" or "SQL parameters") -** can be set using the sqlite3_bind_*() routines defined here. +** can be set using the tdsqlite3_bind_*() routines defined here. ** -** ^The first argument to the sqlite3_bind_*() routines is always -** a pointer to the [sqlite3_stmt] object returned from -** [sqlite3_prepare_v2()] or its variants. +** ^The first argument to the tdsqlite3_bind_*() routines is always +** a pointer to the [tdsqlite3_stmt] object returned from +** [tdsqlite3_prepare_v2()] or its variants. ** ** ^The second argument is the index of the SQL parameter to be set. ** ^The leftmost SQL parameter has an index of 1. ^When the same named ** SQL parameter is used more than once, second and subsequent ** occurrences have the same index as the first occurrence. ** ^The index for named parameters can be looked up using the -** [sqlite3_bind_parameter_index()] API if desired. ^The index +** [tdsqlite3_bind_parameter_index()] API if desired. ^The index ** for "?NNN" parameters is the value of NNN. -** ^The NNN value must be between 1 and the [sqlite3_limit()] +** ^The NNN value must be between 1 and the [tdsqlite3_limit()] ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). ** ** ^The third argument is the value to bind to the parameter. -** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() -** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter -** is ignored and the end result is the same as sqlite3_bind_null(). +** ^If the third parameter to tdsqlite3_bind_text() or tdsqlite3_bind_text16() +** or tdsqlite3_bind_blob() is a NULL pointer then the fourth parameter +** is ignored and the end result is the same as tdsqlite3_bind_null(). ** ** ^(In those routines that have a fourth argument, its value is the ** number of bytes in the parameter. To be clear: the value is the ** number of <u>bytes</u> in the value, not the number of characters.)^ -** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** ^If the fourth parameter to tdsqlite3_bind_text() or tdsqlite3_bind_text16() ** is negative, then the length of the string is ** the number of bytes up to the first zero terminator. -** If the fourth parameter to sqlite3_bind_blob() is negative, then +** If the fourth parameter to tdsqlite3_bind_blob() is negative, then ** the behavior is undefined. -** If a non-negative fourth parameter is provided to sqlite3_bind_text() -** or sqlite3_bind_text16() or sqlite3_bind_text64() then +** If a non-negative fourth parameter is provided to tdsqlite3_bind_text() +** or tdsqlite3_bind_text16() or tdsqlite3_bind_text64() then ** that parameter must be the byte offset ** where the NUL terminator would occur assuming the string were NUL ** terminated. If any NUL characters occur at byte offsets less than @@ -3737,74 +4226,86 @@ typedef struct sqlite3_context sqlite3_context; ** ^The fifth argument to the BLOB and string binding interfaces ** is a destructor used to dispose of the BLOB or ** string after SQLite has finished with it. ^The destructor is called -** to dispose of the BLOB or string even if the call to bind API fails. +** to dispose of the BLOB or string even if the call to the bind API fails, +** except the destructor is not called if the third parameter is a NULL +** pointer or the fourth parameter is negative. ** ^If the fifth argument is ** the special value [SQLITE_STATIC], then SQLite assumes that the ** information is in static, unmanaged space and does not need to be freed. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before -** the sqlite3_bind_*() routine returns. +** the tdsqlite3_bind_*() routine returns. ** -** ^The sixth argument to sqlite3_bind_text64() must be one of +** ^The sixth argument to tdsqlite3_bind_text64() must be one of ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] ** to specify the encoding of the text in the third parameter. If -** the sixth argument to sqlite3_bind_text64() is not one of the +** the sixth argument to tdsqlite3_bind_text64() is not one of the ** allowed values shown above, or if the text encoding is different ** from the encoding specified by the sixth parameter, then the behavior ** is undefined. ** -** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** ^The tdsqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory ** (just an integer to hold its size) while it is being processed. ** Zeroblobs are intended to serve as placeholders for BLOBs whose ** content is later written using -** [sqlite3_blob_open | incremental BLOB I/O] routines. +** [tdsqlite3_blob_open | incremental BLOB I/O] routines. ** ^A negative value for the zeroblob results in a zero-length BLOB. ** -** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** ^The tdsqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in +** [prepared statement] S to have an SQL value of NULL, but to also be +** associated with the pointer P of type T. ^D is either a NULL pointer or +** a pointer to a destructor function for P. ^SQLite will invoke the +** destructor D with a single argument of P when it is finished using +** P. The T parameter should be a static string, preferably a string +** literal. The tdsqlite3_bind_pointer() routine is part of the +** [pointer passing interface] added for SQLite 3.20.0. +** +** ^If any of the tdsqlite3_bind_*() routines are called with a NULL pointer ** for the [prepared statement] or with a prepared statement for which -** [sqlite3_step()] has been called more recently than [sqlite3_reset()], -** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** [tdsqlite3_step()] has been called more recently than [tdsqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any tdsqlite3_bind_() ** routine is passed a [prepared statement] that has been finalized, the ** result is undefined and probably harmful. ** -** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Bindings are not cleared by the [tdsqlite3_reset()] routine. ** ^Unbound parameters are interpreted as NULL. ** -** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** ^The tdsqlite3_bind_* routines return [SQLITE_OK] on success or an ** [error code] if anything goes wrong. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB -** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or +** exceeds limits imposed by [tdsqlite3_limit]([SQLITE_LIMIT_LENGTH]) or ** [SQLITE_MAX_LENGTH]. ** ^[SQLITE_RANGE] is returned if the parameter ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. ** -** See also: [sqlite3_bind_parameter_count()], -** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +** See also: [tdsqlite3_bind_parameter_count()], +** [tdsqlite3_bind_parameter_name()], and [tdsqlite3_bind_parameter_index()]. */ -SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); -SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, +SQLITE_API int tdsqlite3_bind_blob(tdsqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int tdsqlite3_bind_blob64(tdsqlite3_stmt*, int, const void*, tdsqlite3_uint64, void(*)(void*)); -SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); -SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); -SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); -SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); -SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); -SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); -SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, +SQLITE_API int tdsqlite3_bind_double(tdsqlite3_stmt*, int, double); +SQLITE_API int tdsqlite3_bind_int(tdsqlite3_stmt*, int, int); +SQLITE_API int tdsqlite3_bind_int64(tdsqlite3_stmt*, int, tdsqlite3_int64); +SQLITE_API int tdsqlite3_bind_null(tdsqlite3_stmt*, int); +SQLITE_API int tdsqlite3_bind_text(tdsqlite3_stmt*,int,const char*,int,void(*)(void*)); +SQLITE_API int tdsqlite3_bind_text16(tdsqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int tdsqlite3_bind_text64(tdsqlite3_stmt*, int, const char*, tdsqlite3_uint64, void(*)(void*), unsigned char encoding); -SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); -SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); -SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); +SQLITE_API int tdsqlite3_bind_value(tdsqlite3_stmt*, int, const tdsqlite3_value*); +SQLITE_API int tdsqlite3_bind_pointer(tdsqlite3_stmt*, int, void*, const char*,void(*)(void*)); +SQLITE_API int tdsqlite3_bind_zeroblob(tdsqlite3_stmt*, int, int n); +SQLITE_API int tdsqlite3_bind_zeroblob64(tdsqlite3_stmt*, int, tdsqlite3_uint64); /* ** CAPI3REF: Number Of SQL Parameters -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^This routine can be used to find the number of [SQL parameters] ** in a [prepared statement]. SQL parameters are tokens of the ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as -** placeholders for values that are [sqlite3_bind_blob | bound] +** placeholders for values that are [tdsqlite3_bind_blob | bound] ** to the parameters at a later time. ** ** ^(This routine actually returns the index of the largest (rightmost) @@ -3812,17 +4313,17 @@ SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); ** number of unique parameters. If parameters of the ?NNN form are used, ** there may be gaps in the list.)^ ** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_name()], and -** [sqlite3_bind_parameter_index()]. +** See also: [tdsqlite3_bind_blob|tdsqlite3_bind()], +** [tdsqlite3_bind_parameter_name()], and +** [tdsqlite3_bind_parameter_index()]. */ -SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); +SQLITE_API int tdsqlite3_bind_parameter_count(tdsqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_bind_parameter_name(P,N) interface returns +** ^The tdsqlite3_bind_parameter_name(P,N) interface returns ** the name of the N-th [SQL parameter] in the [prepared statement] P. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" @@ -3837,73 +4338,78 @@ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); ** ^If the value N is out of range or if the N-th parameter is ** nameless, then NULL is returned. ^The returned string is ** always in UTF-8 encoding even if the named parameter was -** originally specified as UTF-16 in [sqlite3_prepare16()] or -** [sqlite3_prepare16_v2()]. +** originally specified as UTF-16 in [tdsqlite3_prepare16()], +** [tdsqlite3_prepare16_v2()], or [tdsqlite3_prepare16_v3()]. ** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. +** See also: [tdsqlite3_bind_blob|tdsqlite3_bind()], +** [tdsqlite3_bind_parameter_count()], and +** [tdsqlite3_bind_parameter_index()]. */ -SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); +SQLITE_API const char *tdsqlite3_bind_parameter_name(tdsqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^Return the index of an SQL parameter given its name. ^The ** index value returned is suitable for use as the second -** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** parameter to [tdsqlite3_bind_blob|tdsqlite3_bind()]. ^A zero ** is returned if no matching parameter is found. ^The parameter ** name must be given in UTF-8 even if the original statement -** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. +** was prepared from UTF-16 text using [tdsqlite3_prepare16_v2()] or +** [tdsqlite3_prepare16_v3()]. ** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_name()]. +** See also: [tdsqlite3_bind_blob|tdsqlite3_bind()], +** [tdsqlite3_bind_parameter_count()], and +** [tdsqlite3_bind_parameter_name()]. */ -SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); +SQLITE_API int tdsqlite3_bind_parameter_index(tdsqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset -** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Contrary to the intuition of many, [tdsqlite3_reset()] does not reset +** the [tdsqlite3_bind_blob | bindings] on a [prepared statement]. ** ^Use this routine to reset all host parameters to NULL. */ -SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); +SQLITE_API int tdsqlite3_clear_bindings(tdsqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^Return the number of columns in the result set returned by the -** [prepared statement]. ^This routine returns 0 if pStmt is an SQL -** statement that does not return data (for example an [UPDATE]). +** [prepared statement]. ^If this routine returns 0, that means the +** [prepared statement] returns no data (for example an [UPDATE]). +** ^However, just because this routine returns a positive number does not +** mean that one or more rows of data will be returned. ^A SELECT statement +** will always have a positive tdsqlite3_column_count() but depending on the +** WHERE clause constraints and the table content, it might return no rows. ** -** See also: [sqlite3_data_count()] +** See also: [tdsqlite3_data_count()] */ -SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_column_count(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^These routines return the name assigned to a particular column -** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** in the result set of a [SELECT] statement. ^The tdsqlite3_column_name() ** interface returns a pointer to a zero-terminated UTF-8 string -** and sqlite3_column_name16() returns a pointer to a zero-terminated +** and tdsqlite3_column_name16() returns a pointer to a zero-terminated ** UTF-16 string. ^The first parameter is the [prepared statement] ** that implements the [SELECT] statement. ^The second parameter is the ** column number. ^The leftmost column is number 0. ** ** ^The returned string pointer is valid until either the [prepared statement] -** is destroyed by [sqlite3_finalize()] or until the statement is automatically -** reprepared by the first call to [sqlite3_step()] for a particular run +** is destroyed by [tdsqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [tdsqlite3_step()] for a particular run ** or until the next call to -** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** tdsqlite3_column_name() or tdsqlite3_column_name16() on the same column. ** -** ^If sqlite3_malloc() fails during the processing of either routine +** ^If tdsqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. ** @@ -3912,12 +4418,12 @@ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); ** then the name of the column is unspecified and may change from ** one release of SQLite to the next. */ -SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); -SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); +SQLITE_API const char *tdsqlite3_column_name(tdsqlite3_stmt*, int N); +SQLITE_API const void *tdsqlite3_column_name16(tdsqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^These routines provide a means to determine the database, table, and ** table column that is the origin of a particular result column in @@ -3927,8 +4433,8 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); ** the database name, the _table_ routines return the table name, and ** the origin_ routines return the column name. ** ^The returned string is valid until the [prepared statement] is destroyed -** using [sqlite3_finalize()] or until the statement is automatically -** reprepared by the first call to [sqlite3_step()] for a particular run +** using [tdsqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [tdsqlite3_step()] for a particular run ** or until the same information is requested ** again in a different encoding. ** @@ -3942,7 +4448,7 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); ** ** ^If the Nth column returned by the statement is an expression or ** subquery and is not a column value, then all of these functions return -** NULL. ^These routine might also return NULL if a memory allocation error +** NULL. ^These routines might also return NULL if a memory allocation error ** occurs. ^Otherwise, they return the name of the attached database, table, ** or column that query result column was extracted from. ** @@ -3952,25 +4458,21 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); ** ^These APIs are only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. ** -** If two or more threads call one or more of these routines against the same -** prepared statement and column at the same time then the results are -** undefined. -** ** If two or more threads call one or more -** [sqlite3_column_database_name | column metadata interfaces] +** [tdsqlite3_column_database_name | column metadata interfaces] ** for the same [prepared statement] and result column ** at the same time then the results are undefined. */ -SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); +SQLITE_API const char *tdsqlite3_column_database_name(tdsqlite3_stmt*,int); +SQLITE_API const void *tdsqlite3_column_database_name16(tdsqlite3_stmt*,int); +SQLITE_API const char *tdsqlite3_column_table_name(tdsqlite3_stmt*,int); +SQLITE_API const void *tdsqlite3_column_table_name16(tdsqlite3_stmt*,int); +SQLITE_API const char *tdsqlite3_column_origin_name(tdsqlite3_stmt*,int); +SQLITE_API const void *tdsqlite3_column_origin_name16(tdsqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^(The first parameter is a [prepared statement]. ** If this statement is a [SELECT] statement and the Nth column of the @@ -3998,23 +4500,25 @@ SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); ** is associated with individual values, not with the containers ** used to hold those values. */ -SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); +SQLITE_API const char *tdsqlite3_column_decltype(tdsqlite3_stmt*,int); +SQLITE_API const void *tdsqlite3_column_decltype16(tdsqlite3_stmt*,int); /* ** CAPI3REF: Evaluate An SQL Statement -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** After a [prepared statement] has been prepared using either -** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy -** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** After a [prepared statement] has been prepared using any of +** [tdsqlite3_prepare_v2()], [tdsqlite3_prepare_v3()], [tdsqlite3_prepare16_v2()], +** or [tdsqlite3_prepare16_v3()] or one of the legacy +** interfaces [tdsqlite3_prepare()] or [tdsqlite3_prepare16()], this function ** must be called one or more times to evaluate the statement. ** -** The details of the behavior of the sqlite3_step() interface depend -** on whether the statement was prepared using the newer "v2" interface -** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy -** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the -** new "v2" interface is recommended for new applications but the legacy +** The details of the behavior of the tdsqlite3_step() interface depend +** on whether the statement was prepared using the newer "vX" interfaces +** [tdsqlite3_prepare_v3()], [tdsqlite3_prepare_v2()], [tdsqlite3_prepare16_v3()], +** [tdsqlite3_prepare16_v2()] or the older legacy +** interfaces [tdsqlite3_prepare()] and [tdsqlite3_prepare16()]. The use of the +** new "vX" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** ** ^In the legacy interface, the return value will be either [SQLITE_BUSY], @@ -4030,78 +4534,79 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); ** continuing. ** ** ^[SQLITE_DONE] means that the statement has finished executing -** successfully. sqlite3_step() should not be called again on this virtual -** machine without first calling [sqlite3_reset()] to reset the virtual +** successfully. tdsqlite3_step() should not be called again on this virtual +** machine without first calling [tdsqlite3_reset()] to reset the virtual ** machine back to its initial state. ** ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] ** is returned each time a new row of data is ready for processing by the ** caller. The values may be accessed using the [column access functions]. -** sqlite3_step() is called again to retrieve the next row of data. +** tdsqlite3_step() is called again to retrieve the next row of data. ** ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint -** violation) has occurred. sqlite3_step() should not be called again on -** the VM. More information may be found by calling [sqlite3_errmsg()]. +** violation) has occurred. tdsqlite3_step() should not be called again on +** the VM. More information may be found by calling [tdsqlite3_errmsg()]. ** ^With the legacy interface, a more specific error code (for example, ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) -** can be obtained by calling [sqlite3_reset()] on the +** can be obtained by calling [tdsqlite3_reset()] on the ** [prepared statement]. ^In the "v2" interface, -** the more specific error code is returned directly by sqlite3_step(). +** the more specific error code is returned directly by tdsqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has -** already been [sqlite3_finalize | finalized] or on one that had +** already been [tdsqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** ** For all versions of SQLite up to and including 3.6.23.1, a call to -** [sqlite3_reset()] was required after sqlite3_step() returned anything +** [tdsqlite3_reset()] was required after tdsqlite3_step() returned anything ** other than [SQLITE_ROW] before any subsequent invocation of -** sqlite3_step(). Failure to reset the prepared statement using -** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from -** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], -** sqlite3_step() began -** calling [sqlite3_reset()] automatically in this circumstance rather +** tdsqlite3_step(). Failure to reset the prepared statement using +** [tdsqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** tdsqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], +** tdsqlite3_step() began +** calling [tdsqlite3_reset()] automatically in this circumstance rather ** than returning [SQLITE_MISUSE]. This is not considered a compatibility ** break because any application that ever receives an SQLITE_MISUSE error ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option ** can be used to restore the legacy behavior. ** -** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step() +** <b>Goofy Interface Alert:</b> In the legacy interface, the tdsqlite3_step() ** API always returns a generic error code, [SQLITE_ERROR], following any ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call -** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** [tdsqlite3_reset()] or [tdsqlite3_finalize()] in order to find one of the ** specific [error codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements -** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead -** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** using [tdsqlite3_prepare_v3()] or [tdsqlite3_prepare_v2()] +** or [tdsqlite3_prepare16_v2()] or [tdsqlite3_prepare16_v3()] instead +** of the legacy [tdsqlite3_prepare()] and [tdsqlite3_prepare16()] interfaces, ** then the more specific [error codes] are returned directly -** by sqlite3_step(). The use of the "v2" interface is recommended. +** by tdsqlite3_step(). The use of the "vX" interfaces is recommended. */ -SQLITE_API int sqlite3_step(sqlite3_stmt*); +SQLITE_API int tdsqlite3_step(tdsqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_data_count(P) interface returns the number of columns in the +** ^The tdsqlite3_data_count(P) interface returns the number of columns in the ** current row of the result set of [prepared statement] P. ** ^If prepared statement P does not have results ready to return -** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of -** interfaces) then sqlite3_data_count(P) returns 0. -** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. -** ^The sqlite3_data_count(P) routine returns 0 if the previous call to -** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) -** will return non-zero if previous call to [sqlite3_step](P) returned +** (via calls to the [tdsqlite3_column_int | tdsqlite3_column()] family of +** interfaces) then tdsqlite3_data_count(P) returns 0. +** ^The tdsqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** ^The tdsqlite3_data_count(P) routine returns 0 if the previous call to +** [tdsqlite3_step](P) returned [SQLITE_DONE]. ^The tdsqlite3_data_count(P) +** will return non-zero if previous call to [tdsqlite3_step](P) returned ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] ** where it always returns zero since each step of that multi-step ** pragma returns 0 columns of data. ** -** See also: [sqlite3_column_count()] +** See also: [tdsqlite3_column_count()] */ -SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_data_count(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes @@ -4138,79 +4643,118 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Result Values From A Query ** KEYWORDS: {column access functions} -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt +** +** <b>Summary:</b> +** <blockquote><table border=0 cellpadding=0 cellspacing=0> +** <tr><td><b>tdsqlite3_column_blob</b><td>→<td>BLOB result +** <tr><td><b>tdsqlite3_column_double</b><td>→<td>REAL result +** <tr><td><b>tdsqlite3_column_int</b><td>→<td>32-bit INTEGER result +** <tr><td><b>tdsqlite3_column_int64</b><td>→<td>64-bit INTEGER result +** <tr><td><b>tdsqlite3_column_text</b><td>→<td>UTF-8 TEXT result +** <tr><td><b>tdsqlite3_column_text16</b><td>→<td>UTF-16 TEXT result +** <tr><td><b>tdsqlite3_column_value</b><td>→<td>The result as an +** [tdsqlite3_value|unprotected tdsqlite3_value] object. +** <tr><td> <td> <td> +** <tr><td><b>tdsqlite3_column_bytes</b><td>→<td>Size of a BLOB +** or a UTF-8 TEXT result in bytes +** <tr><td><b>tdsqlite3_column_bytes16 </b> +** <td>→ <td>Size of UTF-16 +** TEXT in bytes +** <tr><td><b>tdsqlite3_column_type</b><td>→<td>Default +** datatype of the result +** </table></blockquote> +** +** <b>Details:</b> ** ** ^These routines return information about a single column of the current ** result row of a query. ^In every case the first argument is a pointer -** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] -** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** to the [prepared statement] that is being evaluated (the [tdsqlite3_stmt*] +** that was returned from [tdsqlite3_prepare_v2()] or one of its variants) ** and the second argument is the index of the column for which information ** should be returned. ^The leftmost column of the result set has the index 0. ** ^The number of columns in the result can be determined using -** [sqlite3_column_count()]. +** [tdsqlite3_column_count()]. ** ** If the SQL statement does not currently point to a valid row, or if the ** column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to -** [sqlite3_step()] has returned [SQLITE_ROW] and neither -** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. -** If any of these routines are called after [sqlite3_reset()] or -** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** [tdsqlite3_step()] has returned [SQLITE_ROW] and neither +** [tdsqlite3_reset()] nor [tdsqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [tdsqlite3_reset()] or +** [tdsqlite3_finalize()] or after [tdsqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. -** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** If [tdsqlite3_step()] or [tdsqlite3_reset()] or [tdsqlite3_finalize()] ** are called from a different thread while any of these routines ** are pending, then the results are undefined. ** -** ^The sqlite3_column_type() routine returns the +** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16) +** each return the value of a result column in a specific data format. If +** the result column is not initially in the requested format (for example, +** if the query returns an integer but the tdsqlite3_column_text() interface +** is used to extract the value) then an automatic type conversion is performed. +** +** ^The tdsqlite3_column_type() routine returns the ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. ^The returned value is one of [SQLITE_INTEGER], -** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value -** returned by sqlite3_column_type() is only meaningful if no type -** conversions have occurred as described below. After a type conversion, -** the value returned by sqlite3_column_type() is undefined. Future -** versions of SQLite may change the behavior of sqlite3_column_type() +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. +** The return value of tdsqlite3_column_type() can be used to decide which +** of the first six interface should be used to extract the column value. +** The value returned by tdsqlite3_column_type() is only meaningful if no +** automatic type conversions have occurred for the value in question. +** After a type conversion, the result of calling tdsqlite3_column_type() +** is undefined, though harmless. Future +** versions of SQLite may change the behavior of tdsqlite3_column_type() ** following a type conversion. ** -** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** If the result is a BLOB or a TEXT string, then the tdsqlite3_column_bytes() +** or tdsqlite3_column_bytes16() interfaces can be used to determine the size +** of that BLOB or string. +** +** ^If the result is a BLOB or UTF-8 string then the tdsqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. -** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** ^If the result is a UTF-16 string, then tdsqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. -** ^If the result is a numeric value then sqlite3_column_bytes() uses -** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** ^If the result is a numeric value then tdsqlite3_column_bytes() uses +** [tdsqlite3_snprintf()] to convert that value to a UTF-8 string and returns ** the number of bytes in that string. -** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** ^If the result is NULL, then tdsqlite3_column_bytes() returns zero. ** -** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** ^If the result is a BLOB or UTF-16 string then the tdsqlite3_column_bytes16() ** routine returns the number of bytes in that BLOB or string. -** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** ^If the result is a UTF-8 string, then tdsqlite3_column_bytes16() converts ** the string to UTF-16 and then returns the number of bytes. -** ^If the result is a numeric value then sqlite3_column_bytes16() uses -** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** ^If the result is a numeric value then tdsqlite3_column_bytes16() uses +** [tdsqlite3_snprintf()] to convert that value to a UTF-16 string and returns ** the number of bytes in that string. -** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** ^If the result is NULL, then tdsqlite3_column_bytes16() returns zero. ** -** ^The values returned by [sqlite3_column_bytes()] and -** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** ^The values returned by [tdsqlite3_column_bytes()] and +** [tdsqlite3_column_bytes16()] do not include the zero terminators at the end ** of the string. ^For clarity: the values returned by -** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** [tdsqlite3_column_bytes()] and [tdsqlite3_column_bytes16()] are the number of ** bytes in the string, not the number of characters. ** -** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** ^Strings returned by tdsqlite3_column_text() and tdsqlite3_column_text16(), ** even empty strings, are always zero-terminated. ^The return -** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. -** -** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an -** [unprotected sqlite3_value] object. In a multithreaded environment, -** an unprotected sqlite3_value object may only be used safely with -** [sqlite3_bind_value()] and [sqlite3_result_value()]. -** If the [unprotected sqlite3_value] object returned by -** [sqlite3_column_value()] is used in any other way, including calls -** to routines like [sqlite3_value_int()], [sqlite3_value_text()], -** or [sqlite3_value_bytes()], the behavior is not threadsafe. -** -** These routines attempt to convert the value where appropriate. ^For -** example, if the internal representation is FLOAT and a text result -** is requested, [sqlite3_snprintf()] is used internally to perform the +** value from tdsqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** <b>Warning:</b> ^The object returned by [tdsqlite3_column_value()] is an +** [unprotected tdsqlite3_value] object. In a multithreaded environment, +** an unprotected tdsqlite3_value object may only be used safely with +** [tdsqlite3_bind_value()] and [tdsqlite3_result_value()]. +** If the [unprotected tdsqlite3_value] object returned by +** [tdsqlite3_column_value()] is used in any other way, including calls +** to routines like [tdsqlite3_value_int()], [tdsqlite3_value_text()], +** or [tdsqlite3_value_bytes()], the behavior is not threadsafe. +** Hence, the tdsqlite3_column_value() interface +** is normally only useful within the implementation of +** [application-defined SQL functions] or [virtual tables], not within +** top-level application code. +** +** The these routines may attempt to convert the datatype of the result. +** ^For example, if the internal representation is FLOAT and a text result +** is requested, [tdsqlite3_snprintf()] is used internally to perform the ** conversion automatically. ^(The following table details the conversions ** that are applied: ** @@ -4238,20 +4782,20 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** </blockquote>)^ ** ** Note that when type conversions occur, pointers returned by prior -** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or -** sqlite3_column_text16() may be invalidated. +** calls to tdsqlite3_column_blob(), tdsqlite3_column_text(), and/or +** tdsqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** ** <ul> -** <li> The initial content is a BLOB and sqlite3_column_text() or -** sqlite3_column_text16() is called. A zero-terminator might +** <li> The initial content is a BLOB and tdsqlite3_column_text() or +** tdsqlite3_column_text16() is called. A zero-terminator might ** need to be added to the string.</li> -** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or -** sqlite3_column_text16() is called. The content must be converted +** <li> The initial content is UTF-8 text and tdsqlite3_column_bytes16() or +** tdsqlite3_column_text16() is called. The content must be converted ** to UTF-16.</li> -** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or -** sqlite3_column_text() is called. The content must be converted +** <li> The initial content is UTF-16 text and tdsqlite3_column_bytes() or +** tdsqlite3_column_text() is called. The content must be converted ** to UTF-8.</li> ** </ul> ** @@ -4265,62 +4809,76 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** in one of the following ways: ** ** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> +** <li>tdsqlite3_column_text() followed by tdsqlite3_column_bytes()</li> +** <li>tdsqlite3_column_blob() followed by tdsqlite3_column_bytes()</li> +** <li>tdsqlite3_column_text16() followed by tdsqlite3_column_bytes16()</li> ** </ul> ** -** In other words, you should call sqlite3_column_text(), -** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result -** into the desired format, then invoke sqlite3_column_bytes() or -** sqlite3_column_bytes16() to find the size of the result. Do not mix calls -** to sqlite3_column_text() or sqlite3_column_blob() with calls to -** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() -** with calls to sqlite3_column_bytes(). +** In other words, you should call tdsqlite3_column_text(), +** tdsqlite3_column_blob(), or tdsqlite3_column_text16() first to force the result +** into the desired format, then invoke tdsqlite3_column_bytes() or +** tdsqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to tdsqlite3_column_text() or tdsqlite3_column_blob() with calls to +** tdsqlite3_column_bytes16(), and do not mix calls to tdsqlite3_column_text16() +** with calls to tdsqlite3_column_bytes(). ** ** ^The pointers returned are valid until a type conversion occurs as -** described above, or until [sqlite3_step()] or [sqlite3_reset()] or -** [sqlite3_finalize()] is called. ^The memory space used to hold strings -** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned -** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into -** [sqlite3_free()]. -** -** ^(If a memory allocation error occurs during the evaluation of any -** of these routines, a default value is returned. The default value -** is either the integer 0, the floating point number 0.0, or a NULL -** pointer. Subsequent calls to [sqlite3_errcode()] will return -** [SQLITE_NOMEM].)^ -*/ -SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); -SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); -SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); -SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); -SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); -SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); +** described above, or until [tdsqlite3_step()] or [tdsqlite3_reset()] or +** [tdsqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** from [tdsqlite3_column_blob()], [tdsqlite3_column_text()], etc. into +** [tdsqlite3_free()]. +** +** As long as the input parameters are correct, these routines will only +** fail if an out-of-memory error occurs during a format conversion. +** Only the following subset of interfaces are subject to out-of-memory +** errors: +** +** <ul> +** <li> tdsqlite3_column_blob() +** <li> tdsqlite3_column_text() +** <li> tdsqlite3_column_text16() +** <li> tdsqlite3_column_bytes() +** <li> tdsqlite3_column_bytes16() +** </ul> +** +** If an out-of-memory error occurs, then the return value from these +** routines is the same as if the column had contained an SQL NULL value. +** Valid SQL NULL returns can be distinguished from out-of-memory errors +** by invoking the [tdsqlite3_errcode()] immediately after the suspect +** return value is obtained and before any +** other SQLite interface is called on the same [database connection]. +*/ +SQLITE_API const void *tdsqlite3_column_blob(tdsqlite3_stmt*, int iCol); +SQLITE_API double tdsqlite3_column_double(tdsqlite3_stmt*, int iCol); +SQLITE_API int tdsqlite3_column_int(tdsqlite3_stmt*, int iCol); +SQLITE_API tdsqlite3_int64 tdsqlite3_column_int64(tdsqlite3_stmt*, int iCol); +SQLITE_API const unsigned char *tdsqlite3_column_text(tdsqlite3_stmt*, int iCol); +SQLITE_API const void *tdsqlite3_column_text16(tdsqlite3_stmt*, int iCol); +SQLITE_API tdsqlite3_value *tdsqlite3_column_value(tdsqlite3_stmt*, int iCol); +SQLITE_API int tdsqlite3_column_bytes(tdsqlite3_stmt*, int iCol); +SQLITE_API int tdsqlite3_column_bytes16(tdsqlite3_stmt*, int iCol); +SQLITE_API int tdsqlite3_column_type(tdsqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object -** DESTRUCTOR: sqlite3_stmt +** DESTRUCTOR: tdsqlite3_stmt ** -** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^The tdsqlite3_finalize() function is called to delete a [prepared statement]. ** ^If the most recent evaluation of the statement encountered no errors -** or if the statement is never been evaluated, then sqlite3_finalize() returns +** or if the statement is never been evaluated, then tdsqlite3_finalize() returns ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then -** sqlite3_finalize(S) returns the appropriate [error code] or +** tdsqlite3_finalize(S) returns the appropriate [error code] or ** [extended error code]. ** -** ^The sqlite3_finalize(S) routine can be called at any point during +** ^The tdsqlite3_finalize(S) routine can be called at any point during ** the life cycle of [prepared statement] S: ** before statement S is ever evaluated, after -** one or more calls to [sqlite3_reset()], or after any call -** to [sqlite3_step()] regardless of whether or not the statement has +** one or more calls to [tdsqlite3_reset()], or after any call +** to [tdsqlite3_step()] regardless of whether or not the statement has ** completed execution. ** -** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** ^Invoking tdsqlite3_finalize() on a NULL pointer is a harmless no-op. ** ** The application must finalize every [prepared statement] in order to avoid ** resource leaks. It is a grievous error for the application to try to use @@ -4328,49 +4886,49 @@ SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); ** statement after it has been finalized can result in undefined and ** undesirable behavior such as segfaults and heap corruption. */ -SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_finalize(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** The sqlite3_reset() function is called to reset a [prepared statement] +** The tdsqlite3_reset() function is called to reset a [prepared statement] ** object back to its initial state, ready to be re-executed. ** ^Any SQL statement variables that had values bound to them using -** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. -** Use [sqlite3_clear_bindings()] to reset the bindings. +** the [tdsqlite3_bind_blob | tdsqlite3_bind_*() API] retain their values. +** Use [tdsqlite3_clear_bindings()] to reset the bindings. ** -** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** ^The [tdsqlite3_reset(S)] interface resets the [prepared statement] S ** back to the beginning of its program. ** -** ^If the most recent call to [sqlite3_step(S)] for the +** ^If the most recent call to [tdsqlite3_step(S)] for the ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], -** or if [sqlite3_step(S)] has never before been called on S, -** then [sqlite3_reset(S)] returns [SQLITE_OK]. +** or if [tdsqlite3_step(S)] has never before been called on S, +** then [tdsqlite3_reset(S)] returns [SQLITE_OK]. ** -** ^If the most recent call to [sqlite3_step(S)] for the +** ^If the most recent call to [tdsqlite3_step(S)] for the ** [prepared statement] S indicated an error, then -** [sqlite3_reset(S)] returns an appropriate [error code]. +** [tdsqlite3_reset(S)] returns an appropriate [error code]. ** -** ^The [sqlite3_reset(S)] interface does not change the values -** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +** ^The [tdsqlite3_reset(S)] interface does not change the values +** of any [tdsqlite3_bind_blob|bindings] on the [prepared statement] S. */ -SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); +SQLITE_API int tdsqlite3_reset(tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions ** KEYWORDS: {function creation routines} -** KEYWORDS: {application-defined SQL function} -** KEYWORDS: {application-defined SQL functions} -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^These functions (collectively known as "function creation routines") ** are used to add SQL functions or aggregates or to redefine the behavior -** of existing SQL functions or aggregates. The only differences between -** these routines are the text encoding expected for -** the second parameter (the name of the function being created) -** and the presence or absence of a destructor callback for -** the application data pointer. +** of existing SQL functions or aggregates. The only differences between +** the three "tdsqlite3_create_function*" routines are the text encoding +** expected for the second parameter (the name of the function being +** created) and the presence or absence of a destructor callback for +** the application data pointer. Function tdsqlite3_create_window_function() +** is similar, but allows the user to supply the extra callback functions +** needed by [aggregate window functions]. ** ** ^The first parameter is the [database connection] to which the SQL ** function is to be added. ^If an application uses more than one database @@ -4388,7 +4946,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** is the number of arguments that the SQL function or ** aggregate takes. ^If this parameter is -1, then the SQL function or ** aggregate may take any number of arguments between 0 and the limit -** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** set by [tdsqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third ** parameter is less than -1 or greater than 127 then the behavior is ** undefined. ** @@ -4396,9 +4954,9 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. The application should set this parameter to ** [SQLITE_UTF16LE] if the function implementation invokes -** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the -** implementation invokes [sqlite3_value_text16be()] on an input, or -** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8] +** [tdsqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the +** implementation invokes [tdsqlite3_value_text16be()] on an input, or +** [SQLITE_UTF16] if [tdsqlite3_value_text16()] is used, or [SQLITE_UTF8] ** otherwise. ^The same SQL function may be registered multiple times using ** different preferred text encodings, with different implementations for ** each encoding. @@ -4413,10 +4971,28 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** perform additional optimizations on deterministic functions, so use ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible. ** +** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY] +** flag, which if present prevents the function from being invoked from +** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions, +** index expressions, or the WHERE clause of partial indexes. +** +** <span style="background-color:#ffff90;"> +** For best security, the [SQLITE_DIRECTONLY] flag is recommended for +** all application-defined SQL functions that do not need to be +** used inside of triggers, view, CHECK constraints, or other elements of +** the database schema. This flags is especially recommended for SQL +** functions that have side effects or reveal internal application state. +** Without this flag, an attacker might be able to modify the schema of +** a database file to include invocations of the function with parameters +** chosen by the attacker, which the application will then execute when +** the database file is opened and read. +** </span> +** ** ^(The fifth parameter is an arbitrary pointer. The implementation of the -** function can gain access to this pointer using [sqlite3_user_data()].)^ +** function can gain access to this pointer using [tdsqlite3_user_data()].)^ ** -** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are +** ^The sixth, seventh and eighth parameters passed to the three +** "tdsqlite3_create_function*" functions, xFunc, xStep and xFinal, are ** pointers to C-language functions that implement the SQL function or ** aggregate. ^A scalar SQL function requires an implementation of the xFunc ** callback only; NULL pointers must be passed as the xStep and xFinal @@ -4425,15 +5001,24 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** SQL function or aggregate, pass NULL pointers for all three function ** callbacks. ** -** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, -** then it is destructor for the application data pointer. -** The destructor is invoked when the function is deleted, either by being -** overloaded or when the database connection closes.)^ -** ^The destructor is also invoked if the call to -** sqlite3_create_function_v2() fails. -** ^When the destructor callback of the tenth parameter is invoked, it -** is passed a single argument which is a copy of the application data -** pointer which was the fifth parameter to sqlite3_create_function_v2(). +** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue +** and xInverse) passed to tdsqlite3_create_window_function are pointers to +** C-language callbacks that implement the new function. xStep and xFinal +** must both be non-NULL. xValue and xInverse may either both be NULL, in +** which case a regular aggregate function is created, or must both be +** non-NULL, in which case the new function may be used as either an aggregate +** or aggregate window function. More details regarding the implementation +** of aggregate window functions are +** [user-defined window functions|available here]. +** +** ^(If the final parameter to tdsqlite3_create_function_v2() or +** tdsqlite3_create_window_function() is not NULL, then it is destructor for +** the application data pointer. The destructor is invoked when the function +** is deleted, either by being overloaded or when the database connection +** closes.)^ ^The destructor is also invoked if the call to +** tdsqlite3_create_function_v2() fails. ^When the destructor callback is +** invoked, it is passed a single argument which is a copy of the application +** data pointer which was the fifth parameter to tdsqlite3_create_function_v2(). ** ** ^It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of @@ -4455,35 +5040,47 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** close the database connection nor finalize or reset the prepared ** statement in which the function is running. */ -SQLITE_API int sqlite3_create_function( - sqlite3 *db, +SQLITE_API int tdsqlite3_create_function( + tdsqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*) + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*) ); -SQLITE_API int sqlite3_create_function16( - sqlite3 *db, +SQLITE_API int tdsqlite3_create_function16( + tdsqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *pApp, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*) + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*) ); -SQLITE_API int sqlite3_create_function_v2( - sqlite3 *db, +SQLITE_API int tdsqlite3_create_function_v2( + tdsqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*), + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*), + void(*xDestroy)(void*) +); +SQLITE_API int tdsqlite3_create_window_function( + tdsqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*), + void (*xValue)(tdsqlite3_context*), + void (*xInverse)(tdsqlite3_context*,int,tdsqlite3_value**), void(*xDestroy)(void*) ); @@ -4498,17 +5095,77 @@ SQLITE_API int sqlite3_create_function_v2( #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */ #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* Deprecated */ -#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ +#define SQLITE_UTF16_ALIGNED 8 /* tdsqlite3_create_collation only */ /* ** CAPI3REF: Function Flags ** ** These constants may be ORed together with the ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument -** to [sqlite3_create_function()], [sqlite3_create_function16()], or -** [sqlite3_create_function_v2()]. +** to [tdsqlite3_create_function()], [tdsqlite3_create_function16()], or +** [tdsqlite3_create_function_v2()]. +** +** <dl> +** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd> +** The SQLITE_DETERMINISTIC flag means that the new function always gives +** the same output when the input parameters are the same. +** The [abs|abs() function] is deterministic, for example, but +** [randomblob|randomblob()] is not. Functions must +** be deterministic in order to be used in certain contexts such as +** with the WHERE clause of [partial indexes] or in [generated columns]. +** SQLite might also optimize deterministic functions by factoring them +** out of inner loops. +** </dd> +** +** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd> +** The SQLITE_DIRECTONLY flag means that the function may only be invoked +** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in +** schema structures such as [CHECK constraints], [DEFAULT clauses], +** [expression indexes], [partial indexes], or [generated columns]. +** The SQLITE_DIRECTONLY flags is a security feature which is recommended +** for all [application-defined SQL functions], and especially for functions +** that have side-effects or that could potentially leak sensitive +** information. +** </dd> +** +** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd> +** The SQLITE_INNOCUOUS flag means that the function is unlikely +** to cause problems even if misused. An innocuous function should have +** no side effects and should not depend on any values other than its +** input parameters. The [abs|abs() function] is an example of an +** innocuous function. +** The [load_extension() SQL function] is not innocuous because of its +** side effects. +** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not +** exactly the same. The [random|random() function] is an example of a +** function that is innocuous but not deterministic. +** <p>Some heightened security settings +** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF]) +** disable the use of SQL functions inside views and triggers and in +** schema structures such as [CHECK constraints], [DEFAULT clauses], +** [expression indexes], [partial indexes], and [generated columns] unless +** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions +** are innocuous. Developers are advised to avoid using the +** SQLITE_INNOCUOUS flag for application-defined functions unless the +** function has been carefully audited and found to be free of potentially +** security-adverse side-effects and information-leaks. +** </dd> +** +** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd> +** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call +** [tdsqlite3_value_subtype()] to inspect the sub-types of its arguments. +** Specifying this flag makes no difference for scalar or aggregate user +** functions. However, if it is not specified for a user-defined window +** function, then any sub-types belonging to arguments passed to the window +** function may be discarded before the window function is called (i.e. +** tdsqlite3_value_subtype() will always return 0). +** </dd> +** </dl> */ -#define SQLITE_DETERMINISTIC 0x800 +#define SQLITE_DETERMINISTIC 0x000000800 +#define SQLITE_DIRECTONLY 0x000080000 +#define SQLITE_SUBTYPE 0x000100000 +#define SQLITE_INNOCUOUS 0x000200000 /* ** CAPI3REF: Deprecated Functions @@ -4521,45 +5178,87 @@ SQLITE_API int sqlite3_create_function_v2( ** these functions, we will not explain what they do. */ #ifndef SQLITE_OMIT_DEPRECATED -SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); -SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); -SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), - void*,sqlite3_int64); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_aggregate_count(tdsqlite3_context*); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_expired(tdsqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_transfer_bindings(tdsqlite3_stmt*, tdsqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_global_recover(void); +SQLITE_API SQLITE_DEPRECATED void tdsqlite3_thread_cleanup(void); +SQLITE_API SQLITE_DEPRECATED int tdsqlite3_memory_alarm(void(*)(void*,tdsqlite3_int64,int), + void*,tdsqlite3_int64); #endif /* ** CAPI3REF: Obtaining SQL Values -** METHOD: sqlite3_value -** -** The C-language implementation of SQL functions and aggregates uses -** this set of interface routines to access the parameter values on -** the function or aggregate. -** -** The xFunc (for scalar functions) or xStep (for aggregates) parameters -** to [sqlite3_create_function()] and [sqlite3_create_function16()] -** define callbacks that implement the SQL functions and aggregates. -** The 3rd parameter to these callbacks is an array of pointers to -** [protected sqlite3_value] objects. There is one [sqlite3_value] object for -** each parameter to the SQL function. These routines are used to -** extract values from the [sqlite3_value] objects. -** -** These routines work only with [protected sqlite3_value] objects. -** Any attempt to use these routines on an [unprotected sqlite3_value] -** object results in undefined behavior. +** METHOD: tdsqlite3_value +** +** <b>Summary:</b> +** <blockquote><table border=0 cellpadding=0 cellspacing=0> +** <tr><td><b>tdsqlite3_value_blob</b><td>→<td>BLOB value +** <tr><td><b>tdsqlite3_value_double</b><td>→<td>REAL value +** <tr><td><b>tdsqlite3_value_int</b><td>→<td>32-bit INTEGER value +** <tr><td><b>tdsqlite3_value_int64</b><td>→<td>64-bit INTEGER value +** <tr><td><b>tdsqlite3_value_pointer</b><td>→<td>Pointer value +** <tr><td><b>tdsqlite3_value_text</b><td>→<td>UTF-8 TEXT value +** <tr><td><b>tdsqlite3_value_text16</b><td>→<td>UTF-16 TEXT value in +** the native byteorder +** <tr><td><b>tdsqlite3_value_text16be</b><td>→<td>UTF-16be TEXT value +** <tr><td><b>tdsqlite3_value_text16le</b><td>→<td>UTF-16le TEXT value +** <tr><td> <td> <td> +** <tr><td><b>tdsqlite3_value_bytes</b><td>→<td>Size of a BLOB +** or a UTF-8 TEXT in bytes +** <tr><td><b>tdsqlite3_value_bytes16 </b> +** <td>→ <td>Size of UTF-16 +** TEXT in bytes +** <tr><td><b>tdsqlite3_value_type</b><td>→<td>Default +** datatype of the value +** <tr><td><b>tdsqlite3_value_numeric_type </b> +** <td>→ <td>Best numeric datatype of the value +** <tr><td><b>tdsqlite3_value_nochange </b> +** <td>→ <td>True if the column is unchanged in an UPDATE +** against a virtual table. +** <tr><td><b>tdsqlite3_value_frombind </b> +** <td>→ <td>True if value originated from a [bound parameter] +** </table></blockquote> +** +** <b>Details:</b> +** +** These routines extract type, size, and content information from +** [protected tdsqlite3_value] objects. Protected tdsqlite3_value objects +** are used to pass parameter information into the functions that +** implement [application-defined SQL functions] and [virtual tables]. +** +** These routines work only with [protected tdsqlite3_value] objects. +** Any attempt to use these routines on an [unprotected tdsqlite3_value] +** is not threadsafe. ** ** ^These routines work just like the corresponding [column access functions] -** except that these routines take a single [protected sqlite3_value] object -** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** except that these routines take a single [protected tdsqlite3_value] object +** pointer instead of a [tdsqlite3_stmt*] pointer and an integer column number. ** -** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** ^The tdsqlite3_value_text16() interface extracts a UTF-16 string ** in the native byte-order of the host machine. ^The -** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** tdsqlite3_value_text16be() and tdsqlite3_value_text16le() interfaces ** extract UTF-16 strings as big-endian and little-endian respectively. ** -** ^(The sqlite3_value_numeric_type() interface attempts to apply +** ^If [tdsqlite3_value] object V was initialized +** using [tdsqlite3_bind_pointer(S,I,P,X,D)] or [tdsqlite3_result_pointer(C,P,X,D)] +** and if X and Y are strings that compare equal according to strcmp(X,Y), +** then tdsqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise, +** tdsqlite3_value_pointer(V,Y) returns a NULL. The tdsqlite3_bind_pointer() +** routine is part of the [pointer passing interface] added for SQLite 3.20.0. +** +** ^(The tdsqlite3_value_type(V) interface returns the +** [SQLITE_INTEGER | datatype code] for the initial datatype of the +** [tdsqlite3_value] object V. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^ +** Other interfaces might change the datatype for an tdsqlite3_value object. +** For example, if the datatype is initially SQLITE_INTEGER and +** tdsqlite3_value_text(V) is called to extract a text value for that +** integer, then subsequent calls to tdsqlite3_value_type(V) might return +** SQLITE_TEXT. Whether or not a persistent internal datatype conversion +** occurs is undefined and may change from one release of SQLite to the next. +** +** ^(The tdsqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other @@ -4567,136 +5266,175 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6 ** then the conversion is performed. Otherwise no conversion occurs. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ ** +** ^Within the [xUpdate] method of a [virtual table], the +** tdsqlite3_value_nochange(X) interface returns true if and only if +** the column corresponding to X is unchanged by the UPDATE operation +** that the xUpdate method call was invoked to implement and if +** and the prior [xColumn] method call that was invoked to extracted +** the value for that column returned without setting a result (probably +** because it queried [tdsqlite3_vtab_nochange()] and found that the column +** was unchanging). ^Within an [xUpdate] method, any value for which +** tdsqlite3_value_nochange(X) is true will in all other respects appear +** to be a NULL value. If tdsqlite3_value_nochange(X) is invoked anywhere other +** than within an [xUpdate] method call for an UPDATE statement, then +** the return value is arbitrary and meaningless. +** +** ^The tdsqlite3_value_frombind(X) interface returns non-zero if the +** value X originated from one of the [tdsqlite3_bind_int|tdsqlite3_bind()] +** interfaces. ^If X comes from an SQL literal value, or a table column, +** or an expression, then tdsqlite3_value_frombind(X) returns zero. +** ** Please pay particular attention to the fact that the pointer returned -** from [sqlite3_value_blob()], [sqlite3_value_text()], or -** [sqlite3_value_text16()] can be invalidated by a subsequent call to -** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], -** or [sqlite3_value_text16()]. +** from [tdsqlite3_value_blob()], [tdsqlite3_value_text()], or +** [tdsqlite3_value_text16()] can be invalidated by a subsequent call to +** [tdsqlite3_value_bytes()], [tdsqlite3_value_bytes16()], [tdsqlite3_value_text()], +** or [tdsqlite3_value_text16()]. ** ** These routines must be called from the same thread as -** the SQL function that supplied the [sqlite3_value*] parameters. -*/ -SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); -SQLITE_API int sqlite3_value_bytes(sqlite3_value*); -SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); -SQLITE_API double sqlite3_value_double(sqlite3_value*); -SQLITE_API int sqlite3_value_int(sqlite3_value*); -SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); -SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); -SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); -SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); -SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); -SQLITE_API int sqlite3_value_type(sqlite3_value*); -SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); +** the SQL function that supplied the [tdsqlite3_value*] parameters. +** +** As long as the input parameter is correct, these routines can only +** fail if an out-of-memory error occurs during a format conversion. +** Only the following subset of interfaces are subject to out-of-memory +** errors: +** +** <ul> +** <li> tdsqlite3_value_blob() +** <li> tdsqlite3_value_text() +** <li> tdsqlite3_value_text16() +** <li> tdsqlite3_value_text16le() +** <li> tdsqlite3_value_text16be() +** <li> tdsqlite3_value_bytes() +** <li> tdsqlite3_value_bytes16() +** </ul> +** +** If an out-of-memory error occurs, then the return value from these +** routines is the same as if the column had contained an SQL NULL value. +** Valid SQL NULL returns can be distinguished from out-of-memory errors +** by invoking the [tdsqlite3_errcode()] immediately after the suspect +** return value is obtained and before any +** other SQLite interface is called on the same [database connection]. +*/ +SQLITE_API const void *tdsqlite3_value_blob(tdsqlite3_value*); +SQLITE_API double tdsqlite3_value_double(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_int(tdsqlite3_value*); +SQLITE_API tdsqlite3_int64 tdsqlite3_value_int64(tdsqlite3_value*); +SQLITE_API void *tdsqlite3_value_pointer(tdsqlite3_value*, const char*); +SQLITE_API const unsigned char *tdsqlite3_value_text(tdsqlite3_value*); +SQLITE_API const void *tdsqlite3_value_text16(tdsqlite3_value*); +SQLITE_API const void *tdsqlite3_value_text16le(tdsqlite3_value*); +SQLITE_API const void *tdsqlite3_value_text16be(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_bytes(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_bytes16(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_type(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_numeric_type(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_nochange(tdsqlite3_value*); +SQLITE_API int tdsqlite3_value_frombind(tdsqlite3_value*); /* ** CAPI3REF: Finding The Subtype Of SQL Values -** METHOD: sqlite3_value +** METHOD: tdsqlite3_value ** -** The sqlite3_value_subtype(V) function returns the subtype for +** The tdsqlite3_value_subtype(V) function returns the subtype for ** an [application-defined SQL function] argument V. The subtype ** information can be used to pass a limited amount of context from -** one SQL function to another. Use the [sqlite3_result_subtype()] +** one SQL function to another. Use the [tdsqlite3_result_subtype()] ** routine to set the subtype for the return value of an SQL function. -** -** SQLite makes no use of subtype itself. It merely passes the subtype -** from the result of one [application-defined SQL function] into the -** input of another. */ -SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); +SQLITE_API unsigned int tdsqlite3_value_subtype(tdsqlite3_value*); /* ** CAPI3REF: Copy And Free SQL Values -** METHOD: sqlite3_value +** METHOD: tdsqlite3_value ** -** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] -** object D and returns a pointer to that copy. ^The [sqlite3_value] returned -** is a [protected sqlite3_value] object even if the input is not. -** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a +** ^The tdsqlite3_value_dup(V) interface makes a copy of the [tdsqlite3_value] +** object D and returns a pointer to that copy. ^The [tdsqlite3_value] returned +** is a [protected tdsqlite3_value] object even if the input is not. +** ^The tdsqlite3_value_dup(V) interface returns NULL if V is NULL or if a ** memory allocation fails. ** -** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object -** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer -** then sqlite3_value_free(V) is a harmless no-op. +** ^The tdsqlite3_value_free(V) interface frees an [tdsqlite3_value] object +** previously obtained from [tdsqlite3_value_dup()]. ^If V is a NULL pointer +** then tdsqlite3_value_free(V) is a harmless no-op. */ -SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*); -SQLITE_API void sqlite3_value_free(sqlite3_value*); +SQLITE_API tdsqlite3_value *tdsqlite3_value_dup(const tdsqlite3_value*); +SQLITE_API void tdsqlite3_value_free(tdsqlite3_value*); /* ** CAPI3REF: Obtain Aggregate Function Context -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** ** Implementations of aggregate SQL functions use this ** routine to allocate memory for storing their state. ** -** ^The first time the sqlite3_aggregate_context(C,N) routine is called -** for a particular aggregate function, SQLite -** allocates N of memory, zeroes out that memory, and returns a pointer +** ^The first time the tdsqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite allocates +** N bytes of memory, zeroes out that memory, and returns a pointer ** to the new memory. ^On second and subsequent calls to -** sqlite3_aggregate_context() for the same aggregate function instance, +** tdsqlite3_aggregate_context() for the same aggregate function instance, ** the same buffer is returned. Sqlite3_aggregate_context() is normally ** called once for each invocation of the xStep callback and then one ** last time when the xFinal callback is invoked. ^(When no rows match ** an aggregate query, the xStep() callback of the aggregate function ** implementation is never called and xFinal() is called exactly once. -** In those cases, sqlite3_aggregate_context() might be called for the +** In those cases, tdsqlite3_aggregate_context() might be called for the ** first time from within xFinal().)^ ** -** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer +** ^The tdsqlite3_aggregate_context(C,N) routine returns a NULL pointer ** when first called if N is less than or equal to zero or if a memory ** allocate error occurs. ** -** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** ^(The amount of space allocated by tdsqlite3_aggregate_context(C,N) is ** determined by the N parameter on first successful call. Changing the -** value of N in subsequent call to sqlite3_aggregate_context() within +** value of N in any subsequents call to tdsqlite3_aggregate_context() within ** the same aggregate function instance will not resize the memory ** allocation.)^ Within the xFinal callback, it is customary to set -** N=0 in calls to sqlite3_aggregate_context(C,N) so that no +** N=0 in calls to tdsqlite3_aggregate_context(C,N) so that no ** pointless memory allocations occur. ** ** ^SQLite automatically frees the memory allocated by -** sqlite3_aggregate_context() when the aggregate query concludes. +** tdsqlite3_aggregate_context() when the aggregate query concludes. ** ** The first parameter must be a copy of the -** [sqlite3_context | SQL function context] that is the first parameter +** [tdsqlite3_context | SQL function context] that is the first parameter ** to the xStep or xFinal callback routine that implements the aggregate ** function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. */ -SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); +SQLITE_API void *tdsqlite3_aggregate_context(tdsqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** -** ^The sqlite3_user_data() interface returns a copy of +** ^The tdsqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally +** of the [tdsqlite3_create_function()] +** and [tdsqlite3_create_function16()] routines that originally ** registered the application defined function. ** ** This routine must be called from the same thread in which ** the application-defined function is running. */ -SQLITE_API void *sqlite3_user_data(sqlite3_context*); +SQLITE_API void *tdsqlite3_user_data(tdsqlite3_context*); /* ** CAPI3REF: Database Connection For Functions -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** -** ^The sqlite3_context_db_handle() interface returns a copy of +** ^The tdsqlite3_context_db_handle() interface returns a copy of ** the pointer to the [database connection] (the 1st parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally +** of the [tdsqlite3_create_function()] +** and [tdsqlite3_create_function16()] routines that originally ** registered the application defined function. */ -SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); +SQLITE_API tdsqlite3 *tdsqlite3_context_db_handle(tdsqlite3_context*); /* ** CAPI3REF: Function Auxiliary Data -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** ** These functions may be used by (non-aggregate) SQL functions to ** associate metadata with argument values. If the same value is passed to @@ -4709,52 +5447,57 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); ** the compiled regular expression can be reused on multiple ** invocations of the same function. ** -** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata -** associated by the sqlite3_set_auxdata() function with the Nth argument -** value to the application-defined function. ^If there is no metadata -** associated with the function argument, this sqlite3_get_auxdata() interface +** ^The tdsqlite3_get_auxdata(C,N) interface returns a pointer to the metadata +** associated by the tdsqlite3_set_auxdata(C,N,P,X) function with the Nth argument +** value to the application-defined function. ^N is zero for the left-most +** function argument. ^If there is no metadata +** associated with the function argument, the tdsqlite3_get_auxdata(C,N) interface ** returns a NULL pointer. ** -** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th +** ^The tdsqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th ** argument of the application-defined function. ^Subsequent -** calls to sqlite3_get_auxdata(C,N) return P from the most recent -** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or +** calls to tdsqlite3_get_auxdata(C,N) return P from the most recent +** tdsqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or ** NULL if the metadata has been discarded. -** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, +** ^After each call to tdsqlite3_set_auxdata(C,N,P,X) where X is not NULL, ** SQLite will invoke the destructor function X with parameter P exactly ** once, when the metadata is discarded. ** SQLite is free to discard the metadata at any time, including: <ul> ** <li> ^(when the corresponding function parameter changes)^, or -** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the +** <li> ^(when [tdsqlite3_reset()] or [tdsqlite3_finalize()] is called for the ** SQL statement)^, or -** <li> ^(when sqlite3_set_auxdata() is invoked again on the same +** <li> ^(when tdsqlite3_set_auxdata() is invoked again on the same ** parameter)^, or -** <li> ^(during the original sqlite3_set_auxdata() call when a memory +** <li> ^(during the original tdsqlite3_set_auxdata() call when a memory ** allocation error occurs.)^ </ul> ** ** Note the last bullet in particular. The destructor X in -** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the -** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() +** tdsqlite3_set_auxdata(C,N,P,X) might be called immediately, before the +** tdsqlite3_set_auxdata() interface even returns. Hence tdsqlite3_set_auxdata() ** should be called near the end of the function implementation and the ** function implementation should not make any use of P after -** sqlite3_set_auxdata() has been called. +** tdsqlite3_set_auxdata() has been called. ** ** ^(In practice, metadata is preserved between function calls for ** function parameters that are compile-time constants, including literal ** values and [parameters] and expressions composed from the same.)^ ** +** The value of the N parameter to these interfaces should be non-negative. +** Future enhancements may make use of negative N values to define new +** kinds of function caching behavior. +** ** These routines must be called from the same thread in which ** the SQL function is running. */ -SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); -SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); +SQLITE_API void *tdsqlite3_get_auxdata(tdsqlite3_context*, int N); +SQLITE_API void tdsqlite3_set_auxdata(tdsqlite3_context*, int N, void*, void (*)(void*)); /* ** CAPI3REF: Constants Defining Special Destructor Behavior ** ** These are special values for the destructor that is passed in as the -** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** final argument to routines like [tdsqlite3_result_blob()]. ^If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant ** and will never change. It does not need to be destroyed. ^The ** SQLITE_TRANSIENT value means that the content will likely change in @@ -4764,89 +5507,89 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi ** The typedef is necessary to work around problems in certain ** C++ compilers. */ -typedef void (*sqlite3_destructor_type)(void*); -#define SQLITE_STATIC ((sqlite3_destructor_type)0) -#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) +typedef void (*tdsqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((tdsqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((tdsqlite3_destructor_type)-1) /* ** CAPI3REF: Setting The Result Of An SQL Function -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** ** These routines are used by the xFunc or xFinal callbacks that ** implement SQL functions and aggregates. See -** [sqlite3_create_function()] and [sqlite3_create_function16()] +** [tdsqlite3_create_function()] and [tdsqlite3_create_function16()] ** for additional information. ** ** These functions work very much like the [parameter binding] family of ** functions used to bind values to host parameters in prepared statements. ** Refer to the [SQL parameter] documentation for additional information. ** -** ^The sqlite3_result_blob() interface sets the result from +** ^The tdsqlite3_result_blob() interface sets the result from ** an application-defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the ** third parameter. ** -** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) +** ^The tdsqlite3_result_zeroblob(C,N) and tdsqlite3_result_zeroblob64(C,N) ** interfaces set the result of the application-defined function to be ** a BLOB containing all zero bytes and N bytes in size. ** -** ^The sqlite3_result_double() interface sets the result from +** ^The tdsqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified ** by its 2nd argument. ** -** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** ^The tdsqlite3_result_error() and tdsqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. ** ^SQLite uses the string pointed to by the -** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** 2nd parameter of tdsqlite3_result_error() or tdsqlite3_result_error16() ** as the text of an error message. ^SQLite interprets the error -** message string from sqlite3_result_error() as UTF-8. ^SQLite -** interprets the string from sqlite3_result_error16() as UTF-16 in native -** byte order. ^If the third parameter to sqlite3_result_error() -** or sqlite3_result_error16() is negative then SQLite takes as the error +** message string from tdsqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from tdsqlite3_result_error16() as UTF-16 in native +** byte order. ^If the third parameter to tdsqlite3_result_error() +** or tdsqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. -** ^If the third parameter to sqlite3_result_error() or -** sqlite3_result_error16() is non-negative then SQLite takes that many +** ^If the third parameter to tdsqlite3_result_error() or +** tdsqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. -** ^The sqlite3_result_error() and sqlite3_result_error16() +** ^The tdsqlite3_result_error() and tdsqlite3_result_error16() ** routines make a private copy of the error message text before ** they return. Hence, the calling function can deallocate or ** modify the text after they return without harm. -** ^The sqlite3_result_error_code() function changes the error code +** ^The tdsqlite3_result_error_code() function changes the error code ** returned by SQLite as a result of an error in a function. ^By default, -** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() -** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** the error code is SQLITE_ERROR. ^A subsequent call to tdsqlite3_result_error() +** or tdsqlite3_result_error16() resets the error code to SQLITE_ERROR. ** -** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an +** ^The tdsqlite3_result_error_toobig() interface causes SQLite to throw an ** error indicating that a string or BLOB is too long to represent. ** -** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an +** ^The tdsqlite3_result_error_nomem() interface causes SQLite to throw an ** error indicating that a memory allocation failed. ** -** ^The sqlite3_result_int() interface sets the return value +** ^The tdsqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. -** ^The sqlite3_result_int64() interface sets the return value +** ^The tdsqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** -** ^The sqlite3_result_null() interface sets the return value +** ^The tdsqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** -** ^The sqlite3_result_text(), sqlite3_result_text16(), -** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** ^The tdsqlite3_result_text(), tdsqlite3_result_text16(), +** tdsqlite3_result_text16le(), and tdsqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. -** ^The sqlite3_result_text64() interface sets the return value of an +** ^The tdsqlite3_result_text64() interface sets the return value of an ** application-defined function to be a text string in an encoding ** specified by the fifth (and last) parameter, which must be one ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. ** ^SQLite takes the text result from the application from -** the 2nd parameter of the sqlite3_result_text* interfaces. -** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** the 2nd parameter of the tdsqlite3_result_text* interfaces. +** ^If the 3rd parameter to the tdsqlite3_result_text* interfaces ** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. -** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** ^If the 3rd parameter to the tdsqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. If the 3rd parameter is non-negative, then it @@ -4855,82 +5598,94 @@ typedef void (*sqlite3_destructor_type)(void*); ** in the string at a byte offset that is less than the value of the 3rd ** parameter, then the resulting string will contain embedded NULs and the ** result of expressions operating on strings with embedded NULs is undefined. -** ^If the 4th parameter to the sqlite3_result_text* interfaces -** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** ^If the 4th parameter to the tdsqlite3_result_text* interfaces +** or tdsqlite3_result_blob is a non-NULL pointer, then SQLite calls that ** function as the destructor on the text or BLOB result when it has ** finished using that result. -** ^If the 4th parameter to the sqlite3_result_text* interfaces or to -** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** ^If the 4th parameter to the tdsqlite3_result_text* interfaces or to +** tdsqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite ** assumes that the text or BLOB result is in constant space and does not ** copy the content of the parameter nor call a destructor on the content ** when it has finished using that result. -** ^If the 4th parameter to the sqlite3_result_text* interfaces -** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT -** then SQLite makes a copy of the result into space obtained from -** from [sqlite3_malloc()] before it returns. +** ^If the 4th parameter to the tdsqlite3_result_text* interfaces +** or tdsqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained +** from [tdsqlite3_malloc()] before it returns. ** -** ^The sqlite3_result_value() interface sets the result of +** ^The tdsqlite3_result_value() interface sets the result of ** the application-defined function to be a copy of the -** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The -** sqlite3_result_value() interface makes a copy of the [sqlite3_value] -** so that the [sqlite3_value] specified in the parameter may change or -** be deallocated after sqlite3_result_value() returns without harm. -** ^A [protected sqlite3_value] object may always be used where an -** [unprotected sqlite3_value] object is required, so either -** kind of [sqlite3_value] object can be used with this interface. +** [unprotected tdsqlite3_value] object specified by the 2nd parameter. ^The +** tdsqlite3_result_value() interface makes a copy of the [tdsqlite3_value] +** so that the [tdsqlite3_value] specified in the parameter may change or +** be deallocated after tdsqlite3_result_value() returns without harm. +** ^A [protected tdsqlite3_value] object may always be used where an +** [unprotected tdsqlite3_value] object is required, so either +** kind of [tdsqlite3_value] object can be used with this interface. +** +** ^The tdsqlite3_result_pointer(C,P,T,D) interface sets the result to an +** SQL NULL value, just like [tdsqlite3_result_null(C)], except that it +** also associates the host-language pointer P or type T with that +** NULL value such that the pointer can be retrieved within an +** [application-defined SQL function] using [tdsqlite3_value_pointer()]. +** ^If the D parameter is not NULL, then it is a pointer to a destructor +** for the P parameter. ^SQLite invokes D with P as its only argument +** when SQLite is finished with P. The T parameter should be a static +** string and preferably a string literal. The tdsqlite3_result_pointer() +** routine is part of the [pointer passing interface] added for SQLite 3.20.0. ** ** If these routines are called from within the different thread ** than the one containing the application-defined function that received -** the [sqlite3_context] pointer, the results are undefined. -*/ -SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*, - sqlite3_uint64,void(*)(void*)); -SQLITE_API void sqlite3_result_double(sqlite3_context*, double); -SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); -SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); -SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); -SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); -SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); -SQLITE_API void sqlite3_result_int(sqlite3_context*, int); -SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); -SQLITE_API void sqlite3_result_null(sqlite3_context*); -SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, +** the [tdsqlite3_context] pointer, the results are undefined. +*/ +SQLITE_API void tdsqlite3_result_blob(tdsqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void tdsqlite3_result_blob64(tdsqlite3_context*,const void*, + tdsqlite3_uint64,void(*)(void*)); +SQLITE_API void tdsqlite3_result_double(tdsqlite3_context*, double); +SQLITE_API void tdsqlite3_result_error(tdsqlite3_context*, const char*, int); +SQLITE_API void tdsqlite3_result_error16(tdsqlite3_context*, const void*, int); +SQLITE_API void tdsqlite3_result_error_toobig(tdsqlite3_context*); +SQLITE_API void tdsqlite3_result_error_nomem(tdsqlite3_context*); +SQLITE_API void tdsqlite3_result_error_code(tdsqlite3_context*, int); +SQLITE_API void tdsqlite3_result_int(tdsqlite3_context*, int); +SQLITE_API void tdsqlite3_result_int64(tdsqlite3_context*, tdsqlite3_int64); +SQLITE_API void tdsqlite3_result_null(tdsqlite3_context*); +SQLITE_API void tdsqlite3_result_text(tdsqlite3_context*, const char*, int, void(*)(void*)); +SQLITE_API void tdsqlite3_result_text64(tdsqlite3_context*, const char*,tdsqlite3_uint64, void(*)(void*), unsigned char encoding); -SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); -SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); -SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); -SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); -SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); +SQLITE_API void tdsqlite3_result_text16(tdsqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void tdsqlite3_result_text16le(tdsqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void tdsqlite3_result_text16be(tdsqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void tdsqlite3_result_value(tdsqlite3_context*, tdsqlite3_value*); +SQLITE_API void tdsqlite3_result_pointer(tdsqlite3_context*, void*,const char*,void(*)(void*)); +SQLITE_API void tdsqlite3_result_zeroblob(tdsqlite3_context*, int n); +SQLITE_API int tdsqlite3_result_zeroblob64(tdsqlite3_context*, tdsqlite3_uint64 n); /* ** CAPI3REF: Setting The Subtype Of An SQL Function -** METHOD: sqlite3_context +** METHOD: tdsqlite3_context ** -** The sqlite3_result_subtype(C,T) function causes the subtype of +** The tdsqlite3_result_subtype(C,T) function causes the subtype of ** the result from the [application-defined SQL function] with -** [sqlite3_context] C to be the value T. Only the lower 8 bits +** [tdsqlite3_context] C to be the value T. Only the lower 8 bits ** of the subtype T are preserved in current versions of SQLite; ** higher order bits are discarded. ** The number of subtype bytes preserved by SQLite might increase ** in future releases of SQLite. */ -SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); +SQLITE_API void tdsqlite3_result_subtype(tdsqlite3_context*,unsigned int); /* ** CAPI3REF: Define New Collating Sequences -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^These functions add, remove, or modify a [collation] associated ** with the [database connection] specified as the first argument. ** ** ^The name of the collation is a UTF-8 string -** for sqlite3_create_collation() and sqlite3_create_collation_v2() -** and a UTF-16 string in native byte order for sqlite3_create_collation16(). -** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** for tdsqlite3_create_collation() and tdsqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for tdsqlite3_create_collation16(). +** ^Collation names that compare equal according to [tdsqlite3_strnicmp()] are ** considered to be the same name. ** ** ^(The third argument (eTextRep) must be one of the constants: @@ -4942,7 +5697,7 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); ** <li> [SQLITE_UTF16_ALIGNED]. ** </ul>)^ ** ^The eTextRep argument determines the encoding of strings passed -** to the collating function callback, xCallback. +** to the collating function callback, xCompare. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep ** force strings to be UTF16 with native byte order. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin @@ -4951,18 +5706,19 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); ** ^The fourth argument, pArg, is an application data pointer that is passed ** through as the first argument to the collating function callback. ** -** ^The fifth argument, xCallback, is a pointer to the collating function. +** ^The fifth argument, xCompare, is a pointer to the collating function. ** ^Multiple collating functions can be registered using the same name but ** with different eTextRep parameters and SQLite will use whichever ** function requires the least amount of data transformation. -** ^If the xCallback argument is NULL then the collating function is +** ^If the xCompare argument is NULL then the collating function is ** deleted. ^When all collating functions having the same name are deleted, ** that collation is no longer usable. ** ** ^The collating function callback is invoked with a copy of the pArg ** application data pointer and with two strings in the encoding specified -** by the eTextRep argument. The collating function must return an -** integer that is negative, zero, or positive +** by the eTextRep argument. The two integer parameters to the collating +** function callback are the length of the two strings, in bytes. The collating +** function must return an integer that is negative, zero, or positive ** if the first string is less than, equal to, or greater than the second, ** respectively. A collating function must always return the same answer ** given the same inputs. If two or more collating functions are registered @@ -4979,44 +5735,44 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); ** </ol> ** ** If a collating function fails any of the above constraints and that -** collating function is registered and used, then the behavior of SQLite +** collating function is registered and used, then the behavior of SQLite ** is undefined. ** -** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** ^The tdsqlite3_create_collation_v2() works like tdsqlite3_create_collation() ** with the addition that the xDestroy callback is invoked on pArg when ** the collating function is deleted. ** ^Collating functions are deleted when they are overridden by later ** calls to the collation creation functions or when the -** [database connection] is closed using [sqlite3_close()]. +** [database connection] is closed using [tdsqlite3_close()]. ** ** ^The xDestroy callback is <u>not</u> called if the -** sqlite3_create_collation_v2() function fails. Applications that invoke -** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** tdsqlite3_create_collation_v2() function fails. Applications that invoke +** tdsqlite3_create_collation_v2() with a non-NULL xDestroy argument should ** check the return code and dispose of the application data pointer ** themselves rather than expecting SQLite to deal with it for them. ** This is different from every other SQLite interface. The inconsistency ** is unfortunate but cannot be changed without breaking backwards ** compatibility. ** -** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +** See also: [tdsqlite3_collation_needed()] and [tdsqlite3_collation_needed16()]. */ -SQLITE_API int sqlite3_create_collation( - sqlite3*, +SQLITE_API int tdsqlite3_create_collation( + tdsqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*) ); -SQLITE_API int sqlite3_create_collation_v2( - sqlite3*, +SQLITE_API int tdsqlite3_create_collation_v2( + tdsqlite3*, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDestroy)(void*) ); -SQLITE_API int sqlite3_create_collation16( - sqlite3*, +SQLITE_API int tdsqlite3_create_collation16( + tdsqlite3*, const void *zName, int eTextRep, void *pArg, @@ -5025,56 +5781,56 @@ SQLITE_API int sqlite3_create_collation16( /* ** CAPI3REF: Collation Needed Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the ** [database connection] to be invoked whenever an undefined collation ** sequence is required. ** -** ^If the function is registered using the sqlite3_collation_needed() API, +** ^If the function is registered using the tdsqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings -** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** encoded in UTF-8. ^If tdsqlite3_collation_needed16() is used, ** the names are passed as UTF-16 in machine native byte order. ** ^A call to either function replaces the existing collation-needed callback. ** ** ^(When the callback is invoked, the first argument passed is a copy -** of the second argument to sqlite3_collation_needed() or -** sqlite3_collation_needed16(). The second argument is the database +** of the second argument to tdsqlite3_collation_needed() or +** tdsqlite3_collation_needed16(). The second argument is the database ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation ** sequence function required. The fourth parameter is the name of the ** required collation sequence.)^ ** ** The callback function should register the desired collation using -** [sqlite3_create_collation()], [sqlite3_create_collation16()], or -** [sqlite3_create_collation_v2()]. +** [tdsqlite3_create_collation()], [tdsqlite3_create_collation16()], or +** [tdsqlite3_create_collation_v2()]. */ -SQLITE_API int sqlite3_collation_needed( - sqlite3*, +SQLITE_API int tdsqlite3_collation_needed( + tdsqlite3*, void*, - void(*)(void*,sqlite3*,int eTextRep,const char*) + void(*)(void*,tdsqlite3*,int eTextRep,const char*) ); -SQLITE_API int sqlite3_collation_needed16( - sqlite3*, +SQLITE_API int tdsqlite3_collation_needed16( + tdsqlite3*, void*, - void(*)(void*,sqlite3*,int eTextRep,const void*) + void(*)(void*,tdsqlite3*,int eTextRep,const void*) ); #ifdef SQLITE_HAS_CODEC /* ** Specify the key for an encrypted database. This routine should be -** called right after sqlite3_open(). +** called right after tdsqlite3_open(). ** ** The code to implement this API is not available in the public release ** of SQLite. */ -SQLITE_API int sqlite3_key( - sqlite3 *db, /* Database to be rekeyed */ +SQLITE_API int tdsqlite3_key( + tdsqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The key */ ); -SQLITE_API int sqlite3_key_v2( - sqlite3 *db, /* Database to be rekeyed */ +SQLITE_API int tdsqlite3_key_v2( + tdsqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The key */ ); @@ -5087,12 +5843,28 @@ SQLITE_API int sqlite3_key_v2( ** The code to implement this API is not available in the public release ** of SQLite. */ -SQLITE_API int sqlite3_rekey( - sqlite3 *db, /* Database to be rekeyed */ +/* BEGIN SQLCIPHER + SQLCipher usage note: + + If the current database is plaintext SQLCipher will NOT encrypt it. + If the current database is encrypted and pNew==0 or nNew==0, SQLCipher + will NOT decrypt it. + + This routine will ONLY work on an already encrypted database in order + to change the key. + + Conversion from plaintext-to-encrypted or encrypted-to-plaintext should + use an ATTACHed database and the sqlcipher_export() convenience function + as per the SQLCipher Documentation. + + END SQLCIPHER +*/ +SQLITE_API int tdsqlite3_rekey( + tdsqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The new key */ ); -SQLITE_API int sqlite3_rekey_v2( - sqlite3 *db, /* Database to be rekeyed */ +SQLITE_API int tdsqlite3_rekey_v2( + tdsqlite3 *db, /* Database to be rekeyed */ const char *zDbName, /* Name of the database */ const void *pKey, int nKey /* The new key */ ); @@ -5101,7 +5873,7 @@ SQLITE_API int sqlite3_rekey_v2( ** Specify the activation key for a SEE database. Unless ** activated, none of the SEE routines will work. */ -SQLITE_API void sqlite3_activate_see( +SQLITE_API void tdsqlite3_activate_see( const char *zPassPhrase /* Activation phrase */ ); #endif @@ -5111,7 +5883,7 @@ SQLITE_API void sqlite3_activate_see( ** Specify the activation key for a CEROD database. Unless ** activated, none of the CEROD routines will work. */ -SQLITE_API void sqlite3_activate_cerod( +SQLITE_API void tdsqlite3_activate_cerod( const char *zPassPhrase /* Activation phrase */ ); #endif @@ -5119,7 +5891,7 @@ SQLITE_API void sqlite3_activate_cerod( /* ** CAPI3REF: Suspend Execution For A Short Time ** -** The sqlite3_sleep() function causes the current thread to suspend execution +** The tdsqlite3_sleep() function causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** ** If the operating system does not support sleep requests with @@ -5128,19 +5900,19 @@ SQLITE_API void sqlite3_activate_cerod( ** requested from the operating system is returned. ** ** ^SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. If the xSleep() method +** method of the default [tdsqlite3_vfs] object. If the xSleep() method ** of the default VFS is not implemented correctly, or not implemented at -** all, then the behavior of sqlite3_sleep() may deviate from the description +** all, then the behavior of tdsqlite3_sleep() may deviate from the description ** in the previous paragraphs. */ -SQLITE_API int sqlite3_sleep(int); +SQLITE_API int tdsqlite3_sleep(int); /* ** CAPI3REF: Name Of The Folder Holding Temporary Files ** ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all temporary files -** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** created by SQLite when using a built-in [tdsqlite3_vfs | VFS] ** will be placed in that directory.)^ ^If this variable ** is a NULL pointer, then SQLite performs a search for an appropriate ** temporary file directory. @@ -5162,22 +5934,22 @@ SQLITE_API int sqlite3_sleep(int); ** thereafter. ** ** ^The [temp_store_directory pragma] may modify this variable and cause -** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** it to point to memory obtained from [tdsqlite3_malloc]. ^Furthermore, ** the [temp_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from -** [sqlite3_malloc] and the pragma may attempt to free that memory -** using [sqlite3_free]. +** [tdsqlite3_malloc] and the pragma may attempt to free that memory +** using [tdsqlite3_free]. ** Hence, if this variable is modified directly, either it should be -** made NULL or made to point to memory obtained from [sqlite3_malloc] +** made NULL or made to point to memory obtained from [tdsqlite3_malloc] ** or else the use of the [temp_store_directory pragma] should be avoided. ** Except when requested by the [temp_store_directory pragma], SQLite -** does not free the memory that sqlite3_temp_directory points to. If +** does not free the memory that tdsqlite3_temp_directory points to. If ** the application wants that memory to be freed, it must do ** so itself, taking care to only do so after all [database connection] ** objects have been destroyed. ** ** <b>Note to Windows Runtime users:</b> The temporary directory must be set -** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various +** prior to calling [tdsqlite3_open] or [tdsqlite3_open_v2]. Otherwise, various ** features that require the use of temporary files may fail. Here is an ** example of how to do this using C++ with the Windows Runtime: ** @@ -5188,10 +5960,10 @@ SQLITE_API int sqlite3_sleep(int); ** memset(zPathBuf, 0, sizeof(zPathBuf)); ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf), ** NULL, NULL); -** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf); +** tdsqlite3_temp_directory = tdsqlite3_mprintf("%s", zPathBuf); ** </pre></blockquote> */ -SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; +SQLITE_API SQLITE_EXTERN char *tdsqlite3_temp_directory; /* ** CAPI3REF: Name Of The Folder Holding Database Files @@ -5199,7 +5971,7 @@ SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; ** ^(If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all database files ** specified with a relative pathname and created or accessed by -** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed +** SQLite when using a built-in windows [tdsqlite3_vfs | VFS] will be assumed ** to be relative to that directory.)^ ^If this variable is a NULL ** pointer, then SQLite assumes that all database files specified ** with a relative pathname are relative to the current directory @@ -5219,23 +5991,58 @@ SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; ** thereafter. ** ** ^The [data_store_directory pragma] may modify this variable and cause -** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** it to point to memory obtained from [tdsqlite3_malloc]. ^Furthermore, ** the [data_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from -** [sqlite3_malloc] and the pragma may attempt to free that memory -** using [sqlite3_free]. +** [tdsqlite3_malloc] and the pragma may attempt to free that memory +** using [tdsqlite3_free]. ** Hence, if this variable is modified directly, either it should be -** made NULL or made to point to memory obtained from [sqlite3_malloc] +** made NULL or made to point to memory obtained from [tdsqlite3_malloc] ** or else the use of the [data_store_directory pragma] should be avoided. */ -SQLITE_API SQLITE_EXTERN char *sqlite3_data_directory; +SQLITE_API SQLITE_EXTERN char *tdsqlite3_data_directory; + +/* +** CAPI3REF: Win32 Specific Interface +** +** These interfaces are available only on Windows. The +** [tdsqlite3_win32_set_directory] interface is used to set the value associated +** with the [tdsqlite3_temp_directory] or [tdsqlite3_data_directory] variable, to +** zValue, depending on the value of the type parameter. The zValue parameter +** should be NULL to cause the previous value to be freed via [tdsqlite3_free]; +** a non-NULL value will be copied into memory obtained from [tdsqlite3_malloc] +** prior to being used. The [tdsqlite3_win32_set_directory] interface returns +** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported, +** or [SQLITE_NOMEM] if memory could not be allocated. The value of the +** [tdsqlite3_data_directory] variable is intended to act as a replacement for +** the current directory on the sub-platforms of Win32 where that concept is +** not present, e.g. WinRT and UWP. The [tdsqlite3_win32_set_directory8] and +** [tdsqlite3_win32_set_directory16] interfaces behave exactly the same as the +** tdsqlite3_win32_set_directory interface except the string parameter must be +** UTF-8 or UTF-16, respectively. +*/ +SQLITE_API int tdsqlite3_win32_set_directory( + unsigned long type, /* Identifier for directory being set or reset */ + void *zValue /* New value for directory being set or reset */ +); +SQLITE_API int tdsqlite3_win32_set_directory8(unsigned long type, const char *zValue); +SQLITE_API int tdsqlite3_win32_set_directory16(unsigned long type, const void *zValue); + +/* +** CAPI3REF: Win32 Directory Types +** +** These macros are only available on Windows. They define the allowed values +** for the type argument to the [tdsqlite3_win32_set_directory] interface. +*/ +#define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1 +#define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2 /* ** CAPI3REF: Test For Auto-Commit Mode ** KEYWORDS: {autocommit mode} -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_get_autocommit() interface returns non-zero or +** ^The tdsqlite3_get_autocommit() interface returns non-zero or ** zero if the given database connection is or is not in autocommit mode, ** respectively. ^Autocommit mode is on by default. ** ^Autocommit mode is disabled by a [BEGIN] statement. @@ -5252,51 +6059,66 @@ SQLITE_API SQLITE_EXTERN char *sqlite3_data_directory; ** connection while this routine is running, then the return value ** is undefined. */ -SQLITE_API int sqlite3_get_autocommit(sqlite3*); +SQLITE_API int tdsqlite3_get_autocommit(tdsqlite3*); /* ** CAPI3REF: Find The Database Handle Of A Prepared Statement -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^The sqlite3_db_handle interface returns the [database connection] handle +** ^The tdsqlite3_db_handle interface returns the [database connection] handle ** to which a [prepared statement] belongs. ^The [database connection] -** returned by sqlite3_db_handle is the same [database connection] +** returned by tdsqlite3_db_handle is the same [database connection] ** that was the first argument -** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** to the [tdsqlite3_prepare_v2()] call (or its variants) that was used to ** create the statement in the first place. */ -SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); +SQLITE_API tdsqlite3 *tdsqlite3_db_handle(tdsqlite3_stmt*); /* ** CAPI3REF: Return The Filename For A Database Connection -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename -** associated with database N of connection D. ^The main database file -** has the name "main". If there is no attached database N on the database +** ^The tdsqlite3_db_filename(D,N) interface returns a pointer to the filename +** associated with database N of connection D. +** ^If there is no attached database N on the database ** connection D, or if database N is a temporary or in-memory database, then -** a NULL pointer is returned. +** this function will return either a NULL pointer or an empty string. +** +** ^The string value returned by this routine is owned and managed by +** the database connection. ^The value will be valid until the database N +** is [DETACH]-ed or until the database connection closes. ** ** ^The filename returned by this function is the output of the ** xFullPathname method of the [VFS]. ^In other words, the filename ** will be an absolute pathname, even if the filename used ** to open the database originally was a URI or relative pathname. +** +** If the filename pointer returned by this routine is not NULL, then it +** can be used as the filename input parameter to these routines: +** <ul> +** <li> [tdsqlite3_uri_parameter()] +** <li> [tdsqlite3_uri_boolean()] +** <li> [tdsqlite3_uri_int64()] +** <li> [tdsqlite3_filename_database()] +** <li> [tdsqlite3_filename_journal()] +** <li> [tdsqlite3_filename_wal()] +** </ul> */ -SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); +SQLITE_API const char *tdsqlite3_db_filename(tdsqlite3 *db, const char *zDbName); /* ** CAPI3REF: Determine if a database is read-only -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N +** ^The tdsqlite3_db_readonly(D,N) interface returns 1 if the database N ** of connection D is read-only, 0 if it is read/write, or -1 if N is not ** the name of a database on connection D. */ -SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); +SQLITE_API int tdsqlite3_db_readonly(tdsqlite3 *db, const char *zDbName); /* ** CAPI3REF: Find the next prepared statement -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This interface returns a pointer to the next [prepared statement] after ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL @@ -5305,28 +6127,28 @@ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); ** satisfies the conditions of this routine, it returns NULL. ** ** The [database connection] pointer D in a call to -** [sqlite3_next_stmt(D,S)] must refer to an open database +** [tdsqlite3_next_stmt(D,S)] must refer to an open database ** connection and in particular must not be a NULL pointer. */ -SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); +SQLITE_API tdsqlite3_stmt *tdsqlite3_next_stmt(tdsqlite3 *pDb, tdsqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_commit_hook() interface registers a callback +** ^The tdsqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is [COMMIT | committed]. -** ^Any callback set by a previous call to sqlite3_commit_hook() +** ^Any callback set by a previous call to tdsqlite3_commit_hook() ** for the same database connection is overridden. -** ^The sqlite3_rollback_hook() interface registers a callback +** ^The tdsqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. -** ^Any callback set by a previous call to sqlite3_rollback_hook() +** ^Any callback set by a previous call to tdsqlite3_rollback_hook() ** for the same database connection is overridden. ** ^The pArg argument is passed through to the callback. ** ^If the callback on a commit hook function returns non-zero, ** then the commit is converted into a rollback. ** -** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** ^The tdsqlite3_commit_hook(D,C,P) and tdsqlite3_rollback_hook(D,C,P) functions ** return the P argument from the previous call of the same function ** on the same [database connection] D, or NULL for ** the first call for each function on D. @@ -5335,10 +6157,10 @@ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); ** The callback implementation must not do anything that will modify ** the database connection that invoked the callback. Any actions ** to modify the database connection must be deferred until after the -** completion of the [sqlite3_step()] call that triggered the commit +** completion of the [tdsqlite3_step()] call that triggered the commit ** or rollback hook in the first place. ** Note that running any other SQL statements, including SELECT statements, -** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify +** or merely calling [tdsqlite3_prepare_v2()] and [tdsqlite3_step()] will modify ** the database connections for the meaning of "modify" in this paragraph. ** ** ^Registering a NULL function disables the callback. @@ -5355,16 +6177,16 @@ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); ** ^The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. ** -** See also the [sqlite3_update_hook()] interface. +** See also the [tdsqlite3_update_hook()] interface. */ -SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); -SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); +SQLITE_API void *tdsqlite3_commit_hook(tdsqlite3*, int(*)(void*), void*); +SQLITE_API void *tdsqlite3_rollback_hook(tdsqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_update_hook() interface registers a callback function +** ^The tdsqlite3_update_hook() interface registers a callback function ** with the [database connection] identified by the first argument ** to be invoked whenever a row is updated, inserted or deleted in ** a [rowid table]. @@ -5374,7 +6196,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); ** ^The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted in a rowid table. ** ^The first argument to the callback is a copy of the third argument -** to sqlite3_update_hook(). +** to tdsqlite3_update_hook(). ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], ** or [SQLITE_UPDATE], depending on the operation that caused the callback ** to be invoked. @@ -5388,7 +6210,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. ** ** ^In the current implementation, the update hook -** is not invoked when duplication rows are deleted because of an +** is not invoked when conflicting rows are deleted because of an ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook ** invoked when rows are deleted using the [truncate optimization]. ** The exceptions defined in this paragraph might change in a future @@ -5397,21 +6219,21 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); ** The update hook implementation must not do anything that will modify ** the database connection that invoked the update hook. Any actions ** to modify the database connection must be deferred until after the -** completion of the [sqlite3_step()] call that triggered the update hook. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** completion of the [tdsqlite3_step()] call that triggered the update hook. +** Note that [tdsqlite3_prepare_v2()] and [tdsqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** -** ^The sqlite3_update_hook(D,C,P) function +** ^The tdsqlite3_update_hook(D,C,P) function ** returns the P argument from the previous call ** on the same [database connection] D, or NULL for ** the first call on D. ** -** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()], -** and [sqlite3_preupdate_hook()] interfaces. +** See also the [tdsqlite3_commit_hook()], [tdsqlite3_rollback_hook()], +** and [tdsqlite3_preupdate_hook()] interfaces. */ -SQLITE_API void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), +SQLITE_API void *tdsqlite3_update_hook( + tdsqlite3*, + void(*)(void *,int ,char const *,char const *,tdsqlite3_int64), void* ); @@ -5429,63 +6251,70 @@ SQLITE_API void *sqlite3_update_hook( ** sharing was enabled or disabled for each thread separately. ** ** ^(The cache sharing mode set by this interface effects all subsequent -** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. -** Existing database connections continue use the sharing mode +** calls to [tdsqlite3_open()], [tdsqlite3_open_v2()], and [tdsqlite3_open16()]. +** Existing database connections continue to use the sharing mode ** that was in effect at the time they were opened.)^ ** ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled ** successfully. An [error code] is returned otherwise.)^ ** -** ^Shared cache is disabled by default. But this might change in -** future releases of SQLite. Applications that care about shared -** cache setting should set it explicitly. +** ^Shared cache is disabled by default. It is recommended that it stay +** that way. In other words, do not use this routine. This interface +** continues to be provided for historical compatibility, but its use is +** discouraged. Any use of shared cache is discouraged. If shared cache +** must be used, it is recommended that shared cache only be enabled for +** individual database connections using the [tdsqlite3_open_v2()] interface +** with the [SQLITE_OPEN_SHAREDCACHE] flag. ** ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 ** and will always return SQLITE_MISUSE. On those systems, ** shared cache mode should be enabled per-database connection via -** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. +** [tdsqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. ** ** This interface is threadsafe on processors where writing a ** 32-bit integer is atomic. ** ** See Also: [SQLite Shared-Cache Mode] */ -SQLITE_API int sqlite3_enable_shared_cache(int); +SQLITE_API int tdsqlite3_enable_shared_cache(int); /* ** CAPI3REF: Attempt To Free Heap Memory ** -** ^The sqlite3_release_memory() interface attempts to free N bytes +** ^The tdsqlite3_release_memory() interface attempts to free N bytes ** of heap memory by deallocating non-essential memory allocations ** held by the database library. Memory used to cache database ** pages to improve performance is an example of non-essential memory. -** ^sqlite3_release_memory() returns the number of bytes actually freed, +** ^tdsqlite3_release_memory() returns the number of bytes actually freed, ** which might be more or less than the amount requested. -** ^The sqlite3_release_memory() routine is a no-op returning zero +** ^The tdsqlite3_release_memory() routine is a no-op returning zero ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. ** -** See also: [sqlite3_db_release_memory()] +** See also: [tdsqlite3_db_release_memory()] */ -SQLITE_API int sqlite3_release_memory(int); +SQLITE_API int tdsqlite3_release_memory(int); /* ** CAPI3REF: Free Memory Used By A Database Connection -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap +** ^The tdsqlite3_db_release_memory(D) interface attempts to free as much heap ** memory as possible from database connection D. Unlike the -** [sqlite3_release_memory()] interface, this interface is in effect even +** [tdsqlite3_release_memory()] interface, this interface is in effect even ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is ** omitted. ** -** See also: [sqlite3_release_memory()] +** See also: [tdsqlite3_release_memory()] */ -SQLITE_API int sqlite3_db_release_memory(sqlite3*); +SQLITE_API int tdsqlite3_db_release_memory(tdsqlite3*); /* ** CAPI3REF: Impose A Limit On Heap Size ** -** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** These interfaces impose limits on the amount of heap memory that will be +** by all database connections within a single process. +** +** ^The tdsqlite3_soft_heap_limit64() interface sets and/or queries the ** soft limit on the amount of heap memory that may be allocated by SQLite. ** ^SQLite strives to keep heap memory utilization below the soft heap ** limit by reducing the number of pages held in the page cache @@ -5495,73 +6324,86 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*); ** an [SQLITE_NOMEM] error. In other words, the soft heap limit ** is advisory only. ** -** ^The return value from sqlite3_soft_heap_limit64() is the size of -** the soft heap limit prior to the call, or negative in the case of an -** error. ^If the argument N is negative -** then no change is made to the soft heap limit. Hence, the current -** size of the soft heap limit can be determined by invoking -** sqlite3_soft_heap_limit64() with a negative argument. -** -** ^If the argument N is zero then the soft heap limit is disabled. +** ^The tdsqlite3_hard_heap_limit64(N) interface sets a hard upper bound of +** N bytes on the amount of memory that will be allocated. ^The +** tdsqlite3_hard_heap_limit64(N) interface is similar to +** tdsqlite3_soft_heap_limit64(N) except that memory allocations will fail +** when the hard heap limit is reached. ** -** ^(The soft heap limit is not enforced in the current implementation +** ^The return value from both tdsqlite3_soft_heap_limit64() and +** tdsqlite3_hard_heap_limit64() is the size of +** the heap limit prior to the call, or negative in the case of an +** error. ^If the argument N is negative +** then no change is made to the heap limit. Hence, the current +** size of heap limits can be determined by invoking +** tdsqlite3_soft_heap_limit64(-1) or tdsqlite3_hard_heap_limit(-1). +** +** ^Setting the heap limits to zero disables the heap limiter mechanism. +** +** ^The soft heap limit may not be greater than the hard heap limit. +** ^If the hard heap limit is enabled and if tdsqlite3_soft_heap_limit(N) +** is invoked with a value of N that is greater than the hard heap limit, +** the the soft heap limit is set to the value of the hard heap limit. +** ^The soft heap limit is automatically enabled whenever the hard heap +** limit is enabled. ^When tdsqlite3_hard_heap_limit64(N) is invoked and +** the soft heap limit is outside the range of 1..N, then the soft heap +** limit is set to N. ^Invoking tdsqlite3_soft_heap_limit64(0) when the +** hard heap limit is enabled makes the soft heap limit equal to the +** hard heap limit. +** +** The memory allocation limits can also be adjusted using +** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit]. +** +** ^(The heap limits are not enforced in the current implementation ** if one or more of following conditions are true: ** ** <ul> -** <li> The soft heap limit is set to zero. +** <li> The limit value is set to zero. ** <li> Memory accounting is disabled using a combination of the -** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** [tdsqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. ** <li> An alternative page cache implementation is specified using -** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). +** [tdsqlite3_config]([SQLITE_CONFIG_PCACHE2],...). ** <li> The page cache allocates from its own memory pool supplied -** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** by [tdsqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than ** from the heap. ** </ul>)^ ** -** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), -** the soft heap limit is enforced -** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] -** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], -** the soft heap limit is enforced on every memory allocation. Without -** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced -** when memory is allocated by the page cache. Testing suggests that because -** the page cache is the predominate memory user in SQLite, most -** applications will achieve adequate soft heap limit enforcement without -** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. -** -** The circumstances under which SQLite will enforce the soft heap limit may +** The circumstances under which SQLite will enforce the heap limits may ** changes in future releases of SQLite. */ -SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); +SQLITE_API tdsqlite3_int64 tdsqlite3_soft_heap_limit64(tdsqlite3_int64 N); +SQLITE_API tdsqlite3_int64 tdsqlite3_hard_heap_limit64(tdsqlite3_int64 N); /* ** CAPI3REF: Deprecated Soft Heap Limit Interface ** DEPRECATED ** -** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** This is a deprecated version of the [tdsqlite3_soft_heap_limit64()] ** interface. This routine is provided for historical compatibility ** only. All new applications should use the -** [sqlite3_soft_heap_limit64()] interface rather than this one. +** [tdsqlite3_soft_heap_limit64()] interface rather than this one. */ -SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); +SQLITE_API SQLITE_DEPRECATED void tdsqlite3_soft_heap_limit(int N); /* ** CAPI3REF: Extract Metadata About A Column Of A Table -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns +** ^(The tdsqlite3_table_column_metadata(X,D,T,C,....) routine returns ** information about column C of table T in database D -** on [database connection] X.)^ ^The sqlite3_table_column_metadata() +** on [database connection] X.)^ ^The tdsqlite3_table_column_metadata() ** interface returns SQLITE_OK and fills in the non-NULL pointers in ** the final five arguments with appropriate values if the specified -** column exists. ^The sqlite3_table_column_metadata() interface returns -** SQLITE_ERROR and if the specified column does not exist. -** ^If the column-name parameter to sqlite3_table_column_metadata() is a +** column exists. ^The tdsqlite3_table_column_metadata() interface returns +** SQLITE_ERROR if the specified column does not exist. +** ^If the column-name parameter to tdsqlite3_table_column_metadata() is a ** NULL pointer, then this routine simply checks for the existence of the ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it -** does not. +** does not. If the table name parameter T in a call to +** tdsqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is +** undefined behavior. ** ** ^The column is identified by the second, third and fourth parameters to ** this function. ^(The second parameter is either the name of the database @@ -5614,8 +6456,8 @@ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); ** parsed, if that has not already been done, and returns an error if ** any errors are encountered while loading the schema. */ -SQLITE_API int sqlite3_table_column_metadata( - sqlite3 *db, /* Connection handle */ +SQLITE_API int tdsqlite3_table_column_metadata( + tdsqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ @@ -5628,11 +6470,11 @@ SQLITE_API int sqlite3_table_column_metadata( /* ** CAPI3REF: Load An Extension -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This interface loads an SQLite extension library from the named file. ** -** ^The sqlite3_load_extension() interface attempts to load an +** ^The tdsqlite3_load_extension() interface attempts to load an ** [SQLite extension] library contained in the file zFile. If ** the file cannot be loaded directly, attempts are made to load ** with various operating-system specific extensions added. @@ -5642,36 +6484,36 @@ SQLITE_API int sqlite3_table_column_metadata( ** ** ^The entry point is zProc. ** ^(zProc may be 0, in which case SQLite will try to come up with an -** entry point name on its own. It first tries "sqlite3_extension_init". -** If that does not work, it constructs a name "sqlite3_X_init" where the +** entry point name on its own. It first tries "tdsqlite3_extension_init". +** If that does not work, it constructs a name "tdsqlite3_X_init" where the ** X is consists of the lower-case equivalent of all ASCII alphabetic ** characters in the filename from the last "/" to the first following ** "." and omitting any initial "lib".)^ -** ^The sqlite3_load_extension() interface returns +** ^The tdsqlite3_load_extension() interface returns ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ^If an error occurs and pzErrMsg is not 0, then the -** [sqlite3_load_extension()] interface shall attempt to +** [tdsqlite3_load_extension()] interface shall attempt to ** fill *pzErrMsg with error message text stored in memory -** obtained from [sqlite3_malloc()]. The calling function -** should free this memory by calling [sqlite3_free()]. +** obtained from [tdsqlite3_malloc()]. The calling function +** should free this memory by calling [tdsqlite3_free()]. ** ** ^Extension loading must be enabled using -** [sqlite3_enable_load_extension()] or -** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) +** [tdsqlite3_enable_load_extension()] or +** [tdsqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) ** prior to calling this API, ** otherwise an error will be returned. ** ** <b>Security warning:</b> It is recommended that the ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this -** interface. The use of the [sqlite3_enable_load_extension()] interface +** interface. The use of the [tdsqlite3_enable_load_extension()] interface ** should be avoided. This will keep the SQL function [load_extension()] ** disabled and prevent SQL injections from giving attackers ** access to extension loading capabilities. ** ** See also the [load_extension() SQL function]. */ -SQLITE_API int sqlite3_load_extension( - sqlite3 *db, /* Load the extension into this database connection */ +SQLITE_API int tdsqlite3_load_extension( + tdsqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Derived from zFile if 0 */ char **pzErrMsg /* Put error message here if not 0 */ @@ -5679,30 +6521,30 @@ SQLITE_API int sqlite3_load_extension( /* ** CAPI3REF: Enable Or Disable Extension Loading -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^So as not to open security holes in older applications that are ** unprepared to deal with [extension loading], and as a means of disabling ** [extension loading] while evaluating user-entered SQL, the following API -** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** is provided to turn the [tdsqlite3_load_extension()] mechanism on and off. ** ** ^Extension loading is off by default. -** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** ^Call the tdsqlite3_enable_load_extension() routine with onoff==1 ** to turn extension loading on and call it with onoff==0 to turn ** it back off again. ** ** ^This interface enables or disables both the C-API -** [sqlite3_load_extension()] and the SQL function [load_extension()]. -** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) +** [tdsqlite3_load_extension()] and the SQL function [load_extension()]. +** ^(Use [tdsqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) ** to enable or disable only the C-API.)^ ** ** <b>Security warning:</b> It is recommended that extension loading -** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method +** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method ** rather than this interface, so the [load_extension()] SQL function ** remains disabled. This will prevent SQL injections from giving attackers ** access to extension loading capabilities. */ -SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); +SQLITE_API int tdsqlite3_enable_load_extension(tdsqlite3 *db, int onoff); /* ** CAPI3REF: Automatically Load Statically Linked Extensions @@ -5719,48 +6561,48 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); ** ** <blockquote><pre> ** int xEntryPoint( -** sqlite3 *db, +** tdsqlite3 *db, ** const char **pzErrMsg, -** const struct sqlite3_api_routines *pThunk +** const struct tdsqlite3_api_routines *pThunk ** ); ** </pre></blockquote>)^ ** ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg -** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** point to an appropriate error message (obtained from [tdsqlite3_mprintf()]) ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg ** is NULL before calling the xEntryPoint(). ^SQLite will invoke -** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any -** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], -** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** [tdsqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [tdsqlite3_open()], [tdsqlite3_open16()], +** or [tdsqlite3_open_v2()] call that provoked the xEntryPoint() will fail. ** -** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** ^Calling tdsqlite3_auto_extension(X) with an entry point X that is already ** on the list of automatic extensions is a harmless no-op. ^No entry point ** will be called more than once for each database connection that is opened. ** -** See also: [sqlite3_reset_auto_extension()] -** and [sqlite3_cancel_auto_extension()] +** See also: [tdsqlite3_reset_auto_extension()] +** and [tdsqlite3_cancel_auto_extension()] */ -SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void)); +SQLITE_API int tdsqlite3_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Cancel Automatic Extension Loading ** -** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the +** ^The [tdsqlite3_cancel_auto_extension(X)] interface unregisters the ** initialization routine X that was registered using a prior call to -** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] +** [tdsqlite3_auto_extension(X)]. ^The [tdsqlite3_cancel_auto_extension(X)] ** routine returns 1 if initialization routine X was successfully ** unregistered and it returns 0 if X was not on the list of initialization ** routines. */ -SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); +SQLITE_API int tdsqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); /* ** CAPI3REF: Reset Automatic Extension Loading ** ** ^This interface disables all automatic extensions previously -** registered using [sqlite3_auto_extension()]. +** registered using [tdsqlite3_auto_extension()]. */ -SQLITE_API void sqlite3_reset_auto_extension(void); +SQLITE_API void tdsqlite3_reset_auto_extension(void); /* ** The interface to the virtual-table mechanism is currently considered @@ -5774,67 +6616,70 @@ SQLITE_API void sqlite3_reset_auto_extension(void); /* ** Structures used by the virtual table interface */ -typedef struct sqlite3_vtab sqlite3_vtab; -typedef struct sqlite3_index_info sqlite3_index_info; -typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; -typedef struct sqlite3_module sqlite3_module; +typedef struct tdsqlite3_vtab tdsqlite3_vtab; +typedef struct tdsqlite3_index_info tdsqlite3_index_info; +typedef struct tdsqlite3_vtab_cursor tdsqlite3_vtab_cursor; +typedef struct tdsqlite3_module tdsqlite3_module; /* ** CAPI3REF: Virtual Table Object -** KEYWORDS: sqlite3_module {virtual table module} +** KEYWORDS: tdsqlite3_module {virtual table module} ** ** This structure, sometimes called a "virtual table module", -** defines the implementation of a [virtual tables]. +** defines the implementation of a [virtual table]. ** This structure consists mostly of methods for the module. ** ** ^A virtual table module is created by filling in a persistent ** instance of this structure and passing a pointer to that instance -** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** to [tdsqlite3_create_module()] or [tdsqlite3_create_module_v2()]. ** ^The registration remains valid until it is replaced by a different ** module or until the [database connection] closes. The content ** of this structure must not change while it is registered with ** any database connection. */ -struct sqlite3_module { +struct tdsqlite3_module { int iVersion; - int (*xCreate)(sqlite3*, void *pAux, + int (*xCreate)(tdsqlite3*, void *pAux, int argc, const char *const*argv, - sqlite3_vtab **ppVTab, char**); - int (*xConnect)(sqlite3*, void *pAux, + tdsqlite3_vtab **ppVTab, char**); + int (*xConnect)(tdsqlite3*, void *pAux, int argc, const char *const*argv, - sqlite3_vtab **ppVTab, char**); - int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); - int (*xDisconnect)(sqlite3_vtab *pVTab); - int (*xDestroy)(sqlite3_vtab *pVTab); - int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); - int (*xClose)(sqlite3_vtab_cursor*); - int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, - int argc, sqlite3_value **argv); - int (*xNext)(sqlite3_vtab_cursor*); - int (*xEof)(sqlite3_vtab_cursor*); - int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); - int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); - int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); - int (*xBegin)(sqlite3_vtab *pVTab); - int (*xSync)(sqlite3_vtab *pVTab); - int (*xCommit)(sqlite3_vtab *pVTab); - int (*xRollback)(sqlite3_vtab *pVTab); - int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + tdsqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(tdsqlite3_vtab *pVTab, tdsqlite3_index_info*); + int (*xDisconnect)(tdsqlite3_vtab *pVTab); + int (*xDestroy)(tdsqlite3_vtab *pVTab); + int (*xOpen)(tdsqlite3_vtab *pVTab, tdsqlite3_vtab_cursor **ppCursor); + int (*xClose)(tdsqlite3_vtab_cursor*); + int (*xFilter)(tdsqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, tdsqlite3_value **argv); + int (*xNext)(tdsqlite3_vtab_cursor*); + int (*xEof)(tdsqlite3_vtab_cursor*); + int (*xColumn)(tdsqlite3_vtab_cursor*, tdsqlite3_context*, int); + int (*xRowid)(tdsqlite3_vtab_cursor*, tdsqlite3_int64 *pRowid); + int (*xUpdate)(tdsqlite3_vtab *, int, tdsqlite3_value **, tdsqlite3_int64 *); + int (*xBegin)(tdsqlite3_vtab *pVTab); + int (*xSync)(tdsqlite3_vtab *pVTab); + int (*xCommit)(tdsqlite3_vtab *pVTab); + int (*xRollback)(tdsqlite3_vtab *pVTab); + int (*xFindFunction)(tdsqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(tdsqlite3_context*,int,tdsqlite3_value**), void **ppArg); - int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + int (*xRename)(tdsqlite3_vtab *pVtab, const char *zNew); /* The methods above are in version 1 of the sqlite_module object. Those ** below are for version 2 and greater. */ - int (*xSavepoint)(sqlite3_vtab *pVTab, int); - int (*xRelease)(sqlite3_vtab *pVTab, int); - int (*xRollbackTo)(sqlite3_vtab *pVTab, int); + int (*xSavepoint)(tdsqlite3_vtab *pVTab, int); + int (*xRelease)(tdsqlite3_vtab *pVTab, int); + int (*xRollbackTo)(tdsqlite3_vtab *pVTab, int); + /* The methods above are in versions 1 and 2 of the sqlite_module object. + ** Those below are for version 3 and greater. */ + int (*xShadowName)(const char*); }; /* ** CAPI3REF: Virtual Table Indexing Information -** KEYWORDS: sqlite3_index_info +** KEYWORDS: tdsqlite3_index_info ** -** The sqlite3_index_info structure and its substructures is used as part +** The tdsqlite3_index_info structure and its substructures is used as part ** of the [virtual table] interface to ** pass information into and receive the reply from the [xBestIndex] ** method of a [virtual table module]. The fields under **Inputs** are the @@ -5865,12 +6710,12 @@ struct sqlite3_module { ** The colUsed field indicates which columns of the virtual table may be ** required by the current scan. Virtual table columns are numbered from ** zero in the order in which they appear within the CREATE TABLE statement -** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), +** passed to tdsqlite3_declare_vtab(). For the first 63 columns (columns 0-62), ** the corresponding bit is set within the colUsed mask if the column may be ** required by SQLite. If the table has at least 64 columns and any column ** to the right of the first 63 is required, then bit 63 of colUsed is also ** set. In other words, column iCol may be required if the expression -** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to +** (colUsed & ((tdsqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to ** non-zero. ** ** The [xBestIndex] method must fill aConstraintUsage[] with information @@ -5878,11 +6723,17 @@ struct sqlite3_module { ** the right-hand side of the corresponding aConstraint[] is evaluated ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit ** is true, then the constraint is assumed to be fully handled by the -** virtual table and is not checked again by SQLite.)^ +** virtual table and might not be checked again by the byte code.)^ ^(The +** aConstraintUsage[].omit flag is an optimization hint. When the omit flag +** is left in its default setting of false, the constraint will always be +** checked separately in byte code. If the omit flag is change to true, then +** the constraint may or may not be checked in byte code. In other words, +** when the omit flag is true there is no guarantee that the constraint will +** not be checked again using byte code.)^ ** ** ^The idxNum and idxPtr values are recorded and passed into the ** [xFilter] method. -** ^[sqlite3_free()] is used to free idxPtr if and only if +** ^[tdsqlite3_free()] is used to free idxPtr if and only if ** needToFreeIdxPtr is true. ** ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in @@ -5913,77 +6764,87 @@ struct sqlite3_module { ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by ** the xUpdate method are automatically rolled back by SQLite. ** -** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info +** IMPORTANT: The estimatedRows field was added to the tdsqlite3_index_info ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). ** If a virtual table extension is ** used with an SQLite version earlier than 3.8.2, the results of attempting ** to read or write the estimatedRows field are undefined (but are likely -** to included crashing the application). The estimatedRows field should -** therefore only be used if [sqlite3_libversion_number()] returns a +** to include crashing the application). The estimatedRows field should +** therefore only be used if [tdsqlite3_libversion_number()] returns a ** value greater than or equal to 3008002. Similarly, the idxFlags field ** was added for [version 3.9.0] ([dateof:3.9.0]). ** It may therefore only be used if -** sqlite3_libversion_number() returns a value greater than or equal to +** tdsqlite3_libversion_number() returns a value greater than or equal to ** 3009000. */ -struct sqlite3_index_info { +struct tdsqlite3_index_info { /* Inputs */ int nConstraint; /* Number of entries in aConstraint */ - struct sqlite3_index_constraint { + struct tdsqlite3_index_constraint { int iColumn; /* Column constrained. -1 for ROWID */ unsigned char op; /* Constraint operator */ unsigned char usable; /* True if this constraint is usable */ int iTermOffset; /* Used internally - xBestIndex should ignore */ } *aConstraint; /* Table of WHERE clause constraints */ int nOrderBy; /* Number of terms in the ORDER BY clause */ - struct sqlite3_index_orderby { + struct tdsqlite3_index_orderby { int iColumn; /* Column number */ unsigned char desc; /* True for DESC. False for ASC. */ } *aOrderBy; /* The ORDER BY clause */ /* Outputs */ - struct sqlite3_index_constraint_usage { + struct tdsqlite3_index_constraint_usage { int argvIndex; /* if >0, constraint is part of argv to xFilter */ unsigned char omit; /* Do not code a test for this constraint */ } *aConstraintUsage; int idxNum; /* Number used to identify the index */ - char *idxStr; /* String, possibly obtained from sqlite3_malloc */ - int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + char *idxStr; /* String, possibly obtained from tdsqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using tdsqlite3_free() if true */ int orderByConsumed; /* True if output is already ordered */ double estimatedCost; /* Estimated cost of using this index */ /* Fields below are only available in SQLite 3.8.2 and later */ - sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ + tdsqlite3_int64 estimatedRows; /* Estimated number of rows returned */ /* Fields below are only available in SQLite 3.9.0 and later */ int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ /* Fields below are only available in SQLite 3.10.0 and later */ - sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ + tdsqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ }; /* ** CAPI3REF: Virtual Table Scan Flags +** +** Virtual table implementations are allowed to set the +** [tdsqlite3_index_info].idxFlags field to some combination of +** these bits. */ #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */ /* ** CAPI3REF: Virtual Table Constraint Operator Codes ** -** These macros defined the allowed values for the -** [sqlite3_index_info].aConstraint[].op field. Each value represents +** These macros define the allowed values for the +** [tdsqlite3_index_info].aConstraint[].op field. Each value represents ** an operator that is part of a constraint term in the wHERE clause of ** a query that uses a [virtual table]. */ -#define SQLITE_INDEX_CONSTRAINT_EQ 2 -#define SQLITE_INDEX_CONSTRAINT_GT 4 -#define SQLITE_INDEX_CONSTRAINT_LE 8 -#define SQLITE_INDEX_CONSTRAINT_LT 16 -#define SQLITE_INDEX_CONSTRAINT_GE 32 -#define SQLITE_INDEX_CONSTRAINT_MATCH 64 -#define SQLITE_INDEX_CONSTRAINT_LIKE 65 -#define SQLITE_INDEX_CONSTRAINT_GLOB 66 -#define SQLITE_INDEX_CONSTRAINT_REGEXP 67 +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 +#define SQLITE_INDEX_CONSTRAINT_LIKE 65 +#define SQLITE_INDEX_CONSTRAINT_GLOB 66 +#define SQLITE_INDEX_CONSTRAINT_REGEXP 67 +#define SQLITE_INDEX_CONSTRAINT_NE 68 +#define SQLITE_INDEX_CONSTRAINT_ISNOT 69 +#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70 +#define SQLITE_INDEX_CONSTRAINT_ISNULL 71 +#define SQLITE_INDEX_CONSTRAINT_IS 72 +#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150 /* ** CAPI3REF: Register A Virtual Table Implementation -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^These routines are used to register a new [virtual table module] name. ** ^Module names must be registered before @@ -5998,32 +6859,55 @@ struct sqlite3_index_info { ** into the [xCreate] and [xConnect] methods of the virtual table module ** when a new virtual table is be being created or reinitialized. ** -** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** ^The tdsqlite3_create_module_v2() interface has a fifth parameter which ** is a pointer to a destructor for the pClientData. ^SQLite will ** invoke the destructor function (if it is not NULL) when SQLite ** no longer needs the pClientData pointer. ^The destructor will also -** be invoked if the call to sqlite3_create_module_v2() fails. -** ^The sqlite3_create_module() -** interface is equivalent to sqlite3_create_module_v2() with a NULL +** be invoked if the call to tdsqlite3_create_module_v2() fails. +** ^The tdsqlite3_create_module() +** interface is equivalent to tdsqlite3_create_module_v2() with a NULL ** destructor. +** +** ^If the third parameter (the pointer to the tdsqlite3_module object) is +** NULL then no new module is create and any existing modules with the +** same name are dropped. +** +** See also: [tdsqlite3_drop_modules()] */ -SQLITE_API int sqlite3_create_module( - sqlite3 *db, /* SQLite connection to register module with */ +SQLITE_API int tdsqlite3_create_module( + tdsqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ - const sqlite3_module *p, /* Methods for the module */ + const tdsqlite3_module *p, /* Methods for the module */ void *pClientData /* Client data for xCreate/xConnect */ ); -SQLITE_API int sqlite3_create_module_v2( - sqlite3 *db, /* SQLite connection to register module with */ +SQLITE_API int tdsqlite3_create_module_v2( + tdsqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ - const sqlite3_module *p, /* Methods for the module */ + const tdsqlite3_module *p, /* Methods for the module */ void *pClientData, /* Client data for xCreate/xConnect */ void(*xDestroy)(void*) /* Module destructor function */ ); /* +** CAPI3REF: Remove Unnecessary Virtual Table Implementations +** METHOD: tdsqlite3 +** +** ^The tdsqlite3_drop_modules(D,L) interface removes all virtual +** table modules from database connection D except those named on list L. +** The L parameter must be either NULL or a pointer to an array of pointers +** to strings where the array is terminated by a single NULL pointer. +** ^If the L parameter is NULL, then all virtual table modules are removed. +** +** See also: [tdsqlite3_create_module()] +*/ +SQLITE_API int tdsqlite3_drop_modules( + tdsqlite3 *db, /* Remove modules from this connection */ + const char **azKeep /* Except, do not remove the ones named here */ +); + +/* ** CAPI3REF: Virtual Table Instance Object -** KEYWORDS: sqlite3_vtab +** KEYWORDS: tdsqlite3_vtab ** ** Every [virtual table module] implementation uses a subclass ** of this object to describe a particular instance @@ -6033,29 +6917,29 @@ SQLITE_API int sqlite3_create_module_v2( ** common to all module implementations. ** ** ^Virtual tables methods can set an error message by assigning a -** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should -** take care that any prior string is freed by a call to [sqlite3_free()] +** string obtained from [tdsqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [tdsqlite3_free()] ** prior to assigning a new string to zErrMsg. ^After the error message ** is delivered up to the client application, the string will be automatically -** freed by sqlite3_free() and the zErrMsg field will be zeroed. +** freed by tdsqlite3_free() and the zErrMsg field will be zeroed. */ -struct sqlite3_vtab { - const sqlite3_module *pModule; /* The module for this virtual table */ +struct tdsqlite3_vtab { + const tdsqlite3_module *pModule; /* The module for this virtual table */ int nRef; /* Number of open cursors */ - char *zErrMsg; /* Error message from sqlite3_mprintf() */ + char *zErrMsg; /* Error message from tdsqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Virtual Table Cursor Object -** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** KEYWORDS: tdsqlite3_vtab_cursor {virtual table cursor} ** ** Every [virtual table module] implementation uses a subclass of the ** following structure to describe cursors that point into the ** [virtual table] and are used ** to loop through the virtual table. Cursors are created using the -** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed -** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** [tdsqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [tdsqlite3_module.xClose | xClose] method. Cursors are used ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods ** of the module. Each module implementation will define ** the content of a cursor structure to suit its own needs. @@ -6063,8 +6947,8 @@ struct sqlite3_vtab { ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. */ -struct sqlite3_vtab_cursor { - sqlite3_vtab *pVtab; /* Virtual table of this cursor */ +struct tdsqlite3_vtab_cursor { + tdsqlite3_vtab *pVtab; /* Virtual table of this cursor */ /* Virtual table implementations will typically add additional fields */ }; @@ -6076,11 +6960,11 @@ struct sqlite3_vtab_cursor { ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */ -SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); +SQLITE_API int tdsqlite3_declare_vtab(tdsqlite3*, const char *zSQL); /* ** CAPI3REF: Overload A Function For A Virtual Table -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^(Virtual tables can provide alternative implementations of functions ** using the [xFindFunction] method of the [virtual table module]. @@ -6095,7 +6979,7 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); ** purpose is to be a placeholder function that can be overloaded ** by a [virtual table]. */ -SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); +SQLITE_API int tdsqlite3_overload_function(tdsqlite3*, const char *zFuncName, int nArg); /* ** The interface to the virtual-table mechanism defined above (back up @@ -6112,19 +6996,19 @@ SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nA ** KEYWORDS: {BLOB handle} {BLOB handles} ** ** An instance of this object represents an open BLOB on which -** [sqlite3_blob_open | incremental BLOB I/O] can be performed. -** ^Objects of this type are created by [sqlite3_blob_open()] -** and destroyed by [sqlite3_blob_close()]. -** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** [tdsqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [tdsqlite3_blob_open()] +** and destroyed by [tdsqlite3_blob_close()]. +** ^The [tdsqlite3_blob_read()] and [tdsqlite3_blob_write()] interfaces ** can be used to read or write small subsections of the BLOB. -** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +** ^The [tdsqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. */ -typedef struct sqlite3_blob sqlite3_blob; +typedef struct tdsqlite3_blob tdsqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O -** METHOD: sqlite3 -** CONSTRUCTOR: sqlite3_blob +** METHOD: tdsqlite3 +** CONSTRUCTOR: tdsqlite3_blob ** ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located ** in row iRow, column zColumn, table zTable in database zDb; @@ -6147,7 +7031,7 @@ typedef struct sqlite3_blob sqlite3_blob; ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored ** in *ppBlob. Otherwise an [error code] is returned and, unless the error ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided -** the API is not misused, it is always safe to call [sqlite3_blob_close()] +** the API is not misused, it is always safe to call [tdsqlite3_blob_close()] ** on *ppBlob after this function it returns. ** ** This function fails with SQLITE_ERROR if any of the following are true: @@ -6168,70 +7052,80 @@ typedef struct sqlite3_blob sqlite3_blob; ** ** ^Unless it returns SQLITE_MISUSE, this function sets the ** [database connection] error code and message accessible via -** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. +** [tdsqlite3_errcode()] and [tdsqlite3_errmsg()] and related functions. ** +** A BLOB referenced by tdsqlite3_blob_open() may be read using the +** [tdsqlite3_blob_read()] interface and modified by using +** [tdsqlite3_blob_write()]. The [BLOB handle] can be moved to a +** different row of the same table using the [tdsqlite3_blob_reopen()] +** interface. However, the column, table, or database of a [BLOB handle] +** cannot be changed after the [BLOB handle] is opened. ** ** ^(If the row that a BLOB handle points to is modified by an ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects ** then the BLOB handle is marked as "expired". ** This is true if any column of the row is changed, even a column ** other than the one the BLOB handle is open on.)^ -** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** ^Calls to [tdsqlite3_blob_read()] and [tdsqlite3_blob_write()] for ** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. ** ^(Changes written into a BLOB prior to the BLOB expiring are not ** rolled back by the expiration of the BLOB. Such changes will eventually ** commit if the transaction continues to completion.)^ ** -** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** ^Use the [tdsqlite3_blob_bytes()] interface to determine the size of ** the opened blob. ^The size of a blob may not be changed by this ** interface. Use the [UPDATE] SQL command to change the size of a ** blob. ** -** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** ^The [tdsqlite3_bind_zeroblob()] and [tdsqlite3_result_zeroblob()] interfaces ** and the built-in [zeroblob] SQL function may be used to create a ** zero-filled blob to read or write using the incremental-blob interface. ** ** To avoid a resource leak, every open [BLOB handle] should eventually -** be released by a call to [sqlite3_blob_close()]. +** be released by a call to [tdsqlite3_blob_close()]. +** +** See also: [tdsqlite3_blob_close()], +** [tdsqlite3_blob_reopen()], [tdsqlite3_blob_read()], +** [tdsqlite3_blob_bytes()], [tdsqlite3_blob_write()]. */ -SQLITE_API int sqlite3_blob_open( - sqlite3*, +SQLITE_API int tdsqlite3_blob_open( + tdsqlite3*, const char *zDb, const char *zTable, const char *zColumn, - sqlite3_int64 iRow, + tdsqlite3_int64 iRow, int flags, - sqlite3_blob **ppBlob + tdsqlite3_blob **ppBlob ); /* ** CAPI3REF: Move a BLOB Handle to a New Row -** METHOD: sqlite3_blob +** METHOD: tdsqlite3_blob ** -** ^This function is used to move an existing blob handle so that it points +** ^This function is used to move an existing [BLOB handle] so that it points ** to a different row of the same database table. ^The new row is identified ** by the rowid value passed as the second argument. Only the row can be ** changed. ^The database, table and column on which the blob handle is open -** remain the same. Moving an existing blob handle to a new row can be +** remain the same. Moving an existing [BLOB handle] to a new row is ** faster than closing the existing handle and opening a new one. ** -** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** ^(The new row must meet the same criteria as for [tdsqlite3_blob_open()] - ** it must exist and there must be either a blob or text value stored in ** the nominated column.)^ ^If the new row is not present in the table, or if ** it does not contain a blob or text value, or if another error occurs, an ** SQLite error code is returned and the blob handle is considered aborted. -** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or -** [sqlite3_blob_reopen()] on an aborted blob handle immediately return -** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** ^All subsequent calls to [tdsqlite3_blob_read()], [tdsqlite3_blob_write()] or +** [tdsqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [tdsqlite3_blob_bytes()] on an aborted blob handle ** always returns zero. ** ** ^This function sets the database handle error code and message. */ -SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); +SQLITE_API int tdsqlite3_blob_reopen(tdsqlite3_blob *, tdsqlite3_int64); /* ** CAPI3REF: Close A BLOB Handle -** DESTRUCTOR: sqlite3_blob +** DESTRUCTOR: tdsqlite3_blob ** ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed ** unconditionally. Even if this routine returns an error code, the @@ -6246,15 +7140,15 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); ** Calling this function with an argument that is not a NULL pointer or an ** open blob handle results in undefined behaviour. ^Calling this routine ** with a null pointer (such as would be returned by a failed call to -** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function +** [tdsqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function ** is passed a valid open blob handle, the values returned by the -** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. +** tdsqlite3_errcode() and tdsqlite3_errmsg() functions are set before returning. */ -SQLITE_API int sqlite3_blob_close(sqlite3_blob *); +SQLITE_API int tdsqlite3_blob_close(tdsqlite3_blob *); /* ** CAPI3REF: Return The Size Of An Open BLOB -** METHOD: sqlite3_blob +** METHOD: tdsqlite3_blob ** ** ^Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. ^The @@ -6262,15 +7156,15 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** by a prior successful call to [tdsqlite3_blob_open()] and which has not +** been closed by [tdsqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. */ -SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); +SQLITE_API int tdsqlite3_blob_bytes(tdsqlite3_blob *); /* ** CAPI3REF: Read Data From A BLOB Incrementally -** METHOD: sqlite3_blob +** METHOD: tdsqlite3_blob ** ** ^(This function is used to read data from an open [BLOB handle] into a ** caller-supplied buffer. N bytes of data are copied into buffer Z @@ -6280,39 +7174,39 @@ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is ** less than zero, [SQLITE_ERROR] is returned and no data is read. ** ^The size of the blob (and hence the maximum value of N+iOffset) -** can be determined using the [sqlite3_blob_bytes()] interface. +** can be determined using the [tdsqlite3_blob_bytes()] interface. ** ** ^An attempt to read from an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ** -** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** ^(On success, tdsqlite3_blob_read() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** by a prior successful call to [tdsqlite3_blob_open()] and which has not +** been closed by [tdsqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** -** See also: [sqlite3_blob_write()]. +** See also: [tdsqlite3_blob_write()]. */ -SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); +SQLITE_API int tdsqlite3_blob_read(tdsqlite3_blob *, void *Z, int N, int iOffset); /* ** CAPI3REF: Write Data Into A BLOB Incrementally -** METHOD: sqlite3_blob +** METHOD: tdsqlite3_blob ** ** ^(This function is used to write data into an open [BLOB handle] from a ** caller-supplied buffer. N bytes of data are copied from the buffer Z ** into the open BLOB, starting at offset iOffset.)^ ** -** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** ^(On success, tdsqlite3_blob_write() returns SQLITE_OK. ** Otherwise, an [error code] or an [extended error code] is returned.)^ ** ^Unless SQLITE_MISUSE is returned, this function sets the ** [database connection] error code and message accessible via -** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. +** [tdsqlite3_errcode()] and [tdsqlite3_errmsg()] and related functions. ** ** ^If the [BLOB handle] passed as the first argument was not opened for -** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** writing (the flags parameter to [tdsqlite3_blob_open()] was zero), ** this function returns [SQLITE_READONLY]. ** ** This function may only modify the contents of the BLOB; it is @@ -6320,7 +7214,7 @@ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); ** ^If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is written. The size of the ** BLOB (and hence the maximum value of N+iOffset) can be determined -** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less +** using the [tdsqlite3_blob_bytes()] interface. ^If N or iOffset are less ** than zero [SQLITE_ERROR] is returned and no data is written. ** ** ^An attempt to write to an expired [BLOB handle] fails with an @@ -6331,31 +7225,31 @@ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); ** or by other independent statements. ** ** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** by a prior successful call to [tdsqlite3_blob_open()] and which has not +** been closed by [tdsqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** -** See also: [sqlite3_blob_read()]. +** See also: [tdsqlite3_blob_read()]. */ -SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); +SQLITE_API int tdsqlite3_blob_write(tdsqlite3_blob *, const void *z, int n, int iOffset); /* ** CAPI3REF: Virtual File System Objects ** -** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** A virtual filesystem (VFS) is an [tdsqlite3_vfs] object ** that SQLite uses to interact ** with the underlying operating system. Most SQLite builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** -** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^The tdsqlite3_vfs_find() interface returns a pointer to a VFS given its name. ** ^Names are case sensitive. ** ^Names are zero-terminated UTF-8 strings. ** ^If there is no match, a NULL pointer is returned. ** ^If zVfsName is NULL then the default VFS is returned. ** -** ^New VFSes are registered with sqlite3_vfs_register(). +** ^New VFSes are registered with tdsqlite3_vfs_register(). ** ^Each new VFS becomes the default VFS if the makeDflt flag is set. ** ^The same VFS can be registered multiple times without injury. ** ^To make an existing VFS into the default VFS, register it again @@ -6364,13 +7258,13 @@ SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOff ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. ** -** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^Unregister a VFS with the tdsqlite3_vfs_unregister() interface. ** ^(If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary.)^ */ -SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); -SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); -SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); +SQLITE_API tdsqlite3_vfs *tdsqlite3_vfs_find(const char *zVfsName); +SQLITE_API int tdsqlite3_vfs_register(tdsqlite3_vfs*, int makeDflt); +SQLITE_API int tdsqlite3_vfs_unregister(tdsqlite3_vfs*); /* ** CAPI3REF: Mutexes @@ -6401,14 +7295,14 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex ** implementation is included with the library. In this case the ** application must supply a custom mutex implementation using the -** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function -** before calling sqlite3_initialize() or any other public sqlite3_ -** function that calls sqlite3_initialize(). +** [SQLITE_CONFIG_MUTEX] option of the tdsqlite3_config() function +** before calling tdsqlite3_initialize() or any other public tdsqlite3_ +** function that calls tdsqlite3_initialize(). ** -** ^The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() +** ^The tdsqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^The tdsqlite3_mutex_alloc() ** routine returns NULL if it is unable to allocate the requested -** mutex. The argument to sqlite3_mutex_alloc() must one of these +** mutex. The argument to tdsqlite3_mutex_alloc() must one of these ** integer constants: ** ** <ul> @@ -6429,7 +7323,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** </ul> ** ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) -** cause sqlite3_mutex_alloc() to create +** cause tdsqlite3_mutex_alloc() to create ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. ** The mutex implementation does not need to make a distinction @@ -6439,7 +7333,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** -** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** ^The other allowed parameters to tdsqlite3_mutex_alloc() (anything other ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return ** a pointer to a static preexisting mutex. ^Nine static mutexes are ** used by the current version of SQLite. Future versions of SQLite @@ -6449,19 +7343,19 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** SQLITE_MUTEX_RECURSIVE. ** ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST -** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** or SQLITE_MUTEX_RECURSIVE) is used then tdsqlite3_mutex_alloc() ** returns a different mutex on every call. ^For the static ** mutex types, the same mutex is returned on every call that has ** the same type number. ** -** ^The sqlite3_mutex_free() routine deallocates a previously +** ^The tdsqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. Attempting to deallocate a static ** mutex results in undefined behavior. ** -** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** ^The tdsqlite3_mutex_enter() and tdsqlite3_mutex_try() routines attempt ** to enter a mutex. ^If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** tdsqlite3_mutex_enter() will block and tdsqlite3_mutex_try() will return +** SQLITE_BUSY. ^The tdsqlite3_mutex_try() interface returns [SQLITE_OK] ** upon successful entry. ^(Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** In such cases, the @@ -6470,27 +7364,27 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined. ** ** ^(Some systems (for example, Windows 95) do not support the operation -** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** implemented by tdsqlite3_mutex_try(). On those systems, tdsqlite3_mutex_try() ** will always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable +** tdsqlite3_mutex_try() as an optimization so this is acceptable ** behavior.)^ ** -** ^The sqlite3_mutex_leave() routine exits a mutex that was +** ^The tdsqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. ** -** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or -** sqlite3_mutex_leave() is a NULL pointer, then all three routines +** ^If the argument to tdsqlite3_mutex_enter(), tdsqlite3_mutex_try(), or +** tdsqlite3_mutex_leave() is a NULL pointer, then all three routines ** behave as no-ops. ** -** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +** See also: [tdsqlite3_mutex_held()] and [tdsqlite3_mutex_notheld()]. */ -SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); -SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); -SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); -SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); -SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); +SQLITE_API tdsqlite3_mutex *tdsqlite3_mutex_alloc(int); +SQLITE_API void tdsqlite3_mutex_free(tdsqlite3_mutex*); +SQLITE_API void tdsqlite3_mutex_enter(tdsqlite3_mutex*); +SQLITE_API int tdsqlite3_mutex_try(tdsqlite3_mutex*); +SQLITE_API void tdsqlite3_mutex_leave(tdsqlite3_mutex*); /* ** CAPI3REF: Mutex Methods Object @@ -6503,41 +7397,41 @@ SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); ** implementation for specialized deployments or systems for which SQLite ** does not provide a suitable implementation. In this case, the application ** creates and populates an instance of this structure to pass -** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** to tdsqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. ** Additionally, an instance of this structure can be used as an ** output variable when querying the system for the current mutex ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. ** ** ^The xMutexInit method defined by this structure is invoked as -** part of system initialization by the sqlite3_initialize() function. +** part of system initialization by the tdsqlite3_initialize() function. ** ^The xMutexInit routine is called by SQLite exactly once for each -** effective call to [sqlite3_initialize()]. +** effective call to [tdsqlite3_initialize()]. ** ** ^The xMutexEnd method defined by this structure is invoked as -** part of system shutdown by the sqlite3_shutdown() function. The +** part of system shutdown by the tdsqlite3_shutdown() function. The ** implementation of this method is expected to release all outstanding ** resources obtained by the mutex methods implementation, especially ** those obtained by the xMutexInit method. ^The xMutexEnd() -** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** interface is invoked exactly once for each call to [tdsqlite3_shutdown()]. ** ** ^(The remaining seven methods defined by this structure (xMutexAlloc, ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and ** xMutexNotheld) implement the following interfaces (respectively): ** ** <ul> -** <li> [sqlite3_mutex_alloc()] </li> -** <li> [sqlite3_mutex_free()] </li> -** <li> [sqlite3_mutex_enter()] </li> -** <li> [sqlite3_mutex_try()] </li> -** <li> [sqlite3_mutex_leave()] </li> -** <li> [sqlite3_mutex_held()] </li> -** <li> [sqlite3_mutex_notheld()] </li> +** <li> [tdsqlite3_mutex_alloc()] </li> +** <li> [tdsqlite3_mutex_free()] </li> +** <li> [tdsqlite3_mutex_enter()] </li> +** <li> [tdsqlite3_mutex_try()] </li> +** <li> [tdsqlite3_mutex_leave()] </li> +** <li> [tdsqlite3_mutex_held()] </li> +** <li> [tdsqlite3_mutex_notheld()] </li> ** </ul>)^ ** -** The only difference is that the public sqlite3_XXX functions enumerated +** The only difference is that the public tdsqlite3_XXX functions enumerated ** above silently ignore any invocations that pass a NULL pointer instead ** of a valid mutex handle. The implementations of the methods defined -** by this structure are not required to handle this case, the results +** by this structure are not required to handle this case. The results ** of passing a NULL pointer instead of a valid mutex handle are undefined ** (i.e. it is acceptable to provide an implementation that segfaults if ** it is passed a NULL pointer). @@ -6547,33 +7441,33 @@ SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); ** intervening calls to xMutexEnd(). Second and subsequent calls to ** xMutexInit() must be no-ops. ** -** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** xMutexInit() must not use SQLite memory allocation ([tdsqlite3_malloc()] ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite ** memory allocation for a fast or recursive mutex. ** -** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** ^SQLite will invoke the xMutexEnd() method when [tdsqlite3_shutdown()] is ** called, but only if the prior call to xMutexInit returned SQLITE_OK. ** If xMutexInit fails in any way, it is expected to clean up after itself ** prior to returning. */ -typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; -struct sqlite3_mutex_methods { +typedef struct tdsqlite3_mutex_methods tdsqlite3_mutex_methods; +struct tdsqlite3_mutex_methods { int (*xMutexInit)(void); int (*xMutexEnd)(void); - sqlite3_mutex *(*xMutexAlloc)(int); - void (*xMutexFree)(sqlite3_mutex *); - void (*xMutexEnter)(sqlite3_mutex *); - int (*xMutexTry)(sqlite3_mutex *); - void (*xMutexLeave)(sqlite3_mutex *); - int (*xMutexHeld)(sqlite3_mutex *); - int (*xMutexNotheld)(sqlite3_mutex *); + tdsqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(tdsqlite3_mutex *); + void (*xMutexEnter)(tdsqlite3_mutex *); + int (*xMutexTry)(tdsqlite3_mutex *); + void (*xMutexLeave)(tdsqlite3_mutex *); + int (*xMutexHeld)(tdsqlite3_mutex *); + int (*xMutexNotheld)(tdsqlite3_mutex *); }; /* ** CAPI3REF: Mutex Verification Routines ** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** The tdsqlite3_mutex_held() and tdsqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. The SQLite core only @@ -6590,24 +7484,24 @@ struct sqlite3_mutex_methods { ** versions of these routines, it should at least provide stubs that always ** return true so that one does not get spurious assertion failures. ** -** If the argument to sqlite3_mutex_held() is a NULL pointer then +** If the argument to tdsqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. This seems counter-intuitive since ** clearly the mutex cannot be held if it does not exist. But ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the -** call to sqlite3_mutex_held() to fail, so a non-zero return is -** the appropriate thing to do. The sqlite3_mutex_notheld() +** call to tdsqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. The tdsqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ #ifndef NDEBUG -SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); -SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); +SQLITE_API int tdsqlite3_mutex_held(tdsqlite3_mutex*); +SQLITE_API int tdsqlite3_mutex_notheld(tdsqlite3_mutex*); #endif /* ** CAPI3REF: Mutex Types ** -** The [sqlite3_mutex_alloc()] interface takes a single argument +** The [tdsqlite3_mutex_alloc()] interface takes a single argument ** which is one of these integer constants. ** ** The set of static mutexes may change from one SQLite release to the @@ -6617,13 +7511,13 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 #define SQLITE_MUTEX_STATIC_MASTER 2 -#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM 3 /* tdsqlite3_malloc() */ #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ -#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ -#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* tdsqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* tdsqlite3_randomness() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ -#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* tdsqlite3PageMalloc() */ #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */ @@ -6633,22 +7527,23 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); /* ** CAPI3REF: Retrieve the mutex for a database connection -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^This interface returns a pointer the [sqlite3_mutex] object that +** ^This interface returns a pointer the [tdsqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** ^If the [threading mode] is Single-thread or Multi-thread then this ** routine returns a NULL pointer. */ -SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); +SQLITE_API tdsqlite3_mutex *tdsqlite3_db_mutex(tdsqlite3*); /* ** CAPI3REF: Low-Level Control Of Database Files -** METHOD: sqlite3 +** METHOD: tdsqlite3 +** KEYWORDS: {file control} ** -** ^The [sqlite3_file_control()] interface makes a direct call to the -** xFileControl method for the [sqlite3_io_methods] object associated +** ^The [tdsqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [tdsqlite3_io_methods] object associated ** with a particular database identified by the second argument. ^The ** name of the database is "main" for the main database or "temp" for the ** TEMP database, or the name that appears after the AS keyword for @@ -6660,28 +7555,35 @@ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); ** the xFileControl method. ^The return value of the xFileControl ** method becomes the return value of this routine. ** -** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes -** a pointer to the underlying [sqlite3_file] object to be written into -** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER -** case is a short-circuit path which does not actually invoke the -** underlying sqlite3_io_methods.xFileControl method. +** A few opcodes for [tdsqlite3_file_control()] are handled directly +** by the SQLite core and never invoke the +** tdsqlite3_io_methods.xFileControl method. +** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes +** a pointer to the underlying [tdsqlite3_file] object to be written into +** the space pointed to by the 4th parameter. The +** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns +** the [tdsqlite3_file] object associated with the journal file instead of +** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns +** a pointer to the underlying [tdsqlite3_vfs] object for the file. +** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter +** from the pager. ** ** ^If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. ^This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might +** code is not remembered and will not be recalled by [tdsqlite3_errcode()] +** or [tdsqlite3_errmsg()]. The underlying xFileControl method might ** also return SQLITE_ERROR. There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. ** -** See also: [SQLITE_FCNTL_LOCKSTATE] +** See also: [file control opcodes] */ -SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); +SQLITE_API int tdsqlite3_file_control(tdsqlite3*, const char *zDbName, int op, void*); /* ** CAPI3REF: Testing Interface ** -** ^The sqlite3_test_control() interface is used to read out internal +** ^The tdsqlite3_test_control() interface is used to read out internal ** state of SQLite and to inject faults into SQLite for testing ** purposes. ^The first parameter is an operation code that determines ** the number, meaning, and operation of all subsequent parameters. @@ -6695,23 +7597,23 @@ SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void* ** Unlike most of the SQLite API, this function is not guaranteed to ** operate consistently from one release to the next. */ -SQLITE_API int sqlite3_test_control(int op, ...); +SQLITE_API int tdsqlite3_test_control(int op, ...); /* ** CAPI3REF: Testing Interface Operation Codes ** ** These constants are the valid operation code parameters used -** as the first argument to [sqlite3_test_control()]. +** as the first argument to [tdsqlite3_test_control()]. ** ** These parameters and their meanings are subject to change ** without notice. These values are for testing purposes only. ** Applications should not use any of these parameters or the -** [sqlite3_test_control()] interface. +** [tdsqlite3_test_control()] interface. */ #define SQLITE_TESTCTRL_FIRST 5 #define SQLITE_TESTCTRL_PRNG_SAVE 5 #define SQLITE_TESTCTRL_PRNG_RESTORE 6 -#define SQLITE_TESTCTRL_PRNG_RESET 7 +#define SQLITE_TESTCTRL_PRNG_RESET 7 /* NOT USED */ #define SQLITE_TESTCTRL_BITVEC_TEST 8 #define SQLITE_TESTCTRL_FAULT_INSTALL 9 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 @@ -6720,8 +7622,9 @@ SQLITE_API int sqlite3_test_control(int op, ...); #define SQLITE_TESTCTRL_ALWAYS 13 #define SQLITE_TESTCTRL_RESERVE 14 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15 -#define SQLITE_TESTCTRL_ISKEYWORD 16 -#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 +#define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */ +#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */ +#define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */ #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19 @@ -6731,7 +7634,194 @@ SQLITE_API int sqlite3_test_control(int op, ...); #define SQLITE_TESTCTRL_ISINIT 23 #define SQLITE_TESTCTRL_SORTER_MMAP 24 #define SQLITE_TESTCTRL_IMPOSTER 25 -#define SQLITE_TESTCTRL_LAST 25 +#define SQLITE_TESTCTRL_PARSER_COVERAGE 26 +#define SQLITE_TESTCTRL_RESULT_INTREAL 27 +#define SQLITE_TESTCTRL_PRNG_SEED 28 +#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS 29 +#define SQLITE_TESTCTRL_LAST 29 /* Largest TESTCTRL */ + +/* +** CAPI3REF: SQL Keyword Checking +** +** These routines provide access to the set of SQL language keywords +** recognized by SQLite. Applications can uses these routines to determine +** whether or not a specific identifier needs to be escaped (for example, +** by enclosing in double-quotes) so as not to confuse the parser. +** +** The tdsqlite3_keyword_count() interface returns the number of distinct +** keywords understood by SQLite. +** +** The tdsqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and +** makes *Z point to that keyword expressed as UTF8 and writes the number +** of bytes in the keyword into *L. The string that *Z points to is not +** zero-terminated. The tdsqlite3_keyword_name(N,Z,L) routine returns +** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z +** or L are NULL or invalid pointers then calls to +** tdsqlite3_keyword_name(N,Z,L) result in undefined behavior. +** +** The tdsqlite3_keyword_check(Z,L) interface checks to see whether or not +** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero +** if it is and zero if not. +** +** The parser used by SQLite is forgiving. It is often possible to use +** a keyword as an identifier as long as such use does not result in a +** parsing ambiguity. For example, the statement +** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and +** creates a new table named "BEGIN" with three columns named +** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid +** using keywords as identifiers. Common techniques used to avoid keyword +** name collisions include: +** <ul> +** <li> Put all identifier names inside double-quotes. This is the official +** SQL way to escape identifier names. +** <li> Put identifier names inside [...]. This is not standard SQL, +** but it is what SQL Server does and so lots of programmers use this +** technique. +** <li> Begin every identifier with the letter "Z" as no SQL keywords start +** with "Z". +** <li> Include a digit somewhere in every identifier name. +** </ul> +** +** Note that the number of keywords understood by SQLite can depend on +** compile-time options. For example, "VACUUM" is not a keyword if +** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also, +** new keywords may be added to future releases of SQLite. +*/ +SQLITE_API int tdsqlite3_keyword_count(void); +SQLITE_API int tdsqlite3_keyword_name(int,const char**,int*); +SQLITE_API int tdsqlite3_keyword_check(const char*,int); + +/* +** CAPI3REF: Dynamic String Object +** KEYWORDS: {dynamic string} +** +** An instance of the tdsqlite3_str object contains a dynamically-sized +** string under construction. +** +** The lifecycle of an tdsqlite3_str object is as follows: +** <ol> +** <li> ^The tdsqlite3_str object is created using [tdsqlite3_str_new()]. +** <li> ^Text is appended to the tdsqlite3_str object using various +** methods, such as [tdsqlite3_str_appendf()]. +** <li> ^The tdsqlite3_str object is destroyed and the string it created +** is returned using the [tdsqlite3_str_finish()] interface. +** </ol> +*/ +typedef struct tdsqlite3_str tdsqlite3_str; + +/* +** CAPI3REF: Create A New Dynamic String Object +** CONSTRUCTOR: tdsqlite3_str +** +** ^The [tdsqlite3_str_new(D)] interface allocates and initializes +** a new [tdsqlite3_str] object. To avoid memory leaks, the object returned by +** [tdsqlite3_str_new()] must be freed by a subsequent call to +** [tdsqlite3_str_finish(X)]. +** +** ^The [tdsqlite3_str_new(D)] interface always returns a pointer to a +** valid [tdsqlite3_str] object, though in the event of an out-of-memory +** error the returned object might be a special singleton that will +** silently reject new text, always return SQLITE_NOMEM from +** [tdsqlite3_str_errcode()], always return 0 for +** [tdsqlite3_str_length()], and always return NULL from +** [tdsqlite3_str_finish(X)]. It is always safe to use the value +** returned by [tdsqlite3_str_new(D)] as the tdsqlite3_str parameter +** to any of the other [tdsqlite3_str] methods. +** +** The D parameter to [tdsqlite3_str_new(D)] may be NULL. If the +** D parameter in [tdsqlite3_str_new(D)] is not NULL, then the maximum +** length of the string contained in the [tdsqlite3_str] object will be +** the value set for [tdsqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead +** of [SQLITE_MAX_LENGTH]. +*/ +SQLITE_API tdsqlite3_str *tdsqlite3_str_new(tdsqlite3*); + +/* +** CAPI3REF: Finalize A Dynamic String +** DESTRUCTOR: tdsqlite3_str +** +** ^The [tdsqlite3_str_finish(X)] interface destroys the tdsqlite3_str object X +** and returns a pointer to a memory buffer obtained from [tdsqlite3_malloc64()] +** that contains the constructed string. The calling application should +** pass the returned value to [tdsqlite3_free()] to avoid a memory leak. +** ^The [tdsqlite3_str_finish(X)] interface may return a NULL pointer if any +** errors were encountered during construction of the string. ^The +** [tdsqlite3_str_finish(X)] interface will also return a NULL pointer if the +** string in [tdsqlite3_str] object X is zero bytes long. +*/ +SQLITE_API char *tdsqlite3_str_finish(tdsqlite3_str*); + +/* +** CAPI3REF: Add Content To A Dynamic String +** METHOD: tdsqlite3_str +** +** These interfaces add content to an tdsqlite3_str object previously obtained +** from [tdsqlite3_str_new()]. +** +** ^The [tdsqlite3_str_appendf(X,F,...)] and +** [tdsqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf] +** functionality of SQLite to append formatted text onto the end of +** [tdsqlite3_str] object X. +** +** ^The [tdsqlite3_str_append(X,S,N)] method appends exactly N bytes from string S +** onto the end of the [tdsqlite3_str] object X. N must be non-negative. +** S must contain at least N non-zero bytes of content. To append a +** zero-terminated string in its entirety, use the [tdsqlite3_str_appendall()] +** method instead. +** +** ^The [tdsqlite3_str_appendall(X,S)] method appends the complete content of +** zero-terminated string S onto the end of [tdsqlite3_str] object X. +** +** ^The [tdsqlite3_str_appendchar(X,N,C)] method appends N copies of the +** single-byte character C onto the end of [tdsqlite3_str] object X. +** ^This method can be used, for example, to add whitespace indentation. +** +** ^The [tdsqlite3_str_reset(X)] method resets the string under construction +** inside [tdsqlite3_str] object X back to zero bytes in length. +** +** These methods do not return a result code. ^If an error occurs, that fact +** is recorded in the [tdsqlite3_str] object and can be recovered by a +** subsequent call to [tdsqlite3_str_errcode(X)]. +*/ +SQLITE_API void tdsqlite3_str_appendf(tdsqlite3_str*, const char *zFormat, ...); +SQLITE_API void tdsqlite3_str_vappendf(tdsqlite3_str*, const char *zFormat, va_list); +SQLITE_API void tdsqlite3_str_append(tdsqlite3_str*, const char *zIn, int N); +SQLITE_API void tdsqlite3_str_appendall(tdsqlite3_str*, const char *zIn); +SQLITE_API void tdsqlite3_str_appendchar(tdsqlite3_str*, int N, char C); +SQLITE_API void tdsqlite3_str_reset(tdsqlite3_str*); + +/* +** CAPI3REF: Status Of A Dynamic String +** METHOD: tdsqlite3_str +** +** These interfaces return the current status of an [tdsqlite3_str] object. +** +** ^If any prior errors have occurred while constructing the dynamic string +** in tdsqlite3_str X, then the [tdsqlite3_str_errcode(X)] method will return +** an appropriate error code. ^The [tdsqlite3_str_errcode(X)] method returns +** [SQLITE_NOMEM] following any out-of-memory error, or +** [SQLITE_TOOBIG] if the size of the dynamic string exceeds +** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors. +** +** ^The [tdsqlite3_str_length(X)] method returns the current length, in bytes, +** of the dynamic string under construction in [tdsqlite3_str] object X. +** ^The length returned by [tdsqlite3_str_length(X)] does not include the +** zero-termination byte. +** +** ^The [tdsqlite3_str_value(X)] method returns a pointer to the current +** content of the dynamic string under construction in X. The value +** returned by [tdsqlite3_str_value(X)] is managed by the tdsqlite3_str object X +** and might be freed or altered by any subsequent method on the same +** [tdsqlite3_str] object. Applications must not used the pointer returned +** [tdsqlite3_str_value(X)] after any subsequent method call on the same +** object. ^Applications may change the content of the string returned +** by [tdsqlite3_str_value(X)] as long as they do not write into any bytes +** outside the range of 0 to [tdsqlite3_str_length(X)] and do not read or +** write any byte after any subsequent tdsqlite3_str method call. +*/ +SQLITE_API int tdsqlite3_str_errcode(tdsqlite3_str*); +SQLITE_API int tdsqlite3_str_length(tdsqlite3_str*); +SQLITE_API char *tdsqlite3_str_value(tdsqlite3_str*); /* ** CAPI3REF: SQLite Runtime Status @@ -6750,20 +7840,20 @@ SQLITE_API int sqlite3_test_control(int op, ...); ** ^(Other parameters record only the highwater mark and not the current ** value. For these latter parameters nothing is written into *pCurrent.)^ ** -** ^The sqlite3_status() and sqlite3_status64() routines return +** ^The tdsqlite3_status() and tdsqlite3_status64() routines return ** SQLITE_OK on success and a non-zero [error code] on failure. ** ** If either the current value or the highwater mark is too large to ** be represented by a 32-bit integer, then the values returned by -** sqlite3_status() are undefined. +** tdsqlite3_status() are undefined. ** -** See also: [sqlite3_db_status()] +** See also: [tdsqlite3_db_status()] */ -SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); -SQLITE_API int sqlite3_status64( +SQLITE_API int tdsqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); +SQLITE_API int tdsqlite3_status64( int op, - sqlite3_int64 *pCurrent, - sqlite3_int64 *pHighwater, + tdsqlite3_int64 *pCurrent, + tdsqlite3_int64 *pHighwater, int resetFlag ); @@ -6773,24 +7863,23 @@ SQLITE_API int sqlite3_status64( ** KEYWORDS: {status parameters} ** ** These integer constants designate various run-time status parameters -** that can be returned by [sqlite3_status()]. +** that can be returned by [tdsqlite3_status()]. ** ** <dl> ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt> ** <dd>This parameter is the current amount of memory checked out -** using [sqlite3_malloc()], either directly or indirectly. The -** figure includes calls made to [sqlite3_malloc()] by the application -** and internal memory usage by the SQLite library. Scratch memory -** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache +** using [tdsqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [tdsqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Auxiliary page-cache ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in ** this parameter. The amount returned is the sum of the allocation -** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^ +** sizes as reported by the xSize method in [tdsqlite3_mem_methods].</dd>)^ ** ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt> ** <dd>This parameter records the largest memory allocation request -** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** handed to [tdsqlite3_malloc()] or [tdsqlite3_realloc()] (or their ** internal equivalents). Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. +** *pHighwater parameter to [tdsqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt> @@ -6807,7 +7896,7 @@ SQLITE_API int sqlite3_status64( ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt> ** <dd>This parameter returns the number of bytes of page cache ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] -** buffer and where forced to overflow to [sqlite3_malloc()]. The +** buffer and where forced to overflow to [tdsqlite3_malloc()]. The ** returned value includes allocations that overflowed because they ** where too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because @@ -6815,33 +7904,18 @@ SQLITE_API int sqlite3_status64( ** ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt> ** <dd>This parameter records the largest memory allocation request -** handed to [pagecache memory allocator]. Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. +** handed to the [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [tdsqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.</dd>)^ ** -** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt> -** <dd>This parameter returns the number of allocations used out of the -** [scratch memory allocator] configured using -** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not -** in bytes. Since a single thread may only have one scratch allocation -** outstanding at time, this parameter also reports the number of threads -** using scratch memory at the same time.</dd>)^ +** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt> +** <dd>No longer used.</dd> ** ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt> -** <dd>This parameter returns the number of bytes of scratch memory -** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] -** buffer and where forced to overflow to [sqlite3_malloc()]. The values -** returned include overflows because the requested allocation was too -** larger (that is, because the requested allocation was larger than the -** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer -** slots were available. -** </dd>)^ +** <dd>No longer used.</dd> ** -** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt> -** <dd>This parameter records the largest memory allocation request -** handed to [scratch memory allocator]. Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. -** The value written into the *pCurrent parameter is undefined.</dd>)^ +** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt> +** <dd>No longer used.</dd> ** ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt> ** <dd>The *pHighwater parameter records the deepest parser stack. @@ -6854,17 +7928,17 @@ SQLITE_API int sqlite3_status64( #define SQLITE_STATUS_MEMORY_USED 0 #define SQLITE_STATUS_PAGECACHE_USED 1 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 -#define SQLITE_STATUS_SCRATCH_USED 3 -#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 +#define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */ +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */ #define SQLITE_STATUS_MALLOC_SIZE 5 #define SQLITE_STATUS_PARSER_STACK 6 #define SQLITE_STATUS_PAGECACHE_SIZE 7 -#define SQLITE_STATUS_SCRATCH_SIZE 8 +#define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */ #define SQLITE_STATUS_MALLOC_COUNT 9 /* ** CAPI3REF: Database Connection Status -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^This interface is used to retrieve runtime status information ** about a single [database connection]. ^The first argument is the @@ -6880,24 +7954,24 @@ SQLITE_API int sqlite3_status64( ** the resetFlg is true, then the highest instantaneous value is ** reset back down to the current value. ** -** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** ^The tdsqlite3_db_status() routine returns SQLITE_OK on success and a ** non-zero [error code] on failure. ** -** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +** See also: [tdsqlite3_status()] and [tdsqlite3_stmt_status()]. */ -SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); +SQLITE_API int tdsqlite3_db_status(tdsqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); /* ** CAPI3REF: Status Parameters for database connections ** KEYWORDS: {SQLITE_DBSTATUS options} ** ** These constants are the available integer "verbs" that can be passed as -** the second argument to the [sqlite3_db_status()] interface. +** the second argument to the [tdsqlite3_db_status()] interface. ** ** New verbs may be added in future releases of SQLite. Existing verbs ** might be discontinued. Applications should check the return code from -** [sqlite3_db_status()] to make sure that the call worked. -** The [sqlite3_db_status()] interface will return a non-zero error code +** [tdsqlite3_db_status()] to make sure that the call worked. +** The [tdsqlite3_db_status()] interface will return a non-zero error code ** if a discontinued or unsupported verb is invoked. ** ** <dl> @@ -6906,7 +7980,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** checked out.</dd>)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt> -** <dd>This parameter returns the number malloc attempts that were +** <dd>This parameter returns the number of malloc attempts that were ** satisfied using lookaside memory. Only the high-water value is meaningful; ** the current value is always zero.)^ ** @@ -6982,6 +8056,15 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. ** </dd> ** +** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt> +** <dd>This parameter returns the number of dirty cache entries that have +** been written to disk in the middle of a transaction due to the page +** cache overflowing. Transactions are more efficient if they are written +** to disk all at once. When pages spill mid-transaction, that introduces +** additional overhead. This parameter can be used help identify +** inefficiencies that can be resolved by increasing the cache size. +** </dd> +** ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt> ** <dd>This parameter returns zero for the current value if and only if ** all foreign key constraints (deferred or immediate) have been @@ -7001,12 +8084,13 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r #define SQLITE_DBSTATUS_CACHE_WRITE 9 #define SQLITE_DBSTATUS_DEFERRED_FKS 10 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 -#define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */ +#define SQLITE_DBSTATUS_CACHE_SPILL 12 +#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */ /* ** CAPI3REF: Prepared Statement Status -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** ^(Each prepared statement maintains various ** [SQLITE_STMTSTATUS counters] that measure the number @@ -7026,16 +8110,16 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** ^If the resetFlg is true, then the counter is reset to zero after this ** interface call returns. ** -** See also: [sqlite3_status()] and [sqlite3_db_status()]. +** See also: [tdsqlite3_status()] and [tdsqlite3_db_status()]. */ -SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); +SQLITE_API int tdsqlite3_stmt_status(tdsqlite3_stmt*, int op,int resetFlg); /* ** CAPI3REF: Status Parameters for prepared statements ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} ** ** These preprocessor macros define integer codes that name counter -** values associated with the [sqlite3_stmt_status()] interface. +** values associated with the [tdsqlite3_stmt_status()] interface. ** The meanings of the various counters are as follows: ** ** <dl> @@ -7064,6 +8148,24 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); ** used as a proxy for the total work done by the prepared statement. ** If the number of virtual machine operations exceeds 2147483647 ** then the value returned by this statement status code is undefined. +** +** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt> +** <dd>^This is the number of times that the prepare statement has been +** automatically regenerated due to schema changes or changes to +** [bound parameters] that might affect the query plan. +** +** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt> +** <dd>^This is the number of times that the prepared statement has +** been run. A single "run" for the purposes of this counter is one +** or more calls to [tdsqlite3_step()] followed by a call to [tdsqlite3_reset()]. +** The counter is incremented on the first [tdsqlite3_step()] call of each +** cycle. +** +** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt> +** <dd>^This is the approximate number of bytes of heap memory +** used to store the prepared statement. ^This value is not actually +** a counter, and so the resetFlg parameter to tdsqlite3_stmt_status() +** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED. ** </dd> ** </dl> */ @@ -7071,32 +8173,35 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); #define SQLITE_STMTSTATUS_SORT 2 #define SQLITE_STMTSTATUS_AUTOINDEX 3 #define SQLITE_STMTSTATUS_VM_STEP 4 +#define SQLITE_STMTSTATUS_REPREPARE 5 +#define SQLITE_STMTSTATUS_RUN 6 +#define SQLITE_STMTSTATUS_MEMUSED 99 /* ** CAPI3REF: Custom Page Cache Object ** -** The sqlite3_pcache type is opaque. It is implemented by +** The tdsqlite3_pcache type is opaque. It is implemented by ** the pluggable module. The SQLite core has no knowledge of ** its size or internal structure and never deals with the -** sqlite3_pcache object except by holding and passing pointers +** tdsqlite3_pcache object except by holding and passing pointers ** to the object. ** -** See [sqlite3_pcache_methods2] for additional information. +** See [tdsqlite3_pcache_methods2] for additional information. */ -typedef struct sqlite3_pcache sqlite3_pcache; +typedef struct tdsqlite3_pcache tdsqlite3_pcache; /* ** CAPI3REF: Custom Page Cache Object ** -** The sqlite3_pcache_page object represents a single page in the +** The tdsqlite3_pcache_page object represents a single page in the ** page cache. The page cache will allocate instances of this ** object. Various methods of the page cache use pointers to instances ** of this object as parameters or as their return value. ** -** See [sqlite3_pcache_methods2] for additional information. +** See [tdsqlite3_pcache_methods2] for additional information. */ -typedef struct sqlite3_pcache_page sqlite3_pcache_page; -struct sqlite3_pcache_page { +typedef struct tdsqlite3_pcache_page tdsqlite3_pcache_page; +struct tdsqlite3_pcache_page { void *pBuf; /* The content of the page */ void *pExtra; /* Extra information associated with the page */ }; @@ -7105,9 +8210,9 @@ struct sqlite3_pcache_page { ** CAPI3REF: Application Defined Page Cache. ** KEYWORDS: {page cache} ** -** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can +** ^(The [tdsqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can ** register an alternative page cache implementation by passing in an -** instance of the sqlite3_pcache_methods2 structure.)^ +** instance of the tdsqlite3_pcache_methods2 structure.)^ ** In many applications, most of the heap memory allocated by ** SQLite is used for the page cache. ** By implementing a @@ -7121,16 +8226,16 @@ struct sqlite3_pcache_page { ** extreme measure that is only needed by the most demanding applications. ** The built-in page cache is recommended for most uses. ** -** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an -** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** ^(The contents of the tdsqlite3_pcache_methods2 structure are copied to an +** internal buffer by SQLite within the call to [tdsqlite3_config]. Hence ** the application may discard the parameter after the call to -** [sqlite3_config()] returns.)^ +** [tdsqlite3_config()] returns.)^ ** ** [[the xInit() page cache method]] ** ^(The xInit() method is called once for each effective -** call to [sqlite3_initialize()])^ +** call to [tdsqlite3_initialize()])^ ** (usually only once during the lifetime of the process). ^(The xInit() -** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ +** method is passed a copy of the tdsqlite3_pcache_methods2.pArg value.)^ ** The intent of the xInit() method is to set up global data structures ** required by the custom page cache implementation. ** ^(If the xInit() method is NULL, then the @@ -7138,14 +8243,14 @@ struct sqlite3_pcache_page { ** page cache.)^ ** ** [[the xShutdown() page cache method]] -** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** ^The xShutdown() method is called by [tdsqlite3_shutdown()]. ** It can be used to clean up ** any outstanding resources before process shutdown, if required. ** ^The xShutdown() method may be NULL. ** ** ^SQLite automatically serializes calls to the xInit method, ** so the xInit method need not be threadsafe. ^The -** xShutdown method is only called from [sqlite3_shutdown()] so it does +** xShutdown method is only called from [tdsqlite3_shutdown()] so it does ** not need to be threadsafe either. All other methods must be threadsafe ** in multithreaded applications. ** @@ -7189,10 +8294,10 @@ struct sqlite3_pcache_page { ** ** [[the xFetch() page cache methods]] ** The xFetch() method locates a page in the cache and returns a pointer to -** an sqlite3_pcache_page object associated with that page, or a NULL pointer. -** The pBuf element of the returned sqlite3_pcache_page object will be a +** an tdsqlite3_pcache_page object associated with that page, or a NULL pointer. +** The pBuf element of the returned tdsqlite3_pcache_page object will be a ** pointer to a buffer of szPage bytes used to store the content of a -** single database page. The pExtra element of sqlite3_pcache_page will be +** single database page. The pExtra element of tdsqlite3_pcache_page will be ** a pointer to the szExtra bytes of extra storage that SQLite has requested ** for each entry in the page cache. ** @@ -7217,7 +8322,7 @@ struct sqlite3_pcache_page { ** ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite ** will only use a createFlag of 2 after a prior call with a createFlag of 1 -** failed.)^ In between the to xFetch() calls, SQLite may +** failed.)^ In between the xFetch() calls, SQLite may ** attempt to unpin one or more cache pages by spilling the content of ** pinned pages to disk and synching the operating system disk cache. ** @@ -7250,8 +8355,8 @@ struct sqlite3_pcache_page { ** [[the xDestroy() page cache method]] ** ^The xDestroy() method is used to delete a cache allocated by xCreate(). ** All resources associated with the specified cache should be freed. ^After -** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] -** handle invalid, and will not use it with any other sqlite3_pcache_methods2 +** calling the xDestroy() method, SQLite considers the [tdsqlite3_pcache*] +** handle invalid, and will not use it with any other tdsqlite3_pcache_methods2 ** functions. ** ** [[the xShrink() page cache method]] @@ -7260,56 +8365,56 @@ struct sqlite3_pcache_page { ** is not obligated to free any memory, but well-behaved implementations should ** do their best. */ -typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; -struct sqlite3_pcache_methods2 { +typedef struct tdsqlite3_pcache_methods2 tdsqlite3_pcache_methods2; +struct tdsqlite3_pcache_methods2 { int iVersion; void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); - sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); - void (*xCachesize)(sqlite3_pcache*, int nCachesize); - int (*xPagecount)(sqlite3_pcache*); - sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); - void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); - void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, + tdsqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); + void (*xCachesize)(tdsqlite3_pcache*, int nCachesize); + int (*xPagecount)(tdsqlite3_pcache*); + tdsqlite3_pcache_page *(*xFetch)(tdsqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(tdsqlite3_pcache*, tdsqlite3_pcache_page*, int discard); + void (*xRekey)(tdsqlite3_pcache*, tdsqlite3_pcache_page*, unsigned oldKey, unsigned newKey); - void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); - void (*xDestroy)(sqlite3_pcache*); - void (*xShrink)(sqlite3_pcache*); + void (*xTruncate)(tdsqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(tdsqlite3_pcache*); + void (*xShrink)(tdsqlite3_pcache*); }; /* ** This is the obsolete pcache_methods object that has now been replaced -** by sqlite3_pcache_methods2. This object is not used by SQLite. It is +** by tdsqlite3_pcache_methods2. This object is not used by SQLite. It is ** retained in the header file for backwards compatibility only. */ -typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; -struct sqlite3_pcache_methods { +typedef struct tdsqlite3_pcache_methods tdsqlite3_pcache_methods; +struct tdsqlite3_pcache_methods { void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); - sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); - void (*xCachesize)(sqlite3_pcache*, int nCachesize); - int (*xPagecount)(sqlite3_pcache*); - void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); - void (*xUnpin)(sqlite3_pcache*, void*, int discard); - void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); - void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); - void (*xDestroy)(sqlite3_pcache*); + tdsqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(tdsqlite3_pcache*, int nCachesize); + int (*xPagecount)(tdsqlite3_pcache*); + void *(*xFetch)(tdsqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(tdsqlite3_pcache*, void*, int discard); + void (*xRekey)(tdsqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(tdsqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(tdsqlite3_pcache*); }; /* ** CAPI3REF: Online Backup Object ** -** The sqlite3_backup object records state information about an ongoing -** online backup operation. ^The sqlite3_backup object is created by -** a call to [sqlite3_backup_init()] and is destroyed by a call to -** [sqlite3_backup_finish()]. +** The tdsqlite3_backup object records state information about an ongoing +** online backup operation. ^The tdsqlite3_backup object is created by +** a call to [tdsqlite3_backup_init()] and is destroyed by a call to +** [tdsqlite3_backup_finish()]. ** ** See Also: [Using the SQLite Online Backup API] */ -typedef struct sqlite3_backup sqlite3_backup; +typedef struct tdsqlite3_backup tdsqlite3_backup; /* ** CAPI3REF: Online Backup API. @@ -7330,63 +8435,63 @@ typedef struct sqlite3_backup sqlite3_backup; ** ** ^(To perform a backup operation: ** <ol> -** <li><b>sqlite3_backup_init()</b> is called once to initialize the +** <li><b>tdsqlite3_backup_init()</b> is called once to initialize the ** backup, -** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer +** <li><b>tdsqlite3_backup_step()</b> is called one or more times to transfer ** the data between the two databases, and finally -** <li><b>sqlite3_backup_finish()</b> is called to release all resources +** <li><b>tdsqlite3_backup_finish()</b> is called to release all resources ** associated with the backup operation. ** </ol>)^ -** There should be exactly one call to sqlite3_backup_finish() for each -** successful call to sqlite3_backup_init(). +** There should be exactly one call to tdsqlite3_backup_finish() for each +** successful call to tdsqlite3_backup_init(). ** -** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b> +** [[tdsqlite3_backup_init()]] <b>tdsqlite3_backup_init()</b> ** -** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** ^The D and N arguments to tdsqlite3_backup_init(D,N,S,M) are the ** [database connection] associated with the destination database ** and the database name, respectively. ** ^The database name is "main" for the main database, "temp" for the ** temporary database, or the name specified after the AS keyword in ** an [ATTACH] statement for an attached database. ** ^The S and M arguments passed to -** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** tdsqlite3_backup_init(D,N,S,M) identify the [database connection] ** and database name of the source database, respectively. ** ^The source and destination [database connections] (parameters S and D) -** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** must be different or else tdsqlite3_backup_init(D,N,S,M) will fail with ** an error. ** -** ^A call to sqlite3_backup_init() will fail, returning NULL, if +** ^A call to tdsqlite3_backup_init() will fail, returning NULL, if ** there is already a read or read-write transaction open on the ** destination database. ** -** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** ^If an error occurs within tdsqlite3_backup_init(D,N,S,M), then NULL is ** returned and an error code and error message are stored in the ** destination [database connection] D. -** ^The error code and message for the failed call to sqlite3_backup_init() -** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or -** [sqlite3_errmsg16()] functions. -** ^A successful call to sqlite3_backup_init() returns a pointer to an -** [sqlite3_backup] object. -** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and -** sqlite3_backup_finish() functions to perform the specified backup +** ^The error code and message for the failed call to tdsqlite3_backup_init() +** can be retrieved using the [tdsqlite3_errcode()], [tdsqlite3_errmsg()], and/or +** [tdsqlite3_errmsg16()] functions. +** ^A successful call to tdsqlite3_backup_init() returns a pointer to an +** [tdsqlite3_backup] object. +** ^The [tdsqlite3_backup] object may be used with the tdsqlite3_backup_step() and +** tdsqlite3_backup_finish() functions to perform the specified backup ** operation. ** -** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b> +** [[tdsqlite3_backup_step()]] <b>tdsqlite3_backup_step()</b> ** -** ^Function sqlite3_backup_step(B,N) will copy up to N pages between -** the source and destination databases specified by [sqlite3_backup] object B. +** ^Function tdsqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [tdsqlite3_backup] object B. ** ^If N is negative, all remaining source pages are copied. -** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** ^If tdsqlite3_backup_step(B,N) successfully copies N pages and there ** are still more pages to be copied, then the function returns [SQLITE_OK]. -** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** ^If tdsqlite3_backup_step(B,N) successfully finishes copying all pages ** from source to destination, then it returns [SQLITE_DONE]. -** ^If an error occurs while running sqlite3_backup_step(B,N), +** ^If an error occurs while running tdsqlite3_backup_step(B,N), ** then an [error code] is returned. ^As well as [SQLITE_OK] and -** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_DONE], a call to tdsqlite3_backup_step() may return [SQLITE_READONLY], ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. ** -** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +** ^(The tdsqlite3_backup_step() might return [SQLITE_READONLY] if ** <ol> ** <li> the destination database was opened read-only, or ** <li> the destination database is using write-ahead-log journaling @@ -7395,76 +8500,76 @@ typedef struct sqlite3_backup sqlite3_backup; ** destination and source page sizes differ. ** </ol>)^ ** -** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then -** the [sqlite3_busy_handler | busy-handler function] +** ^If tdsqlite3_backup_step() cannot obtain a required file-system lock, then +** the [tdsqlite3_busy_handler | busy-handler function] ** is invoked (if one is specified). ^If the ** busy-handler returns non-zero before the lock is available, then ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to -** sqlite3_backup_step() can be retried later. ^If the source +** tdsqlite3_backup_step() can be retried later. ^If the source ** [database connection] -** is being used to write to the source database when sqlite3_backup_step() +** is being used to write to the source database when tdsqlite3_backup_step() ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this -** case the call to sqlite3_backup_step() can be retried later on. ^(If +** case the call to tdsqlite3_backup_step() can be retried later on. ^(If ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or ** [SQLITE_READONLY] is returned, then -** there is no point in retrying the call to sqlite3_backup_step(). These +** there is no point in retrying the call to tdsqlite3_backup_step(). These ** errors are considered fatal.)^ The application must accept ** that the backup operation has failed and pass the backup operation handle -** to the sqlite3_backup_finish() to release associated resources. +** to the tdsqlite3_backup_finish() to release associated resources. ** -** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** ^The first call to tdsqlite3_backup_step() obtains an exclusive lock ** on the destination file. ^The exclusive lock is not released until either -** sqlite3_backup_finish() is called or the backup operation is complete -** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to -** sqlite3_backup_step() obtains a [shared lock] on the source database that -** lasts for the duration of the sqlite3_backup_step() call. +** tdsqlite3_backup_finish() is called or the backup operation is complete +** and tdsqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** tdsqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the tdsqlite3_backup_step() call. ** ^Because the source database is not locked between calls to -** sqlite3_backup_step(), the source database may be modified mid-way +** tdsqlite3_backup_step(), the source database may be modified mid-way ** through the backup process. ^If the source database is modified by an ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be automatically -** restarted by the next call to sqlite3_backup_step(). ^If the source +** restarted by the next call to tdsqlite3_backup_step(). ^If the source ** database is modified by the using the same database connection as is used ** by the backup operation, then the backup database is automatically ** updated at the same time. ** -** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b> +** [[tdsqlite3_backup_finish()]] <b>tdsqlite3_backup_finish()</b> ** -** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** When tdsqlite3_backup_step() has returned [SQLITE_DONE], or when the ** application wishes to abandon the backup operation, the application -** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). -** ^The sqlite3_backup_finish() interfaces releases all -** resources associated with the [sqlite3_backup] object. -** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** should destroy the [tdsqlite3_backup] by passing it to tdsqlite3_backup_finish(). +** ^The tdsqlite3_backup_finish() interfaces releases all +** resources associated with the [tdsqlite3_backup] object. +** ^If tdsqlite3_backup_step() has not yet returned [SQLITE_DONE], then any ** active write-transaction on the destination database is rolled back. -** The [sqlite3_backup] object is invalid -** and may not be used following a call to sqlite3_backup_finish(). +** The [tdsqlite3_backup] object is invalid +** and may not be used following a call to tdsqlite3_backup_finish(). ** -** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no -** sqlite3_backup_step() errors occurred, regardless or whether or not -** sqlite3_backup_step() completed. +** ^The value returned by tdsqlite3_backup_finish is [SQLITE_OK] if no +** tdsqlite3_backup_step() errors occurred, regardless or whether or not +** tdsqlite3_backup_step() completed. ** ^If an out-of-memory condition or IO error occurred during any prior -** sqlite3_backup_step() call on the same [sqlite3_backup] object, then -** sqlite3_backup_finish() returns the corresponding [error code]. +** tdsqlite3_backup_step() call on the same [tdsqlite3_backup] object, then +** tdsqlite3_backup_finish() returns the corresponding [error code]. ** -** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from tdsqlite3_backup_step() ** is not a permanent error and does not affect the return value of -** sqlite3_backup_finish(). +** tdsqlite3_backup_finish(). ** -** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]] -** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b> +** [[tdsqlite3_backup_remaining()]] [[tdsqlite3_backup_pagecount()]] +** <b>tdsqlite3_backup_remaining() and tdsqlite3_backup_pagecount()</b> ** -** ^The sqlite3_backup_remaining() routine returns the number of pages still -** to be backed up at the conclusion of the most recent sqlite3_backup_step(). -** ^The sqlite3_backup_pagecount() routine returns the total number of pages +** ^The tdsqlite3_backup_remaining() routine returns the number of pages still +** to be backed up at the conclusion of the most recent tdsqlite3_backup_step(). +** ^The tdsqlite3_backup_pagecount() routine returns the total number of pages ** in the source database at the conclusion of the most recent -** sqlite3_backup_step(). +** tdsqlite3_backup_step(). ** ^(The values returned by these functions are only updated by -** sqlite3_backup_step(). If the source database is modified in a way that +** tdsqlite3_backup_step(). If the source database is modified in a way that ** changes the size of the source database or the number of pages remaining, -** those changes are not reflected in the output of sqlite3_backup_pagecount() -** and sqlite3_backup_remaining() until after the next -** sqlite3_backup_step().)^ +** those changes are not reflected in the output of tdsqlite3_backup_pagecount() +** and tdsqlite3_backup_remaining() until after the next +** tdsqlite3_backup_step().)^ ** ** <b>Concurrent Usage of Database Handles</b> ** @@ -7476,8 +8581,8 @@ typedef struct sqlite3_backup sqlite3_backup; ** ** However, the application must guarantee that the destination ** [database connection] is not passed to any other API (by any thread) after -** sqlite3_backup_init() is called and before the corresponding call to -** sqlite3_backup_finish(). SQLite does not currently check to see +** tdsqlite3_backup_init() is called and before the corresponding call to +** tdsqlite3_backup_finish(). SQLite does not currently check to see ** if the application incorrectly accesses the destination [database connection] ** and so no error code is reported, but the operations may malfunction ** nevertheless. Use of the destination database connection while a @@ -7488,29 +8593,29 @@ typedef struct sqlite3_backup sqlite3_backup; ** is not accessed while the backup is running. In practice this means ** that the application must guarantee that the disk file being ** backed up to is not accessed by any connection within the process, -** not just the specific connection that was passed to sqlite3_backup_init(). +** not just the specific connection that was passed to tdsqlite3_backup_init(). ** -** The [sqlite3_backup] object itself is partially threadsafe. Multiple -** threads may safely make multiple concurrent calls to sqlite3_backup_step(). -** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** The [tdsqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to tdsqlite3_backup_step(). +** However, the tdsqlite3_backup_remaining() and tdsqlite3_backup_pagecount() ** APIs are not strictly speaking threadsafe. If they are invoked at the -** same time as another thread is invoking sqlite3_backup_step() it is +** same time as another thread is invoking tdsqlite3_backup_step() it is ** possible that they return invalid values. */ -SQLITE_API sqlite3_backup *sqlite3_backup_init( - sqlite3 *pDest, /* Destination database handle */ +SQLITE_API tdsqlite3_backup *tdsqlite3_backup_init( + tdsqlite3 *pDest, /* Destination database handle */ const char *zDestName, /* Destination database name */ - sqlite3 *pSource, /* Source database handle */ + tdsqlite3 *pSource, /* Source database handle */ const char *zSourceName /* Source database name */ ); -SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); -SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); -SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); -SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); +SQLITE_API int tdsqlite3_backup_step(tdsqlite3_backup *p, int nPage); +SQLITE_API int tdsqlite3_backup_finish(tdsqlite3_backup *p); +SQLITE_API int tdsqlite3_backup_remaining(tdsqlite3_backup *p); +SQLITE_API int tdsqlite3_backup_pagecount(tdsqlite3_backup *p); /* ** CAPI3REF: Unlock Notification -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** ** ^When running in shared-cache mode, a database operation may fail with ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or @@ -7531,17 +8636,17 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** identity of the database connection (the blocking connection) that ** has locked the required resource is stored internally. ^After an ** application receives an SQLITE_LOCKED error, it may call the -** sqlite3_unlock_notify() method with the blocked connection handle as +** tdsqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked ** when the blocking connections current transaction is concluded. ^The -** callback is invoked from within the [sqlite3_step] or [sqlite3_close] -** call that concludes the blocking connections transaction. +** callback is invoked from within the [tdsqlite3_step] or [tdsqlite3_close] +** call that concludes the blocking connection's transaction. ** -** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** ^(If tdsqlite3_unlock_notify() is called in a multi-threaded application, ** there is a chance that the blocking connection will have already -** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** concluded its transaction by the time tdsqlite3_unlock_notify() is invoked. ** If this happens, then the specified callback is invoked immediately, -** from within the call to sqlite3_unlock_notify().)^ +** from within the call to tdsqlite3_unlock_notify().)^ ** ** ^If the blocked connection is attempting to obtain a write-lock on a ** shared-cache table, and more than one other connection currently holds @@ -7549,19 +8654,19 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** the other connections to use as the blocking connection. ** ** ^(There may be at most one unlock-notify callback registered by a -** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection. If tdsqlite3_unlock_notify() is called when the ** blocked connection already has a registered unlock-notify callback, -** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** then the new callback replaces the old.)^ ^If tdsqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing ** unlock-notify callback is canceled. ^The blocked connections ** unlock-notify callback may also be canceled by closing the blocked -** connection using [sqlite3_close()]. +** connection using [tdsqlite3_close()]. ** ** The unlock-notify callback is not reentrant. If an application invokes -** any sqlite3_xxx API functions from within an unlock-notify callback, a +** any tdsqlite3_xxx API functions from within an unlock-notify callback, a ** crash or deadlock may be the result. ** -** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** ^Unless deadlock is detected (see below), tdsqlite3_unlock_notify() always ** returns SQLITE_OK. ** ** <b>Callback Invocation Details</b> @@ -7573,7 +8678,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** an unlock-notify callback is a pointer to an array of void* pointers, ** and the second is the number of entries in the array. ** -** When a blocking connections transaction is concluded, there may be +** When a blocking connection's transaction is concluded, there may be ** more than one blocked connection that has registered for an unlock-notify ** callback. ^If two or more such blocked connections have specified the ** same callback function, then instead of invoking the callback function @@ -7592,8 +8697,8 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** Y is waiting on connection X's transaction, then neither connection ** will proceed and the system may remain deadlocked indefinitely. ** -** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock -** detection. ^If a given call to sqlite3_unlock_notify() would put the +** To avoid this scenario, the tdsqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to tdsqlite3_unlock_notify() would put the ** system in a deadlocked state, then SQLITE_LOCKED is returned and no ** unlock-notify callback is registered. The system is said to be in ** a deadlocked state if connection A has registered for an unlock-notify @@ -7607,24 +8712,24 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** ** <b>The "DROP TABLE" Exception</b> ** -** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost -** always appropriate to call sqlite3_unlock_notify(). There is however, +** When a call to [tdsqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call tdsqlite3_unlock_notify(). There is however, ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, ** SQLite checks if there are any currently executing SELECT statements ** that belong to the same connection. If there are, SQLITE_LOCKED is ** returned. In this case there is no "blocking connection", so invoking -** sqlite3_unlock_notify() results in the unlock-notify callback being +** tdsqlite3_unlock_notify() results in the unlock-notify callback being ** invoked immediately. If the application then re-attempts the "DROP TABLE" ** or "DROP INDEX" query, an infinite loop might be the result. ** ** One way around this problem is to check the extended error code returned -** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** by an tdsqlite3_step() call. ^(If there is a blocking connection, then the ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in ** the special "DROP TABLE/INDEX" case, the extended error code is just ** SQLITE_LOCKED.)^ */ -SQLITE_API int sqlite3_unlock_notify( - sqlite3 *pBlocked, /* Waiting connection */ +SQLITE_API int tdsqlite3_unlock_notify( + tdsqlite3 *pBlocked, /* Waiting connection */ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ void *pNotifyArg /* Argument to pass to xNotify */ ); @@ -7633,82 +8738,82 @@ SQLITE_API int sqlite3_unlock_notify( /* ** CAPI3REF: String Comparison ** -** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications +** ^The [tdsqlite3_stricmp()] and [tdsqlite3_strnicmp()] APIs allow applications ** and extensions to compare the contents of two buffers containing UTF-8 ** strings in a case-independent fashion, using the same definition of "case ** independence" that SQLite uses internally when comparing identifiers. */ -SQLITE_API int sqlite3_stricmp(const char *, const char *); -SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); +SQLITE_API int tdsqlite3_stricmp(const char *, const char *); +SQLITE_API int tdsqlite3_strnicmp(const char *, const char *, int); /* ** CAPI3REF: String Globbing * -** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if +** ^The [tdsqlite3_strglob(P,X)] interface returns zero if and only if ** string X matches the [GLOB] pattern P. ** ^The definition of [GLOB] pattern matching used in -** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the -** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function +** [tdsqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the +** SQL dialect understood by SQLite. ^The [tdsqlite3_strglob(P,X)] function ** is case sensitive. ** ** Note that this routine returns zero on a match and non-zero if the strings -** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +** do not match, the same as [tdsqlite3_stricmp()] and [tdsqlite3_strnicmp()]. ** -** See also: [sqlite3_strlike()]. +** See also: [tdsqlite3_strlike()]. */ -SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); +SQLITE_API int tdsqlite3_strglob(const char *zGlob, const char *zStr); /* ** CAPI3REF: String LIKE Matching * -** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if +** ^The [tdsqlite3_strlike(P,X,E)] interface returns zero if and only if ** string X matches the [LIKE] pattern P with escape character E. ** ^The definition of [LIKE] pattern matching used in -** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" +** [tdsqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without -** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0. -** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case +** the ESCAPE clause, set the E parameter of [tdsqlite3_strlike(P,X,E)] to 0. +** ^As with the LIKE operator, the [tdsqlite3_strlike(P,X,E)] function is case ** insensitive - equivalent upper and lower case ASCII characters match ** one another. ** -** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though +** ^The [tdsqlite3_strlike(P,X,E)] function matches Unicode characters, though ** only ASCII characters are case folded. ** ** Note that this routine returns zero on a match and non-zero if the strings -** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. +** do not match, the same as [tdsqlite3_stricmp()] and [tdsqlite3_strnicmp()]. ** -** See also: [sqlite3_strglob()]. +** See also: [tdsqlite3_strglob()]. */ -SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); +SQLITE_API int tdsqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); /* ** CAPI3REF: Error Logging Interface ** -** ^The [sqlite3_log()] interface writes a message into the [error log] -** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^The [tdsqlite3_log()] interface writes a message into the [error log] +** established by the [SQLITE_CONFIG_LOG] option to [tdsqlite3_config()]. ** ^If logging is enabled, the zFormat string and subsequent arguments are -** used with [sqlite3_snprintf()] to generate the final output string. +** used with [tdsqlite3_snprintf()] to generate the final output string. ** -** The sqlite3_log() interface is intended for use by extensions such as +** The tdsqlite3_log() interface is intended for use by extensions such as ** virtual tables, collating functions, and SQL functions. While there is -** nothing to prevent an application from calling sqlite3_log(), doing so +** nothing to prevent an application from calling tdsqlite3_log(), doing so ** is considered bad form. ** ** The zFormat string must not be NULL. ** -** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** To avoid deadlocks and other threading problems, the tdsqlite3_log() routine ** will not use dynamically allocated memory. The log message is stored in ** a fixed-length buffer on the stack. If the log message is longer than ** a few hundred characters, it will be truncated to the length of the ** buffer. */ -SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); +SQLITE_API void tdsqlite3_log(int iErrCode, const char *zFormat, ...); /* ** CAPI3REF: Write-Ahead Log Commit Hook -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The [sqlite3_wal_hook()] function is used to register a callback that +** ^The [tdsqlite3_wal_hook()] function is used to register a callback that ** is invoked each time data is committed to a database in wal mode. ** ** ^(The callback is invoked by SQLite after the commit has taken place and @@ -7716,7 +8821,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); ** may read, write or [checkpoint] the database as required. ** ** ^The first parameter passed to the callback function when it is invoked -** is a copy of the third parameter passed to sqlite3_wal_hook() when +** is a copy of the third parameter passed to tdsqlite3_wal_hook() when ** registering the callback. ^The second is a copy of the database handle. ** ^The third parameter is the name of the database that was written to - ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter @@ -7732,24 +8837,24 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); ** are undefined. ** ** A single database handle may have at most a single write-ahead log callback -** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** registered at one time. ^Calling [tdsqlite3_wal_hook()] replaces any ** previously registered write-ahead log callback. ^Note that the -** [sqlite3_wal_autocheckpoint()] interface and the -** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will -** overwrite any prior [sqlite3_wal_hook()] settings. +** [tdsqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [tdsqlite3_wal_hook()] and will +** overwrite any prior [tdsqlite3_wal_hook()] settings. */ -SQLITE_API void *sqlite3_wal_hook( - sqlite3*, - int(*)(void *,sqlite3*,const char*,int), +SQLITE_API void *tdsqlite3_wal_hook( + tdsqlite3*, + int(*)(void *,tdsqlite3*,const char*,int), void* ); /* ** CAPI3REF: Configure an auto-checkpoint -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around -** [sqlite3_wal_hook()] that causes any database on [database connection] D +** ^The [tdsqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [tdsqlite3_wal_hook()] that causes any database on [database connection] D ** to automatically [checkpoint] ** after committing a transaction if there are N or ** more frames in the [write-ahead log] file. ^Passing zero or @@ -7757,15 +8862,15 @@ SQLITE_API void *sqlite3_wal_hook( ** checkpoints entirely. ** ** ^The callback registered by this function replaces any existing callback -** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback -** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** registered using [tdsqlite3_wal_hook()]. ^Likewise, registering a callback +** using [tdsqlite3_wal_hook()] disables the automatic checkpoint mechanism ** configured by this function. ** ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface ** from SQL. ** ** ^Checkpoints initiated by this mechanism are -** [sqlite3_wal_checkpoint_v2|PASSIVE]. +** [tdsqlite3_wal_checkpoint_v2|PASSIVE]. ** ** ^Every new [database connection] defaults to having the auto-checkpoint ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] @@ -7773,35 +8878,35 @@ SQLITE_API void *sqlite3_wal_hook( ** is only necessary if the default setting is found to be suboptimal ** for a particular application. */ -SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); +SQLITE_API int tdsqlite3_wal_autocheckpoint(tdsqlite3 *db, int N); /* ** CAPI3REF: Checkpoint a database -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to -** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ +** ^(The tdsqlite3_wal_checkpoint(D,X) is equivalent to +** [tdsqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ ** -** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the +** In brief, tdsqlite3_wal_checkpoint(D,X) causes the content in the ** [write-ahead log] for database X on [database connection] D to be ** transferred into the database file and for the write-ahead log to ** be reset. See the [checkpointing] documentation for addition ** information. ** ** This interface used to be the only way to cause a checkpoint to -** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()] +** occur. But then the newer and more powerful [tdsqlite3_wal_checkpoint_v2()] ** interface was added. This interface is retained for backwards ** compatibility and as a convenience for applications that need to manually ** start a callback but which do not need the full power (and corresponding -** complication) of [sqlite3_wal_checkpoint_v2()]. +** complication) of [tdsqlite3_wal_checkpoint_v2()]. */ -SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); +SQLITE_API int tdsqlite3_wal_checkpoint(tdsqlite3 *db, const char *zDb); /* ** CAPI3REF: Checkpoint a database -** METHOD: sqlite3 +** METHOD: tdsqlite3 ** -** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint +** ^(The tdsqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint ** operation on database X of [database connection] D in mode M. Status ** information is written back into integers pointed to by L and C.)^ ** ^(The M parameter must be a valid [checkpoint mode]:)^ @@ -7817,7 +8922,7 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); ** ** <dt>SQLITE_CHECKPOINT_FULL<dd> ** ^This mode blocks (it invokes the -** [sqlite3_busy_handler|busy-handler callback]) until there is no +** [tdsqlite3_busy_handler|busy-handler callback]) until there is no ** database writer and all readers are reading from the most recent database ** snapshot. ^It then checkpoints all frames in the log file and syncs the ** database file. ^This mode blocks new database writers while it is pending, @@ -7882,15 +8987,15 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); ** attached database, SQLITE_ERROR is returned to the caller. ** ** ^Unless it returns SQLITE_MISUSE, -** the sqlite3_wal_checkpoint_v2() interface +** the tdsqlite3_wal_checkpoint_v2() interface ** sets the error information that is queried by -** [sqlite3_errcode()] and [sqlite3_errmsg()]. +** [tdsqlite3_errcode()] and [tdsqlite3_errmsg()]. ** ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface ** from SQL. */ -SQLITE_API int sqlite3_wal_checkpoint_v2( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3_wal_checkpoint_v2( + tdsqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ @@ -7902,8 +9007,8 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( ** KEYWORDS: {checkpoint mode} ** ** These constants define all valid values for the "checkpoint mode" passed -** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface. -** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the +** as the third parameter to the [tdsqlite3_wal_checkpoint_v2()] interface. +** See the [tdsqlite3_wal_checkpoint_v2()] documentation for details on the ** meaning of each of these checkpoint modes. */ #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ @@ -7921,25 +9026,32 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( ** If this interface is invoked outside the context of an xConnect or ** xCreate virtual table method then the behavior is undefined. ** -** At present, there is only one option that may be configured using -** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options -** may be added in the future. +** In the call tdsqlite3_vtab_config(D,C,...) the D parameter is the +** [database connection] in which the virtual table is being created and +** which is passed in as the first argument to the [xConnect] or [xCreate] +** method that is invoking tdsqlite3_vtab_config(). The C parameter is one +** of the [virtual table configuration options]. The presence and meaning +** of parameters after C depend on which [virtual table configuration option] +** is used. */ -SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); +SQLITE_API int tdsqlite3_vtab_config(tdsqlite3*, int op, ...); /* ** CAPI3REF: Virtual Table Configuration Options +** KEYWORDS: {virtual table configuration options} +** KEYWORDS: {virtual table configuration option} ** ** These macros define the various options to the -** [sqlite3_vtab_config()] interface that [virtual table] implementations +** [tdsqlite3_vtab_config()] interface that [virtual table] implementations ** can use to customize and optimize their behavior. ** ** <dl> -** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT +** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]] +** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt> ** <dd>Calls of the form -** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, +** [tdsqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, ** where X is an integer. If X is zero, then the [virtual table] whose -** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not +** [xCreate] or [xConnect] method invoked [tdsqlite3_vtab_config()] does not ** support constraints. In this configuration (which is the default) if ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been @@ -7958,15 +9070,37 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); ** ** Virtual table implementations that are required to handle OR REPLACE ** must do so within the [xUpdate] method. If a call to the -** [sqlite3_vtab_on_conflict()] function indicates that the current ON +** [tdsqlite3_vtab_on_conflict()] function indicates that the current ON ** CONFLICT policy is REPLACE, the virtual table implementation should ** silently replace the appropriate rows within the xUpdate callback and ** return SQLITE_OK. Or, if this is not possible, it may return ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT ** constraint handling. +** </dd> +** +** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt> +** <dd>Calls of the form +** [tdsqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the +** the [xConnect] or [xCreate] methods of a [virtual table] implmentation +** prohibits that virtual table from being used from within triggers and +** views. +** </dd> +** +** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt> +** <dd>Calls of the form +** [tdsqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the +** the [xConnect] or [xCreate] methods of a [virtual table] implmentation +** identify that virtual table as being safe to use from within triggers +** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the +** virtual table can do no serious harm even if it is controlled by a +** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS +** flag unless absolutely necessary. +** </dd> ** </dl> */ #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 +#define SQLITE_VTAB_INNOCUOUS 2 +#define SQLITE_VTAB_DIRECTONLY 3 /* ** CAPI3REF: Determine The Virtual Table Conflict Policy @@ -7978,22 +9112,56 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); ** of the SQL statement that triggered the call to the [xUpdate] method of the ** [virtual table]. */ -SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); +SQLITE_API int tdsqlite3_vtab_on_conflict(tdsqlite3 *); + +/* +** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE +** +** If the tdsqlite3_vtab_nochange(X) routine is called within the [xColumn] +** method of a [virtual table], then it returns true if and only if the +** column is being fetched as part of an UPDATE operation during which the +** column value will not change. Applications might use this to substitute +** a return value that is less expensive to compute and that the corresponding +** [xUpdate] method understands as a "no-change" value. +** +** If the [xColumn] method calls tdsqlite3_vtab_nochange() and finds that +** the column is not changed by the UPDATE statement, then the xColumn +** method can optionally return without setting a result, without calling +** any of the [tdsqlite3_result_int|tdsqlite3_result_xxxxx() interfaces]. +** In that case, [tdsqlite3_value_nochange(X)] will return true for the +** same column in the [xUpdate] method. +*/ +SQLITE_API int tdsqlite3_vtab_nochange(tdsqlite3_context*); + +/* +** CAPI3REF: Determine The Collation For a Virtual Table Constraint +** +** This function may only be called from within a call to the [xBestIndex] +** method of a [virtual table]. +** +** The first argument must be the tdsqlite3_index_info object that is the +** first parameter to the xBestIndex() method. The second argument must be +** an index into the aConstraint[] array belonging to the tdsqlite3_index_info +** structure passed to xBestIndex. This function returns a pointer to a buffer +** containing the name of the collation sequence for the corresponding +** constraint. +*/ +SQLITE_API SQLITE_EXPERIMENTAL const char *tdsqlite3_vtab_collation(tdsqlite3_index_info*,int); /* ** CAPI3REF: Conflict resolution modes ** KEYWORDS: {conflict resolution mode} ** -** These constants are returned by [sqlite3_vtab_on_conflict()] to +** These constants are returned by [tdsqlite3_vtab_on_conflict()] to ** inform a [virtual table] implementation what the [ON CONFLICT] mode ** is for the SQL statement being evaluated. ** ** Note that the [SQLITE_IGNORE] constant is also used as a potential -** return value from the [sqlite3_set_authorizer()] callback and that +** return value from the [tdsqlite3_set_authorizer()] callback and that ** [SQLITE_ABORT] is also a [result code]. */ #define SQLITE_ROLLBACK 1 -/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ +/* #define SQLITE_IGNORE 2 // Also used by tdsqlite3_authorizer() callback */ #define SQLITE_FAIL 3 /* #define SQLITE_ABORT 4 // Also an error code */ #define SQLITE_REPLACE 5 @@ -8003,8 +9171,8 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); ** KEYWORDS: {scanstatus options} ** ** The following constants can be used for the T parameter to the -** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a -** different metric for sqlite3_stmt_scanstatus() to return. +** [tdsqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a +** different metric for tdsqlite3_stmt_scanstatus() to return. ** ** When the value returned to V is a string, space to hold that string is ** managed by the prepared statement S and will be automatically freed when @@ -8012,15 +9180,15 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); ** ** <dl> ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt> -** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be +** <dd>^The [tdsqlite3_int64] variable pointed to by the V parameter will be ** set to the total number of times that the X-th loop has run.</dd> ** ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt> -** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set +** <dd>^The [tdsqlite3_int64] variable pointed to by the V parameter will be set ** to the total number of rows examined by all iterations of the X-th loop.</dd> ** ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt> -** <dd>^The "double" variable pointed to by the T parameter will be set to the +** <dd>^The "double" variable pointed to by the V parameter will be set to the ** query planner's estimate for the average number of rows output from each ** iteration of the X-th loop. If the query planner's estimates was accurate, ** then this value will approximate the quotient NVISIT/NLOOP and the @@ -8028,17 +9196,17 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); ** be the NLOOP value for the current loop. ** ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt> -** <dd>^The "const char *" variable pointed to by the T parameter will be set +** <dd>^The "const char *" variable pointed to by the V parameter will be set ** to a zero-terminated UTF-8 string containing the name of the index or table ** used for the X-th loop. ** ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt> -** <dd>^The "const char *" variable pointed to by the T parameter will be set +** <dd>^The "const char *" variable pointed to by the V parameter will be set ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] ** description for the X-th loop. ** ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt> -** <dd>^The "int" variable pointed to by the T parameter will be set to the +** <dd>^The "int" variable pointed to by the V parameter will be set to the ** "select-id" for the X-th loop. The select-id identifies which query or ** subquery the loop is part of. The main query has a select-id of zero. ** The select-id is the same value as is output in the first column @@ -8054,7 +9222,7 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); /* ** CAPI3REF: Prepared Statement Scan Status -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** ** This interface returns information about the predicted and measured ** performance for pStmt. Advanced applications can use this @@ -8081,10 +9249,10 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); ** as if the loop did not exist - it returns non-zero and leave the variable ** that pOut points to unchanged. ** -** See also: [sqlite3_stmt_scanstatus_reset()] +** See also: [tdsqlite3_stmt_scanstatus_reset()] */ -SQLITE_API int sqlite3_stmt_scanstatus( - sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ +SQLITE_API int tdsqlite3_stmt_scanstatus( + tdsqlite3_stmt *pStmt, /* Prepared statement for which info desired */ int idx, /* Index of loop to report on */ int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ void *pOut /* Result written here */ @@ -8092,24 +9260,24 @@ SQLITE_API int sqlite3_stmt_scanstatus( /* ** CAPI3REF: Zero Scan-Status Counters -** METHOD: sqlite3_stmt +** METHOD: tdsqlite3_stmt ** -** ^Zero all [sqlite3_stmt_scanstatus()] related event counters. +** ^Zero all [tdsqlite3_stmt_scanstatus()] related event counters. ** ** This API is only available if the library is built with pre-processor ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined. */ -SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); +SQLITE_API void tdsqlite3_stmt_scanstatus_reset(tdsqlite3_stmt*); /* ** CAPI3REF: Flush caches to disk mid-transaction ** ** ^If a write-transaction is open on [database connection] D when the -** [sqlite3_db_cacheflush(D)] interface invoked, any dirty +** [tdsqlite3_db_cacheflush(D)] interface invoked, any dirty ** pages in the pager-cache that are not currently in use are written out ** to disk. A dirty page may be in use if a database cursor created by an ** active SQL statement is reading from it, or if it is page 1 of a database -** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)] +** file (page 1 is always "in use"). ^The [tdsqlite3_db_cacheflush(D)] ** interface flushes caches for all schemas - "main", "temp", and ** any [attached] databases. ** @@ -8126,12 +9294,12 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); ** example an IO error or out-of-memory condition), then processing is ** abandoned and an SQLite [error code] is returned to the caller immediately. ** -** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK. +** ^Otherwise, if no error occurs, [tdsqlite3_db_cacheflush()] returns SQLITE_OK. ** ** ^This function does not set the database handle error code or message -** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions. +** returned by the [tdsqlite3_errcode()] and [tdsqlite3_errmsg()] functions. */ -SQLITE_API int sqlite3_db_cacheflush(sqlite3*); +SQLITE_API int tdsqlite3_db_cacheflush(tdsqlite3*); /* ** CAPI3REF: The pre-update hook. @@ -8139,20 +9307,20 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); ** ^These interfaces are only available if SQLite is compiled using the ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option. ** -** ^The [sqlite3_preupdate_hook()] interface registers a callback function +** ^The [tdsqlite3_preupdate_hook()] interface registers a callback function ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation -** on a [rowid table]. +** on a database table. ** ^At most one preupdate hook may be registered at a time on a single -** [database connection]; each call to [sqlite3_preupdate_hook()] overrides +** [database connection]; each call to [tdsqlite3_preupdate_hook()] overrides ** the previous setting. -** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()] +** ^The preupdate hook is disabled by invoking [tdsqlite3_preupdate_hook()] ** with a NULL pointer as the second parameter. -** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as +** ^The third parameter to [tdsqlite3_preupdate_hook()] is passed through as ** the first parameter to callbacks. ** -** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate -** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID] -** tables. +** ^The preupdate hook only fires for changes to real database tables; the +** preupdate hook is not invoked for changes to [virtual tables] or to +** system tables like sqlite_master or sqlite_stat1. ** ** ^The second parameter to the preupdate callback is a pointer to ** the [database connection] that registered the preupdate hook. @@ -8166,15 +9334,19 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); ** databases.)^ ** ^The fifth parameter to the preupdate callback is the name of the ** table that is being modified. -** ^The sixth parameter to the preupdate callback is the initial [rowid] of the -** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is -** undefined for SQLITE_INSERT changes. -** ^The seventh parameter to the preupdate callback is the final [rowid] of -** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is -** undefined for SQLITE_DELETE changes. -** -** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()], -** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces +** +** For an UPDATE or DELETE operation on a [rowid table], the sixth +** parameter passed to the preupdate callback is the initial [rowid] of the +** row being modified or deleted. For an INSERT operation on a rowid table, +** or any operation on a WITHOUT ROWID table, the value of the sixth +** parameter is undefined. For an INSERT or UPDATE on a rowid table the +** seventh parameter is the final rowid value of the row being inserted +** or updated. The value of the seventh parameter passed to the callback +** function is not defined for operations on WITHOUT ROWID tables, or for +** INSERT operations on rowid tables. +** +** The [tdsqlite3_preupdate_old()], [tdsqlite3_preupdate_new()], +** [tdsqlite3_preupdate_count()], and [tdsqlite3_preupdate_depth()] interfaces ** provide additional information about a preupdate event. These routines ** may only be called from within a preupdate callback. Invoking any of ** these routines from outside of a preupdate callback or with a @@ -8182,52 +9354,54 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); ** to the preupdate callback results in undefined and probably undesirable ** behavior. ** -** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns +** ^The [tdsqlite3_preupdate_count(D)] interface returns the number of columns ** in the row that is being inserted, updated, or deleted. ** -** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to -** a [protected sqlite3_value] that contains the value of the Nth column of +** ^The [tdsqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to +** a [protected tdsqlite3_value] that contains the value of the Nth column of ** the table row before it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the -** behavior is undefined. The [sqlite3_value] that P points to +** behavior is undefined. The [tdsqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** -** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to -** a [protected sqlite3_value] that contains the value of the Nth column of +** ^The [tdsqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to +** a [protected tdsqlite3_value] that contains the value of the Nth column of ** the table row after it is updated. The N parameter must be between 0 ** and one less than the number of columns or the behavior will be ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the -** behavior is undefined. The [sqlite3_value] that P points to +** behavior is undefined. The [tdsqlite3_value] that P points to ** will be destroyed when the preupdate callback returns. ** -** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate +** ^The [tdsqlite3_preupdate_depth(D)] interface returns 0 if the preupdate ** callback was invoked as a result of a direct insert, update, or delete ** operation; or 1 for inserts, updates, or deletes invoked by top-level ** triggers; or 2 for changes resulting from triggers called by top-level ** triggers; and so forth. ** -** See also: [sqlite3_update_hook()] +** See also: [tdsqlite3_update_hook()] */ -SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_preupdate_hook( - sqlite3 *db, +#if defined(SQLITE_ENABLE_PREUPDATE_HOOK) +SQLITE_API void *tdsqlite3_preupdate_hook( + tdsqlite3 *db, void(*xPreUpdate)( void *pCtx, /* Copy of third arg to preupdate_hook() */ - sqlite3 *db, /* Database handle */ + tdsqlite3 *db, /* Database handle */ int op, /* SQLITE_UPDATE, DELETE or INSERT */ char const *zDb, /* Database name */ char const *zName, /* Table name */ - sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ - sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ + tdsqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ + tdsqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ ), void* ); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_count(sqlite3 *); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_depth(sqlite3 *); -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); +SQLITE_API int tdsqlite3_preupdate_old(tdsqlite3 *, int, tdsqlite3_value **); +SQLITE_API int tdsqlite3_preupdate_count(tdsqlite3 *); +SQLITE_API int tdsqlite3_preupdate_depth(tdsqlite3 *); +SQLITE_API int tdsqlite3_preupdate_new(tdsqlite3 *, int, tdsqlite3_value **); +#endif /* ** CAPI3REF: Low-level system error code @@ -8235,16 +9409,15 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_new(sqlite3 *, int, sqlite3 ** ^Attempt to return the underlying operating system error code or error ** number that caused the most recent I/O error or failure to open a file. ** The return value is OS-dependent. For example, on unix systems, after -** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be +** [tdsqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be ** called to get back the underlying "errno" that caused the problem, such ** as ENOSPC, EAUTH, EISDIR, and so forth. */ -SQLITE_API int sqlite3_system_errno(sqlite3*); +SQLITE_API int tdsqlite3_system_errno(tdsqlite3*); /* ** CAPI3REF: Database Snapshot -** KEYWORDS: {snapshot} -** EXPERIMENTAL +** KEYWORDS: {snapshot} {tdsqlite3_snapshot} ** ** An instance of the snapshot object records the state of a [WAL mode] ** database for some specific point in history. @@ -8257,65 +9430,96 @@ SQLITE_API int sqlite3_system_errno(sqlite3*); ** Subsequent changes to the database from other connections are not seen ** by the reader until a new read transaction is started. ** -** The sqlite3_snapshot object records state information about an historical +** The tdsqlite3_snapshot object records state information about an historical ** version of the database file so that it is possible to later open a new read ** transaction that sees that historical version of the database rather than ** the most recent version. -** -** The constructor for this object is [sqlite3_snapshot_get()]. The -** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer -** to an historical snapshot (if possible). The destructor for -** sqlite3_snapshot objects is [sqlite3_snapshot_free()]. */ -typedef struct sqlite3_snapshot sqlite3_snapshot; +typedef struct tdsqlite3_snapshot { + unsigned char hidden[48]; +} tdsqlite3_snapshot; /* ** CAPI3REF: Record A Database Snapshot -** EXPERIMENTAL +** CONSTRUCTOR: tdsqlite3_snapshot ** -** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a -** new [sqlite3_snapshot] object that records the current state of +** ^The [tdsqlite3_snapshot_get(D,S,P)] interface attempts to make a +** new [tdsqlite3_snapshot] object that records the current state of ** schema S in database connection D. ^On success, the -** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly -** created [sqlite3_snapshot] object into *P and returns SQLITE_OK. -** ^If schema S of [database connection] D is not a [WAL mode] database -** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)] -** leaves the *P value unchanged and returns an appropriate [error code]. -** -** The [sqlite3_snapshot] object returned from a successful call to -** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()] +** [tdsqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly +** created [tdsqlite3_snapshot] object into *P and returns SQLITE_OK. +** If there is not already a read-transaction open on schema S when +** this function is called, one is opened automatically. +** +** The following must be true for this function to succeed. If any of +** the following statements are false when tdsqlite3_snapshot_get() is +** called, SQLITE_ERROR is returned. The final value of *P is undefined +** in this case. +** +** <ul> +** <li> The database handle must not be in [autocommit mode]. +** +** <li> Schema S of [database connection] D must be a [WAL mode] database. +** +** <li> There must not be a write transaction open on schema S of database +** connection D. +** +** <li> One or more transactions must have been written to the current wal +** file since it was created on disk (by any connection). This means +** that a snapshot cannot be taken on a wal mode database with no wal +** file immediately after it is first opened. At least one transaction +** must be written to it first. +** </ul> +** +** This function may also return SQLITE_NOMEM. If it is called with the +** database handle in autocommit mode but fails for some other reason, +** whether or not a read transaction is opened on schema S is undefined. +** +** The [tdsqlite3_snapshot] object returned from a successful call to +** [tdsqlite3_snapshot_get()] must be freed using [tdsqlite3_snapshot_free()] ** to avoid a memory leak. ** -** The [sqlite3_snapshot_get()] interface is only available when the -** SQLITE_ENABLE_SNAPSHOT compile-time option is used. +** The [tdsqlite3_snapshot_get()] interface is only available when the +** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( - sqlite3 *db, +SQLITE_API SQLITE_EXPERIMENTAL int tdsqlite3_snapshot_get( + tdsqlite3 *db, const char *zSchema, - sqlite3_snapshot **ppSnapshot + tdsqlite3_snapshot **ppSnapshot ); /* ** CAPI3REF: Start a read transaction on an historical snapshot -** EXPERIMENTAL -** -** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a -** read transaction for schema S of -** [database connection] D such that the read transaction -** refers to historical [snapshot] P, rather than the most -** recent change to the database. -** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success -** or an appropriate [error code] if it fails. -** -** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be -** the first operation following the [BEGIN] that takes the schema S -** out of [autocommit mode]. -** ^In other words, schema S must not currently be in -** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the -** database connection D must be out of [autocommit mode]. -** ^A [snapshot] will fail to open if it has been overwritten by a -** [checkpoint]. -** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the +** METHOD: tdsqlite3_snapshot +** +** ^The [tdsqlite3_snapshot_open(D,S,P)] interface either starts a new read +** transaction or upgrades an existing one for schema S of +** [database connection] D such that the read transaction refers to +** historical [snapshot] P, rather than the most recent change to the +** database. ^The [tdsqlite3_snapshot_open()] interface returns SQLITE_OK +** on success or an appropriate [error code] if it fails. +** +** ^In order to succeed, the database connection must not be in +** [autocommit mode] when [tdsqlite3_snapshot_open(D,S,P)] is called. If there +** is already a read transaction open on schema S, then the database handle +** must have no active statements (SELECT statements that have been passed +** to tdsqlite3_step() but not tdsqlite3_reset() or tdsqlite3_finalize()). +** SQLITE_ERROR is returned if either of these conditions is violated, or +** if schema S does not exist, or if the snapshot object is invalid. +** +** ^A call to tdsqlite3_snapshot_open() will fail to open if the specified +** snapshot has been overwritten by a [checkpoint]. In this case +** SQLITE_ERROR_SNAPSHOT is returned. +** +** If there is already a read transaction open when this function is +** invoked, then the same read transaction remains open (on the same +** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT +** is returned. If another error code - for example SQLITE_PROTOCOL or an +** SQLITE_IOERR error code - is returned, then the final state of the +** read transaction is undefined. If SQLITE_OK is returned, then the +** read transaction is now open on database snapshot P. +** +** ^(A call to [tdsqlite3_snapshot_open(D,S,P)] will fail if the ** database connection D does not know that the database file for ** schema S is in [WAL mode]. A database connection might not know ** that the database file is in [WAL mode] if there has been no prior @@ -8324,40 +9528,40 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( ** (Hint: Run "[PRAGMA application_id]" against a newly opened ** database connection in order to make it ready to use snapshots.) ** -** The [sqlite3_snapshot_open()] interface is only available when the -** SQLITE_ENABLE_SNAPSHOT compile-time option is used. +** The [tdsqlite3_snapshot_open()] interface is only available when the +** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( - sqlite3 *db, +SQLITE_API SQLITE_EXPERIMENTAL int tdsqlite3_snapshot_open( + tdsqlite3 *db, const char *zSchema, - sqlite3_snapshot *pSnapshot + tdsqlite3_snapshot *pSnapshot ); /* ** CAPI3REF: Destroy a snapshot -** EXPERIMENTAL +** DESTRUCTOR: tdsqlite3_snapshot ** -** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P. -** The application must eventually free every [sqlite3_snapshot] object +** ^The [tdsqlite3_snapshot_free(P)] interface destroys [tdsqlite3_snapshot] P. +** The application must eventually free every [tdsqlite3_snapshot] object ** using this routine to avoid a memory leak. ** -** The [sqlite3_snapshot_free()] interface is only available when the -** SQLITE_ENABLE_SNAPSHOT compile-time option is used. +** The [tdsqlite3_snapshot_free()] interface is only available when the +** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); +SQLITE_API SQLITE_EXPERIMENTAL void tdsqlite3_snapshot_free(tdsqlite3_snapshot*); /* ** CAPI3REF: Compare the ages of two snapshot handles. -** EXPERIMENTAL +** METHOD: tdsqlite3_snapshot ** -** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages +** The tdsqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages ** of two valid snapshot handles. ** ** If the two snapshot handles are not associated with the same database ** file, the result of the comparison is undefined. ** ** Additionally, the result of the comparison is only valid if both of the -** snapshot handles were obtained by calling sqlite3_snapshot_get() since the +** snapshot handles were obtained by calling tdsqlite3_snapshot_get() since the ** last time the wal file was deleted. The wal file is deleted when the ** database is changed back to rollback mode or when the number of database ** clients drops to zero. If either snapshot handle was obtained before the @@ -8367,13 +9571,163 @@ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); ** Otherwise, this API returns a negative value if P1 refers to an older ** snapshot than P2, zero if the two handles refer to the same database ** snapshot, and a positive value if P1 is a newer snapshot than P2. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_SNAPSHOT] option. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( - sqlite3_snapshot *p1, - sqlite3_snapshot *p2 +SQLITE_API SQLITE_EXPERIMENTAL int tdsqlite3_snapshot_cmp( + tdsqlite3_snapshot *p1, + tdsqlite3_snapshot *p2 +); + +/* +** CAPI3REF: Recover snapshots from a wal file +** METHOD: tdsqlite3_snapshot +** +** If a [WAL file] remains on disk after all database connections close +** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control] +** or because the last process to have the database opened exited without +** calling [tdsqlite3_close()]) and a new connection is subsequently opened +** on that database and [WAL file], the [tdsqlite3_snapshot_open()] interface +** will only be able to open the last transaction added to the WAL file +** even though the WAL file contains other valid transactions. +** +** This function attempts to scan the WAL file associated with database zDb +** of database handle db and make all valid snapshots available to +** tdsqlite3_snapshot_open(). It is an error if there is already a read +** transaction open on the database, or if the database is not a WAL mode +** database. +** +** SQLITE_OK is returned if successful, or an SQLite error code otherwise. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_SNAPSHOT] option. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int tdsqlite3_snapshot_recover(tdsqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Serialize a database +** +** The tdsqlite3_serialize(D,S,P,F) interface returns a pointer to memory +** that is a serialization of the S database on [database connection] D. +** If P is not a NULL pointer, then the size of the database in bytes +** is written into *P. +** +** For an ordinary on-disk database file, the serialization is just a +** copy of the disk file. For an in-memory database or a "TEMP" database, +** the serialization is the same sequence of bytes which would be written +** to disk if that database where backed up to disk. +** +** The usual case is that tdsqlite3_serialize() copies the serialization of +** the database into memory obtained from [tdsqlite3_malloc64()] and returns +** a pointer to that memory. The caller is responsible for freeing the +** returned value to avoid a memory leak. However, if the F argument +** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations +** are made, and the tdsqlite3_serialize() function will return a pointer +** to the contiguous memory representation of the database that SQLite +** is currently using for that database, or NULL if the no such contiguous +** memory representation of the database exists. A contiguous memory +** representation of the database will usually only exist if there has +** been a prior call to [tdsqlite3_deserialize(D,S,...)] with the same +** values of D and S. +** The size of the database is written into *P even if the +** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy +** of the database exists. +** +** A call to tdsqlite3_serialize(D,S,P,F) might return NULL even if the +** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory +** allocation error occurs. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_DESERIALIZE] option. +*/ +SQLITE_API unsigned char *tdsqlite3_serialize( + tdsqlite3 *db, /* The database connection */ + const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */ + tdsqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */ + unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */ ); /* +** CAPI3REF: Flags for tdsqlite3_serialize +** +** Zero or more of the following constants can be OR-ed together for +** the F argument to [tdsqlite3_serialize(D,S,P,F)]. +** +** SQLITE_SERIALIZE_NOCOPY means that [tdsqlite3_serialize()] will return +** a pointer to contiguous in-memory database that it is currently using, +** without making a copy of the database. If SQLite is not currently using +** a contiguous in-memory database, then this option causes +** [tdsqlite3_serialize()] to return a NULL pointer. SQLite will only be +** using a contiguous in-memory database if it has been initialized by a +** prior call to [tdsqlite3_deserialize()]. +*/ +#define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */ + +/* +** CAPI3REF: Deserialize a database +** +** The tdsqlite3_deserialize(D,S,P,N,M,F) interface causes the +** [database connection] D to disconnect from database S and then +** reopen S as an in-memory database based on the serialization contained +** in P. The serialized database P is N bytes in size. M is the size of +** the buffer P, which might be larger than N. If M is larger than N, and +** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is +** permitted to add content to the in-memory database as long as the total +** size does not exceed M bytes. +** +** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will +** invoke tdsqlite3_free() on the serialization buffer when the database +** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then +** SQLite will try to increase the buffer size using tdsqlite3_realloc64() +** if writes on the database cause it to grow larger than M bytes. +** +** The tdsqlite3_deserialize() interface will fail with SQLITE_BUSY if the +** database is currently in a read transaction or is involved in a backup +** operation. +** +** If tdsqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the +** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then +** [tdsqlite3_free()] is invoked on argument P prior to returning. +** +** This interface is only available if SQLite is compiled with the +** [SQLITE_ENABLE_DESERIALIZE] option. +*/ +SQLITE_API int tdsqlite3_deserialize( + tdsqlite3 *db, /* The database connection */ + const char *zSchema, /* Which DB to reopen with the deserialization */ + unsigned char *pData, /* The serialized database content */ + tdsqlite3_int64 szDb, /* Number bytes in the deserialization */ + tdsqlite3_int64 szBuf, /* Total size of buffer pData[] */ + unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */ +); + +/* +** CAPI3REF: Flags for tdsqlite3_deserialize() +** +** The following are allowed values for 6th argument (the F argument) to +** the [tdsqlite3_deserialize(D,S,P,N,M,F)] interface. +** +** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization +** in the P argument is held in memory obtained from [tdsqlite3_malloc64()] +** and that SQLite should take ownership of this memory and automatically +** free it when it has finished using it. Without this flag, the caller +** is responsible for freeing any dynamically allocated memory. +** +** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to +** grow the size of the database using calls to [tdsqlite3_realloc64()]. This +** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used. +** Without this flag, the deserialized database cannot increase in size beyond +** the number of bytes specified by the M parameter. +** +** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database +** should be treated as read-only. +*/ +#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call tdsqlite3_free() on close */ +#define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using tdsqlite3_realloc64() */ +#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */ + +/* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ @@ -8386,7 +9740,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( #endif #endif /* SQLITE3_H */ -/******** Begin file sqlite3rtree.h *********/ +/******** Begin file tdsqlite3rtree.h *********/ /* ** 2010 August 30 ** @@ -8408,16 +9762,16 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( extern "C" { #endif -typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; -typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; +typedef struct tdsqlite3_rtree_geometry tdsqlite3_rtree_geometry; +typedef struct tdsqlite3_rtree_query_info tdsqlite3_rtree_query_info; /* The double-precision datatype used by RTree depends on the ** SQLITE_RTREE_INT_ONLY compile-time option. */ #ifdef SQLITE_RTREE_INT_ONLY - typedef sqlite3_int64 sqlite3_rtree_dbl; + typedef tdsqlite3_int64 tdsqlite3_rtree_dbl; #else - typedef double sqlite3_rtree_dbl; + typedef double tdsqlite3_rtree_dbl; #endif /* @@ -8426,10 +9780,10 @@ typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; ** ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...) */ -SQLITE_API int sqlite3_rtree_geometry_callback( - sqlite3 *db, +SQLITE_API int tdsqlite3_rtree_geometry_callback( + tdsqlite3 *db, const char *zGeom, - int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*), + int (*xGeom)(tdsqlite3_rtree_geometry*, int, tdsqlite3_rtree_dbl*,int*), void *pContext ); @@ -8438,10 +9792,10 @@ SQLITE_API int sqlite3_rtree_geometry_callback( ** A pointer to a structure of the following type is passed as the first ** argument to callbacks registered using rtree_geometry_callback(). */ -struct sqlite3_rtree_geometry { +struct tdsqlite3_rtree_geometry { void *pContext; /* Copy of pContext passed to s_r_g_c() */ int nParam; /* Size of array aParam[] */ - sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ + tdsqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ void *pUser; /* Callback implementation user data */ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ }; @@ -8452,10 +9806,10 @@ struct sqlite3_rtree_geometry { ** ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...) */ -SQLITE_API int sqlite3_rtree_query_callback( - sqlite3 *db, +SQLITE_API int tdsqlite3_rtree_query_callback( + tdsqlite3 *db, const char *zQueryFunc, - int (*xQueryFunc)(sqlite3_rtree_query_info*), + int (*xQueryFunc)(tdsqlite3_rtree_query_info*), void *pContext, void (*xDestructor)(void*) ); @@ -8464,34 +9818,34 @@ SQLITE_API int sqlite3_rtree_query_callback( /* ** A pointer to a structure of the following type is passed as the ** argument to scored geometry callback registered using -** sqlite3_rtree_query_callback(). +** tdsqlite3_rtree_query_callback(). ** ** Note that the first 5 fields of this structure are identical to -** sqlite3_rtree_geometry. This structure is a subclass of -** sqlite3_rtree_geometry. +** tdsqlite3_rtree_geometry. This structure is a subclass of +** tdsqlite3_rtree_geometry. */ -struct sqlite3_rtree_query_info { +struct tdsqlite3_rtree_query_info { void *pContext; /* pContext from when function registered */ int nParam; /* Number of function parameters */ - sqlite3_rtree_dbl *aParam; /* value of function parameters */ + tdsqlite3_rtree_dbl *aParam; /* value of function parameters */ void *pUser; /* callback can use this, if desired */ void (*xDelUser)(void*); /* function to free pUser */ - sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ + tdsqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ unsigned int *anQueue; /* Number of pending entries in the queue */ int nCoord; /* Number of coordinates */ int iLevel; /* Level of current node or entry */ int mxLevel; /* The largest iLevel value in the tree */ - sqlite3_int64 iRowid; /* Rowid for current entry */ - sqlite3_rtree_dbl rParentScore; /* Score of parent node */ + tdsqlite3_int64 iRowid; /* Rowid for current entry */ + tdsqlite3_rtree_dbl rParentScore; /* Score of parent node */ int eParentWithin; /* Visibility of parent node */ - int eWithin; /* OUT: Visiblity */ - sqlite3_rtree_dbl rScore; /* OUT: Write the score here */ + int eWithin; /* OUT: Visibility */ + tdsqlite3_rtree_dbl rScore; /* OUT: Write the score here */ /* The following fields are only available in 3.8.11 and later */ - sqlite3_value **apSqlParam; /* Original SQL values of parameters */ + tdsqlite3_value **apSqlParam; /* Original SQL values of parameters */ }; /* -** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin. +** Allowed values for tdsqlite3_rtree_query.eWithin and .eParentWithin. */ #define NOT_WITHIN 0 /* Object completely outside of query region */ #define PARTLY_WITHIN 1 /* Object partially overlaps query region */ @@ -8504,8 +9858,8 @@ struct sqlite3_rtree_query_info { #endif /* ifndef _SQLITE3RTREE_H_ */ -/******** End of sqlite3rtree.h *********/ -/******** Begin file sqlite3session.h *********/ +/******** End of tdsqlite3rtree.h *********/ +/******** Begin file tdsqlite3session.h *********/ #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) #define __SQLITESESSION_H_ 1 @@ -8520,16 +9874,23 @@ extern "C" { /* ** CAPI3REF: Session Object Handle +** +** An instance of this object is a [session] that can be used to +** record changes to a database. */ -typedef struct sqlite3_session sqlite3_session; +typedef struct tdsqlite3_session tdsqlite3_session; /* ** CAPI3REF: Changeset Iterator Handle +** +** An instance of this object acts as a cursor for iterating +** over the elements of a [changeset] or [patchset]. */ -typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; +typedef struct tdsqlite3_changeset_iter tdsqlite3_changeset_iter; /* ** CAPI3REF: Create A New Session Object +** CONSTRUCTOR: tdsqlite3_session ** ** Create a new session object attached to database handle db. If successful, ** a pointer to the new object is written to *ppSession and SQLITE_OK is @@ -8540,13 +9901,13 @@ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; ** database handle. ** ** Session objects created using this function should be deleted using the -** [sqlite3session_delete()] function before the database handle that they +** [tdsqlite3session_delete()] function before the database handle that they ** are attached to is itself closed. If the database handle is closed before ** the session object is deleted, then the results of calling any session -** module function, including [sqlite3session_delete()] on the session object +** module function, including [tdsqlite3session_delete()] on the session object ** are undefined. ** -** Because the session module uses the [sqlite3_preupdate_hook()] API, it +** Because the session module uses the [tdsqlite3_preupdate_hook()] API, it ** is not possible for an application to register a pre-update hook on a ** database handle that has one or more session objects attached. Nor is ** it possible to create a session object attached to a database handle for @@ -8558,34 +9919,36 @@ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; ** attached database. It is not an error if database zDb is not attached ** to the database when the session object is created. */ -int sqlite3session_create( - sqlite3 *db, /* Database handle */ +SQLITE_API int tdsqlite3session_create( + tdsqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (e.g. "main") */ - sqlite3_session **ppSession /* OUT: New session object */ + tdsqlite3_session **ppSession /* OUT: New session object */ ); /* ** CAPI3REF: Delete A Session Object +** DESTRUCTOR: tdsqlite3_session ** ** Delete a session object previously allocated using -** [sqlite3session_create()]. Once a session object has been deleted, the +** [tdsqlite3session_create()]. Once a session object has been deleted, the ** results of attempting to use pSession with any other session module ** function are undefined. ** ** Session objects must be deleted before the database handle to which they ** are attached is closed. Refer to the documentation for -** [sqlite3session_create()] for details. +** [tdsqlite3session_create()] for details. */ -void sqlite3session_delete(sqlite3_session *pSession); +SQLITE_API void tdsqlite3session_delete(tdsqlite3_session *pSession); /* ** CAPI3REF: Enable Or Disable A Session Object +** METHOD: tdsqlite3_session ** ** Enable or disable the recording of changes by a session object. When ** enabled, a session object records changes made to the database. When ** disabled - it does not. A newly created session object is enabled. -** Refer to the documentation for [sqlite3session_changeset()] for further +** Refer to the documentation for [tdsqlite3session_changeset()] for further ** details regarding how enabling and disabling a session object affects ** the eventual changesets. ** @@ -8596,10 +9959,11 @@ void sqlite3session_delete(sqlite3_session *pSession); ** The return value indicates the final state of the session object: 0 if ** the session is disabled, or 1 if it is enabled. */ -int sqlite3session_enable(sqlite3_session *pSession, int bEnable); +SQLITE_API int tdsqlite3session_enable(tdsqlite3_session *pSession, int bEnable); /* ** CAPI3REF: Set Or Clear the Indirect Change Flag +** METHOD: tdsqlite3_session ** ** Each change recorded by a session object is marked as either direct or ** indirect. A change is marked as indirect if either: @@ -8625,15 +9989,16 @@ int sqlite3session_enable(sqlite3_session *pSession, int bEnable); ** The return value indicates the final state of the indirect flag: 0 if ** it is clear, or 1 if it is set. */ -int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); +SQLITE_API int tdsqlite3session_indirect(tdsqlite3_session *pSession, int bIndirect); /* ** CAPI3REF: Attach A Table To A Session Object +** METHOD: tdsqlite3_session ** ** If argument zTab is not NULL, then it is the name of a table to attach ** to the session object passed as the first argument. All subsequent changes ** made to the table while the session object is enabled will be recorded. See -** documentation for [sqlite3session_changeset()] for further details. +** documentation for [tdsqlite3session_changeset()] for further details. ** ** Or, if argument zTab is NULL, then changes are recorded for all tables ** in the database. If additional tables are added to the database (by @@ -8654,23 +10019,53 @@ int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); ** ** SQLITE_OK is returned if the call completes without error. Or, if an error ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. -*/ -int sqlite3session_attach( - sqlite3_session *pSession, /* Session object */ +** +** <h3>Special sqlite_stat1 Handling</h3> +** +** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to +** some of the rules above. In SQLite, the schema of sqlite_stat1 is: +** <pre> +** CREATE TABLE sqlite_stat1(tbl,idx,stat) +** </pre> +** +** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are +** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes +** are recorded for rows for which (idx IS NULL) is true. However, for such +** rows a zero-length blob (SQL value X'') is stored in the changeset or +** patchset instead of a NULL value. This allows such changesets to be +** manipulated by legacy implementations of tdsqlite3changeset_invert(), +** concat() and similar. +** +** The tdsqlite3changeset_apply() function automatically converts the +** zero-length blob back to a NULL value when updating the sqlite_stat1 +** table. However, if the application calls tdsqlite3changeset_new(), +** tdsqlite3changeset_old() or tdsqlite3changeset_conflict on a changeset +** iterator directly (including on a changeset iterator passed to a +** conflict-handler callback) then the X'' value is returned. The application +** must translate X'' to NULL itself if required. +** +** Legacy (older than 3.22.0) versions of the sessions module cannot capture +** changes made to the sqlite_stat1 table. Legacy versions of the +** tdsqlite3changeset_apply() function silently ignore any modifications to the +** sqlite_stat1 table that are part of a changeset or patchset. +*/ +SQLITE_API int tdsqlite3session_attach( + tdsqlite3_session *pSession, /* Session object */ const char *zTab /* Table name */ ); /* ** CAPI3REF: Set a table filter on a Session Object. +** METHOD: tdsqlite3_session ** ** The second argument (xFilter) is the "filter callback". For changes to rows ** in tables that are not attached to the Session object, the filter is called ** to determine whether changes to the table's rows should be tracked or not. -** If xFilter returns 0, changes is not tracked. Note that once a table is +** If xFilter returns 0, changes are not tracked. Note that once a table is ** attached, xFilter will not be called again. */ -void sqlite3session_table_filter( - sqlite3_session *pSession, /* Session object */ +SQLITE_API void tdsqlite3session_table_filter( + tdsqlite3_session *pSession, /* Session object */ int(*xFilter)( void *pCtx, /* Copy of third arg to _filter_table() */ const char *zTab /* Table name */ @@ -8680,6 +10075,7 @@ void sqlite3session_table_filter( /* ** CAPI3REF: Generate A Changeset From A Session Object +** METHOD: tdsqlite3_session ** ** Obtain a changeset containing changes to the tables attached to the ** session object passed as the first argument. If successful, @@ -8709,8 +10105,8 @@ void sqlite3session_table_filter( ** DELETE change only. ** ** The contents of a changeset may be traversed using an iterator created -** using the [sqlite3changeset_start()] API. A changeset may be applied to -** a database with a compatible schema using the [sqlite3changeset_apply()] +** using the [tdsqlite3changeset_start()] API. A changeset may be applied to +** a database with a compatible schema using the [tdsqlite3changeset_apply()] ** API. ** ** Within a changeset generated by this function, all changes related to a @@ -8718,12 +10114,12 @@ void sqlite3session_table_filter( ** a changeset or when applying a changeset to a database, all changes related ** to a single table are processed before moving on to the next table. Tables ** are sorted in the same order in which they were attached (or auto-attached) -** to the sqlite3_session object. The order in which the changes related to +** to the tdsqlite3_session object. The order in which the changes related to ** a single table are stored is undefined. ** ** Following a successful call to this function, it is the responsibility of ** the caller to eventually free the buffer that *ppChangeset points to using -** [sqlite3_free()]. +** [tdsqlite3_free()]. ** ** <h3>Changeset Generation</h3> ** @@ -8771,7 +10167,7 @@ void sqlite3session_table_filter( ** active, the resulting changeset will contain an UPDATE change instead of ** a DELETE and an INSERT. ** -** When a session object is disabled (see the [sqlite3session_enable()] API), +** When a session object is disabled (see the [tdsqlite3session_enable()] API), ** it does not accumulate records when rows are inserted, updated or deleted. ** This may appear to have some counter-intuitive effects if a single row ** is written to more than once during a session. For example, if a row @@ -8782,18 +10178,19 @@ void sqlite3session_table_filter( ** another field of the same row is updated while the session is enabled, the ** resulting changeset will contain an UPDATE change that updates both fields. */ -int sqlite3session_changeset( - sqlite3_session *pSession, /* Session object */ +SQLITE_API int tdsqlite3session_changeset( + tdsqlite3_session *pSession, /* Session object */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ); /* -** CAPI3REF: Load The Difference Between Tables Into A Session +** CAPI3REF: Load The Difference Between Tables Into A Session +** METHOD: tdsqlite3_session ** ** If it is not already attached to the session object passed as the first ** argument, this function attaches table zTbl in the same manner as the -** [sqlite3session_attach()] function. If zTbl does not exist, or if it +** [tdsqlite3session_attach()] function. If zTbl does not exist, or if it ** does not have a primary key, this function is a no-op (but does not return ** an error). ** @@ -8826,25 +10223,26 @@ int sqlite3session_changeset( ** the from-table, a DELETE record is added to the session object. ** ** <li> For each row (primary key) that exists in both tables, but features -** different in each, an UPDATE record is added to the session. +** different non-PK values in each, an UPDATE record is added to the +** session. ** </ul> ** ** To clarify, if this function is called and then a changeset constructed -** using [sqlite3session_changeset()], then after applying that changeset to +** using [tdsqlite3session_changeset()], then after applying that changeset to ** database zFrom the contents of the two compatible tables would be ** identical. ** ** It an error if database zFrom does not exist or does not contain the ** required compatible table. ** -** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite +** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to free this buffer using -** sqlite3_free(). +** tdsqlite3_free(). */ -int sqlite3session_diff( - sqlite3_session *pSession, +SQLITE_API int tdsqlite3session_diff( + tdsqlite3_session *pSession, const char *zFromDb, const char *zTbl, char **pzErrMsg @@ -8853,6 +10251,7 @@ int sqlite3session_diff( /* ** CAPI3REF: Generate A Patchset From A Session Object +** METHOD: tdsqlite3_session ** ** The differences between a patchset and a changeset are that: ** @@ -8864,25 +10263,25 @@ int sqlite3session_diff( ** </ul> ** ** A patchset blob may be used with up to date versions of all -** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), +** tdsqlite3changeset_xxx API functions except for tdsqlite3changeset_invert(), ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly, ** attempting to use a patchset blob with old versions of the -** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. +** tdsqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. ** ** Because the non-primary key "old.*" fields are omitted, no ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset -** is passed to the sqlite3changeset_apply() API. Other conflict types work +** is passed to the tdsqlite3changeset_apply() API. Other conflict types work ** in the same way as for changesets. ** ** Changes within a patchset are ordered in the same way as for changesets -** generated by the sqlite3session_changeset() function (i.e. all changes for +** generated by the tdsqlite3session_changeset() function (i.e. all changes for ** a single table are grouped together, tables appear in the order in which ** they were attached to the session object). */ -int sqlite3session_patchset( - sqlite3_session *pSession, /* Session object */ - int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ - void **ppPatchset /* OUT: Buffer containing changeset */ +SQLITE_API int tdsqlite3session_patchset( + tdsqlite3_session *pSession, /* Session object */ + int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */ + void **ppPatchset /* OUT: Buffer containing patchset */ ); /* @@ -8893,17 +10292,18 @@ int sqlite3session_patchset( ** more changes have been recorded, return zero. ** ** Even if this function returns zero, it is possible that calling -** [sqlite3session_changeset()] on the session handle may still return a +** [tdsqlite3session_changeset()] on the session handle may still return a ** changeset that contains no changes. This can happen when a row in ** an attached table is modified and then later on the original values ** are restored. However, if this function returns non-zero, then it is -** guaranteed that a call to sqlite3session_changeset() will return a +** guaranteed that a call to tdsqlite3session_changeset() will return a ** changeset containing zero changes. */ -int sqlite3session_isempty(sqlite3_session *pSession); +SQLITE_API int tdsqlite3session_isempty(tdsqlite3_session *pSession); /* ** CAPI3REF: Create An Iterator To Traverse A Changeset +** CONSTRUCTOR: tdsqlite3_changeset_iter ** ** Create an iterator used to iterate through the contents of a changeset. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK @@ -8914,49 +10314,76 @@ int sqlite3session_isempty(sqlite3_session *pSession); ** iterator created by this function: ** ** <ul> -** <li> [sqlite3changeset_next()] -** <li> [sqlite3changeset_op()] -** <li> [sqlite3changeset_new()] -** <li> [sqlite3changeset_old()] +** <li> [tdsqlite3changeset_next()] +** <li> [tdsqlite3changeset_op()] +** <li> [tdsqlite3changeset_new()] +** <li> [tdsqlite3changeset_old()] ** </ul> ** ** It is the responsibility of the caller to eventually destroy the iterator -** by passing it to [sqlite3changeset_finalize()]. The buffer containing the +** by passing it to [tdsqlite3changeset_finalize()]. The buffer containing the ** changeset (pChangeset) must remain valid until after the iterator is ** destroyed. ** ** Assuming the changeset blob was created by one of the -** [sqlite3session_changeset()], [sqlite3changeset_concat()] or -** [sqlite3changeset_invert()] functions, all changes within the changeset +** [tdsqlite3session_changeset()], [tdsqlite3changeset_concat()] or +** [tdsqlite3changeset_invert()] functions, all changes within the changeset ** that apply to a single table are grouped together. This means that when ** an application iterates through a changeset using an iterator created by ** this function, all changes that relate to a single table are visited ** consecutively. There is no chance that the iterator will visit a change ** the applies to table X, then one for table Y, and then later on visit ** another change for table X. +** +** The behavior of tdsqlite3changeset_start_v2() and its streaming equivalent +** may be modified by passing a combination of +** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter. +** +** Note that the tdsqlite3changeset_start_v2() API is still <b>experimental</b> +** and therefore subject to change. */ -int sqlite3changeset_start( - sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ +SQLITE_API int tdsqlite3changeset_start( + tdsqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ int nChangeset, /* Size of changeset blob in bytes */ void *pChangeset /* Pointer to blob containing changeset */ ); +SQLITE_API int tdsqlite3changeset_start_v2( + tdsqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ + int nChangeset, /* Size of changeset blob in bytes */ + void *pChangeset, /* Pointer to blob containing changeset */ + int flags /* SESSION_CHANGESETSTART_* flags */ +); + +/* +** CAPI3REF: Flags for tdsqlite3changeset_start_v2 +** +** The following flags may passed via the 4th parameter to +** [tdsqlite3changeset_start_v2] and [tdsqlite3changeset_start_v2_strm]: +** +** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd> +** Invert the changeset while iterating through it. This is equivalent to +** inverting a changeset using tdsqlite3changeset_invert() before applying it. +** It is an error to specify this flag with a patchset. +*/ +#define SQLITE_CHANGESETSTART_INVERT 0x0002 /* ** CAPI3REF: Advance A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** -** This function may only be used with iterators created by function -** [sqlite3changeset_start()]. If it is called on an iterator passed to -** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE +** This function may only be used with iterators created by the function +** [tdsqlite3changeset_start()]. If it is called on an iterator passed to +** a conflict-handler callback by [tdsqlite3changeset_apply()], SQLITE_MISUSE ** is returned and the call has no effect. ** -** Immediately after an iterator is created by sqlite3changeset_start(), it +** Immediately after an iterator is created by tdsqlite3changeset_start(), it ** does not point to any change in the changeset. Assuming the changeset ** is not empty, the first call to this function advances the iterator to ** point to the first change in the changeset. Each subsequent call advances ** the iterator to point to the next change in the changeset (if any). If ** no error occurs and the iterator points to a valid change after a call -** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. +** to tdsqlite3changeset_next() has advanced it, SQLITE_ROW is returned. ** Otherwise, if all changes in the changeset have already been visited, ** SQLITE_DONE is returned. ** @@ -8964,26 +10391,27 @@ int sqlite3changeset_start( ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or ** SQLITE_NOMEM. */ -int sqlite3changeset_next(sqlite3_changeset_iter *pIter); +SQLITE_API int tdsqlite3changeset_next(tdsqlite3_changeset_iter *pIter); /* ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** The pIter argument passed to this function may either be an iterator -** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator -** created by [sqlite3changeset_start()]. In the latter case, the most recent -** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this +** passed to a conflict-handler by [tdsqlite3changeset_apply()], or an iterator +** created by [tdsqlite3changeset_start()]. In the latter case, the most recent +** call to [tdsqlite3changeset_next()] must have returned [SQLITE_ROW]. If this ** is not the case, this function returns [SQLITE_MISUSE]. ** ** If argument pzTab is not NULL, then *pzTab is set to point to a ** nul-terminated utf-8 encoded string containing the name of the table ** affected by the current change. The buffer remains valid until either -** sqlite3changeset_next() is called on the iterator or until the +** tdsqlite3changeset_next() is called on the iterator or until the ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is ** set to the number of columns in the table affected by the change. If -** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change +** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change ** is an indirect change, or false (0) otherwise. See the documentation for -** [sqlite3session_indirect()] for a description of direct and indirect +** [tdsqlite3session_indirect()] for a description of direct and indirect ** changes. Finally, if pOp is not NULL, then *pOp is set to one of ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the ** type of change that the iterator currently points to. @@ -8992,8 +10420,8 @@ int sqlite3changeset_next(sqlite3_changeset_iter *pIter); ** SQLite error code is returned. The values of the output variables may not ** be trusted in this case. */ -int sqlite3changeset_op( - sqlite3_changeset_iter *pIter, /* Iterator object */ +SQLITE_API int tdsqlite3changeset_op( + tdsqlite3_changeset_iter *pIter, /* Iterator object */ const char **pzTab, /* OUT: Pointer to table name */ int *pnCol, /* OUT: Number of columns in table */ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ @@ -9002,6 +10430,7 @@ int sqlite3changeset_op( /* ** CAPI3REF: Obtain The Primary Key Definition Of A Table +** METHOD: tdsqlite3_changeset_iter ** ** For each modified table, a changeset includes the following: ** @@ -9025,19 +10454,20 @@ int sqlite3changeset_op( ** SQLITE_OK is returned and the output variables populated as described ** above. */ -int sqlite3changeset_pk( - sqlite3_changeset_iter *pIter, /* Iterator object */ +SQLITE_API int tdsqlite3changeset_pk( + tdsqlite3_changeset_iter *pIter, /* Iterator object */ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ int *pnCol /* OUT: Number of entries in output array */ ); /* ** CAPI3REF: Obtain old.* Values From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** The pIter argument passed to this function may either be an iterator -** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator -** created by [sqlite3changeset_start()]. In the latter case, the most recent -** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. +** passed to a conflict-handler by [tdsqlite3changeset_apply()], or an iterator +** created by [tdsqlite3changeset_start()]. In the latter case, the most recent +** call to [tdsqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. @@ -9047,7 +10477,7 @@ int sqlite3changeset_pk( ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected -** sqlite3_value object containing the iVal'th value from the vector of +** tdsqlite3_value object containing the iVal'th value from the vector of ** original row values stored as part of the UPDATE or DELETE change and ** returns SQLITE_OK. The name of the function comes from the fact that this ** is similar to the "old.*" columns available to update or delete triggers. @@ -9055,19 +10485,20 @@ int sqlite3changeset_pk( ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ -int sqlite3changeset_old( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_old( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ - sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ + tdsqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain new.* Values From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** The pIter argument passed to this function may either be an iterator -** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator -** created by [sqlite3changeset_start()]. In the latter case, the most recent -** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. +** passed to a conflict-handler by [tdsqlite3changeset_apply()], or an iterator +** created by [tdsqlite3changeset_start()]. In the latter case, the most recent +** call to [tdsqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. @@ -9077,7 +10508,7 @@ int sqlite3changeset_old( ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected -** sqlite3_value object containing the iVal'th value from the vector of +** tdsqlite3_value object containing the iVal'th value from the vector of ** new row values stored as part of the UPDATE or INSERT change and ** returns SQLITE_OK. If the change is an UPDATE and does not include ** a new value for the requested column, *ppValue is set to NULL and @@ -9088,17 +10519,18 @@ int sqlite3changeset_old( ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ -int sqlite3changeset_new( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_new( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ - sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ + tdsqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** This function should only be used with iterator objects passed to a -** conflict-handler callback by [sqlite3changeset_apply()] with either +** conflict-handler callback by [tdsqlite3changeset_apply()] with either ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue ** is set to NULL. @@ -9108,21 +10540,22 @@ int sqlite3changeset_new( ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected -** sqlite3_value object containing the iVal'th value from the +** tdsqlite3_value object containing the iVal'th value from the ** "conflicting row" associated with the current conflict-handler callback ** and returns SQLITE_OK. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ -int sqlite3changeset_conflict( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_conflict( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ - sqlite3_value **ppValue /* OUT: Value from conflicting row */ + tdsqlite3_value **ppValue /* OUT: Value from conflicting row */ ); /* ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations +** METHOD: tdsqlite3_changeset_iter ** ** This function may only be called with an iterator passed to an ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case @@ -9131,40 +10564,43 @@ int sqlite3changeset_conflict( ** ** In all other cases this function returns SQLITE_MISUSE. */ -int sqlite3changeset_fk_conflicts( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +SQLITE_API int tdsqlite3changeset_fk_conflicts( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int *pnOut /* OUT: Number of FK violations */ ); /* ** CAPI3REF: Finalize A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** This function is used to finalize an iterator allocated with -** [sqlite3changeset_start()]. +** [tdsqlite3changeset_start()]. ** ** This function should only be called on iterators created using the -** [sqlite3changeset_start()] function. If an application calls this +** [tdsqlite3changeset_start()] function. If an application calls this ** function with an iterator passed to a conflict-handler by -** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the +** [tdsqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the ** call has no effect. ** -** If an error was encountered within a call to an sqlite3changeset_xxx() -** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an -** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding +** If an error was encountered within a call to an tdsqlite3changeset_xxx() +** function (for example an [SQLITE_CORRUPT] in [tdsqlite3changeset_next()] or an +** [SQLITE_NOMEM] in [tdsqlite3changeset_new()]) then an error code corresponding ** to that error is returned by this function. Otherwise, SQLITE_OK is ** returned. This is to allow the following pattern (pseudo-code): ** -** sqlite3changeset_start(); -** while( SQLITE_ROW==sqlite3changeset_next() ){ +** <pre> +** tdsqlite3changeset_start(); +** while( SQLITE_ROW==tdsqlite3changeset_next() ){ ** // Do something with change. ** } -** rc = sqlite3changeset_finalize(); +** rc = tdsqlite3changeset_finalize(); ** if( rc!=SQLITE_OK ){ ** // An error has occurred ** } +** </pre> */ -int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); +SQLITE_API int tdsqlite3changeset_finalize(tdsqlite3_changeset_iter *pIter); /* ** CAPI3REF: Invert A Changeset @@ -9187,14 +10623,14 @@ int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are ** zeroed and an SQLite error code returned. ** -** It is the responsibility of the caller to eventually call sqlite3_free() +** It is the responsibility of the caller to eventually call tdsqlite3_free() ** on the *ppOut pointer to free the buffer allocation following a successful ** call to this function. ** ** WARNING/TODO: This function currently assumes that the input is a valid ** changeset. If it is not, the results are undefined. */ -int sqlite3changeset_invert( +SQLITE_API int tdsqlite3changeset_invert( int nIn, const void *pIn, /* Input changeset */ int *pnOut, void **ppOut /* OUT: Inverse of input */ ); @@ -9207,23 +10643,25 @@ int sqlite3changeset_invert( ** changeset A followed by changeset B. ** ** This function combines the two input changesets using an -** sqlite3_changegroup object. Calling it produces similar results as the +** tdsqlite3_changegroup object. Calling it produces similar results as the ** following code fragment: ** -** sqlite3_changegroup *pGrp; -** rc = sqlite3_changegroup_new(&pGrp); -** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA); -** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB); +** <pre> +** tdsqlite3_changegroup *pGrp; +** rc = tdsqlite3_changegroup_new(&pGrp); +** if( rc==SQLITE_OK ) rc = tdsqlite3changegroup_add(pGrp, nA, pA); +** if( rc==SQLITE_OK ) rc = tdsqlite3changegroup_add(pGrp, nB, pB); ** if( rc==SQLITE_OK ){ -** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); +** rc = tdsqlite3changegroup_output(pGrp, pnOut, ppOut); ** }else{ ** *ppOut = 0; ** *pnOut = 0; ** } +** </pre> ** -** Refer to the sqlite3_changegroup documentation below for details. +** Refer to the tdsqlite3_changegroup documentation below for details. */ -int sqlite3changeset_concat( +SQLITE_API int tdsqlite3changeset_concat( int nA, /* Number of bytes in buffer pA */ void *pA, /* Pointer to buffer containing changeset A */ int nB, /* Number of bytes in buffer pB */ @@ -9235,48 +10673,53 @@ int sqlite3changeset_concat( /* ** CAPI3REF: Changegroup Handle +** +** A changegroup is an object used to combine two or more +** [changesets] or [patchsets] */ -typedef struct sqlite3_changegroup sqlite3_changegroup; +typedef struct tdsqlite3_changegroup tdsqlite3_changegroup; /* ** CAPI3REF: Create A New Changegroup Object +** CONSTRUCTOR: tdsqlite3_changegroup ** -** An sqlite3_changegroup object is used to combine two or more changesets +** An tdsqlite3_changegroup object is used to combine two or more changesets ** (or patchsets) into a single changeset (or patchset). A single changegroup ** object may combine changesets or patchsets, but not both. The output is ** always in the same format as the input. ** ** If successful, this function returns SQLITE_OK and populates (*pp) with -** a pointer to a new sqlite3_changegroup object before returning. The caller +** a pointer to a new tdsqlite3_changegroup object before returning. The caller ** should eventually free the returned object using a call to -** sqlite3changegroup_delete(). If an error occurs, an SQLite error code +** tdsqlite3changegroup_delete(). If an error occurs, an SQLite error code ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL. ** -** The usual usage pattern for an sqlite3_changegroup object is as follows: +** The usual usage pattern for an tdsqlite3_changegroup object is as follows: ** ** <ul> -** <li> It is created using a call to sqlite3changegroup_new(). +** <li> It is created using a call to tdsqlite3changegroup_new(). ** ** <li> Zero or more changesets (or patchsets) are added to the object -** by calling sqlite3changegroup_add(). +** by calling tdsqlite3changegroup_add(). ** ** <li> The result of combining all input changesets together is obtained -** by the application via a call to sqlite3changegroup_output(). +** by the application via a call to tdsqlite3changegroup_output(). ** -** <li> The object is deleted using a call to sqlite3changegroup_delete(). +** <li> The object is deleted using a call to tdsqlite3changegroup_delete(). ** </ul> ** ** Any number of calls to add() and output() may be made between the calls to ** new() and delete(), and in any order. ** -** As well as the regular sqlite3changegroup_add() and -** sqlite3changegroup_output() functions, also available are the streaming -** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm(). +** As well as the regular tdsqlite3changegroup_add() and +** tdsqlite3changegroup_output() functions, also available are the streaming +** versions tdsqlite3changegroup_add_strm() and tdsqlite3changegroup_output_strm(). */ -int sqlite3changegroup_new(sqlite3_changegroup **pp); +SQLITE_API int tdsqlite3changegroup_new(tdsqlite3_changegroup **pp); /* ** CAPI3REF: Add A Changeset To A Changegroup +** METHOD: tdsqlite3_changegroup ** ** Add all changes within the changeset (or patchset) in buffer pData (size ** nData bytes) to the changegroup. @@ -9345,23 +10788,24 @@ int sqlite3changegroup_new(sqlite3_changegroup **pp); ** case, this function fails with SQLITE_SCHEMA. If the input changeset ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is ** returned. Or, if an out-of-memory condition occurs during processing, this -** function returns SQLITE_NOMEM. In all cases, if an error occurs the -** final contents of the changegroup is undefined. +** function returns SQLITE_NOMEM. In all cases, if an error occurs the state +** of the final contents of the changegroup is undefined. ** ** If no error occurs, SQLITE_OK is returned. */ -int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); +SQLITE_API int tdsqlite3changegroup_add(tdsqlite3_changegroup*, int nData, void *pData); /* ** CAPI3REF: Obtain A Composite Changeset From A Changegroup +** METHOD: tdsqlite3_changegroup ** ** Obtain a buffer containing a changeset (or patchset) representing the ** current contents of the changegroup. If the inputs to the changegroup ** were themselves changesets, the output is a changeset. Or, if the ** inputs were patchsets, the output is also a patchset. ** -** As with the output of the sqlite3session_changeset() and -** sqlite3session_patchset() functions, all changes related to a single +** As with the output of the tdsqlite3session_changeset() and +** tdsqlite3session_patchset() functions, all changes related to a single ** table are grouped together in the output of this function. Tables appear ** in the same order as for the very first changeset added to the changegroup. ** If the second or subsequent changesets added to the changegroup contain @@ -9374,35 +10818,35 @@ int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); ** is returned and the output variables are set to the size of and a ** pointer to the output buffer, respectively. In this case it is the ** responsibility of the caller to eventually free the buffer using a -** call to sqlite3_free(). +** call to tdsqlite3_free(). */ -int sqlite3changegroup_output( - sqlite3_changegroup*, +SQLITE_API int tdsqlite3changegroup_output( + tdsqlite3_changegroup*, int *pnData, /* OUT: Size of output buffer in bytes */ void **ppData /* OUT: Pointer to output buffer */ ); /* ** CAPI3REF: Delete A Changegroup Object +** DESTRUCTOR: tdsqlite3_changegroup */ -void sqlite3changegroup_delete(sqlite3_changegroup*); +SQLITE_API void tdsqlite3changegroup_delete(tdsqlite3_changegroup*); /* ** CAPI3REF: Apply A Changeset To A Database ** -** Apply a changeset to a database. This function attempts to update the -** "main" database attached to handle db with the changes found in the -** changeset passed via the second and third arguments. +** Apply a changeset or patchset to a database. These functions attempt to +** update the "main" database attached to handle db with the changes found in +** the changeset passed via the second and third arguments. ** -** The fourth argument (xFilter) passed to this function is the "filter +** The fourth argument (xFilter) passed to these functions is the "filter ** callback". If it is not NULL, then for each table affected by at least one ** change in the changeset, the filter callback is invoked with ** the table name as the second argument, and a copy of the context pointer -** passed as the sixth argument to this function as the first. If the "filter -** callback" returns zero, then no attempt is made to apply any changes to -** the table. Otherwise, if the return value is non-zero or the xFilter -** argument to this function is NULL, all changes related to the table are -** attempted. +** passed as the sixth argument as the first. If the "filter callback" +** returns zero, then no attempt is made to apply any changes to the table. +** Otherwise, if the return value is non-zero or the xFilter argument to +** is NULL, all changes related to the table are attempted. ** ** For each table that is not excluded by the filter callback, this function ** tests that the target database contains a compatible table. A table is @@ -9411,7 +10855,7 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** <ul> ** <li> The table has the same name as the name recorded in the ** changeset, and -** <li> The table has the same number of columns as recorded in the +** <li> The table has at least as many columns as recorded in the ** changeset, and ** <li> The table has primary key columns in the same position as ** recorded in the changeset. @@ -9419,13 +10863,13 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** ** If there is no compatible table, it is not an error, but none of the ** changes associated with the table are applied. A warning message is issued -** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most +** via the tdsqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most ** one such warning is issued for each table in the changeset. ** ** For each change for which there is a compatible table, an attempt is made ** to modify the table contents according to the UPDATE, INSERT or DELETE ** change. If a change cannot be applied cleanly, the conflict handler -** function passed as the fifth argument to sqlite3changeset_apply() may be +** function passed as the fifth argument to tdsqlite3changeset_apply() may be ** invoked. A description of exactly when the conflict handler is invoked for ** each type of change is below. ** @@ -9439,15 +10883,15 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** if the second argument passed to the conflict handler is either ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler ** returns an illegal value, any changes already made are rolled back and -** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different -** actions are taken by sqlite3changeset_apply() depending on the value +** the call to tdsqlite3changeset_apply() returns SQLITE_MISUSE. Different +** actions are taken by tdsqlite3changeset_apply() depending on the value ** returned by each invocation of the conflict-handler function. Refer to ** the documentation for the three ** [SQLITE_CHANGESET_OMIT|available return values] for details. ** ** <dl> ** <dt>DELETE Changes<dd> -** For each DELETE change, this function checks if the target database +** For each DELETE change, the function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all non-primary key columns also match the values stored in @@ -9456,7 +10900,11 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** If a row with matching primary key values is found, but one or more of ** the non-primary key fields contains a value different from the original ** row value stored in the changeset, the conflict-handler function is -** invoked with [SQLITE_CHANGESET_DATA] as the second argument. +** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the +** database table has more columns than are recorded in the changeset, +** only the values of those non-primary key fields are compared against +** the current database contents - any trailing database table columns +** are ignored. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] @@ -9471,7 +10919,9 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** ** <dt>INSERT Changes<dd> ** For each INSERT change, an attempt is made to insert the new row into -** the database. +** the database. If the changeset row contains fewer fields than the +** database table, the trailing fields are populated with their default +** values. ** ** If the attempt to insert the row fails because the database already ** contains a row with the same primary key values, the conflict handler @@ -9486,16 +10936,16 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** [SQLITE_CHANGESET_REPLACE]. ** ** <dt>UPDATE Changes<dd> -** For each UPDATE change, this function checks if the target database +** For each UPDATE change, the function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values -** stored in all non-primary key columns also match the values stored in -** the changeset the row is updated within the target database. +** stored in all modified non-primary key columns also match the values +** stored in the changeset the row is updated within the target database. ** ** If a row with matching primary key values is found, but one or more of -** the non-primary key fields contains a value different from an original -** row value stored in the changeset, the conflict-handler function is -** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since +** the modified non-primary key fields contains a value different from an +** original row value stored in the changeset, the conflict-handler function +** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since ** UPDATE changes only contain values for non-primary key fields that are ** to be modified, only those fields need to match the original values to ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. @@ -9514,17 +10964,34 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** ** It is safe to execute SQL statements, including those that write to the ** table that the callback related to, from within the xConflict callback. -** This can be used to further customize the applications conflict +** This can be used to further customize the application's conflict ** resolution strategy. ** -** All changes made by this function are enclosed in a savepoint transaction. +** All changes made by these functions are enclosed in a savepoint transaction. ** If any other error (aside from a constraint failure when attempting to ** write to the target database) occurs, then the savepoint transaction is ** rolled back, restoring the target database to its original state, and an ** SQLite error code returned. -*/ -int sqlite3changeset_apply( - sqlite3 *db, /* Apply change to "main" db of this handle */ +** +** If the output parameters (ppRebase) and (pnRebase) are non-NULL and +** the input is a changeset (not a patchset), then tdsqlite3changeset_apply_v2() +** may set (*ppRebase) to point to a "rebase" that may be used with the +** tdsqlite3_rebaser APIs buffer before returning. In this case (*pnRebase) +** is set to the size of the buffer in bytes. It is the responsibility of the +** caller to eventually free any such buffer using tdsqlite3_free(). The buffer +** is only allocated and populated if one or more conflicts were encountered +** while applying the patchset. See comments surrounding the tdsqlite3_rebaser +** APIs for further details. +** +** The behavior of tdsqlite3changeset_apply_v2() and its streaming equivalent +** may be modified by passing a combination of +** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter. +** +** Note that the tdsqlite3changeset_apply_v2() API is still <b>experimental</b> +** and therefore subject to change. +*/ +SQLITE_API int tdsqlite3changeset_apply( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ int(*xFilter)( @@ -9534,10 +11001,51 @@ int sqlite3changeset_apply( int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); +SQLITE_API int tdsqlite3changeset_apply_v2( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, /* OUT: Rebase data */ + int flags /* SESSION_CHANGESETAPPLY_* flags */ +); + +/* +** CAPI3REF: Flags for tdsqlite3changeset_apply_v2 +** +** The following flags may passed via the 9th parameter to +** [tdsqlite3changeset_apply_v2] and [tdsqlite3changeset_apply_v2_strm]: +** +** <dl> +** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd> +** Usually, the sessions module encloses all operations performed by +** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The +** SAVEPOINT is committed if the changeset or patchset is successfully +** applied, or rolled back if an error occurs. Specifying this flag +** causes the sessions module to omit this savepoint. In this case, if the +** caller has an open transaction or savepoint when apply_v2() is called, +** it may revert the partially applied changeset by rolling it back. +** +** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd> +** Invert the changeset before applying it. This is equivalent to inverting +** a changeset using tdsqlite3changeset_invert() before applying it. It is +** an error to specify this flag with a patchset. +*/ +#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001 +#define SQLITE_CHANGESETAPPLY_INVERT 0x0002 /* ** CAPI3REF: Constants Passed To The Conflict Handler @@ -9561,7 +11069,7 @@ int sqlite3changeset_apply( ** required PRIMARY KEY fields is not present in the database. ** ** There is no conflicting row in this case. The results of invoking the -** sqlite3changeset_conflict() API are undefined. +** tdsqlite3changeset_conflict() API are undefined. ** ** <dt>SQLITE_CHANGESET_CONFLICT<dd> ** CHANGESET_CONFLICT is passed as the second argument to the conflict @@ -9581,8 +11089,8 @@ int sqlite3changeset_apply( ** CHANGESET_ABORT, the changeset is rolled back. ** ** No current or conflicting row information is provided. The only function -** it is possible to call on the supplied sqlite3_changeset_iter handle -** is sqlite3changeset_fk_conflicts(). +** it is possible to call on the supplied tdsqlite3_changeset_iter handle +** is tdsqlite3changeset_fk_conflicts(). ** ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd> ** If any other constraint violation occurs while applying a change (i.e. @@ -9590,7 +11098,7 @@ int sqlite3changeset_apply( ** invoked with CHANGESET_CONSTRAINT as the second argument. ** ** There is no conflicting row in this case. The results of invoking the -** sqlite3changeset_conflict() API are undefined. +** tdsqlite3changeset_conflict() API are undefined. ** ** </dl> */ @@ -9615,7 +11123,7 @@ int sqlite3changeset_apply( ** This value may only be returned if the second argument to the conflict ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this ** is not the case, any changes applied so far are rolled back and the -** call to sqlite3changeset_apply() returns SQLITE_MISUSE. +** call to tdsqlite3changeset_apply() returns SQLITE_MISUSE. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict ** handler, then the conflicting row is either updated or deleted, depending @@ -9628,13 +11136,168 @@ int sqlite3changeset_apply( ** ** <dt>SQLITE_CHANGESET_ABORT<dd> ** If this value is returned, any changes applied so far are rolled back -** and the call to sqlite3changeset_apply() returns SQLITE_ABORT. +** and the call to tdsqlite3changeset_apply() returns SQLITE_ABORT. ** </dl> */ #define SQLITE_CHANGESET_OMIT 0 #define SQLITE_CHANGESET_REPLACE 1 #define SQLITE_CHANGESET_ABORT 2 +/* +** CAPI3REF: Rebasing changesets +** EXPERIMENTAL +** +** Suppose there is a site hosting a database in state S0. And that +** modifications are made that move that database to state S1 and a +** changeset recorded (the "local" changeset). Then, a changeset based +** on S0 is received from another site (the "remote" changeset) and +** applied to the database. The database is then in state +** (S1+"remote"), where the exact state depends on any conflict +** resolution decisions (OMIT or REPLACE) made while applying "remote". +** Rebasing a changeset is to update it to take those conflict +** resolution decisions into account, so that the same conflicts +** do not have to be resolved elsewhere in the network. +** +** For example, if both the local and remote changesets contain an +** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)": +** +** local: INSERT INTO t1 VALUES(1, 'v1'); +** remote: INSERT INTO t1 VALUES(1, 'v2'); +** +** and the conflict resolution is REPLACE, then the INSERT change is +** removed from the local changeset (it was overridden). Or, if the +** conflict resolution was "OMIT", then the local changeset is modified +** to instead contain: +** +** UPDATE t1 SET b = 'v2' WHERE a=1; +** +** Changes within the local changeset are rebased as follows: +** +** <dl> +** <dt>Local INSERT<dd> +** This may only conflict with a remote INSERT. If the conflict +** resolution was OMIT, then add an UPDATE change to the rebased +** changeset. Or, if the conflict resolution was REPLACE, add +** nothing to the rebased changeset. +** +** <dt>Local DELETE<dd> +** This may conflict with a remote UPDATE or DELETE. In both cases the +** only possible resolution is OMIT. If the remote operation was a +** DELETE, then add no change to the rebased changeset. If the remote +** operation was an UPDATE, then the old.* fields of change are updated +** to reflect the new.* values in the UPDATE. +** +** <dt>Local UPDATE<dd> +** This may conflict with a remote UPDATE or DELETE. If it conflicts +** with a DELETE, and the conflict resolution was OMIT, then the update +** is changed into an INSERT. Any undefined values in the new.* record +** from the update change are filled in using the old.* values from +** the conflicting DELETE. Or, if the conflict resolution was REPLACE, +** the UPDATE change is simply omitted from the rebased changeset. +** +** If conflict is with a remote UPDATE and the resolution is OMIT, then +** the old.* values are rebased using the new.* values in the remote +** change. Or, if the resolution is REPLACE, then the change is copied +** into the rebased changeset with updates to columns also updated by +** the conflicting remote UPDATE removed. If this means no columns would +** be updated, the change is omitted. +** </dl> +** +** A local change may be rebased against multiple remote changes +** simultaneously. If a single key is modified by multiple remote +** changesets, they are combined as follows before the local changeset +** is rebased: +** +** <ul> +** <li> If there has been one or more REPLACE resolutions on a +** key, it is rebased according to a REPLACE. +** +** <li> If there have been no REPLACE resolutions on a key, then +** the local changeset is rebased according to the most recent +** of the OMIT resolutions. +** </ul> +** +** Note that conflict resolutions from multiple remote changesets are +** combined on a per-field basis, not per-row. This means that in the +** case of multiple remote UPDATE operations, some fields of a single +** local change may be rebased for REPLACE while others are rebased for +** OMIT. +** +** In order to rebase a local changeset, the remote changeset must first +** be applied to the local database using tdsqlite3changeset_apply_v2() and +** the buffer of rebase information captured. Then: +** +** <ol> +** <li> An tdsqlite3_rebaser object is created by calling +** tdsqlite3rebaser_create(). +** <li> The new object is configured with the rebase buffer obtained from +** tdsqlite3changeset_apply_v2() by calling tdsqlite3rebaser_configure(). +** If the local changeset is to be rebased against multiple remote +** changesets, then tdsqlite3rebaser_configure() should be called +** multiple times, in the same order that the multiple +** tdsqlite3changeset_apply_v2() calls were made. +** <li> Each local changeset is rebased by calling tdsqlite3rebaser_rebase(). +** <li> The tdsqlite3_rebaser object is deleted by calling +** tdsqlite3rebaser_delete(). +** </ol> +*/ +typedef struct tdsqlite3_rebaser tdsqlite3_rebaser; + +/* +** CAPI3REF: Create a changeset rebaser object. +** EXPERIMENTAL +** +** Allocate a new changeset rebaser object. If successful, set (*ppNew) to +** point to the new object and return SQLITE_OK. Otherwise, if an error +** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) +** to NULL. +*/ +SQLITE_API int tdsqlite3rebaser_create(tdsqlite3_rebaser **ppNew); + +/* +** CAPI3REF: Configure a changeset rebaser object. +** EXPERIMENTAL +** +** Configure the changeset rebaser object to rebase changesets according +** to the conflict resolutions described by buffer pRebase (size nRebase +** bytes), which must have been obtained from a previous call to +** tdsqlite3changeset_apply_v2(). +*/ +SQLITE_API int tdsqlite3rebaser_configure( + tdsqlite3_rebaser*, + int nRebase, const void *pRebase +); + +/* +** CAPI3REF: Rebase a changeset +** EXPERIMENTAL +** +** Argument pIn must point to a buffer containing a changeset nIn bytes +** in size. This function allocates and populates a buffer with a copy +** of the changeset rebased according to the configuration of the +** rebaser object passed as the first argument. If successful, (*ppOut) +** is set to point to the new buffer containing the rebased changeset and +** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the +** responsibility of the caller to eventually free the new buffer using +** tdsqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut) +** are set to zero and an SQLite error code returned. +*/ +SQLITE_API int tdsqlite3rebaser_rebase( + tdsqlite3_rebaser*, + int nIn, const void *pIn, + int *pnOut, void **ppOut +); + +/* +** CAPI3REF: Delete a changeset rebaser object. +** EXPERIMENTAL +** +** Delete the changeset rebaser object and all associated resources. There +** should be one call to this function for each successful invocation +** of tdsqlite3rebaser_create(). +*/ +SQLITE_API void tdsqlite3rebaser_delete(tdsqlite3_rebaser *p); + /* ** CAPI3REF: Streaming Versions of API functions. ** @@ -9643,18 +11306,19 @@ int sqlite3changeset_apply( ** ** <table border=1 style="margin-left:8ex;margin-right:8ex"> ** <tr><th>Streaming function<th>Non-streaming equivalent</th> -** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply] -** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat] -** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert] -** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start] -** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset] -** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset] +** <tr><td>tdsqlite3changeset_apply_strm<td>[tdsqlite3changeset_apply] +** <tr><td>tdsqlite3changeset_apply_strm_v2<td>[tdsqlite3changeset_apply_v2] +** <tr><td>tdsqlite3changeset_concat_strm<td>[tdsqlite3changeset_concat] +** <tr><td>tdsqlite3changeset_invert_strm<td>[tdsqlite3changeset_invert] +** <tr><td>tdsqlite3changeset_start_strm<td>[tdsqlite3changeset_start] +** <tr><td>tdsqlite3session_changeset_strm<td>[tdsqlite3session_changeset] +** <tr><td>tdsqlite3session_patchset_strm<td>[tdsqlite3session_patchset] ** </table> ** ** Non-streaming functions that accept changesets (or patchsets) as input ** require that the entire changeset be stored in a single buffer in memory. ** Similarly, those that return a changeset or patchset do so by returning -** a pointer to a single large buffer allocated using sqlite3_malloc(). +** a pointer to a single large buffer allocated using tdsqlite3_malloc(). ** Normally this is convenient. However, if an application running in a ** low-memory environment is required to handle very large changesets, the ** large contiguous memory allocations required can become onerous. @@ -9687,7 +11351,7 @@ int sqlite3changeset_apply( ** an error, all processing is abandoned and the streaming API function ** returns a copy of the error code to the caller. ** -** In the case of sqlite3changeset_start_strm(), the xInput callback may be +** In the case of tdsqlite3changeset_start_strm(), the xInput callback may be ** invoked by the sessions module at any point during the lifetime of the ** iterator. If such an xInput callback returns an error, the iterator enters ** an error state, whereby all subsequent calls to iterator functions @@ -9724,8 +11388,8 @@ int sqlite3changeset_apply( ** parameter set to a value less than or equal to zero. Other than this, ** no guarantees are made as to the size of the chunks of data returned. */ -int sqlite3changeset_apply_strm( - sqlite3 *db, /* Apply change to "main" db of this handle */ +SQLITE_API int tdsqlite3changeset_apply_strm( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ void *pIn, /* First arg for xInput */ int(*xFilter)( @@ -9735,11 +11399,28 @@ int sqlite3changeset_apply_strm( int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); -int sqlite3changeset_concat_strm( +SQLITE_API int tdsqlite3changeset_apply_v2_strm( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +); +SQLITE_API int tdsqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, int (*xInputB)(void *pIn, void *pData, int *pnData), @@ -9747,36 +11428,88 @@ int sqlite3changeset_concat_strm( int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3changeset_invert_strm( +SQLITE_API int tdsqlite3changeset_invert_strm( int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3changeset_start_strm( - sqlite3_changeset_iter **pp, +SQLITE_API int tdsqlite3changeset_start_strm( + tdsqlite3_changeset_iter **pp, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); -int sqlite3session_changeset_strm( - sqlite3_session *pSession, +SQLITE_API int tdsqlite3changeset_start_v2_strm( + tdsqlite3_changeset_iter **pp, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int flags +); +SQLITE_API int tdsqlite3session_changeset_strm( + tdsqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3session_patchset_strm( - sqlite3_session *pSession, +SQLITE_API int tdsqlite3session_patchset_strm( + tdsqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3changegroup_add_strm(sqlite3_changegroup*, +SQLITE_API int tdsqlite3changegroup_add_strm(tdsqlite3_changegroup*, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); -int sqlite3changegroup_output_strm(sqlite3_changegroup*, +SQLITE_API int tdsqlite3changegroup_output_strm(tdsqlite3_changegroup*, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); +SQLITE_API int tdsqlite3rebaser_rebase_strm( + tdsqlite3_rebaser *pRebaser, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut +); +/* +** CAPI3REF: Configure global parameters +** +** The tdsqlite3session_config() interface is used to make global configuration +** changes to the sessions module in order to tune it to the specific needs +** of the application. +** +** The tdsqlite3session_config() interface is not threadsafe. If it is invoked +** while any other thread is inside any other sessions method then the +** results are undefined. Furthermore, if it is invoked after any sessions +** related objects have been created, the results are also undefined. +** +** The first argument to the tdsqlite3session_config() function must be one +** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The +** interpretation of the (void*) value passed as the second parameter and +** the effect of calling this function depends on the value of the first +** parameter. +** +** <dl> +** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd> +** By default, the sessions module streaming interfaces attempt to input +** and output data in approximately 1 KiB chunks. This operand may be used +** to set and query the value of this configuration setting. The pointer +** passed as the second argument must point to a value of type (int). +** If this value is greater than 0, it is used as the new streaming data +** chunk size for both input and output. Before returning, the (int) value +** pointed to by pArg is set to the final value of the streaming interface +** chunk size. +** </dl> +** +** This function returns SQLITE_OK if successful, or an SQLite error code +** otherwise. +*/ +SQLITE_API int tdsqlite3session_config(int op, void *pArg); + +/* +** CAPI3REF: Values for tdsqlite3session_config(). +*/ +#define SQLITE_SESSION_CONFIG_STRMSIZE 1 /* ** Make sure we can call this stuff from C++. @@ -9787,7 +11520,7 @@ int sqlite3changegroup_output_strm(sqlite3_changegroup*, #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */ -/******** End of sqlite3session.h *********/ +/******** End of tdsqlite3session.h *********/ /******** Begin file fts5.h *********/ /* ** 2014 May 31 @@ -9821,7 +11554,7 @@ extern "C" { ** CUSTOM AUXILIARY FUNCTIONS ** ** Virtual table implementations may overload SQL functions by implementing -** the sqlite3_module.xFindFunction() method. +** the tdsqlite3_module.xFindFunction() method. */ typedef struct Fts5ExtensionApi Fts5ExtensionApi; @@ -9831,9 +11564,9 @@ typedef struct Fts5PhraseIter Fts5PhraseIter; typedef void (*fts5_extension_function)( const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ Fts5Context *pFts, /* First arg to pass to pApi functions */ - sqlite3_context *pCtx, /* Context for returning result/error */ + tdsqlite3_context *pCtx, /* Context for returning result/error */ int nVal, /* Number of values in apVal[] array */ - sqlite3_value **apVal /* Array of trailing arguments */ + tdsqlite3_value **apVal /* Array of trailing arguments */ ); struct Fts5PhraseIter { @@ -9910,12 +11643,8 @@ struct Fts5PhraseIter { ** ** Usually, output parameter *piPhrase is set to the phrase number, *piCol ** to the column in which it occurs and *piOff the token offset of the -** first token of the phrase. The exception is if the table was created -** with the offsets=0 option specified. In this case *piOff is always -** set to -1. -** -** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) -** if an error occurs. +** first token of the phrase. Returns SQLITE_OK if successful, or an error +** code (i.e. SQLITE_NOMEM) if an error occurs. ** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. @@ -9953,10 +11682,10 @@ struct Fts5PhraseIter { ** ** xSetAuxdata(pFts5, pAux, xDelete) ** -** Save the pointer passed as the second argument as the extension functions +** Save the pointer passed as the second argument as the extension function's ** "auxiliary data". The pointer may then be retrieved by the current or any ** future invocation of the same fts5 extension function made as part of -** of the same MATCH query using the xGetAuxdata() API. +** the same MATCH query using the xGetAuxdata() API. ** ** Each extension function is allocated a single auxiliary data slot for ** each FTS query (MATCH expression). If the extension function is invoked @@ -9971,7 +11700,7 @@ struct Fts5PhraseIter { ** The xDelete callback, if one is specified, is also invoked on the ** auxiliary data pointer after the FTS5 query has finished. ** -** If an error (e.g. an OOM condition) occurs within this function, an +** If an error (e.g. an OOM condition) occurs within this function, ** the auxiliary data is set to NULL and an error code returned. If the ** xDelete parameter was not NULL, it is invoked on the auxiliary data ** pointer before returning. @@ -10062,8 +11791,8 @@ struct Fts5ExtensionApi { void *(*xUserData)(Fts5Context*); int (*xColumnCount)(Fts5Context*); - int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); - int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); + int (*xRowCount)(Fts5Context*, tdsqlite3_int64 *pnRow); + int (*xColumnTotalSize)(Fts5Context*, int iCol, tdsqlite3_int64 *pnToken); int (*xTokenize)(Fts5Context*, const char *pText, int nText, /* Text to tokenize */ @@ -10077,7 +11806,7 @@ struct Fts5ExtensionApi { int (*xInstCount)(Fts5Context*, int *pnInst); int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); - sqlite3_int64 (*xRowid)(Fts5Context*); + tdsqlite3_int64 (*xRowid)(Fts5Context*); int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); @@ -10195,8 +11924,8 @@ struct Fts5ExtensionApi { ** ** There are several ways to approach this in FTS5: ** -** <ol><li> By mapping all synonyms to a single token. In this case, the -** In the above example, this means that the tokenizer returns the +** <ol><li> By mapping all synonyms to a single token. In this case, using +** the above example, this means that the tokenizer returns the ** same token for inputs "first" and "1st". Say that token is in ** fact "first", so that when the user inserts the document "I won ** 1st place" entries are added to the index for tokens "i", "won", @@ -10204,11 +11933,11 @@ struct Fts5ExtensionApi { ** the tokenizer substitutes "first" for "1st" and the query works ** as expected. ** -** <li> By adding multiple synonyms for a single term to the FTS index. -** In this case, when tokenizing query text, the tokenizer may -** provide multiple synonyms for a single term within the document. -** FTS5 then queries the index for each synonym individually. For -** example, faced with the query: +** <li> By querying the index for all synonyms of each query term +** separately. In this case, when tokenizing query text, the +** tokenizer may provide multiple synonyms for a single term +** within the document. FTS5 then queries the index for each +** synonym individually. For example, faced with the query: ** ** <codeblock> ** ... MATCH 'first place'</codeblock> @@ -10232,9 +11961,9 @@ struct Fts5ExtensionApi { ** "place". ** ** This way, even if the tokenizer does not provide synonyms -** when tokenizing query text (it should not - to do would be +** when tokenizing query text (it should not - to do so would be ** inefficient), it doesn't matter if the user queries for -** 'first + place' or '1st + place', as there are entires in the +** 'first + place' or '1st + place', as there are entries in the ** FTS index corresponding to both forms of the first token. ** </ol> ** @@ -10262,7 +11991,7 @@ struct Fts5ExtensionApi { ** extra data to the FTS index or require FTS5 to query for multiple terms, ** so it is efficient in terms of disk space and query speed. However, it ** does not support prefix queries very well. If, as suggested above, the -** token "first" is subsituted for "1st" by the tokenizer, then the query: +** token "first" is substituted for "1st" by the tokenizer, then the query: ** ** <codeblock> ** ... MATCH '1s*'</codeblock> diff --git a/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3ext.h b/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3ext.h index ce87e74690..1b5d136d58 100644 --- a/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3ext.h +++ b/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3ext.h @@ -29,526 +29,616 @@ ** versions of SQLite will not be able to load each other's shared ** libraries! */ -struct sqlite3_api_routines { - void * (*aggregate_context)(sqlite3_context*,int nBytes); - int (*aggregate_count)(sqlite3_context*); - int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); - int (*bind_double)(sqlite3_stmt*,int,double); - int (*bind_int)(sqlite3_stmt*,int,int); - int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); - int (*bind_null)(sqlite3_stmt*,int); - int (*bind_parameter_count)(sqlite3_stmt*); - int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); - const char * (*bind_parameter_name)(sqlite3_stmt*,int); - int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); - int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); - int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); - int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); - int (*busy_timeout)(sqlite3*,int ms); - int (*changes)(sqlite3*); - int (*close)(sqlite3*); - int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, +struct tdsqlite3_api_routines { + void * (*aggregate_context)(tdsqlite3_context*,int nBytes); + int (*aggregate_count)(tdsqlite3_context*); + int (*bind_blob)(tdsqlite3_stmt*,int,const void*,int n,void(*)(void*)); + int (*bind_double)(tdsqlite3_stmt*,int,double); + int (*bind_int)(tdsqlite3_stmt*,int,int); + int (*bind_int64)(tdsqlite3_stmt*,int,sqlite_int64); + int (*bind_null)(tdsqlite3_stmt*,int); + int (*bind_parameter_count)(tdsqlite3_stmt*); + int (*bind_parameter_index)(tdsqlite3_stmt*,const char*zName); + const char * (*bind_parameter_name)(tdsqlite3_stmt*,int); + int (*bind_text)(tdsqlite3_stmt*,int,const char*,int n,void(*)(void*)); + int (*bind_text16)(tdsqlite3_stmt*,int,const void*,int,void(*)(void*)); + int (*bind_value)(tdsqlite3_stmt*,int,const tdsqlite3_value*); + int (*busy_handler)(tdsqlite3*,int(*)(void*,int),void*); + int (*busy_timeout)(tdsqlite3*,int ms); + int (*changes)(tdsqlite3*); + int (*close)(tdsqlite3*); + int (*collation_needed)(tdsqlite3*,void*,void(*)(void*,tdsqlite3*, int eTextRep,const char*)); - int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, + int (*collation_needed16)(tdsqlite3*,void*,void(*)(void*,tdsqlite3*, int eTextRep,const void*)); - const void * (*column_blob)(sqlite3_stmt*,int iCol); - int (*column_bytes)(sqlite3_stmt*,int iCol); - int (*column_bytes16)(sqlite3_stmt*,int iCol); - int (*column_count)(sqlite3_stmt*pStmt); - const char * (*column_database_name)(sqlite3_stmt*,int); - const void * (*column_database_name16)(sqlite3_stmt*,int); - const char * (*column_decltype)(sqlite3_stmt*,int i); - const void * (*column_decltype16)(sqlite3_stmt*,int); - double (*column_double)(sqlite3_stmt*,int iCol); - int (*column_int)(sqlite3_stmt*,int iCol); - sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); - const char * (*column_name)(sqlite3_stmt*,int); - const void * (*column_name16)(sqlite3_stmt*,int); - const char * (*column_origin_name)(sqlite3_stmt*,int); - const void * (*column_origin_name16)(sqlite3_stmt*,int); - const char * (*column_table_name)(sqlite3_stmt*,int); - const void * (*column_table_name16)(sqlite3_stmt*,int); - const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); - const void * (*column_text16)(sqlite3_stmt*,int iCol); - int (*column_type)(sqlite3_stmt*,int iCol); - sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); - void * (*commit_hook)(sqlite3*,int(*)(void*),void*); + const void * (*column_blob)(tdsqlite3_stmt*,int iCol); + int (*column_bytes)(tdsqlite3_stmt*,int iCol); + int (*column_bytes16)(tdsqlite3_stmt*,int iCol); + int (*column_count)(tdsqlite3_stmt*pStmt); + const char * (*column_database_name)(tdsqlite3_stmt*,int); + const void * (*column_database_name16)(tdsqlite3_stmt*,int); + const char * (*column_decltype)(tdsqlite3_stmt*,int i); + const void * (*column_decltype16)(tdsqlite3_stmt*,int); + double (*column_double)(tdsqlite3_stmt*,int iCol); + int (*column_int)(tdsqlite3_stmt*,int iCol); + sqlite_int64 (*column_int64)(tdsqlite3_stmt*,int iCol); + const char * (*column_name)(tdsqlite3_stmt*,int); + const void * (*column_name16)(tdsqlite3_stmt*,int); + const char * (*column_origin_name)(tdsqlite3_stmt*,int); + const void * (*column_origin_name16)(tdsqlite3_stmt*,int); + const char * (*column_table_name)(tdsqlite3_stmt*,int); + const void * (*column_table_name16)(tdsqlite3_stmt*,int); + const unsigned char * (*column_text)(tdsqlite3_stmt*,int iCol); + const void * (*column_text16)(tdsqlite3_stmt*,int iCol); + int (*column_type)(tdsqlite3_stmt*,int iCol); + tdsqlite3_value* (*column_value)(tdsqlite3_stmt*,int iCol); + void * (*commit_hook)(tdsqlite3*,int(*)(void*),void*); int (*complete)(const char*sql); int (*complete16)(const void*sql); - int (*create_collation)(sqlite3*,const char*,int,void*, + int (*create_collation)(tdsqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*)); - int (*create_collation16)(sqlite3*,const void*,int,void*, + int (*create_collation16)(tdsqlite3*,const void*,int,void*, int(*)(void*,int,const void*,int,const void*)); - int (*create_function)(sqlite3*,const char*,int,int,void*, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*)); - int (*create_function16)(sqlite3*,const void*,int,int,void*, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*)); - int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); - int (*data_count)(sqlite3_stmt*pStmt); - sqlite3 * (*db_handle)(sqlite3_stmt*); - int (*declare_vtab)(sqlite3*,const char*); + int (*create_function)(tdsqlite3*,const char*,int,int,void*, + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*)); + int (*create_function16)(tdsqlite3*,const void*,int,int,void*, + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*)); + int (*create_module)(tdsqlite3*,const char*,const tdsqlite3_module*,void*); + int (*data_count)(tdsqlite3_stmt*pStmt); + tdsqlite3 * (*db_handle)(tdsqlite3_stmt*); + int (*declare_vtab)(tdsqlite3*,const char*); int (*enable_shared_cache)(int); - int (*errcode)(sqlite3*db); - const char * (*errmsg)(sqlite3*); - const void * (*errmsg16)(sqlite3*); - int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); - int (*expired)(sqlite3_stmt*); - int (*finalize)(sqlite3_stmt*pStmt); + int (*errcode)(tdsqlite3*db); + const char * (*errmsg)(tdsqlite3*); + const void * (*errmsg16)(tdsqlite3*); + int (*exec)(tdsqlite3*,const char*,tdsqlite3_callback,void*,char**); + int (*expired)(tdsqlite3_stmt*); + int (*finalize)(tdsqlite3_stmt*pStmt); void (*free)(void*); void (*free_table)(char**result); - int (*get_autocommit)(sqlite3*); - void * (*get_auxdata)(sqlite3_context*,int); - int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); + int (*get_autocommit)(tdsqlite3*); + void * (*get_auxdata)(tdsqlite3_context*,int); + int (*get_table)(tdsqlite3*,const char*,char***,int*,int*,char**); int (*global_recover)(void); - void (*interruptx)(sqlite3*); - sqlite_int64 (*last_insert_rowid)(sqlite3*); + void (*interruptx)(tdsqlite3*); + sqlite_int64 (*last_insert_rowid)(tdsqlite3*); const char * (*libversion)(void); int (*libversion_number)(void); void *(*malloc)(int); char * (*mprintf)(const char*,...); - int (*open)(const char*,sqlite3**); - int (*open16)(const void*,sqlite3**); - int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); - int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); - void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); - void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); + int (*open)(const char*,tdsqlite3**); + int (*open16)(const void*,tdsqlite3**); + int (*prepare)(tdsqlite3*,const char*,int,tdsqlite3_stmt**,const char**); + int (*prepare16)(tdsqlite3*,const void*,int,tdsqlite3_stmt**,const void**); + void * (*profile)(tdsqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); + void (*progress_handler)(tdsqlite3*,int,int(*)(void*),void*); void *(*realloc)(void*,int); - int (*reset)(sqlite3_stmt*pStmt); - void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_double)(sqlite3_context*,double); - void (*result_error)(sqlite3_context*,const char*,int); - void (*result_error16)(sqlite3_context*,const void*,int); - void (*result_int)(sqlite3_context*,int); - void (*result_int64)(sqlite3_context*,sqlite_int64); - void (*result_null)(sqlite3_context*); - void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); - void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_value)(sqlite3_context*,sqlite3_value*); - void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); - int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, + int (*reset)(tdsqlite3_stmt*pStmt); + void (*result_blob)(tdsqlite3_context*,const void*,int,void(*)(void*)); + void (*result_double)(tdsqlite3_context*,double); + void (*result_error)(tdsqlite3_context*,const char*,int); + void (*result_error16)(tdsqlite3_context*,const void*,int); + void (*result_int)(tdsqlite3_context*,int); + void (*result_int64)(tdsqlite3_context*,sqlite_int64); + void (*result_null)(tdsqlite3_context*); + void (*result_text)(tdsqlite3_context*,const char*,int,void(*)(void*)); + void (*result_text16)(tdsqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16be)(tdsqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16le)(tdsqlite3_context*,const void*,int,void(*)(void*)); + void (*result_value)(tdsqlite3_context*,tdsqlite3_value*); + void * (*rollback_hook)(tdsqlite3*,void(*)(void*),void*); + int (*set_authorizer)(tdsqlite3*,int(*)(void*,int,const char*,const char*, const char*,const char*),void*); - void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); - char * (*snprintf)(int,char*,const char*,...); - int (*step)(sqlite3_stmt*); - int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, + void (*set_auxdata)(tdsqlite3_context*,int,void*,void (*)(void*)); + char * (*xsnprintf)(int,char*,const char*,...); + int (*step)(tdsqlite3_stmt*); + int (*table_column_metadata)(tdsqlite3*,const char*,const char*,const char*, char const**,char const**,int*,int*,int*); void (*thread_cleanup)(void); - int (*total_changes)(sqlite3*); - void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); - int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); - void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, + int (*total_changes)(tdsqlite3*); + void * (*trace)(tdsqlite3*,void(*xTrace)(void*,const char*),void*); + int (*transfer_bindings)(tdsqlite3_stmt*,tdsqlite3_stmt*); + void * (*update_hook)(tdsqlite3*,void(*)(void*,int ,char const*,char const*, sqlite_int64),void*); - void * (*user_data)(sqlite3_context*); - const void * (*value_blob)(sqlite3_value*); - int (*value_bytes)(sqlite3_value*); - int (*value_bytes16)(sqlite3_value*); - double (*value_double)(sqlite3_value*); - int (*value_int)(sqlite3_value*); - sqlite_int64 (*value_int64)(sqlite3_value*); - int (*value_numeric_type)(sqlite3_value*); - const unsigned char * (*value_text)(sqlite3_value*); - const void * (*value_text16)(sqlite3_value*); - const void * (*value_text16be)(sqlite3_value*); - const void * (*value_text16le)(sqlite3_value*); - int (*value_type)(sqlite3_value*); + void * (*user_data)(tdsqlite3_context*); + const void * (*value_blob)(tdsqlite3_value*); + int (*value_bytes)(tdsqlite3_value*); + int (*value_bytes16)(tdsqlite3_value*); + double (*value_double)(tdsqlite3_value*); + int (*value_int)(tdsqlite3_value*); + sqlite_int64 (*value_int64)(tdsqlite3_value*); + int (*value_numeric_type)(tdsqlite3_value*); + const unsigned char * (*value_text)(tdsqlite3_value*); + const void * (*value_text16)(tdsqlite3_value*); + const void * (*value_text16be)(tdsqlite3_value*); + const void * (*value_text16le)(tdsqlite3_value*); + int (*value_type)(tdsqlite3_value*); char *(*vmprintf)(const char*,va_list); /* Added ??? */ - int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); + int (*overload_function)(tdsqlite3*, const char *zFuncName, int nArg); /* Added by 3.3.13 */ - int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); - int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); - int (*clear_bindings)(sqlite3_stmt*); + int (*prepare_v2)(tdsqlite3*,const char*,int,tdsqlite3_stmt**,const char**); + int (*prepare16_v2)(tdsqlite3*,const void*,int,tdsqlite3_stmt**,const void**); + int (*clear_bindings)(tdsqlite3_stmt*); /* Added by 3.4.1 */ - int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, + int (*create_module_v2)(tdsqlite3*,const char*,const tdsqlite3_module*,void*, void (*xDestroy)(void *)); /* Added by 3.5.0 */ - int (*bind_zeroblob)(sqlite3_stmt*,int,int); - int (*blob_bytes)(sqlite3_blob*); - int (*blob_close)(sqlite3_blob*); - int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, - int,sqlite3_blob**); - int (*blob_read)(sqlite3_blob*,void*,int,int); - int (*blob_write)(sqlite3_blob*,const void*,int,int); - int (*create_collation_v2)(sqlite3*,const char*,int,void*, + int (*bind_zeroblob)(tdsqlite3_stmt*,int,int); + int (*blob_bytes)(tdsqlite3_blob*); + int (*blob_close)(tdsqlite3_blob*); + int (*blob_open)(tdsqlite3*,const char*,const char*,const char*,tdsqlite3_int64, + int,tdsqlite3_blob**); + int (*blob_read)(tdsqlite3_blob*,void*,int,int); + int (*blob_write)(tdsqlite3_blob*,const void*,int,int); + int (*create_collation_v2)(tdsqlite3*,const char*,int,void*, int(*)(void*,int,const void*,int,const void*), void(*)(void*)); - int (*file_control)(sqlite3*,const char*,int,void*); - sqlite3_int64 (*memory_highwater)(int); - sqlite3_int64 (*memory_used)(void); - sqlite3_mutex *(*mutex_alloc)(int); - void (*mutex_enter)(sqlite3_mutex*); - void (*mutex_free)(sqlite3_mutex*); - void (*mutex_leave)(sqlite3_mutex*); - int (*mutex_try)(sqlite3_mutex*); - int (*open_v2)(const char*,sqlite3**,int,const char*); + int (*file_control)(tdsqlite3*,const char*,int,void*); + tdsqlite3_int64 (*memory_highwater)(int); + tdsqlite3_int64 (*memory_used)(void); + tdsqlite3_mutex *(*mutex_alloc)(int); + void (*mutex_enter)(tdsqlite3_mutex*); + void (*mutex_free)(tdsqlite3_mutex*); + void (*mutex_leave)(tdsqlite3_mutex*); + int (*mutex_try)(tdsqlite3_mutex*); + int (*open_v2)(const char*,tdsqlite3**,int,const char*); int (*release_memory)(int); - void (*result_error_nomem)(sqlite3_context*); - void (*result_error_toobig)(sqlite3_context*); + void (*result_error_nomem)(tdsqlite3_context*); + void (*result_error_toobig)(tdsqlite3_context*); int (*sleep)(int); void (*soft_heap_limit)(int); - sqlite3_vfs *(*vfs_find)(const char*); - int (*vfs_register)(sqlite3_vfs*,int); - int (*vfs_unregister)(sqlite3_vfs*); + tdsqlite3_vfs *(*vfs_find)(const char*); + int (*vfs_register)(tdsqlite3_vfs*,int); + int (*vfs_unregister)(tdsqlite3_vfs*); int (*xthreadsafe)(void); - void (*result_zeroblob)(sqlite3_context*,int); - void (*result_error_code)(sqlite3_context*,int); + void (*result_zeroblob)(tdsqlite3_context*,int); + void (*result_error_code)(tdsqlite3_context*,int); int (*test_control)(int, ...); void (*randomness)(int,void*); - sqlite3 *(*context_db_handle)(sqlite3_context*); - int (*extended_result_codes)(sqlite3*,int); - int (*limit)(sqlite3*,int,int); - sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); - const char *(*sql)(sqlite3_stmt*); + tdsqlite3 *(*context_db_handle)(tdsqlite3_context*); + int (*extended_result_codes)(tdsqlite3*,int); + int (*limit)(tdsqlite3*,int,int); + tdsqlite3_stmt *(*next_stmt)(tdsqlite3*,tdsqlite3_stmt*); + const char *(*sql)(tdsqlite3_stmt*); int (*status)(int,int*,int*,int); - int (*backup_finish)(sqlite3_backup*); - sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); - int (*backup_pagecount)(sqlite3_backup*); - int (*backup_remaining)(sqlite3_backup*); - int (*backup_step)(sqlite3_backup*,int); + int (*backup_finish)(tdsqlite3_backup*); + tdsqlite3_backup *(*backup_init)(tdsqlite3*,const char*,tdsqlite3*,const char*); + int (*backup_pagecount)(tdsqlite3_backup*); + int (*backup_remaining)(tdsqlite3_backup*); + int (*backup_step)(tdsqlite3_backup*,int); const char *(*compileoption_get)(int); int (*compileoption_used)(const char*); - int (*create_function_v2)(sqlite3*,const char*,int,int,void*, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*), + int (*create_function_v2)(tdsqlite3*,const char*,int,int,void*, + void (*xFunc)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*), void(*xDestroy)(void*)); - int (*db_config)(sqlite3*,int,...); - sqlite3_mutex *(*db_mutex)(sqlite3*); - int (*db_status)(sqlite3*,int,int*,int*,int); - int (*extended_errcode)(sqlite3*); + int (*db_config)(tdsqlite3*,int,...); + tdsqlite3_mutex *(*db_mutex)(tdsqlite3*); + int (*db_status)(tdsqlite3*,int,int*,int*,int); + int (*extended_errcode)(tdsqlite3*); void (*log)(int,const char*,...); - sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); + tdsqlite3_int64 (*soft_heap_limit64)(tdsqlite3_int64); const char *(*sourceid)(void); - int (*stmt_status)(sqlite3_stmt*,int,int); + int (*stmt_status)(tdsqlite3_stmt*,int,int); int (*strnicmp)(const char*,const char*,int); - int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); - int (*wal_autocheckpoint)(sqlite3*,int); - int (*wal_checkpoint)(sqlite3*,const char*); - void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); - int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); - int (*vtab_config)(sqlite3*,int op,...); - int (*vtab_on_conflict)(sqlite3*); + int (*unlock_notify)(tdsqlite3*,void(*)(void**,int),void*); + int (*wal_autocheckpoint)(tdsqlite3*,int); + int (*wal_checkpoint)(tdsqlite3*,const char*); + void *(*wal_hook)(tdsqlite3*,int(*)(void*,tdsqlite3*,const char*,int),void*); + int (*blob_reopen)(tdsqlite3_blob*,tdsqlite3_int64); + int (*vtab_config)(tdsqlite3*,int op,...); + int (*vtab_on_conflict)(tdsqlite3*); /* Version 3.7.16 and later */ - int (*close_v2)(sqlite3*); - const char *(*db_filename)(sqlite3*,const char*); - int (*db_readonly)(sqlite3*,const char*); - int (*db_release_memory)(sqlite3*); + int (*close_v2)(tdsqlite3*); + const char *(*db_filename)(tdsqlite3*,const char*); + int (*db_readonly)(tdsqlite3*,const char*); + int (*db_release_memory)(tdsqlite3*); const char *(*errstr)(int); - int (*stmt_busy)(sqlite3_stmt*); - int (*stmt_readonly)(sqlite3_stmt*); + int (*stmt_busy)(tdsqlite3_stmt*); + int (*stmt_readonly)(tdsqlite3_stmt*); int (*stricmp)(const char*,const char*); int (*uri_boolean)(const char*,const char*,int); - sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); + tdsqlite3_int64 (*uri_int64)(const char*,const char*,tdsqlite3_int64); const char *(*uri_parameter)(const char*,const char*); - char *(*vsnprintf)(int,char*,const char*,va_list); - int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); + char *(*xvsnprintf)(int,char*,const char*,va_list); + int (*wal_checkpoint_v2)(tdsqlite3*,const char*,int,int*,int*); /* Version 3.8.7 and later */ int (*auto_extension)(void(*)(void)); - int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64, + int (*bind_blob64)(tdsqlite3_stmt*,int,const void*,tdsqlite3_uint64, void(*)(void*)); - int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64, + int (*bind_text64)(tdsqlite3_stmt*,int,const char*,tdsqlite3_uint64, void(*)(void*),unsigned char); int (*cancel_auto_extension)(void(*)(void)); - int (*load_extension)(sqlite3*,const char*,const char*,char**); - void *(*malloc64)(sqlite3_uint64); - sqlite3_uint64 (*msize)(void*); - void *(*realloc64)(void*,sqlite3_uint64); + int (*load_extension)(tdsqlite3*,const char*,const char*,char**); + void *(*malloc64)(tdsqlite3_uint64); + tdsqlite3_uint64 (*msize)(void*); + void *(*realloc64)(void*,tdsqlite3_uint64); void (*reset_auto_extension)(void); - void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64, + void (*result_blob64)(tdsqlite3_context*,const void*,tdsqlite3_uint64, void(*)(void*)); - void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64, + void (*result_text64)(tdsqlite3_context*,const char*,tdsqlite3_uint64, void(*)(void*), unsigned char); int (*strglob)(const char*,const char*); /* Version 3.8.11 and later */ - sqlite3_value *(*value_dup)(const sqlite3_value*); - void (*value_free)(sqlite3_value*); - int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64); - int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64); + tdsqlite3_value *(*value_dup)(const tdsqlite3_value*); + void (*value_free)(tdsqlite3_value*); + int (*result_zeroblob64)(tdsqlite3_context*,tdsqlite3_uint64); + int (*bind_zeroblob64)(tdsqlite3_stmt*, int, tdsqlite3_uint64); /* Version 3.9.0 and later */ - unsigned int (*value_subtype)(sqlite3_value*); - void (*result_subtype)(sqlite3_context*,unsigned int); + unsigned int (*value_subtype)(tdsqlite3_value*); + void (*result_subtype)(tdsqlite3_context*,unsigned int); /* Version 3.10.0 and later */ - int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int); + int (*status64)(int,tdsqlite3_int64*,tdsqlite3_int64*,int); int (*strlike)(const char*,const char*,unsigned int); - int (*db_cacheflush)(sqlite3*); + int (*db_cacheflush)(tdsqlite3*); /* Version 3.12.0 and later */ - int (*system_errno)(sqlite3*); + int (*system_errno)(tdsqlite3*); /* Version 3.14.0 and later */ - int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); - char *(*expanded_sql)(sqlite3_stmt*); + int (*trace_v2)(tdsqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); + char *(*expanded_sql)(tdsqlite3_stmt*); + /* Version 3.18.0 and later */ + void (*set_last_insert_rowid)(tdsqlite3*,tdsqlite3_int64); + /* Version 3.20.0 and later */ + int (*prepare_v3)(tdsqlite3*,const char*,int,unsigned int, + tdsqlite3_stmt**,const char**); + int (*prepare16_v3)(tdsqlite3*,const void*,int,unsigned int, + tdsqlite3_stmt**,const void**); + int (*bind_pointer)(tdsqlite3_stmt*,int,void*,const char*,void(*)(void*)); + void (*result_pointer)(tdsqlite3_context*,void*,const char*,void(*)(void*)); + void *(*value_pointer)(tdsqlite3_value*,const char*); + int (*vtab_nochange)(tdsqlite3_context*); + int (*value_nochange)(tdsqlite3_value*); + const char *(*vtab_collation)(tdsqlite3_index_info*,int); + /* Version 3.24.0 and later */ + int (*keyword_count)(void); + int (*keyword_name)(int,const char**,int*); + int (*keyword_check)(const char*,int); + tdsqlite3_str *(*str_new)(tdsqlite3*); + char *(*str_finish)(tdsqlite3_str*); + void (*str_appendf)(tdsqlite3_str*, const char *zFormat, ...); + void (*str_vappendf)(tdsqlite3_str*, const char *zFormat, va_list); + void (*str_append)(tdsqlite3_str*, const char *zIn, int N); + void (*str_appendall)(tdsqlite3_str*, const char *zIn); + void (*str_appendchar)(tdsqlite3_str*, int N, char C); + void (*str_reset)(tdsqlite3_str*); + int (*str_errcode)(tdsqlite3_str*); + int (*str_length)(tdsqlite3_str*); + char *(*str_value)(tdsqlite3_str*); + /* Version 3.25.0 and later */ + int (*create_window_function)(tdsqlite3*,const char*,int,int,void*, + void (*xStep)(tdsqlite3_context*,int,tdsqlite3_value**), + void (*xFinal)(tdsqlite3_context*), + void (*xValue)(tdsqlite3_context*), + void (*xInv)(tdsqlite3_context*,int,tdsqlite3_value**), + void(*xDestroy)(void*)); + /* Version 3.26.0 and later */ + const char *(*normalized_sql)(tdsqlite3_stmt*); + /* Version 3.28.0 and later */ + int (*stmt_isexplain)(tdsqlite3_stmt*); + int (*value_frombind)(tdsqlite3_value*); + /* Version 3.30.0 and later */ + int (*drop_modules)(tdsqlite3*,const char**); + /* Version 3.31.0 and later */ + tdsqlite3_int64 (*hard_heap_limit64)(tdsqlite3_int64); + const char *(*uri_key)(const char*,int); + const char *(*filename_database)(const char*); + const char *(*filename_journal)(const char*); + const char *(*filename_wal)(const char*); }; /* ** This is the function signature used for all extension entry points. It ** is also defined in the file "loadext.c". */ -typedef int (*sqlite3_loadext_entry)( - sqlite3 *db, /* Handle to the database. */ +typedef int (*tdsqlite3_loadext_entry)( + tdsqlite3 *db, /* Handle to the database. */ char **pzErrMsg, /* Used to set error string on failure. */ - const sqlite3_api_routines *pThunk /* Extension API function pointers. */ + const tdsqlite3_api_routines *pThunk /* Extension API function pointers. */ ); /* ** The following macros redefine the API routines so that they are -** redirected through the global sqlite3_api structure. +** redirected through the global tdsqlite3_api structure. ** ** This header file is also used by the loadext.c source file ** (part of the main SQLite library - not an extension) so that -** it can get access to the sqlite3_api_routines structure +** it can get access to the tdsqlite3_api_routines structure ** definition. But the main library does not want to redefine ** the API. So the redefinition macros are only valid if the ** SQLITE_CORE macros is undefined. */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) -#define sqlite3_aggregate_context sqlite3_api->aggregate_context +#define tdsqlite3_aggregate_context tdsqlite3_api->aggregate_context #ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_aggregate_count sqlite3_api->aggregate_count +#define tdsqlite3_aggregate_count tdsqlite3_api->aggregate_count #endif -#define sqlite3_bind_blob sqlite3_api->bind_blob -#define sqlite3_bind_double sqlite3_api->bind_double -#define sqlite3_bind_int sqlite3_api->bind_int -#define sqlite3_bind_int64 sqlite3_api->bind_int64 -#define sqlite3_bind_null sqlite3_api->bind_null -#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count -#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index -#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name -#define sqlite3_bind_text sqlite3_api->bind_text -#define sqlite3_bind_text16 sqlite3_api->bind_text16 -#define sqlite3_bind_value sqlite3_api->bind_value -#define sqlite3_busy_handler sqlite3_api->busy_handler -#define sqlite3_busy_timeout sqlite3_api->busy_timeout -#define sqlite3_changes sqlite3_api->changes -#define sqlite3_close sqlite3_api->close -#define sqlite3_collation_needed sqlite3_api->collation_needed -#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 -#define sqlite3_column_blob sqlite3_api->column_blob -#define sqlite3_column_bytes sqlite3_api->column_bytes -#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 -#define sqlite3_column_count sqlite3_api->column_count -#define sqlite3_column_database_name sqlite3_api->column_database_name -#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 -#define sqlite3_column_decltype sqlite3_api->column_decltype -#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 -#define sqlite3_column_double sqlite3_api->column_double -#define sqlite3_column_int sqlite3_api->column_int -#define sqlite3_column_int64 sqlite3_api->column_int64 -#define sqlite3_column_name sqlite3_api->column_name -#define sqlite3_column_name16 sqlite3_api->column_name16 -#define sqlite3_column_origin_name sqlite3_api->column_origin_name -#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 -#define sqlite3_column_table_name sqlite3_api->column_table_name -#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 -#define sqlite3_column_text sqlite3_api->column_text -#define sqlite3_column_text16 sqlite3_api->column_text16 -#define sqlite3_column_type sqlite3_api->column_type -#define sqlite3_column_value sqlite3_api->column_value -#define sqlite3_commit_hook sqlite3_api->commit_hook -#define sqlite3_complete sqlite3_api->complete -#define sqlite3_complete16 sqlite3_api->complete16 -#define sqlite3_create_collation sqlite3_api->create_collation -#define sqlite3_create_collation16 sqlite3_api->create_collation16 -#define sqlite3_create_function sqlite3_api->create_function -#define sqlite3_create_function16 sqlite3_api->create_function16 -#define sqlite3_create_module sqlite3_api->create_module -#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 -#define sqlite3_data_count sqlite3_api->data_count -#define sqlite3_db_handle sqlite3_api->db_handle -#define sqlite3_declare_vtab sqlite3_api->declare_vtab -#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache -#define sqlite3_errcode sqlite3_api->errcode -#define sqlite3_errmsg sqlite3_api->errmsg -#define sqlite3_errmsg16 sqlite3_api->errmsg16 -#define sqlite3_exec sqlite3_api->exec +#define tdsqlite3_bind_blob tdsqlite3_api->bind_blob +#define tdsqlite3_bind_double tdsqlite3_api->bind_double +#define tdsqlite3_bind_int tdsqlite3_api->bind_int +#define tdsqlite3_bind_int64 tdsqlite3_api->bind_int64 +#define tdsqlite3_bind_null tdsqlite3_api->bind_null +#define tdsqlite3_bind_parameter_count tdsqlite3_api->bind_parameter_count +#define tdsqlite3_bind_parameter_index tdsqlite3_api->bind_parameter_index +#define tdsqlite3_bind_parameter_name tdsqlite3_api->bind_parameter_name +#define tdsqlite3_bind_text tdsqlite3_api->bind_text +#define tdsqlite3_bind_text16 tdsqlite3_api->bind_text16 +#define tdsqlite3_bind_value tdsqlite3_api->bind_value +#define tdsqlite3_busy_handler tdsqlite3_api->busy_handler +#define tdsqlite3_busy_timeout tdsqlite3_api->busy_timeout +#define tdsqlite3_changes tdsqlite3_api->changes +#define tdsqlite3_close tdsqlite3_api->close +#define tdsqlite3_collation_needed tdsqlite3_api->collation_needed +#define tdsqlite3_collation_needed16 tdsqlite3_api->collation_needed16 +#define tdsqlite3_column_blob tdsqlite3_api->column_blob +#define tdsqlite3_column_bytes tdsqlite3_api->column_bytes +#define tdsqlite3_column_bytes16 tdsqlite3_api->column_bytes16 +#define tdsqlite3_column_count tdsqlite3_api->column_count +#define tdsqlite3_column_database_name tdsqlite3_api->column_database_name +#define tdsqlite3_column_database_name16 tdsqlite3_api->column_database_name16 +#define tdsqlite3_column_decltype tdsqlite3_api->column_decltype +#define tdsqlite3_column_decltype16 tdsqlite3_api->column_decltype16 +#define tdsqlite3_column_double tdsqlite3_api->column_double +#define tdsqlite3_column_int tdsqlite3_api->column_int +#define tdsqlite3_column_int64 tdsqlite3_api->column_int64 +#define tdsqlite3_column_name tdsqlite3_api->column_name +#define tdsqlite3_column_name16 tdsqlite3_api->column_name16 +#define tdsqlite3_column_origin_name tdsqlite3_api->column_origin_name +#define tdsqlite3_column_origin_name16 tdsqlite3_api->column_origin_name16 +#define tdsqlite3_column_table_name tdsqlite3_api->column_table_name +#define tdsqlite3_column_table_name16 tdsqlite3_api->column_table_name16 +#define tdsqlite3_column_text tdsqlite3_api->column_text +#define tdsqlite3_column_text16 tdsqlite3_api->column_text16 +#define tdsqlite3_column_type tdsqlite3_api->column_type +#define tdsqlite3_column_value tdsqlite3_api->column_value +#define tdsqlite3_commit_hook tdsqlite3_api->commit_hook +#define tdsqlite3_complete tdsqlite3_api->complete +#define tdsqlite3_complete16 tdsqlite3_api->complete16 +#define tdsqlite3_create_collation tdsqlite3_api->create_collation +#define tdsqlite3_create_collation16 tdsqlite3_api->create_collation16 +#define tdsqlite3_create_function tdsqlite3_api->create_function +#define tdsqlite3_create_function16 tdsqlite3_api->create_function16 +#define tdsqlite3_create_module tdsqlite3_api->create_module +#define tdsqlite3_create_module_v2 tdsqlite3_api->create_module_v2 +#define tdsqlite3_data_count tdsqlite3_api->data_count +#define tdsqlite3_db_handle tdsqlite3_api->db_handle +#define tdsqlite3_declare_vtab tdsqlite3_api->declare_vtab +#define tdsqlite3_enable_shared_cache tdsqlite3_api->enable_shared_cache +#define tdsqlite3_errcode tdsqlite3_api->errcode +#define tdsqlite3_errmsg tdsqlite3_api->errmsg +#define tdsqlite3_errmsg16 tdsqlite3_api->errmsg16 +#define tdsqlite3_exec tdsqlite3_api->exec #ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_expired sqlite3_api->expired +#define tdsqlite3_expired tdsqlite3_api->expired #endif -#define sqlite3_finalize sqlite3_api->finalize -#define sqlite3_free sqlite3_api->free -#define sqlite3_free_table sqlite3_api->free_table -#define sqlite3_get_autocommit sqlite3_api->get_autocommit -#define sqlite3_get_auxdata sqlite3_api->get_auxdata -#define sqlite3_get_table sqlite3_api->get_table +#define tdsqlite3_finalize tdsqlite3_api->finalize +#define tdsqlite3_free tdsqlite3_api->free +#define tdsqlite3_free_table tdsqlite3_api->free_table +#define tdsqlite3_get_autocommit tdsqlite3_api->get_autocommit +#define tdsqlite3_get_auxdata tdsqlite3_api->get_auxdata +#define tdsqlite3_get_table tdsqlite3_api->get_table #ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_global_recover sqlite3_api->global_recover +#define tdsqlite3_global_recover tdsqlite3_api->global_recover #endif -#define sqlite3_interrupt sqlite3_api->interruptx -#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid -#define sqlite3_libversion sqlite3_api->libversion -#define sqlite3_libversion_number sqlite3_api->libversion_number -#define sqlite3_malloc sqlite3_api->malloc -#define sqlite3_mprintf sqlite3_api->mprintf -#define sqlite3_open sqlite3_api->open -#define sqlite3_open16 sqlite3_api->open16 -#define sqlite3_prepare sqlite3_api->prepare -#define sqlite3_prepare16 sqlite3_api->prepare16 -#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 -#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 -#define sqlite3_profile sqlite3_api->profile -#define sqlite3_progress_handler sqlite3_api->progress_handler -#define sqlite3_realloc sqlite3_api->realloc -#define sqlite3_reset sqlite3_api->reset -#define sqlite3_result_blob sqlite3_api->result_blob -#define sqlite3_result_double sqlite3_api->result_double -#define sqlite3_result_error sqlite3_api->result_error -#define sqlite3_result_error16 sqlite3_api->result_error16 -#define sqlite3_result_int sqlite3_api->result_int -#define sqlite3_result_int64 sqlite3_api->result_int64 -#define sqlite3_result_null sqlite3_api->result_null -#define sqlite3_result_text sqlite3_api->result_text -#define sqlite3_result_text16 sqlite3_api->result_text16 -#define sqlite3_result_text16be sqlite3_api->result_text16be -#define sqlite3_result_text16le sqlite3_api->result_text16le -#define sqlite3_result_value sqlite3_api->result_value -#define sqlite3_rollback_hook sqlite3_api->rollback_hook -#define sqlite3_set_authorizer sqlite3_api->set_authorizer -#define sqlite3_set_auxdata sqlite3_api->set_auxdata -#define sqlite3_snprintf sqlite3_api->snprintf -#define sqlite3_step sqlite3_api->step -#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata -#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup -#define sqlite3_total_changes sqlite3_api->total_changes -#define sqlite3_trace sqlite3_api->trace +#define tdsqlite3_interrupt tdsqlite3_api->interruptx +#define tdsqlite3_last_insert_rowid tdsqlite3_api->last_insert_rowid +#define tdsqlite3_libversion tdsqlite3_api->libversion +#define tdsqlite3_libversion_number tdsqlite3_api->libversion_number +#define tdsqlite3_malloc tdsqlite3_api->malloc +#define tdsqlite3_mprintf tdsqlite3_api->mprintf +#define tdsqlite3_open tdsqlite3_api->open +#define tdsqlite3_open16 tdsqlite3_api->open16 +#define tdsqlite3_prepare tdsqlite3_api->prepare +#define tdsqlite3_prepare16 tdsqlite3_api->prepare16 +#define tdsqlite3_prepare_v2 tdsqlite3_api->prepare_v2 +#define tdsqlite3_prepare16_v2 tdsqlite3_api->prepare16_v2 +#define tdsqlite3_profile tdsqlite3_api->profile +#define tdsqlite3_progress_handler tdsqlite3_api->progress_handler +#define tdsqlite3_realloc tdsqlite3_api->realloc +#define tdsqlite3_reset tdsqlite3_api->reset +#define tdsqlite3_result_blob tdsqlite3_api->result_blob +#define tdsqlite3_result_double tdsqlite3_api->result_double +#define tdsqlite3_result_error tdsqlite3_api->result_error +#define tdsqlite3_result_error16 tdsqlite3_api->result_error16 +#define tdsqlite3_result_int tdsqlite3_api->result_int +#define tdsqlite3_result_int64 tdsqlite3_api->result_int64 +#define tdsqlite3_result_null tdsqlite3_api->result_null +#define tdsqlite3_result_text tdsqlite3_api->result_text +#define tdsqlite3_result_text16 tdsqlite3_api->result_text16 +#define tdsqlite3_result_text16be tdsqlite3_api->result_text16be +#define tdsqlite3_result_text16le tdsqlite3_api->result_text16le +#define tdsqlite3_result_value tdsqlite3_api->result_value +#define tdsqlite3_rollback_hook tdsqlite3_api->rollback_hook +#define tdsqlite3_set_authorizer tdsqlite3_api->set_authorizer +#define tdsqlite3_set_auxdata tdsqlite3_api->set_auxdata +#define tdsqlite3_snprintf tdsqlite3_api->xsnprintf +#define tdsqlite3_step tdsqlite3_api->step +#define tdsqlite3_table_column_metadata tdsqlite3_api->table_column_metadata +#define tdsqlite3_thread_cleanup tdsqlite3_api->thread_cleanup +#define tdsqlite3_total_changes tdsqlite3_api->total_changes +#define tdsqlite3_trace tdsqlite3_api->trace #ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings +#define tdsqlite3_transfer_bindings tdsqlite3_api->transfer_bindings #endif -#define sqlite3_update_hook sqlite3_api->update_hook -#define sqlite3_user_data sqlite3_api->user_data -#define sqlite3_value_blob sqlite3_api->value_blob -#define sqlite3_value_bytes sqlite3_api->value_bytes -#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 -#define sqlite3_value_double sqlite3_api->value_double -#define sqlite3_value_int sqlite3_api->value_int -#define sqlite3_value_int64 sqlite3_api->value_int64 -#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type -#define sqlite3_value_text sqlite3_api->value_text -#define sqlite3_value_text16 sqlite3_api->value_text16 -#define sqlite3_value_text16be sqlite3_api->value_text16be -#define sqlite3_value_text16le sqlite3_api->value_text16le -#define sqlite3_value_type sqlite3_api->value_type -#define sqlite3_vmprintf sqlite3_api->vmprintf -#define sqlite3_vsnprintf sqlite3_api->vsnprintf -#define sqlite3_overload_function sqlite3_api->overload_function -#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 -#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 -#define sqlite3_clear_bindings sqlite3_api->clear_bindings -#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob -#define sqlite3_blob_bytes sqlite3_api->blob_bytes -#define sqlite3_blob_close sqlite3_api->blob_close -#define sqlite3_blob_open sqlite3_api->blob_open -#define sqlite3_blob_read sqlite3_api->blob_read -#define sqlite3_blob_write sqlite3_api->blob_write -#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 -#define sqlite3_file_control sqlite3_api->file_control -#define sqlite3_memory_highwater sqlite3_api->memory_highwater -#define sqlite3_memory_used sqlite3_api->memory_used -#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc -#define sqlite3_mutex_enter sqlite3_api->mutex_enter -#define sqlite3_mutex_free sqlite3_api->mutex_free -#define sqlite3_mutex_leave sqlite3_api->mutex_leave -#define sqlite3_mutex_try sqlite3_api->mutex_try -#define sqlite3_open_v2 sqlite3_api->open_v2 -#define sqlite3_release_memory sqlite3_api->release_memory -#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem -#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig -#define sqlite3_sleep sqlite3_api->sleep -#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit -#define sqlite3_vfs_find sqlite3_api->vfs_find -#define sqlite3_vfs_register sqlite3_api->vfs_register -#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister -#define sqlite3_threadsafe sqlite3_api->xthreadsafe -#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob -#define sqlite3_result_error_code sqlite3_api->result_error_code -#define sqlite3_test_control sqlite3_api->test_control -#define sqlite3_randomness sqlite3_api->randomness -#define sqlite3_context_db_handle sqlite3_api->context_db_handle -#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes -#define sqlite3_limit sqlite3_api->limit -#define sqlite3_next_stmt sqlite3_api->next_stmt -#define sqlite3_sql sqlite3_api->sql -#define sqlite3_status sqlite3_api->status -#define sqlite3_backup_finish sqlite3_api->backup_finish -#define sqlite3_backup_init sqlite3_api->backup_init -#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount -#define sqlite3_backup_remaining sqlite3_api->backup_remaining -#define sqlite3_backup_step sqlite3_api->backup_step -#define sqlite3_compileoption_get sqlite3_api->compileoption_get -#define sqlite3_compileoption_used sqlite3_api->compileoption_used -#define sqlite3_create_function_v2 sqlite3_api->create_function_v2 -#define sqlite3_db_config sqlite3_api->db_config -#define sqlite3_db_mutex sqlite3_api->db_mutex -#define sqlite3_db_status sqlite3_api->db_status -#define sqlite3_extended_errcode sqlite3_api->extended_errcode -#define sqlite3_log sqlite3_api->log -#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 -#define sqlite3_sourceid sqlite3_api->sourceid -#define sqlite3_stmt_status sqlite3_api->stmt_status -#define sqlite3_strnicmp sqlite3_api->strnicmp -#define sqlite3_unlock_notify sqlite3_api->unlock_notify -#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint -#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint -#define sqlite3_wal_hook sqlite3_api->wal_hook -#define sqlite3_blob_reopen sqlite3_api->blob_reopen -#define sqlite3_vtab_config sqlite3_api->vtab_config -#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict +#define tdsqlite3_update_hook tdsqlite3_api->update_hook +#define tdsqlite3_user_data tdsqlite3_api->user_data +#define tdsqlite3_value_blob tdsqlite3_api->value_blob +#define tdsqlite3_value_bytes tdsqlite3_api->value_bytes +#define tdsqlite3_value_bytes16 tdsqlite3_api->value_bytes16 +#define tdsqlite3_value_double tdsqlite3_api->value_double +#define tdsqlite3_value_int tdsqlite3_api->value_int +#define tdsqlite3_value_int64 tdsqlite3_api->value_int64 +#define tdsqlite3_value_numeric_type tdsqlite3_api->value_numeric_type +#define tdsqlite3_value_text tdsqlite3_api->value_text +#define tdsqlite3_value_text16 tdsqlite3_api->value_text16 +#define tdsqlite3_value_text16be tdsqlite3_api->value_text16be +#define tdsqlite3_value_text16le tdsqlite3_api->value_text16le +#define tdsqlite3_value_type tdsqlite3_api->value_type +#define tdsqlite3_vmprintf tdsqlite3_api->vmprintf +#define tdsqlite3_vsnprintf tdsqlite3_api->xvsnprintf +#define tdsqlite3_overload_function tdsqlite3_api->overload_function +#define tdsqlite3_prepare_v2 tdsqlite3_api->prepare_v2 +#define tdsqlite3_prepare16_v2 tdsqlite3_api->prepare16_v2 +#define tdsqlite3_clear_bindings tdsqlite3_api->clear_bindings +#define tdsqlite3_bind_zeroblob tdsqlite3_api->bind_zeroblob +#define tdsqlite3_blob_bytes tdsqlite3_api->blob_bytes +#define tdsqlite3_blob_close tdsqlite3_api->blob_close +#define tdsqlite3_blob_open tdsqlite3_api->blob_open +#define tdsqlite3_blob_read tdsqlite3_api->blob_read +#define tdsqlite3_blob_write tdsqlite3_api->blob_write +#define tdsqlite3_create_collation_v2 tdsqlite3_api->create_collation_v2 +#define tdsqlite3_file_control tdsqlite3_api->file_control +#define tdsqlite3_memory_highwater tdsqlite3_api->memory_highwater +#define tdsqlite3_memory_used tdsqlite3_api->memory_used +#define tdsqlite3_mutex_alloc tdsqlite3_api->mutex_alloc +#define tdsqlite3_mutex_enter tdsqlite3_api->mutex_enter +#define tdsqlite3_mutex_free tdsqlite3_api->mutex_free +#define tdsqlite3_mutex_leave tdsqlite3_api->mutex_leave +#define tdsqlite3_mutex_try tdsqlite3_api->mutex_try +#define tdsqlite3_open_v2 tdsqlite3_api->open_v2 +#define tdsqlite3_release_memory tdsqlite3_api->release_memory +#define tdsqlite3_result_error_nomem tdsqlite3_api->result_error_nomem +#define tdsqlite3_result_error_toobig tdsqlite3_api->result_error_toobig +#define tdsqlite3_sleep tdsqlite3_api->sleep +#define tdsqlite3_soft_heap_limit tdsqlite3_api->soft_heap_limit +#define tdsqlite3_vfs_find tdsqlite3_api->vfs_find +#define tdsqlite3_vfs_register tdsqlite3_api->vfs_register +#define tdsqlite3_vfs_unregister tdsqlite3_api->vfs_unregister +#define tdsqlite3_threadsafe tdsqlite3_api->xthreadsafe +#define tdsqlite3_result_zeroblob tdsqlite3_api->result_zeroblob +#define tdsqlite3_result_error_code tdsqlite3_api->result_error_code +#define tdsqlite3_test_control tdsqlite3_api->test_control +#define tdsqlite3_randomness tdsqlite3_api->randomness +#define tdsqlite3_context_db_handle tdsqlite3_api->context_db_handle +#define tdsqlite3_extended_result_codes tdsqlite3_api->extended_result_codes +#define tdsqlite3_limit tdsqlite3_api->limit +#define tdsqlite3_next_stmt tdsqlite3_api->next_stmt +#define tdsqlite3_sql tdsqlite3_api->sql +#define tdsqlite3_status tdsqlite3_api->status +#define tdsqlite3_backup_finish tdsqlite3_api->backup_finish +#define tdsqlite3_backup_init tdsqlite3_api->backup_init +#define tdsqlite3_backup_pagecount tdsqlite3_api->backup_pagecount +#define tdsqlite3_backup_remaining tdsqlite3_api->backup_remaining +#define tdsqlite3_backup_step tdsqlite3_api->backup_step +#define tdsqlite3_compileoption_get tdsqlite3_api->compileoption_get +#define tdsqlite3_compileoption_used tdsqlite3_api->compileoption_used +#define tdsqlite3_create_function_v2 tdsqlite3_api->create_function_v2 +#define tdsqlite3_db_config tdsqlite3_api->db_config +#define tdsqlite3_db_mutex tdsqlite3_api->db_mutex +#define tdsqlite3_db_status tdsqlite3_api->db_status +#define tdsqlite3_extended_errcode tdsqlite3_api->extended_errcode +#define tdsqlite3_log tdsqlite3_api->log +#define tdsqlite3_soft_heap_limit64 tdsqlite3_api->soft_heap_limit64 +#define tdsqlite3_sourceid tdsqlite3_api->sourceid +#define tdsqlite3_stmt_status tdsqlite3_api->stmt_status +#define tdsqlite3_strnicmp tdsqlite3_api->strnicmp +#define tdsqlite3_unlock_notify tdsqlite3_api->unlock_notify +#define tdsqlite3_wal_autocheckpoint tdsqlite3_api->wal_autocheckpoint +#define tdsqlite3_wal_checkpoint tdsqlite3_api->wal_checkpoint +#define tdsqlite3_wal_hook tdsqlite3_api->wal_hook +#define tdsqlite3_blob_reopen tdsqlite3_api->blob_reopen +#define tdsqlite3_vtab_config tdsqlite3_api->vtab_config +#define tdsqlite3_vtab_on_conflict tdsqlite3_api->vtab_on_conflict /* Version 3.7.16 and later */ -#define sqlite3_close_v2 sqlite3_api->close_v2 -#define sqlite3_db_filename sqlite3_api->db_filename -#define sqlite3_db_readonly sqlite3_api->db_readonly -#define sqlite3_db_release_memory sqlite3_api->db_release_memory -#define sqlite3_errstr sqlite3_api->errstr -#define sqlite3_stmt_busy sqlite3_api->stmt_busy -#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly -#define sqlite3_stricmp sqlite3_api->stricmp -#define sqlite3_uri_boolean sqlite3_api->uri_boolean -#define sqlite3_uri_int64 sqlite3_api->uri_int64 -#define sqlite3_uri_parameter sqlite3_api->uri_parameter -#define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf -#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 +#define tdsqlite3_close_v2 tdsqlite3_api->close_v2 +#define tdsqlite3_db_filename tdsqlite3_api->db_filename +#define tdsqlite3_db_readonly tdsqlite3_api->db_readonly +#define tdsqlite3_db_release_memory tdsqlite3_api->db_release_memory +#define tdsqlite3_errstr tdsqlite3_api->errstr +#define tdsqlite3_stmt_busy tdsqlite3_api->stmt_busy +#define tdsqlite3_stmt_readonly tdsqlite3_api->stmt_readonly +#define tdsqlite3_stricmp tdsqlite3_api->stricmp +#define tdsqlite3_uri_boolean tdsqlite3_api->uri_boolean +#define tdsqlite3_uri_int64 tdsqlite3_api->uri_int64 +#define tdsqlite3_uri_parameter tdsqlite3_api->uri_parameter +#define tdsqlite3_uri_vsnprintf tdsqlite3_api->xvsnprintf +#define tdsqlite3_wal_checkpoint_v2 tdsqlite3_api->wal_checkpoint_v2 /* Version 3.8.7 and later */ -#define sqlite3_auto_extension sqlite3_api->auto_extension -#define sqlite3_bind_blob64 sqlite3_api->bind_blob64 -#define sqlite3_bind_text64 sqlite3_api->bind_text64 -#define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension -#define sqlite3_load_extension sqlite3_api->load_extension -#define sqlite3_malloc64 sqlite3_api->malloc64 -#define sqlite3_msize sqlite3_api->msize -#define sqlite3_realloc64 sqlite3_api->realloc64 -#define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension -#define sqlite3_result_blob64 sqlite3_api->result_blob64 -#define sqlite3_result_text64 sqlite3_api->result_text64 -#define sqlite3_strglob sqlite3_api->strglob +#define tdsqlite3_auto_extension tdsqlite3_api->auto_extension +#define tdsqlite3_bind_blob64 tdsqlite3_api->bind_blob64 +#define tdsqlite3_bind_text64 tdsqlite3_api->bind_text64 +#define tdsqlite3_cancel_auto_extension tdsqlite3_api->cancel_auto_extension +#define tdsqlite3_load_extension tdsqlite3_api->load_extension +#define tdsqlite3_malloc64 tdsqlite3_api->malloc64 +#define tdsqlite3_msize tdsqlite3_api->msize +#define tdsqlite3_realloc64 tdsqlite3_api->realloc64 +#define tdsqlite3_reset_auto_extension tdsqlite3_api->reset_auto_extension +#define tdsqlite3_result_blob64 tdsqlite3_api->result_blob64 +#define tdsqlite3_result_text64 tdsqlite3_api->result_text64 +#define tdsqlite3_strglob tdsqlite3_api->strglob /* Version 3.8.11 and later */ -#define sqlite3_value_dup sqlite3_api->value_dup -#define sqlite3_value_free sqlite3_api->value_free -#define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64 -#define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64 +#define tdsqlite3_value_dup tdsqlite3_api->value_dup +#define tdsqlite3_value_free tdsqlite3_api->value_free +#define tdsqlite3_result_zeroblob64 tdsqlite3_api->result_zeroblob64 +#define tdsqlite3_bind_zeroblob64 tdsqlite3_api->bind_zeroblob64 /* Version 3.9.0 and later */ -#define sqlite3_value_subtype sqlite3_api->value_subtype -#define sqlite3_result_subtype sqlite3_api->result_subtype +#define tdsqlite3_value_subtype tdsqlite3_api->value_subtype +#define tdsqlite3_result_subtype tdsqlite3_api->result_subtype /* Version 3.10.0 and later */ -#define sqlite3_status64 sqlite3_api->status64 -#define sqlite3_strlike sqlite3_api->strlike -#define sqlite3_db_cacheflush sqlite3_api->db_cacheflush +#define tdsqlite3_status64 tdsqlite3_api->status64 +#define tdsqlite3_strlike tdsqlite3_api->strlike +#define tdsqlite3_db_cacheflush tdsqlite3_api->db_cacheflush /* Version 3.12.0 and later */ -#define sqlite3_system_errno sqlite3_api->system_errno +#define tdsqlite3_system_errno tdsqlite3_api->system_errno /* Version 3.14.0 and later */ -#define sqlite3_trace_v2 sqlite3_api->trace_v2 -#define sqlite3_expanded_sql sqlite3_api->expanded_sql +#define tdsqlite3_trace_v2 tdsqlite3_api->trace_v2 +#define tdsqlite3_expanded_sql tdsqlite3_api->expanded_sql +/* Version 3.18.0 and later */ +#define tdsqlite3_set_last_insert_rowid tdsqlite3_api->set_last_insert_rowid +/* Version 3.20.0 and later */ +#define tdsqlite3_prepare_v3 tdsqlite3_api->prepare_v3 +#define tdsqlite3_prepare16_v3 tdsqlite3_api->prepare16_v3 +#define tdsqlite3_bind_pointer tdsqlite3_api->bind_pointer +#define tdsqlite3_result_pointer tdsqlite3_api->result_pointer +#define tdsqlite3_value_pointer tdsqlite3_api->value_pointer +/* Version 3.22.0 and later */ +#define tdsqlite3_vtab_nochange tdsqlite3_api->vtab_nochange +#define tdsqlite3_value_nochange tdsqlite3_api->value_nochange +#define tdsqlite3_vtab_collation tdsqlite3_api->vtab_collation +/* Version 3.24.0 and later */ +#define tdsqlite3_keyword_count tdsqlite3_api->keyword_count +#define tdsqlite3_keyword_name tdsqlite3_api->keyword_name +#define tdsqlite3_keyword_check tdsqlite3_api->keyword_check +#define tdsqlite3_str_new tdsqlite3_api->str_new +#define tdsqlite3_str_finish tdsqlite3_api->str_finish +#define tdsqlite3_str_appendf tdsqlite3_api->str_appendf +#define tdsqlite3_str_vappendf tdsqlite3_api->str_vappendf +#define tdsqlite3_str_append tdsqlite3_api->str_append +#define tdsqlite3_str_appendall tdsqlite3_api->str_appendall +#define tdsqlite3_str_appendchar tdsqlite3_api->str_appendchar +#define tdsqlite3_str_reset tdsqlite3_api->str_reset +#define tdsqlite3_str_errcode tdsqlite3_api->str_errcode +#define tdsqlite3_str_length tdsqlite3_api->str_length +#define tdsqlite3_str_value tdsqlite3_api->str_value +/* Version 3.25.0 and later */ +#define tdsqlite3_create_window_function tdsqlite3_api->create_window_function +/* Version 3.26.0 and later */ +#define tdsqlite3_normalized_sql tdsqlite3_api->normalized_sql +/* Version 3.28.0 and later */ +#define tdsqlite3_stmt_isexplain tdsqlite3_api->isexplain +#define tdsqlite3_value_frombind tdsqlite3_api->frombind +/* Version 3.30.0 and later */ +#define tdsqlite3_drop_modules tdsqlite3_api->drop_modules +/* Version 3.31.0 andn later */ +#define tdsqlite3_hard_heap_limit64 tdsqlite3_api->hard_heap_limit64 +#define tdsqlite3_uri_key tdsqlite3_api->uri_key +#define tdsqlite3_filename_database tdsqlite3_api->filename_database +#define tdsqlite3_filename_journal tdsqlite3_api->filename_journal +#define tdsqlite3_filename_wal tdsqlite3_api->filename_wal #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) /* This case when the file really is being compiled as a loadable ** extension */ -# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; -# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; +# define SQLITE_EXTENSION_INIT1 const tdsqlite3_api_routines *tdsqlite3_api=0; +# define SQLITE_EXTENSION_INIT2(v) tdsqlite3_api=v; # define SQLITE_EXTENSION_INIT3 \ - extern const sqlite3_api_routines *sqlite3_api; + extern const tdsqlite3_api_routines *tdsqlite3_api; #else /* This case when the file is being statically linked into the ** application */ diff --git a/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3session.h b/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3session.h index d9f806e54f..5ad10cd56e 100644 --- a/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3session.h +++ b/protocols/Telegram/tdlib/td/sqlite/sqlite/sqlite3session.h @@ -12,16 +12,23 @@ extern "C" { /* ** CAPI3REF: Session Object Handle +** +** An instance of this object is a [session] that can be used to +** record changes to a database. */ -typedef struct sqlite3_session sqlite3_session; +typedef struct tdsqlite3_session tdsqlite3_session; /* ** CAPI3REF: Changeset Iterator Handle +** +** An instance of this object acts as a cursor for iterating +** over the elements of a [changeset] or [patchset]. */ -typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; +typedef struct tdsqlite3_changeset_iter tdsqlite3_changeset_iter; /* ** CAPI3REF: Create A New Session Object +** CONSTRUCTOR: tdsqlite3_session ** ** Create a new session object attached to database handle db. If successful, ** a pointer to the new object is written to *ppSession and SQLITE_OK is @@ -32,13 +39,13 @@ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; ** database handle. ** ** Session objects created using this function should be deleted using the -** [sqlite3session_delete()] function before the database handle that they +** [tdsqlite3session_delete()] function before the database handle that they ** are attached to is itself closed. If the database handle is closed before ** the session object is deleted, then the results of calling any session -** module function, including [sqlite3session_delete()] on the session object +** module function, including [tdsqlite3session_delete()] on the session object ** are undefined. ** -** Because the session module uses the [sqlite3_preupdate_hook()] API, it +** Because the session module uses the [tdsqlite3_preupdate_hook()] API, it ** is not possible for an application to register a pre-update hook on a ** database handle that has one or more session objects attached. Nor is ** it possible to create a session object attached to a database handle for @@ -50,34 +57,36 @@ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; ** attached database. It is not an error if database zDb is not attached ** to the database when the session object is created. */ -int sqlite3session_create( - sqlite3 *db, /* Database handle */ +int tdsqlite3session_create( + tdsqlite3 *db, /* Database handle */ const char *zDb, /* Name of db (e.g. "main") */ - sqlite3_session **ppSession /* OUT: New session object */ + tdsqlite3_session **ppSession /* OUT: New session object */ ); /* ** CAPI3REF: Delete A Session Object +** DESTRUCTOR: tdsqlite3_session ** ** Delete a session object previously allocated using -** [sqlite3session_create()]. Once a session object has been deleted, the +** [tdsqlite3session_create()]. Once a session object has been deleted, the ** results of attempting to use pSession with any other session module ** function are undefined. ** ** Session objects must be deleted before the database handle to which they ** are attached is closed. Refer to the documentation for -** [sqlite3session_create()] for details. +** [tdsqlite3session_create()] for details. */ -void sqlite3session_delete(sqlite3_session *pSession); +void tdsqlite3session_delete(tdsqlite3_session *pSession); /* ** CAPI3REF: Enable Or Disable A Session Object +** METHOD: tdsqlite3_session ** ** Enable or disable the recording of changes by a session object. When ** enabled, a session object records changes made to the database. When ** disabled - it does not. A newly created session object is enabled. -** Refer to the documentation for [sqlite3session_changeset()] for further +** Refer to the documentation for [tdsqlite3session_changeset()] for further ** details regarding how enabling and disabling a session object affects ** the eventual changesets. ** @@ -88,10 +97,11 @@ void sqlite3session_delete(sqlite3_session *pSession); ** The return value indicates the final state of the session object: 0 if ** the session is disabled, or 1 if it is enabled. */ -int sqlite3session_enable(sqlite3_session *pSession, int bEnable); +int tdsqlite3session_enable(tdsqlite3_session *pSession, int bEnable); /* ** CAPI3REF: Set Or Clear the Indirect Change Flag +** METHOD: tdsqlite3_session ** ** Each change recorded by a session object is marked as either direct or ** indirect. A change is marked as indirect if either: @@ -117,15 +127,16 @@ int sqlite3session_enable(sqlite3_session *pSession, int bEnable); ** The return value indicates the final state of the indirect flag: 0 if ** it is clear, or 1 if it is set. */ -int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); +int tdsqlite3session_indirect(tdsqlite3_session *pSession, int bIndirect); /* ** CAPI3REF: Attach A Table To A Session Object +** METHOD: tdsqlite3_session ** ** If argument zTab is not NULL, then it is the name of a table to attach ** to the session object passed as the first argument. All subsequent changes ** made to the table while the session object is enabled will be recorded. See -** documentation for [sqlite3session_changeset()] for further details. +** documentation for [tdsqlite3session_changeset()] for further details. ** ** Or, if argument zTab is NULL, then changes are recorded for all tables ** in the database. If additional tables are added to the database (by @@ -146,23 +157,53 @@ int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); ** ** SQLITE_OK is returned if the call completes without error. Or, if an error ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. +** +** <h3>Special sqlite_stat1 Handling</h3> +** +** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to +** some of the rules above. In SQLite, the schema of sqlite_stat1 is: +** <pre> +** CREATE TABLE sqlite_stat1(tbl,idx,stat) +** </pre> +** +** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are +** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes +** are recorded for rows for which (idx IS NULL) is true. However, for such +** rows a zero-length blob (SQL value X'') is stored in the changeset or +** patchset instead of a NULL value. This allows such changesets to be +** manipulated by legacy implementations of tdsqlite3changeset_invert(), +** concat() and similar. +** +** The tdsqlite3changeset_apply() function automatically converts the +** zero-length blob back to a NULL value when updating the sqlite_stat1 +** table. However, if the application calls tdsqlite3changeset_new(), +** tdsqlite3changeset_old() or tdsqlite3changeset_conflict on a changeset +** iterator directly (including on a changeset iterator passed to a +** conflict-handler callback) then the X'' value is returned. The application +** must translate X'' to NULL itself if required. +** +** Legacy (older than 3.22.0) versions of the sessions module cannot capture +** changes made to the sqlite_stat1 table. Legacy versions of the +** tdsqlite3changeset_apply() function silently ignore any modifications to the +** sqlite_stat1 table that are part of a changeset or patchset. */ -int sqlite3session_attach( - sqlite3_session *pSession, /* Session object */ +int tdsqlite3session_attach( + tdsqlite3_session *pSession, /* Session object */ const char *zTab /* Table name */ ); /* ** CAPI3REF: Set a table filter on a Session Object. +** METHOD: tdsqlite3_session ** ** The second argument (xFilter) is the "filter callback". For changes to rows ** in tables that are not attached to the Session object, the filter is called ** to determine whether changes to the table's rows should be tracked or not. -** If xFilter returns 0, changes is not tracked. Note that once a table is +** If xFilter returns 0, changes are not tracked. Note that once a table is ** attached, xFilter will not be called again. */ -void sqlite3session_table_filter( - sqlite3_session *pSession, /* Session object */ +void tdsqlite3session_table_filter( + tdsqlite3_session *pSession, /* Session object */ int(*xFilter)( void *pCtx, /* Copy of third arg to _filter_table() */ const char *zTab /* Table name */ @@ -172,6 +213,7 @@ void sqlite3session_table_filter( /* ** CAPI3REF: Generate A Changeset From A Session Object +** METHOD: tdsqlite3_session ** ** Obtain a changeset containing changes to the tables attached to the ** session object passed as the first argument. If successful, @@ -201,8 +243,8 @@ void sqlite3session_table_filter( ** DELETE change only. ** ** The contents of a changeset may be traversed using an iterator created -** using the [sqlite3changeset_start()] API. A changeset may be applied to -** a database with a compatible schema using the [sqlite3changeset_apply()] +** using the [tdsqlite3changeset_start()] API. A changeset may be applied to +** a database with a compatible schema using the [tdsqlite3changeset_apply()] ** API. ** ** Within a changeset generated by this function, all changes related to a @@ -210,12 +252,12 @@ void sqlite3session_table_filter( ** a changeset or when applying a changeset to a database, all changes related ** to a single table are processed before moving on to the next table. Tables ** are sorted in the same order in which they were attached (or auto-attached) -** to the sqlite3_session object. The order in which the changes related to +** to the tdsqlite3_session object. The order in which the changes related to ** a single table are stored is undefined. ** ** Following a successful call to this function, it is the responsibility of ** the caller to eventually free the buffer that *ppChangeset points to using -** [sqlite3_free()]. +** [tdsqlite3_free()]. ** ** <h3>Changeset Generation</h3> ** @@ -263,7 +305,7 @@ void sqlite3session_table_filter( ** active, the resulting changeset will contain an UPDATE change instead of ** a DELETE and an INSERT. ** -** When a session object is disabled (see the [sqlite3session_enable()] API), +** When a session object is disabled (see the [tdsqlite3session_enable()] API), ** it does not accumulate records when rows are inserted, updated or deleted. ** This may appear to have some counter-intuitive effects if a single row ** is written to more than once during a session. For example, if a row @@ -274,18 +316,19 @@ void sqlite3session_table_filter( ** another field of the same row is updated while the session is enabled, the ** resulting changeset will contain an UPDATE change that updates both fields. */ -int sqlite3session_changeset( - sqlite3_session *pSession, /* Session object */ +int tdsqlite3session_changeset( + tdsqlite3_session *pSession, /* Session object */ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ void **ppChangeset /* OUT: Buffer containing changeset */ ); /* -** CAPI3REF: Load The Difference Between Tables Into A Session +** CAPI3REF: Load The Difference Between Tables Into A Session +** METHOD: tdsqlite3_session ** ** If it is not already attached to the session object passed as the first ** argument, this function attaches table zTbl in the same manner as the -** [sqlite3session_attach()] function. If zTbl does not exist, or if it +** [tdsqlite3session_attach()] function. If zTbl does not exist, or if it ** does not have a primary key, this function is a no-op (but does not return ** an error). ** @@ -318,25 +361,26 @@ int sqlite3session_changeset( ** the from-table, a DELETE record is added to the session object. ** ** <li> For each row (primary key) that exists in both tables, but features -** different in each, an UPDATE record is added to the session. +** different non-PK values in each, an UPDATE record is added to the +** session. ** </ul> ** ** To clarify, if this function is called and then a changeset constructed -** using [sqlite3session_changeset()], then after applying that changeset to +** using [tdsqlite3session_changeset()], then after applying that changeset to ** database zFrom the contents of the two compatible tables would be ** identical. ** ** It an error if database zFrom does not exist or does not contain the ** required compatible table. ** -** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite +** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg ** may be set to point to a buffer containing an English language error ** message. It is the responsibility of the caller to free this buffer using -** sqlite3_free(). +** tdsqlite3_free(). */ -int sqlite3session_diff( - sqlite3_session *pSession, +int tdsqlite3session_diff( + tdsqlite3_session *pSession, const char *zFromDb, const char *zTbl, char **pzErrMsg @@ -345,6 +389,7 @@ int sqlite3session_diff( /* ** CAPI3REF: Generate A Patchset From A Session Object +** METHOD: tdsqlite3_session ** ** The differences between a patchset and a changeset are that: ** @@ -356,25 +401,25 @@ int sqlite3session_diff( ** </ul> ** ** A patchset blob may be used with up to date versions of all -** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), +** tdsqlite3changeset_xxx API functions except for tdsqlite3changeset_invert(), ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly, ** attempting to use a patchset blob with old versions of the -** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. +** tdsqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. ** ** Because the non-primary key "old.*" fields are omitted, no ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset -** is passed to the sqlite3changeset_apply() API. Other conflict types work +** is passed to the tdsqlite3changeset_apply() API. Other conflict types work ** in the same way as for changesets. ** ** Changes within a patchset are ordered in the same way as for changesets -** generated by the sqlite3session_changeset() function (i.e. all changes for +** generated by the tdsqlite3session_changeset() function (i.e. all changes for ** a single table are grouped together, tables appear in the order in which ** they were attached to the session object). */ -int sqlite3session_patchset( - sqlite3_session *pSession, /* Session object */ - int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */ - void **ppPatchset /* OUT: Buffer containing changeset */ +int tdsqlite3session_patchset( + tdsqlite3_session *pSession, /* Session object */ + int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */ + void **ppPatchset /* OUT: Buffer containing patchset */ ); /* @@ -385,17 +430,18 @@ int sqlite3session_patchset( ** more changes have been recorded, return zero. ** ** Even if this function returns zero, it is possible that calling -** [sqlite3session_changeset()] on the session handle may still return a +** [tdsqlite3session_changeset()] on the session handle may still return a ** changeset that contains no changes. This can happen when a row in ** an attached table is modified and then later on the original values ** are restored. However, if this function returns non-zero, then it is -** guaranteed that a call to sqlite3session_changeset() will return a +** guaranteed that a call to tdsqlite3session_changeset() will return a ** changeset containing zero changes. */ -int sqlite3session_isempty(sqlite3_session *pSession); +int tdsqlite3session_isempty(tdsqlite3_session *pSession); /* ** CAPI3REF: Create An Iterator To Traverse A Changeset +** CONSTRUCTOR: tdsqlite3_changeset_iter ** ** Create an iterator used to iterate through the contents of a changeset. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK @@ -406,49 +452,76 @@ int sqlite3session_isempty(sqlite3_session *pSession); ** iterator created by this function: ** ** <ul> -** <li> [sqlite3changeset_next()] -** <li> [sqlite3changeset_op()] -** <li> [sqlite3changeset_new()] -** <li> [sqlite3changeset_old()] +** <li> [tdsqlite3changeset_next()] +** <li> [tdsqlite3changeset_op()] +** <li> [tdsqlite3changeset_new()] +** <li> [tdsqlite3changeset_old()] ** </ul> ** ** It is the responsibility of the caller to eventually destroy the iterator -** by passing it to [sqlite3changeset_finalize()]. The buffer containing the +** by passing it to [tdsqlite3changeset_finalize()]. The buffer containing the ** changeset (pChangeset) must remain valid until after the iterator is ** destroyed. ** ** Assuming the changeset blob was created by one of the -** [sqlite3session_changeset()], [sqlite3changeset_concat()] or -** [sqlite3changeset_invert()] functions, all changes within the changeset +** [tdsqlite3session_changeset()], [tdsqlite3changeset_concat()] or +** [tdsqlite3changeset_invert()] functions, all changes within the changeset ** that apply to a single table are grouped together. This means that when ** an application iterates through a changeset using an iterator created by ** this function, all changes that relate to a single table are visited ** consecutively. There is no chance that the iterator will visit a change ** the applies to table X, then one for table Y, and then later on visit ** another change for table X. +** +** The behavior of tdsqlite3changeset_start_v2() and its streaming equivalent +** may be modified by passing a combination of +** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter. +** +** Note that the tdsqlite3changeset_start_v2() API is still <b>experimental</b> +** and therefore subject to change. */ -int sqlite3changeset_start( - sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ +int tdsqlite3changeset_start( + tdsqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ int nChangeset, /* Size of changeset blob in bytes */ void *pChangeset /* Pointer to blob containing changeset */ ); +int tdsqlite3changeset_start_v2( + tdsqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ + int nChangeset, /* Size of changeset blob in bytes */ + void *pChangeset, /* Pointer to blob containing changeset */ + int flags /* SESSION_CHANGESETSTART_* flags */ +); + +/* +** CAPI3REF: Flags for tdsqlite3changeset_start_v2 +** +** The following flags may passed via the 4th parameter to +** [tdsqlite3changeset_start_v2] and [tdsqlite3changeset_start_v2_strm]: +** +** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd> +** Invert the changeset while iterating through it. This is equivalent to +** inverting a changeset using tdsqlite3changeset_invert() before applying it. +** It is an error to specify this flag with a patchset. +*/ +#define SQLITE_CHANGESETSTART_INVERT 0x0002 /* ** CAPI3REF: Advance A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** -** This function may only be used with iterators created by function -** [sqlite3changeset_start()]. If it is called on an iterator passed to -** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE +** This function may only be used with iterators created by the function +** [tdsqlite3changeset_start()]. If it is called on an iterator passed to +** a conflict-handler callback by [tdsqlite3changeset_apply()], SQLITE_MISUSE ** is returned and the call has no effect. ** -** Immediately after an iterator is created by sqlite3changeset_start(), it +** Immediately after an iterator is created by tdsqlite3changeset_start(), it ** does not point to any change in the changeset. Assuming the changeset ** is not empty, the first call to this function advances the iterator to ** point to the first change in the changeset. Each subsequent call advances ** the iterator to point to the next change in the changeset (if any). If ** no error occurs and the iterator points to a valid change after a call -** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. +** to tdsqlite3changeset_next() has advanced it, SQLITE_ROW is returned. ** Otherwise, if all changes in the changeset have already been visited, ** SQLITE_DONE is returned. ** @@ -456,26 +529,27 @@ int sqlite3changeset_start( ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or ** SQLITE_NOMEM. */ -int sqlite3changeset_next(sqlite3_changeset_iter *pIter); +int tdsqlite3changeset_next(tdsqlite3_changeset_iter *pIter); /* ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** The pIter argument passed to this function may either be an iterator -** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator -** created by [sqlite3changeset_start()]. In the latter case, the most recent -** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this +** passed to a conflict-handler by [tdsqlite3changeset_apply()], or an iterator +** created by [tdsqlite3changeset_start()]. In the latter case, the most recent +** call to [tdsqlite3changeset_next()] must have returned [SQLITE_ROW]. If this ** is not the case, this function returns [SQLITE_MISUSE]. ** ** If argument pzTab is not NULL, then *pzTab is set to point to a ** nul-terminated utf-8 encoded string containing the name of the table ** affected by the current change. The buffer remains valid until either -** sqlite3changeset_next() is called on the iterator or until the +** tdsqlite3changeset_next() is called on the iterator or until the ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is ** set to the number of columns in the table affected by the change. If -** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change +** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change ** is an indirect change, or false (0) otherwise. See the documentation for -** [sqlite3session_indirect()] for a description of direct and indirect +** [tdsqlite3session_indirect()] for a description of direct and indirect ** changes. Finally, if pOp is not NULL, then *pOp is set to one of ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the ** type of change that the iterator currently points to. @@ -484,8 +558,8 @@ int sqlite3changeset_next(sqlite3_changeset_iter *pIter); ** SQLite error code is returned. The values of the output variables may not ** be trusted in this case. */ -int sqlite3changeset_op( - sqlite3_changeset_iter *pIter, /* Iterator object */ +int tdsqlite3changeset_op( + tdsqlite3_changeset_iter *pIter, /* Iterator object */ const char **pzTab, /* OUT: Pointer to table name */ int *pnCol, /* OUT: Number of columns in table */ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ @@ -494,6 +568,7 @@ int sqlite3changeset_op( /* ** CAPI3REF: Obtain The Primary Key Definition Of A Table +** METHOD: tdsqlite3_changeset_iter ** ** For each modified table, a changeset includes the following: ** @@ -517,19 +592,20 @@ int sqlite3changeset_op( ** SQLITE_OK is returned and the output variables populated as described ** above. */ -int sqlite3changeset_pk( - sqlite3_changeset_iter *pIter, /* Iterator object */ +int tdsqlite3changeset_pk( + tdsqlite3_changeset_iter *pIter, /* Iterator object */ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ int *pnCol /* OUT: Number of entries in output array */ ); /* ** CAPI3REF: Obtain old.* Values From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** The pIter argument passed to this function may either be an iterator -** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator -** created by [sqlite3changeset_start()]. In the latter case, the most recent -** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. +** passed to a conflict-handler by [tdsqlite3changeset_apply()], or an iterator +** created by [tdsqlite3changeset_start()]. In the latter case, the most recent +** call to [tdsqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. @@ -539,7 +615,7 @@ int sqlite3changeset_pk( ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected -** sqlite3_value object containing the iVal'th value from the vector of +** tdsqlite3_value object containing the iVal'th value from the vector of ** original row values stored as part of the UPDATE or DELETE change and ** returns SQLITE_OK. The name of the function comes from the fact that this ** is similar to the "old.*" columns available to update or delete triggers. @@ -547,19 +623,20 @@ int sqlite3changeset_pk( ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ -int sqlite3changeset_old( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +int tdsqlite3changeset_old( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ - sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ + tdsqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain new.* Values From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** The pIter argument passed to this function may either be an iterator -** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator -** created by [sqlite3changeset_start()]. In the latter case, the most recent -** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. +** passed to a conflict-handler by [tdsqlite3changeset_apply()], or an iterator +** created by [tdsqlite3changeset_start()]. In the latter case, the most recent +** call to [tdsqlite3changeset_next()] must have returned SQLITE_ROW. ** Furthermore, it may only be called if the type of change that the iterator ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise, ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. @@ -569,7 +646,7 @@ int sqlite3changeset_old( ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected -** sqlite3_value object containing the iVal'th value from the vector of +** tdsqlite3_value object containing the iVal'th value from the vector of ** new row values stored as part of the UPDATE or INSERT change and ** returns SQLITE_OK. If the change is an UPDATE and does not include ** a new value for the requested column, *ppValue is set to NULL and @@ -580,17 +657,18 @@ int sqlite3changeset_old( ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ -int sqlite3changeset_new( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +int tdsqlite3changeset_new( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ - sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ + tdsqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ ); /* ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** This function should only be used with iterator objects passed to a -** conflict-handler callback by [sqlite3changeset_apply()] with either +** conflict-handler callback by [tdsqlite3changeset_apply()] with either ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue ** is set to NULL. @@ -600,21 +678,22 @@ int sqlite3changeset_new( ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. ** ** If successful, this function sets *ppValue to point to a protected -** sqlite3_value object containing the iVal'th value from the +** tdsqlite3_value object containing the iVal'th value from the ** "conflicting row" associated with the current conflict-handler callback ** and returns SQLITE_OK. ** ** If some other error occurs (e.g. an OOM condition), an SQLite error code ** is returned and *ppValue is set to NULL. */ -int sqlite3changeset_conflict( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +int tdsqlite3changeset_conflict( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int iVal, /* Column number */ - sqlite3_value **ppValue /* OUT: Value from conflicting row */ + tdsqlite3_value **ppValue /* OUT: Value from conflicting row */ ); /* ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations +** METHOD: tdsqlite3_changeset_iter ** ** This function may only be called with an iterator passed to an ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case @@ -623,40 +702,43 @@ int sqlite3changeset_conflict( ** ** In all other cases this function returns SQLITE_MISUSE. */ -int sqlite3changeset_fk_conflicts( - sqlite3_changeset_iter *pIter, /* Changeset iterator */ +int tdsqlite3changeset_fk_conflicts( + tdsqlite3_changeset_iter *pIter, /* Changeset iterator */ int *pnOut /* OUT: Number of FK violations */ ); /* ** CAPI3REF: Finalize A Changeset Iterator +** METHOD: tdsqlite3_changeset_iter ** ** This function is used to finalize an iterator allocated with -** [sqlite3changeset_start()]. +** [tdsqlite3changeset_start()]. ** ** This function should only be called on iterators created using the -** [sqlite3changeset_start()] function. If an application calls this +** [tdsqlite3changeset_start()] function. If an application calls this ** function with an iterator passed to a conflict-handler by -** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the +** [tdsqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the ** call has no effect. ** -** If an error was encountered within a call to an sqlite3changeset_xxx() -** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an -** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding +** If an error was encountered within a call to an tdsqlite3changeset_xxx() +** function (for example an [SQLITE_CORRUPT] in [tdsqlite3changeset_next()] or an +** [SQLITE_NOMEM] in [tdsqlite3changeset_new()]) then an error code corresponding ** to that error is returned by this function. Otherwise, SQLITE_OK is ** returned. This is to allow the following pattern (pseudo-code): ** -** sqlite3changeset_start(); -** while( SQLITE_ROW==sqlite3changeset_next() ){ +** <pre> +** tdsqlite3changeset_start(); +** while( SQLITE_ROW==tdsqlite3changeset_next() ){ ** // Do something with change. ** } -** rc = sqlite3changeset_finalize(); +** rc = tdsqlite3changeset_finalize(); ** if( rc!=SQLITE_OK ){ ** // An error has occurred ** } +** </pre> */ -int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); +int tdsqlite3changeset_finalize(tdsqlite3_changeset_iter *pIter); /* ** CAPI3REF: Invert A Changeset @@ -679,14 +761,14 @@ int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are ** zeroed and an SQLite error code returned. ** -** It is the responsibility of the caller to eventually call sqlite3_free() +** It is the responsibility of the caller to eventually call tdsqlite3_free() ** on the *ppOut pointer to free the buffer allocation following a successful ** call to this function. ** ** WARNING/TODO: This function currently assumes that the input is a valid ** changeset. If it is not, the results are undefined. */ -int sqlite3changeset_invert( +int tdsqlite3changeset_invert( int nIn, const void *pIn, /* Input changeset */ int *pnOut, void **ppOut /* OUT: Inverse of input */ ); @@ -699,23 +781,25 @@ int sqlite3changeset_invert( ** changeset A followed by changeset B. ** ** This function combines the two input changesets using an -** sqlite3_changegroup object. Calling it produces similar results as the +** tdsqlite3_changegroup object. Calling it produces similar results as the ** following code fragment: ** -** sqlite3_changegroup *pGrp; -** rc = sqlite3_changegroup_new(&pGrp); -** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA); -** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB); +** <pre> +** tdsqlite3_changegroup *pGrp; +** rc = tdsqlite3_changegroup_new(&pGrp); +** if( rc==SQLITE_OK ) rc = tdsqlite3changegroup_add(pGrp, nA, pA); +** if( rc==SQLITE_OK ) rc = tdsqlite3changegroup_add(pGrp, nB, pB); ** if( rc==SQLITE_OK ){ -** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); +** rc = tdsqlite3changegroup_output(pGrp, pnOut, ppOut); ** }else{ ** *ppOut = 0; ** *pnOut = 0; ** } +** </pre> ** -** Refer to the sqlite3_changegroup documentation below for details. +** Refer to the tdsqlite3_changegroup documentation below for details. */ -int sqlite3changeset_concat( +int tdsqlite3changeset_concat( int nA, /* Number of bytes in buffer pA */ void *pA, /* Pointer to buffer containing changeset A */ int nB, /* Number of bytes in buffer pB */ @@ -727,48 +811,53 @@ int sqlite3changeset_concat( /* ** CAPI3REF: Changegroup Handle +** +** A changegroup is an object used to combine two or more +** [changesets] or [patchsets] */ -typedef struct sqlite3_changegroup sqlite3_changegroup; +typedef struct tdsqlite3_changegroup tdsqlite3_changegroup; /* ** CAPI3REF: Create A New Changegroup Object +** CONSTRUCTOR: tdsqlite3_changegroup ** -** An sqlite3_changegroup object is used to combine two or more changesets +** An tdsqlite3_changegroup object is used to combine two or more changesets ** (or patchsets) into a single changeset (or patchset). A single changegroup ** object may combine changesets or patchsets, but not both. The output is ** always in the same format as the input. ** ** If successful, this function returns SQLITE_OK and populates (*pp) with -** a pointer to a new sqlite3_changegroup object before returning. The caller +** a pointer to a new tdsqlite3_changegroup object before returning. The caller ** should eventually free the returned object using a call to -** sqlite3changegroup_delete(). If an error occurs, an SQLite error code +** tdsqlite3changegroup_delete(). If an error occurs, an SQLite error code ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL. ** -** The usual usage pattern for an sqlite3_changegroup object is as follows: +** The usual usage pattern for an tdsqlite3_changegroup object is as follows: ** ** <ul> -** <li> It is created using a call to sqlite3changegroup_new(). +** <li> It is created using a call to tdsqlite3changegroup_new(). ** ** <li> Zero or more changesets (or patchsets) are added to the object -** by calling sqlite3changegroup_add(). +** by calling tdsqlite3changegroup_add(). ** ** <li> The result of combining all input changesets together is obtained -** by the application via a call to sqlite3changegroup_output(). +** by the application via a call to tdsqlite3changegroup_output(). ** -** <li> The object is deleted using a call to sqlite3changegroup_delete(). +** <li> The object is deleted using a call to tdsqlite3changegroup_delete(). ** </ul> ** ** Any number of calls to add() and output() may be made between the calls to ** new() and delete(), and in any order. ** -** As well as the regular sqlite3changegroup_add() and -** sqlite3changegroup_output() functions, also available are the streaming -** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm(). +** As well as the regular tdsqlite3changegroup_add() and +** tdsqlite3changegroup_output() functions, also available are the streaming +** versions tdsqlite3changegroup_add_strm() and tdsqlite3changegroup_output_strm(). */ -int sqlite3changegroup_new(sqlite3_changegroup **pp); +int tdsqlite3changegroup_new(tdsqlite3_changegroup **pp); /* ** CAPI3REF: Add A Changeset To A Changegroup +** METHOD: tdsqlite3_changegroup ** ** Add all changes within the changeset (or patchset) in buffer pData (size ** nData bytes) to the changegroup. @@ -837,23 +926,24 @@ int sqlite3changegroup_new(sqlite3_changegroup **pp); ** case, this function fails with SQLITE_SCHEMA. If the input changeset ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is ** returned. Or, if an out-of-memory condition occurs during processing, this -** function returns SQLITE_NOMEM. In all cases, if an error occurs the -** final contents of the changegroup is undefined. +** function returns SQLITE_NOMEM. In all cases, if an error occurs the state +** of the final contents of the changegroup is undefined. ** ** If no error occurs, SQLITE_OK is returned. */ -int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); +int tdsqlite3changegroup_add(tdsqlite3_changegroup*, int nData, void *pData); /* ** CAPI3REF: Obtain A Composite Changeset From A Changegroup +** METHOD: tdsqlite3_changegroup ** ** Obtain a buffer containing a changeset (or patchset) representing the ** current contents of the changegroup. If the inputs to the changegroup ** were themselves changesets, the output is a changeset. Or, if the ** inputs were patchsets, the output is also a patchset. ** -** As with the output of the sqlite3session_changeset() and -** sqlite3session_patchset() functions, all changes related to a single +** As with the output of the tdsqlite3session_changeset() and +** tdsqlite3session_patchset() functions, all changes related to a single ** table are grouped together in the output of this function. Tables appear ** in the same order as for the very first changeset added to the changegroup. ** If the second or subsequent changesets added to the changegroup contain @@ -866,35 +956,35 @@ int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); ** is returned and the output variables are set to the size of and a ** pointer to the output buffer, respectively. In this case it is the ** responsibility of the caller to eventually free the buffer using a -** call to sqlite3_free(). +** call to tdsqlite3_free(). */ -int sqlite3changegroup_output( - sqlite3_changegroup*, +int tdsqlite3changegroup_output( + tdsqlite3_changegroup*, int *pnData, /* OUT: Size of output buffer in bytes */ void **ppData /* OUT: Pointer to output buffer */ ); /* ** CAPI3REF: Delete A Changegroup Object +** DESTRUCTOR: tdsqlite3_changegroup */ -void sqlite3changegroup_delete(sqlite3_changegroup*); +void tdsqlite3changegroup_delete(tdsqlite3_changegroup*); /* ** CAPI3REF: Apply A Changeset To A Database ** -** Apply a changeset to a database. This function attempts to update the -** "main" database attached to handle db with the changes found in the -** changeset passed via the second and third arguments. +** Apply a changeset or patchset to a database. These functions attempt to +** update the "main" database attached to handle db with the changes found in +** the changeset passed via the second and third arguments. ** -** The fourth argument (xFilter) passed to this function is the "filter +** The fourth argument (xFilter) passed to these functions is the "filter ** callback". If it is not NULL, then for each table affected by at least one ** change in the changeset, the filter callback is invoked with ** the table name as the second argument, and a copy of the context pointer -** passed as the sixth argument to this function as the first. If the "filter -** callback" returns zero, then no attempt is made to apply any changes to -** the table. Otherwise, if the return value is non-zero or the xFilter -** argument to this function is NULL, all changes related to the table are -** attempted. +** passed as the sixth argument as the first. If the "filter callback" +** returns zero, then no attempt is made to apply any changes to the table. +** Otherwise, if the return value is non-zero or the xFilter argument to +** is NULL, all changes related to the table are attempted. ** ** For each table that is not excluded by the filter callback, this function ** tests that the target database contains a compatible table. A table is @@ -903,7 +993,7 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** <ul> ** <li> The table has the same name as the name recorded in the ** changeset, and -** <li> The table has the same number of columns as recorded in the +** <li> The table has at least as many columns as recorded in the ** changeset, and ** <li> The table has primary key columns in the same position as ** recorded in the changeset. @@ -911,13 +1001,13 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** ** If there is no compatible table, it is not an error, but none of the ** changes associated with the table are applied. A warning message is issued -** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most +** via the tdsqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most ** one such warning is issued for each table in the changeset. ** ** For each change for which there is a compatible table, an attempt is made ** to modify the table contents according to the UPDATE, INSERT or DELETE ** change. If a change cannot be applied cleanly, the conflict handler -** function passed as the fifth argument to sqlite3changeset_apply() may be +** function passed as the fifth argument to tdsqlite3changeset_apply() may be ** invoked. A description of exactly when the conflict handler is invoked for ** each type of change is below. ** @@ -931,15 +1021,15 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** if the second argument passed to the conflict handler is either ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler ** returns an illegal value, any changes already made are rolled back and -** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different -** actions are taken by sqlite3changeset_apply() depending on the value +** the call to tdsqlite3changeset_apply() returns SQLITE_MISUSE. Different +** actions are taken by tdsqlite3changeset_apply() depending on the value ** returned by each invocation of the conflict-handler function. Refer to ** the documentation for the three ** [SQLITE_CHANGESET_OMIT|available return values] for details. ** ** <dl> ** <dt>DELETE Changes<dd> -** For each DELETE change, this function checks if the target database +** For each DELETE change, the function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values ** stored in all non-primary key columns also match the values stored in @@ -948,7 +1038,11 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** If a row with matching primary key values is found, but one or more of ** the non-primary key fields contains a value different from the original ** row value stored in the changeset, the conflict-handler function is -** invoked with [SQLITE_CHANGESET_DATA] as the second argument. +** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the +** database table has more columns than are recorded in the changeset, +** only the values of those non-primary key fields are compared against +** the current database contents - any trailing database table columns +** are ignored. ** ** If no row with matching primary key values is found in the database, ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] @@ -963,7 +1057,9 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** ** <dt>INSERT Changes<dd> ** For each INSERT change, an attempt is made to insert the new row into -** the database. +** the database. If the changeset row contains fewer fields than the +** database table, the trailing fields are populated with their default +** values. ** ** If the attempt to insert the row fails because the database already ** contains a row with the same primary key values, the conflict handler @@ -978,16 +1074,16 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** [SQLITE_CHANGESET_REPLACE]. ** ** <dt>UPDATE Changes<dd> -** For each UPDATE change, this function checks if the target database +** For each UPDATE change, the function checks if the target database ** contains a row with the same primary key value (or values) as the ** original row values stored in the changeset. If it does, and the values -** stored in all non-primary key columns also match the values stored in -** the changeset the row is updated within the target database. +** stored in all modified non-primary key columns also match the values +** stored in the changeset the row is updated within the target database. ** ** If a row with matching primary key values is found, but one or more of -** the non-primary key fields contains a value different from an original -** row value stored in the changeset, the conflict-handler function is -** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since +** the modified non-primary key fields contains a value different from an +** original row value stored in the changeset, the conflict-handler function +** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since ** UPDATE changes only contain values for non-primary key fields that are ** to be modified, only those fields need to match the original values to ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. @@ -1006,17 +1102,34 @@ void sqlite3changegroup_delete(sqlite3_changegroup*); ** ** It is safe to execute SQL statements, including those that write to the ** table that the callback related to, from within the xConflict callback. -** This can be used to further customize the applications conflict +** This can be used to further customize the application's conflict ** resolution strategy. ** -** All changes made by this function are enclosed in a savepoint transaction. +** All changes made by these functions are enclosed in a savepoint transaction. ** If any other error (aside from a constraint failure when attempting to ** write to the target database) occurs, then the savepoint transaction is ** rolled back, restoring the target database to its original state, and an ** SQLite error code returned. +** +** If the output parameters (ppRebase) and (pnRebase) are non-NULL and +** the input is a changeset (not a patchset), then tdsqlite3changeset_apply_v2() +** may set (*ppRebase) to point to a "rebase" that may be used with the +** tdsqlite3_rebaser APIs buffer before returning. In this case (*pnRebase) +** is set to the size of the buffer in bytes. It is the responsibility of the +** caller to eventually free any such buffer using tdsqlite3_free(). The buffer +** is only allocated and populated if one or more conflicts were encountered +** while applying the patchset. See comments surrounding the tdsqlite3_rebaser +** APIs for further details. +** +** The behavior of tdsqlite3changeset_apply_v2() and its streaming equivalent +** may be modified by passing a combination of +** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter. +** +** Note that the tdsqlite3changeset_apply_v2() API is still <b>experimental</b> +** and therefore subject to change. */ -int sqlite3changeset_apply( - sqlite3 *db, /* Apply change to "main" db of this handle */ +int tdsqlite3changeset_apply( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ int(*xFilter)( @@ -1026,10 +1139,51 @@ int sqlite3changeset_apply( int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); +int tdsqlite3changeset_apply_v2( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, /* OUT: Rebase data */ + int flags /* SESSION_CHANGESETAPPLY_* flags */ +); + +/* +** CAPI3REF: Flags for tdsqlite3changeset_apply_v2 +** +** The following flags may passed via the 9th parameter to +** [tdsqlite3changeset_apply_v2] and [tdsqlite3changeset_apply_v2_strm]: +** +** <dl> +** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd> +** Usually, the sessions module encloses all operations performed by +** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The +** SAVEPOINT is committed if the changeset or patchset is successfully +** applied, or rolled back if an error occurs. Specifying this flag +** causes the sessions module to omit this savepoint. In this case, if the +** caller has an open transaction or savepoint when apply_v2() is called, +** it may revert the partially applied changeset by rolling it back. +** +** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd> +** Invert the changeset before applying it. This is equivalent to inverting +** a changeset using tdsqlite3changeset_invert() before applying it. It is +** an error to specify this flag with a patchset. +*/ +#define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001 +#define SQLITE_CHANGESETAPPLY_INVERT 0x0002 /* ** CAPI3REF: Constants Passed To The Conflict Handler @@ -1053,7 +1207,7 @@ int sqlite3changeset_apply( ** required PRIMARY KEY fields is not present in the database. ** ** There is no conflicting row in this case. The results of invoking the -** sqlite3changeset_conflict() API are undefined. +** tdsqlite3changeset_conflict() API are undefined. ** ** <dt>SQLITE_CHANGESET_CONFLICT<dd> ** CHANGESET_CONFLICT is passed as the second argument to the conflict @@ -1073,8 +1227,8 @@ int sqlite3changeset_apply( ** CHANGESET_ABORT, the changeset is rolled back. ** ** No current or conflicting row information is provided. The only function -** it is possible to call on the supplied sqlite3_changeset_iter handle -** is sqlite3changeset_fk_conflicts(). +** it is possible to call on the supplied tdsqlite3_changeset_iter handle +** is tdsqlite3changeset_fk_conflicts(). ** ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd> ** If any other constraint violation occurs while applying a change (i.e. @@ -1082,7 +1236,7 @@ int sqlite3changeset_apply( ** invoked with CHANGESET_CONSTRAINT as the second argument. ** ** There is no conflicting row in this case. The results of invoking the -** sqlite3changeset_conflict() API are undefined. +** tdsqlite3changeset_conflict() API are undefined. ** ** </dl> */ @@ -1107,7 +1261,7 @@ int sqlite3changeset_apply( ** This value may only be returned if the second argument to the conflict ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this ** is not the case, any changes applied so far are rolled back and the -** call to sqlite3changeset_apply() returns SQLITE_MISUSE. +** call to tdsqlite3changeset_apply() returns SQLITE_MISUSE. ** ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict ** handler, then the conflicting row is either updated or deleted, depending @@ -1120,13 +1274,168 @@ int sqlite3changeset_apply( ** ** <dt>SQLITE_CHANGESET_ABORT<dd> ** If this value is returned, any changes applied so far are rolled back -** and the call to sqlite3changeset_apply() returns SQLITE_ABORT. +** and the call to tdsqlite3changeset_apply() returns SQLITE_ABORT. ** </dl> */ #define SQLITE_CHANGESET_OMIT 0 #define SQLITE_CHANGESET_REPLACE 1 #define SQLITE_CHANGESET_ABORT 2 +/* +** CAPI3REF: Rebasing changesets +** EXPERIMENTAL +** +** Suppose there is a site hosting a database in state S0. And that +** modifications are made that move that database to state S1 and a +** changeset recorded (the "local" changeset). Then, a changeset based +** on S0 is received from another site (the "remote" changeset) and +** applied to the database. The database is then in state +** (S1+"remote"), where the exact state depends on any conflict +** resolution decisions (OMIT or REPLACE) made while applying "remote". +** Rebasing a changeset is to update it to take those conflict +** resolution decisions into account, so that the same conflicts +** do not have to be resolved elsewhere in the network. +** +** For example, if both the local and remote changesets contain an +** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)": +** +** local: INSERT INTO t1 VALUES(1, 'v1'); +** remote: INSERT INTO t1 VALUES(1, 'v2'); +** +** and the conflict resolution is REPLACE, then the INSERT change is +** removed from the local changeset (it was overridden). Or, if the +** conflict resolution was "OMIT", then the local changeset is modified +** to instead contain: +** +** UPDATE t1 SET b = 'v2' WHERE a=1; +** +** Changes within the local changeset are rebased as follows: +** +** <dl> +** <dt>Local INSERT<dd> +** This may only conflict with a remote INSERT. If the conflict +** resolution was OMIT, then add an UPDATE change to the rebased +** changeset. Or, if the conflict resolution was REPLACE, add +** nothing to the rebased changeset. +** +** <dt>Local DELETE<dd> +** This may conflict with a remote UPDATE or DELETE. In both cases the +** only possible resolution is OMIT. If the remote operation was a +** DELETE, then add no change to the rebased changeset. If the remote +** operation was an UPDATE, then the old.* fields of change are updated +** to reflect the new.* values in the UPDATE. +** +** <dt>Local UPDATE<dd> +** This may conflict with a remote UPDATE or DELETE. If it conflicts +** with a DELETE, and the conflict resolution was OMIT, then the update +** is changed into an INSERT. Any undefined values in the new.* record +** from the update change are filled in using the old.* values from +** the conflicting DELETE. Or, if the conflict resolution was REPLACE, +** the UPDATE change is simply omitted from the rebased changeset. +** +** If conflict is with a remote UPDATE and the resolution is OMIT, then +** the old.* values are rebased using the new.* values in the remote +** change. Or, if the resolution is REPLACE, then the change is copied +** into the rebased changeset with updates to columns also updated by +** the conflicting remote UPDATE removed. If this means no columns would +** be updated, the change is omitted. +** </dl> +** +** A local change may be rebased against multiple remote changes +** simultaneously. If a single key is modified by multiple remote +** changesets, they are combined as follows before the local changeset +** is rebased: +** +** <ul> +** <li> If there has been one or more REPLACE resolutions on a +** key, it is rebased according to a REPLACE. +** +** <li> If there have been no REPLACE resolutions on a key, then +** the local changeset is rebased according to the most recent +** of the OMIT resolutions. +** </ul> +** +** Note that conflict resolutions from multiple remote changesets are +** combined on a per-field basis, not per-row. This means that in the +** case of multiple remote UPDATE operations, some fields of a single +** local change may be rebased for REPLACE while others are rebased for +** OMIT. +** +** In order to rebase a local changeset, the remote changeset must first +** be applied to the local database using tdsqlite3changeset_apply_v2() and +** the buffer of rebase information captured. Then: +** +** <ol> +** <li> An tdsqlite3_rebaser object is created by calling +** tdsqlite3rebaser_create(). +** <li> The new object is configured with the rebase buffer obtained from +** tdsqlite3changeset_apply_v2() by calling tdsqlite3rebaser_configure(). +** If the local changeset is to be rebased against multiple remote +** changesets, then tdsqlite3rebaser_configure() should be called +** multiple times, in the same order that the multiple +** tdsqlite3changeset_apply_v2() calls were made. +** <li> Each local changeset is rebased by calling tdsqlite3rebaser_rebase(). +** <li> The tdsqlite3_rebaser object is deleted by calling +** tdsqlite3rebaser_delete(). +** </ol> +*/ +typedef struct tdsqlite3_rebaser tdsqlite3_rebaser; + +/* +** CAPI3REF: Create a changeset rebaser object. +** EXPERIMENTAL +** +** Allocate a new changeset rebaser object. If successful, set (*ppNew) to +** point to the new object and return SQLITE_OK. Otherwise, if an error +** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) +** to NULL. +*/ +int tdsqlite3rebaser_create(tdsqlite3_rebaser **ppNew); + +/* +** CAPI3REF: Configure a changeset rebaser object. +** EXPERIMENTAL +** +** Configure the changeset rebaser object to rebase changesets according +** to the conflict resolutions described by buffer pRebase (size nRebase +** bytes), which must have been obtained from a previous call to +** tdsqlite3changeset_apply_v2(). +*/ +int tdsqlite3rebaser_configure( + tdsqlite3_rebaser*, + int nRebase, const void *pRebase +); + +/* +** CAPI3REF: Rebase a changeset +** EXPERIMENTAL +** +** Argument pIn must point to a buffer containing a changeset nIn bytes +** in size. This function allocates and populates a buffer with a copy +** of the changeset rebased according to the configuration of the +** rebaser object passed as the first argument. If successful, (*ppOut) +** is set to point to the new buffer containing the rebased changeset and +** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the +** responsibility of the caller to eventually free the new buffer using +** tdsqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut) +** are set to zero and an SQLite error code returned. +*/ +int tdsqlite3rebaser_rebase( + tdsqlite3_rebaser*, + int nIn, const void *pIn, + int *pnOut, void **ppOut +); + +/* +** CAPI3REF: Delete a changeset rebaser object. +** EXPERIMENTAL +** +** Delete the changeset rebaser object and all associated resources. There +** should be one call to this function for each successful invocation +** of tdsqlite3rebaser_create(). +*/ +void tdsqlite3rebaser_delete(tdsqlite3_rebaser *p); + /* ** CAPI3REF: Streaming Versions of API functions. ** @@ -1135,18 +1444,19 @@ int sqlite3changeset_apply( ** ** <table border=1 style="margin-left:8ex;margin-right:8ex"> ** <tr><th>Streaming function<th>Non-streaming equivalent</th> -** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply] -** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat] -** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert] -** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start] -** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset] -** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset] +** <tr><td>tdsqlite3changeset_apply_strm<td>[tdsqlite3changeset_apply] +** <tr><td>tdsqlite3changeset_apply_strm_v2<td>[tdsqlite3changeset_apply_v2] +** <tr><td>tdsqlite3changeset_concat_strm<td>[tdsqlite3changeset_concat] +** <tr><td>tdsqlite3changeset_invert_strm<td>[tdsqlite3changeset_invert] +** <tr><td>tdsqlite3changeset_start_strm<td>[tdsqlite3changeset_start] +** <tr><td>tdsqlite3session_changeset_strm<td>[tdsqlite3session_changeset] +** <tr><td>tdsqlite3session_patchset_strm<td>[tdsqlite3session_patchset] ** </table> ** ** Non-streaming functions that accept changesets (or patchsets) as input ** require that the entire changeset be stored in a single buffer in memory. ** Similarly, those that return a changeset or patchset do so by returning -** a pointer to a single large buffer allocated using sqlite3_malloc(). +** a pointer to a single large buffer allocated using tdsqlite3_malloc(). ** Normally this is convenient. However, if an application running in a ** low-memory environment is required to handle very large changesets, the ** large contiguous memory allocations required can become onerous. @@ -1179,7 +1489,7 @@ int sqlite3changeset_apply( ** an error, all processing is abandoned and the streaming API function ** returns a copy of the error code to the caller. ** -** In the case of sqlite3changeset_start_strm(), the xInput callback may be +** In the case of tdsqlite3changeset_start_strm(), the xInput callback may be ** invoked by the sessions module at any point during the lifetime of the ** iterator. If such an xInput callback returns an error, the iterator enters ** an error state, whereby all subsequent calls to iterator functions @@ -1216,8 +1526,8 @@ int sqlite3changeset_apply( ** parameter set to a value less than or equal to zero. Other than this, ** no guarantees are made as to the size of the chunks of data returned. */ -int sqlite3changeset_apply_strm( - sqlite3 *db, /* Apply change to "main" db of this handle */ +int tdsqlite3changeset_apply_strm( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ void *pIn, /* First arg for xInput */ int(*xFilter)( @@ -1227,11 +1537,28 @@ int sqlite3changeset_apply_strm( int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ - sqlite3_changeset_iter *p /* Handle describing change and conflict */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ ), void *pCtx /* First argument passed to xConflict */ ); -int sqlite3changeset_concat_strm( +int tdsqlite3changeset_apply_v2_strm( + tdsqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + tdsqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +); +int tdsqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, int (*xInputB)(void *pIn, void *pData, int *pnData), @@ -1239,36 +1566,88 @@ int sqlite3changeset_concat_strm( int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3changeset_invert_strm( +int tdsqlite3changeset_invert_strm( int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3changeset_start_strm( - sqlite3_changeset_iter **pp, +int tdsqlite3changeset_start_strm( + tdsqlite3_changeset_iter **pp, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); -int sqlite3session_changeset_strm( - sqlite3_session *pSession, +int tdsqlite3changeset_start_v2_strm( + tdsqlite3_changeset_iter **pp, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int flags +); +int tdsqlite3session_changeset_strm( + tdsqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3session_patchset_strm( - sqlite3_session *pSession, +int tdsqlite3session_patchset_strm( + tdsqlite3_session *pSession, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); -int sqlite3changegroup_add_strm(sqlite3_changegroup*, +int tdsqlite3changegroup_add_strm(tdsqlite3_changegroup*, int (*xInput)(void *pIn, void *pData, int *pnData), void *pIn ); -int sqlite3changegroup_output_strm(sqlite3_changegroup*, +int tdsqlite3changegroup_output_strm(tdsqlite3_changegroup*, int (*xOutput)(void *pOut, const void *pData, int nData), void *pOut ); +int tdsqlite3rebaser_rebase_strm( + tdsqlite3_rebaser *pRebaser, + int (*xInput)(void *pIn, void *pData, int *pnData), + void *pIn, + int (*xOutput)(void *pOut, const void *pData, int nData), + void *pOut +); +/* +** CAPI3REF: Configure global parameters +** +** The tdsqlite3session_config() interface is used to make global configuration +** changes to the sessions module in order to tune it to the specific needs +** of the application. +** +** The tdsqlite3session_config() interface is not threadsafe. If it is invoked +** while any other thread is inside any other sessions method then the +** results are undefined. Furthermore, if it is invoked after any sessions +** related objects have been created, the results are also undefined. +** +** The first argument to the tdsqlite3session_config() function must be one +** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The +** interpretation of the (void*) value passed as the second parameter and +** the effect of calling this function depends on the value of the first +** parameter. +** +** <dl> +** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd> +** By default, the sessions module streaming interfaces attempt to input +** and output data in approximately 1 KiB chunks. This operand may be used +** to set and query the value of this configuration setting. The pointer +** passed as the second argument must point to a value of type (int). +** If this value is greater than 0, it is used as the new streaming data +** chunk size for both input and output. Before returning, the (int) value +** pointed to by pArg is set to the final value of the streaming interface +** chunk size. +** </dl> +** +** This function returns SQLITE_OK if successful, or an SQLite error code +** otherwise. +*/ +int tdsqlite3session_config(int op, void *pArg); + +/* +** CAPI3REF: Values for tdsqlite3session_config(). +*/ +#define SQLITE_SESSION_CONFIG_STRMSIZE 1 /* ** Make sure we can call this stuff from C++. |